Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84ee932c27 | ||
|
|
77f21a4734 | ||
|
|
a24cf5ac3c | ||
|
|
22c55854f3 | ||
|
|
b59388065f |
No files matched your search
@@ -15,6 +15,10 @@ BLOB_STORAGE_DIR=./data/blobs
|
||||
# use stays signed in; one left alone for this long has to sign in again.
|
||||
SESSION_TTL_HOURS=720
|
||||
|
||||
# Anyone may create a user. Off by default: then only the first user can
|
||||
# register, which is how a new server gets its owner.
|
||||
#OPEN_REGISTRATION=true
|
||||
|
||||
# Days mail stays in Trash before it's permanently deleted. 0 disables purging.
|
||||
TRASH_RETENTION_DAYS=30
|
||||
|
||||
|
||||
@@ -19,6 +19,18 @@ jobs:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Gitea rejects a workflow file it can't parse without running
|
||||
# anything, which for release.yml only shows up when a tag is pushed.
|
||||
# Parsing them all here catches that on master, before tagging.
|
||||
- name: Check workflow files parse
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import glob, yaml
|
||||
for f in sorted(glob.glob(".gitea/workflows/*.yml")):
|
||||
yaml.safe_load(open(f))
|
||||
print("ok", f)
|
||||
PY
|
||||
|
||||
- name: Set up Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
|
||||
@@ -7,42 +7,27 @@ on:
|
||||
jobs:
|
||||
image:
|
||||
runs-on: rocky-10
|
||||
outputs:
|
||||
version: ${{ steps.image.outputs.version }}
|
||||
digest: ${{ steps.image.outputs.digest }}
|
||||
steps:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Derive registry and version
|
||||
id: meta
|
||||
run: |
|
||||
# gitea.server_url is the web root, e.g. https://git.app.ygg — the
|
||||
# container registry lives on that same host, so there's no
|
||||
# hostname to hardcode or keep in sync.
|
||||
REGISTRY="$(echo '${{ gitea.server_url }}' | sed -E 's#^https?://##')"
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
echo "registry=$REGISTRY" >> "$GITHUB_OUTPUT"
|
||||
echo "image=$REGISTRY/${{ gitea.repository }}" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Log in to container registry
|
||||
run: |
|
||||
echo '${{ secrets.REGISTRY_TOKEN }}' \
|
||||
| docker login '${{ steps.meta.outputs.registry }}' \
|
||||
-u '${{ gitea.actor }}' --password-stdin
|
||||
|
||||
# The shared ygg action builds ./Dockerfile as
|
||||
# git.app.ygg/mtps/tern-server, tagged with the version (v stripped)
|
||||
# and latest, with OCI source/revision/created/version labels. It logs
|
||||
# in through a temporary DOCKER_CONFIG, so the token never lands in the
|
||||
# runner's ~/.docker, and builds with --progress=plain.
|
||||
- name: Build and push image
|
||||
env:
|
||||
DOCKER_BUILDKIT: '1'
|
||||
run: |
|
||||
IMAGE='${{ steps.meta.outputs.image }}'
|
||||
VERSION='${{ steps.meta.outputs.version }}'
|
||||
# --progress=plain: without it BuildKit renders an animated TTY
|
||||
# progress display, repainting every step on each frame. In a log
|
||||
# file that became ~15k lines of cursor-movement escapes for a
|
||||
# build that only has a few hundred lines of real output.
|
||||
docker build --progress=plain -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
|
||||
docker push "$IMAGE:$VERSION"
|
||||
docker push "$IMAGE:latest"
|
||||
id: image
|
||||
uses: https://git.app.ygg/ygg/actions/push-image@v2
|
||||
with:
|
||||
registry-token: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
- name: Log out
|
||||
if: always()
|
||||
run: docker logout '${{ steps.meta.outputs.registry }}' || true
|
||||
- name: Show image
|
||||
env:
|
||||
TAGS: ${{ steps.image.outputs.tags }}
|
||||
DIGEST: ${{ steps.image.outputs.digest }}
|
||||
run: |
|
||||
printf 'tags: %s\ndigest: %s\n' "$TAGS" "$DIGEST"
|
||||
Generated
+1
-1
@@ -3047,7 +3047,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tern-server"
|
||||
version = "0.8.0"
|
||||
version = "0.8.2"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tern-server"
|
||||
version = "0.8.0"
|
||||
version = "0.8.2"
|
||||
edition = "2021"
|
||||
description = "Tern sync server — the only component that speaks IMAP/SMTP"
|
||||
|
||||
|
||||
@@ -11,4 +11,7 @@ WORKDIR /app
|
||||
COPY --from=builder /build/target/release/tern-server ./tern-server
|
||||
COPY migrations ./migrations
|
||||
EXPOSE 8080
|
||||
# Healthy once the server answers /healthz (after migrations, on its port).
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=5 \
|
||||
CMD ["./tern-server", "healthcheck"]
|
||||
CMD ["./tern-server"]
|
||||
@@ -91,6 +91,14 @@ The phone's UnifiedPush distributor (e.g. the ntfy app) hands it an endpoint on
|
||||
- `PUSH_VAPID_SUBJECT=mailto:you@example.org` — a contact address for push-service operators.
|
||||
- **Any signed-in user can make the server POST to a URL of their choosing** (their push endpoint). Fine for a personal server; on a shared one, restrict outbound traffic at the network level.
|
||||
|
||||
## Registration
|
||||
|
||||
Only the first user can sign up, which is how a new server gets its owner. After that, `POST /api/auth/register` answers 403 unless `OPEN_REGISTRATION=true`. An open sign-up would let anyone on the internet use the server to make outbound IMAP, SMTP and push connections.
|
||||
|
||||
## Deployment
|
||||
|
||||
[`deploy/`](deploy/README.md) holds the production deployment to tern.mtps.pl: the whole stack as one compose project, deployed on every release by the shared `ygg/actions/deploy` action. The image's `HEALTHCHECK` runs `tern-server healthcheck`, so `docker compose up --wait` only succeeds once the server answers `/healthz`.
|
||||
|
||||
## Sessions
|
||||
|
||||
Sessions expire `SESSION_TTL_HOURS` (default 30 days) after they were last *used*, not after sign-in: each request pushes expiry back out, at most once an hour. A phone that syncs on push, or an open tab, stays signed in; a device left unused for the full period has to sign in again.
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Deployment
|
||||
|
||||
[`tern.yml`](tern.yml) deploys the whole Tern stack to **tern.mtps.pl** as one compose project (`deploy/compose` in the ygg management repo). The deploy runs automatically at the end of every `tern-web` release, through the shared [`ygg/actions/deploy`](https://git.app.ygg/ygg/actions/src/branch/main/deploy) action.
|
||||
|
||||
## What runs
|
||||
|
||||
| service | image | role |
|
||||
|---|---|---|
|
||||
| `db` | `postgres:16-alpine` | Tern's database, in the `db-data` volume |
|
||||
| `server` | `git.app.ygg/mtps/tern-server:<version>` | the API and sync engine; mail and attachments live in the `blob-data` volume |
|
||||
| `web` | `git.app.ygg/ygg/static-server` | serves the matching `tern-web` release (`tern-web-<version>.tgz`) |
|
||||
| `proxy` | `nginx:1.29-alpine` | puts the webapp and its API on one origin, published on port **11901** |
|
||||
|
||||
- **Routing:** the `proxy` sends `/api` (including the `/api/ws` WebSocket) to the server and everything else to the webapp. The webapp needs both on one origin.
|
||||
- **Rate limit:** sign-in and sign-up are rate-limited per client.
|
||||
- **Kara's nginx:** the `site` role proxies tern.mtps.pl to port 11901, with `websocket.conf` included for live updates.
|
||||
- **Trust store:** the server and webapp mount the host's CA bundle, so IMAP/SMTP servers, push servers and git.app.ygg behind the internal CA are trusted.
|
||||
|
||||
## How a release deploys
|
||||
|
||||
1. Tags go out server-first (see [`../docs/release-process.md`](../docs/release-process.md)). tern-server's release pushes `tern-server:<version>` with [`ygg/actions/push-image`](https://git.app.ygg/ygg/actions/src/branch/main/push-image).
|
||||
2. tern-web's release publishes `tern-web-<version>.tgz`. Then its `deploy` job does three things:
|
||||
- checks out this file at the same tag;
|
||||
- checks that the server image for that version exists;
|
||||
- runs `deploy/compose` with `version=<version>`.
|
||||
3. On kara, `docker compose up --wait` replaces the running containers. A deploy only succeeds once every service is healthy: the server is healthy when it answers `/healthz`, which is after migrations have run. So a server that can't start fails the workflow instead of quietly going down.
|
||||
|
||||
The deploy lives in tern-web, not tern-server, because of the single runner. Tags are queued server-first, so by the time tern-web's release runs, both artifacts exist. A deploy job in tern-server would have to wait for tern-web while holding the only runner.
|
||||
|
||||
## One-time setup
|
||||
|
||||
1. **Secrets on kara:** `/opt/ygg/secrets/env/tern.env`. It's copied next to the compose file as `.env`.
|
||||
|
||||
```ini
|
||||
POSTGRES_PASSWORD=<openssl rand -hex 24>
|
||||
CREDENTIAL_KEY=<openssl rand -base64 32>
|
||||
# optional: PUSH_URL_REWRITE, PUSH_TLS_INSECURE, PUSH_VAPID_SUBJECT,
|
||||
# SESSION_TTL_HOURS, TRASH_RETENTION_DAYS, OPEN_REGISTRATION, RUST_LOG
|
||||
```
|
||||
|
||||
Back up `CREDENTIAL_KEY` somewhere other than kara. Without it, the stored IMAP/SMTP passwords and the VAPID key can't be decrypted.
|
||||
|
||||
2. **Secrets on the `mtps/tern-web` repository:** `DEPLOY_SSH_KEY` and `DEPLOY_KNOWN_HOSTS`, the same values as the `ygg` org's secrets. The tern repositories belong to `mtps`, so the org-level secrets don't reach them.
|
||||
|
||||
3. **PyYAML on the runner** (`dnf install python3-pyyaml`). The deploy action converts this YAML file to JSON before sending it.
|
||||
|
||||
4. **Create your user.** Only the first user can register unless `OPEN_REGISTRATION=true` is set. Sign up once in the Android app (*Create a new user on this server*) or with `curl -X POST https://tern.mtps.pl/api/auth/register -H 'Content-Type: application/json' -d '{"username":"…","password":"…"}'`. After that, sign-up is closed.
|
||||
|
||||
## By hand
|
||||
|
||||
The same deploy, run directly on kara, with `tern.yml` copied to the dist directory:
|
||||
|
||||
```bash
|
||||
/opt/ygg/play.sh deploy/compose -e @/opt/ygg/dist/compose/tern.yml -e version=0.9.0
|
||||
```
|
||||
|
||||
To take it down, add `-e compose_state=destroy`. That stops the project and removes the nginx site. The `db-data` and `blob-data` volumes are kept.
|
||||
|
||||
## Escaping in `tern.yml`
|
||||
|
||||
The file is processed twice, so some characters need escaping:
|
||||
|
||||
- **Ansible** templates `{{ … }}`. That's how `{{ version }}` gets filled in. Wrap anything else that looks like Jinja in `{% raw %}`.
|
||||
- **Docker compose** interpolates `$`. That's how `${POSTGRES_PASSWORD}` comes from `.env`. The proxy's nginx variables are therefore written `$$host`, `$$http_upgrade`, and so on.
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
# Tern's production deployment: the whole stack as one compose project,
|
||||
# deployed by tern-web's release workflow through ygg/actions/deploy
|
||||
# (`deploy/compose` on kara). See deploy/README.md.
|
||||
#
|
||||
# `version` arrives as an extra var (the release tag without its v) and is
|
||||
# templated in by Ansible. Secrets come from /opt/ygg/secrets/env/tern.env
|
||||
# on kara, copied next to compose.yml as .env — never put them in here:
|
||||
# this file is sent on the command line.
|
||||
#
|
||||
# Escaping: Ansible templates {{ }}, and compose interpolates $, so a
|
||||
# literal $ (nginx variables) is written $$.
|
||||
|
||||
compose_project: tern
|
||||
|
||||
domain: tern.mtps.pl
|
||||
cert: mtps.pl
|
||||
site_port: 11901
|
||||
# Kara's nginx proxies the domain here; the include passes the WebSocket
|
||||
# upgrade through for live updates (/api/ws).
|
||||
site_includes: websocket.conf
|
||||
|
||||
compose:
|
||||
services:
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: tern
|
||||
POSTGRES_DB: tern
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in tern.env}
|
||||
volumes:
|
||||
- db-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U tern -d tern"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
server:
|
||||
image: "git.app.ygg/mtps/tern-server:{{ version }}"
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
DATABASE_URL: postgres://tern:${POSTGRES_PASSWORD}@db:5432/tern
|
||||
BIND_ADDR: 0.0.0.0:8080
|
||||
CREDENTIAL_KEY: ${CREDENTIAL_KEY:?set CREDENTIAL_KEY in tern.env}
|
||||
BLOB_STORAGE_DIR: /data/blobs
|
||||
SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-720}
|
||||
TRASH_RETENTION_DAYS: ${TRASH_RETENTION_DAYS:-30}
|
||||
OPEN_REGISTRATION: ${OPEN_REGISTRATION:-false}
|
||||
PUSH_URL_REWRITE: ${PUSH_URL_REWRITE:-}
|
||||
PUSH_TLS_INSECURE: ${PUSH_TLS_INSECURE:-false}
|
||||
PUSH_VAPID_SUBJECT: ${PUSH_VAPID_SUBJECT:-mailto:postmaster@mtps.pl}
|
||||
RUST_LOG: ${RUST_LOG:-tern_server=info}
|
||||
volumes:
|
||||
- blob-data:/data/blobs
|
||||
# The host's trust store, so IMAP/SMTP and push servers behind the
|
||||
# internal CA are trusted like public ones (same as the static role).
|
||||
- /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:/etc/ssl/certs/ca-certificates.crt:ro
|
||||
|
||||
# The webapp: static-server downloads this version's tern-web release.
|
||||
web:
|
||||
image: git.app.ygg/ygg/static-server:latest
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
GITEA_REPOSITORY_URL: https://git.app.ygg/mtps/tern-web
|
||||
GITEA_RELEASE: "v{{ version }}"
|
||||
GITEA_ASSET_NAME: "tern-web-{{ version }}.tgz"
|
||||
SSL_CERT_FILE: /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
|
||||
volumes:
|
||||
- /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:ro
|
||||
|
||||
# One origin for the webapp and its API, as the webapp requires: /api
|
||||
# (including the /api/ws socket) goes to the server, the rest to web.
|
||||
proxy:
|
||||
image: nginx:1.29-alpine
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- server
|
||||
- web
|
||||
ports:
|
||||
- "11901:80"
|
||||
configs:
|
||||
- source: proxy
|
||||
target: /etc/nginx/conf.d/default.conf
|
||||
|
||||
volumes:
|
||||
db-data: {}
|
||||
blob-data: {}
|
||||
|
||||
configs:
|
||||
proxy:
|
||||
content: |
|
||||
# Kara's nginx sits in front; trust its X-Forwarded-For so rate
|
||||
# limits apply per client rather than to kara as a whole.
|
||||
set_real_ip_from 10.0.0.0/8;
|
||||
set_real_ip_from 172.16.0.0/12;
|
||||
set_real_ip_from 192.168.0.0/16;
|
||||
set_real_ip_from 200::/7;
|
||||
real_ip_header X-Forwarded-For;
|
||||
real_ip_recursive on;
|
||||
|
||||
# Login and sign-up: slow enough to make guessing passwords
|
||||
# pointless, loose enough for a person retyping one.
|
||||
limit_req_zone $$binary_remote_addr zone=tern_auth:10m rate=10r/m;
|
||||
|
||||
map $$http_upgrade $$connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
|
||||
location /api/auth/ {
|
||||
limit_req zone=tern_auth burst=10 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_pass http://server:8080;
|
||||
proxy_set_header Host $$host;
|
||||
proxy_set_header X-Forwarded-For $$proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://server:8080;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $$host;
|
||||
proxy_set_header X-Forwarded-For $$proxy_add_x_forwarded_for;
|
||||
proxy_set_header Upgrade $$http_upgrade;
|
||||
proxy_set_header Connection $$connection_upgrade;
|
||||
# The server pings sockets every 25 s; this only ends dead ones.
|
||||
proxy_read_timeout 1h;
|
||||
}
|
||||
|
||||
location = /healthz {
|
||||
proxy_pass http://server:8080;
|
||||
access_log off;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://web:8080;
|
||||
proxy_set_header Host $$host;
|
||||
}
|
||||
}
|
||||
@@ -114,8 +114,8 @@ All three workflows target `runs-on: rocky-10` and follow the conventions alread
|
||||
|
||||
What still needs doing, in order of how likely it is to bite:
|
||||
|
||||
1. **`REGISTRY_TOKEN` secret on `tern-server`** — a token with `write:package` scope, for pushing the image. Unlike the release jobs, this one can't use the automatic `GITHUB_TOKEN`, whose scope doesn't reliably cover the package registry. (Worth trying `GITHUB_TOKEN` first on your instance; if it works, drop the extra secret.)
|
||||
2. **The container registry is enabled**, and `gitea.server_url` matches the registry host. The workflow derives the registry from that rather than hardcoding — verify on the first run that the pushed image lands where you expect.
|
||||
1. **`REGISTRY_TOKEN` secret on `tern-server`** — a token with `write:package` scope, for pushing the image. The automatic `GITHUB_TOKEN` can't push packages on this instance. The secret is passed to the shared [`ygg/actions/push-image`](https://git.app.ygg/ygg/actions/src/branch/main/push-image) action as an input, because actions can't read secrets themselves.
|
||||
2. **The container registry is enabled**, and `gitea.server_url` matches the registry host. `push-image` derives the registry from it rather than hardcoding one, and pushes `git.app.ygg/mtps/tern-server`.
|
||||
3. **Android signing secrets** — see §3 above: `ANDROID_KEYSTORE_B64`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD`.
|
||||
4. **`docker build` available to the job** — already proven on this runner.
|
||||
|
||||
|
||||
+19
-1
@@ -37,11 +37,28 @@ pub async fn register(
|
||||
|
||||
let password_hash = hash_password(&req.password)?;
|
||||
|
||||
// Unless sign-up is open, only the first user may register. The lock
|
||||
// makes "is this the first user?" and the insert one step, so two
|
||||
// registrations racing on a fresh server can't both be first.
|
||||
let mut tx = state.pool.begin().await?;
|
||||
sqlx::query("SELECT pg_advisory_xact_lock(hashtext('tern-register'))")
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
if !state.config.open_registration {
|
||||
let has_users: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM users)")
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if has_users {
|
||||
return Err(ApiError::Forbidden(
|
||||
"registration is closed on this server — ask its owner for an account".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let user: User =
|
||||
sqlx::query_as("INSERT INTO users (username, password_hash) VALUES ($1, $2) RETURNING *")
|
||||
.bind(&req.username)
|
||||
.bind(&password_hash)
|
||||
.fetch_one(&state.pool)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
sqlx::Error::Database(db_err) if db_err.is_unique_violation() => {
|
||||
@@ -49,6 +66,7 @@ pub async fn register(
|
||||
}
|
||||
other => ApiError::Sqlx(other),
|
||||
})?;
|
||||
tx.commit().await?;
|
||||
|
||||
create_session(&state, user.id).await.map(Json)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,10 @@ pub struct Config {
|
||||
pub session_ttl_hours: i64,
|
||||
/// Days mail stays in Trash before it's purged for good. 0 disables.
|
||||
pub trash_retention_days: u32,
|
||||
/// Whether anyone may create a user. When off, only the very first
|
||||
/// user can register — enough to set a server up, without leaving
|
||||
/// sign-up open on a public address.
|
||||
pub open_registration: bool,
|
||||
pub push: PushConfig,
|
||||
}
|
||||
|
||||
@@ -119,6 +123,10 @@ impl Config {
|
||||
blob_storage_dir,
|
||||
session_ttl_hours,
|
||||
trash_retention_days,
|
||||
open_registration: matches!(
|
||||
std::env::var("OPEN_REGISTRATION").as_deref(),
|
||||
Ok("1" | "true" | "yes")
|
||||
),
|
||||
push: PushConfig::from_env()?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ pub enum ApiError {
|
||||
Unauthorized,
|
||||
#[error("bad request: {0}")]
|
||||
BadRequest(String),
|
||||
#[error("{0}")]
|
||||
Forbidden(String),
|
||||
#[error(transparent)]
|
||||
Internal(#[from] anyhow::Error),
|
||||
#[error(transparent)]
|
||||
@@ -25,6 +27,7 @@ impl IntoResponse for ApiError {
|
||||
ApiError::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
|
||||
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, self.to_string()),
|
||||
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
|
||||
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, self.to_string()),
|
||||
ApiError::Sqlx(e) => {
|
||||
tracing::error!("db error: {e:#}");
|
||||
(
|
||||
|
||||
+24
@@ -7,6 +7,9 @@ use tern_server::{db, imap_sync};
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let _ = dotenvy::dotenv();
|
||||
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
|
||||
return healthcheck();
|
||||
}
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::from_default_env()
|
||||
@@ -70,3 +73,24 @@ async fn main() -> anyhow::Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `tern-server healthcheck`: exits 0 if the server on this host answers
|
||||
/// `/healthz`. For the image's HEALTHCHECK, which has no curl, so that
|
||||
/// `docker compose up --wait` waits until the server is really serving —
|
||||
/// and fails a deploy whose server can't start.
|
||||
fn healthcheck() -> anyhow::Result<()> {
|
||||
use std::io::{Read, Write};
|
||||
let bind = std::env::var("BIND_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".to_string());
|
||||
let port = bind.rsplit(':').next().unwrap_or("8080");
|
||||
let mut stream = std::net::TcpStream::connect(format!("127.0.0.1:{port}"))?;
|
||||
stream.set_read_timeout(Some(std::time::Duration::from_secs(3)))?;
|
||||
stream.write_all(b"GET /healthz HTTP/1.0\r\nHost: localhost\r\n\r\n")?;
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response)?;
|
||||
anyhow::ensure!(
|
||||
response.starts_with("HTTP/1.1 200") || response.starts_with("HTTP/1.0 200"),
|
||||
"unhealthy: {}",
|
||||
response.lines().next().unwrap_or("no response")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -42,6 +42,7 @@ fn test_router() -> axum::Router {
|
||||
blob_storage_dir: std::path::PathBuf::from("/tmp/tern-test"),
|
||||
session_ttl_hours: 1,
|
||||
trash_retention_days: 30,
|
||||
open_registration: false,
|
||||
push: Default::default(),
|
||||
},
|
||||
outbox_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
|
||||
|
||||
Reference in new issue
Block a user