Document codebase: comments, per-area READMEs, deployment guide
Readability pass across all four areas of the stack. Comments explain why rather than what, concentrated at the points where behaviour is non-obvious: concurrency, caching, auth, scraping and nginx templating. Backend: doc comments on every exported declaration across handlers, services, models and resolvers. Resolver commentary lives inside function bodies so gqlgen does not strip it on regeneration; schema files use # comments rather than description blocks so introspection output is unchanged. Extracted the duplicated auth-cookie blocks into helpers. Frontend: header comments on every component, store and view, including STATUS: notes marking which of the parallel/legacy views are still live. Documented the non-reactive animation-state pattern, the homeData hub and the WebSocket stale-socket guard. Removed a few dead imports and named the reconnect-backoff and poll-interval constants. Python: module and function docstrings covering the Travelodge scraping contract, the deadline threading, the two-executor concurrency and the NDJSON streaming protocol. Infra: header blocks on every compose file, nginx template, Dockerfile and entrypoint, covering the config selection, envsubst allow-lists, rate-limit semantics and volume persistence. Hoisted the duplicated envsubst variable list in nginx/entrypoint.sh. New: backend/README.md, python/README.md, DEPLOYMENT.md, .env.example, backend/graph/doc.go. Refreshed vue/README.md. Corrected CLAUDE.md, which stated a 24h access token where main.go sets 7 days. No behaviour change. go build/vet, vite build, py_compile and docker compose config all pass. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
+154
@@ -0,0 +1,154 @@
|
||||
# =============================================================================
|
||||
# .env.example — template for the real ./.env, which is GITIGNORED.
|
||||
#
|
||||
# HOW ENV REACHES THE CONTAINERS — two separate mechanisms, both reading this
|
||||
# same file, and it is worth knowing which is which:
|
||||
# 1. ${VAR} interpolation in docker-compose.yml. Done by the compose CLI when
|
||||
# it parses the file, before any container exists. This is how container
|
||||
# names, published ports and the Hasura database URL are built.
|
||||
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
|
||||
# variables inside that container. nginx, backend, db, icecast2, quartz,
|
||||
# certbot and gitea all do this.
|
||||
# The `python` service deliberately does neither wholesale — it uses an
|
||||
# explicit `environment:` allow-list of three variables, so it never sees the
|
||||
# database password or any API key.
|
||||
#
|
||||
# HOW TO USE
|
||||
# cp .env.example .env then fill in every value.
|
||||
# Distribute to the Raspberry Pi with ./sync-secrets.sh (newer file wins in
|
||||
# either direction — see that script's header before editing on both hosts).
|
||||
#
|
||||
# CAUTION: an unset variable does not fail loudly. envsubst renders it as an
|
||||
# empty string, which for a password field means "no password". After editing,
|
||||
# check `docker compose config` shows what you expect.
|
||||
#
|
||||
# NOTHING IN THIS FILE HAS A REAL VALUE. Values are blank or obviously
|
||||
# placeholder on purpose; never commit a filled-in copy.
|
||||
# =============================================================================
|
||||
|
||||
# --- Postgres ----------------------------------------------------------------
|
||||
# One instance, two databases: POSTGRES_DB for the Go backend, POSTGRES_GITEA_DB
|
||||
# for Gitea. Only POSTGRES_DB is auto-created on first init; the Gitea one must
|
||||
# be created by hand on a fresh volume.
|
||||
# POSTGRES_HOST doubles as the db container's name.
|
||||
POSTGRES_USER=
|
||||
POSTGRES_PASSWORD=
|
||||
POSTGRES_DB=
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_HOST=db
|
||||
|
||||
# --- Gitea -------------------------------------------------------------------
|
||||
# GITEA_HOST is the container name AND the nginx upstream host.
|
||||
# The three secrets below are passed as GITEA__section__KEY overrides so the
|
||||
# committed app.ini.template can keep those fields blank. Generate each as a
|
||||
# long random hex string.
|
||||
GITEA_HOST=gitea
|
||||
GITEA_PORT=3000
|
||||
GITEA_INTERNAL_TOKEN=
|
||||
GITEA_LFS_JWT_SECRET=
|
||||
GITEA_OAUTH2_JWT_SECRET=
|
||||
POSTGRES_GITEA_DB=gitea
|
||||
|
||||
# --- Gitea Actions runner ----------------------------------------------------
|
||||
# The runner is NOT a container; it runs on the Pi via gitea-runner/run.sh.
|
||||
# The registration token is SINGLE-USE: it is exchanged for a permanent
|
||||
# identity in gitea-runner/.runner on first registration, after which this
|
||||
# value is ignored. Mint it in Site Administration -> Actions -> Runners.
|
||||
GITEA_RUNNER_HOST=
|
||||
GITEA_RUNNER_NAME=pi-runner
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN=
|
||||
|
||||
# --- Email ingest (backend) --------------------------------------------------
|
||||
# IMAP_PASSWORD should be an app-specific password, not the account password.
|
||||
EMAIL_BACKEND=
|
||||
IMAP_HOST=
|
||||
IMAP_PORT=993
|
||||
IMAP_EMAIL=
|
||||
IMAP_PASSWORD=
|
||||
EMAIL_SYNC_INTERVAL=
|
||||
EMAIL_SYNC_ENABLED=
|
||||
|
||||
# --- Services that nginx substitutes but no longer runs -----------------------
|
||||
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
|
||||
# compose service uses them today. Harmless if blank.
|
||||
UPTIMEKUMA_HOST=
|
||||
UPTIMEKUMA_PORT=
|
||||
WALLABAG_HOST=
|
||||
WALLABAG_PORT=
|
||||
|
||||
# --- Quartz (notes site at /notes/) ------------------------------------------
|
||||
QUARTZ_HOST=quartz
|
||||
QUARTZ_PORT=8080
|
||||
|
||||
# --- Go backend --------------------------------------------------------------
|
||||
# BACKEND_HOST is the container name and the nginx upstream.
|
||||
# BACKEND_ENDPOINT is the public URL prefix nginx mounts the API at and then
|
||||
# strips; the Vue app's GraphQL client assumes /api.
|
||||
# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs
|
||||
# everyone out.
|
||||
BACKEND_PORT=8080
|
||||
BACKEND_HOST=backend
|
||||
BACKEND_SECRET=
|
||||
BACKEND_ENDPOINT=/api
|
||||
|
||||
# --- Obsidian vault ----------------------------------------------------------
|
||||
# HOST path, interpolated straight into two bind mounts: read-write into the
|
||||
# backend, read-only into quartz. Must be an absolute path that exists on the
|
||||
# host or the stack will not start.
|
||||
OBSIDIAN_DIR=
|
||||
|
||||
# --- Spotify -----------------------------------------------------------------
|
||||
# The redirect URI must match EXACTLY what is registered in the Spotify
|
||||
# developer dashboard. The dev override sets its own localhost value.
|
||||
# The resulting refresh token is persisted to ./backend/token/ so it survives
|
||||
# rebuilds.
|
||||
SPOTIFY_CLIENT_ID=
|
||||
SPOTIFY_CLIENT_SECRET=
|
||||
SPOTIFY_REDIRECT_URI=
|
||||
SPOTIFY_AUTH_STATE=
|
||||
|
||||
# --- Icecast / liquidsoap radio ----------------------------------------------
|
||||
# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast
|
||||
# with it, and a live-broadcasting client authenticates to the liquidsoap
|
||||
# harbor port with it. Anyone holding it can take over the stream.
|
||||
# LIQUIDSOAP_HARBOR_PORT is the only non-nginx port published to the host.
|
||||
ICECAST_SOURCE_PASSWORD=
|
||||
ICECAST_RELAY_PASSWORD=
|
||||
ICECAST_ADMIN_USER=
|
||||
ICECAST_ADMIN_PASSWORD=
|
||||
ICECAST_HOST=icecast2
|
||||
ICECAST_PORT=8000
|
||||
ICECAST_MOUNT=/stream
|
||||
LIQUIDSOAP_HARBOR_MOUNT=/live
|
||||
LIQUIDSOAP_HARBOR_PORT=8001
|
||||
|
||||
# --- TLS / identity ----------------------------------------------------------
|
||||
# DOMAIN is the APEX domain with no scheme and no www; certbot requests both
|
||||
# it and www.DOMAIN on one certificate, and nginx canonicalises to www.
|
||||
# EMAIL is the Let's Encrypt account address for expiry notices.
|
||||
DOMAIN=
|
||||
EMAIL=
|
||||
|
||||
# --- Third-party API keys (backend) ------------------------------------------
|
||||
CLAUDE_API_KEY=
|
||||
STEAM_API_KEY=
|
||||
STEAM_ID=
|
||||
|
||||
# --- Hasura (admin-only DB console at /hasura/) ------------------------------
|
||||
# Additionally gated by an nginx auth_request against the backend's admin check,
|
||||
# so the admin secret is not the only barrier.
|
||||
HASURA_GRAPHQL_ADMIN_SECRET=
|
||||
HASURA_HOST=hasura
|
||||
HASURA_PORT=8080
|
||||
|
||||
# --- Development-only switch -------------------------------------------------
|
||||
# Leave EMPTY/false in production. docker-compose.dev.yml sets SEED_DB=true for
|
||||
# local work; setting it on the Pi would inject test data into the live site.
|
||||
SEED_DB=
|
||||
|
||||
# --- Python FastAPI service (/py/) -------------------------------------------
|
||||
PYTHON_HOST=python
|
||||
PYTHON_PORT=8000
|
||||
|
||||
# TfL Unified API key (500 req/min); used by the Python hotel finder
|
||||
TFL_APP_KEY=
|
||||
@@ -75,7 +75,25 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
|
||||
## Key Patterns
|
||||
|
||||
- **GraphQL models vs GORM models**: `gqlgen.yml` maps GraphQL types directly to GORM models in `backend/models`. The `graph/model/` package has only generated input/payload types.
|
||||
- **Auth flow**: Login sets `access_token` (24h) and `refresh_token` (365h) as HTTP-only cookies. `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context.
|
||||
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. There is no token revocation — logout only clears cookies.
|
||||
- **GraphQL resolvers authorise themselves.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. Every resolver that needs auth must check it itself. See `backend/graph/doc.go`.
|
||||
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
|
||||
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
|
||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field).
|
||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field) — except `ProcessedEmail`, whose dedup must see history. Note that a `uniqueIndex` still collides with soft-deleted rows.
|
||||
|
||||
## Further documentation
|
||||
|
||||
Each area has its own README with the detail that doesn't belong here:
|
||||
|
||||
- `backend/README.md` — request lifecycle, auth model, GraphQL-vs-REST split and why each REST endpoint isn't GraphQL, service rundown, gotchas.
|
||||
- `vue/README.md` — app structure, routing, store/GraphQL data flow, the design-token styling system, and a live-vs-legacy map of the views.
|
||||
- `python/README.md` — endpoints, the NDJSON streaming contract, the hotel pricing method, and the scraper's fragility points.
|
||||
- `DEPLOYMENT.md` — service topology and ports, dev vs prod boot paths, TLS first-run and renewal, what persists, env vars, and an ops runbook.
|
||||
- `.env.example` — every environment variable the stack reads, documented, with blank values.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them.
|
||||
- **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating.
|
||||
- **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output.
|
||||
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead — e.g. `views/unused/CoverLetters.vue` is actually live on `/cv`.
|
||||
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
# Deployment
|
||||
|
||||
How this site is put together and how to operate it. Application code is
|
||||
documented in `CLAUDE.md` and `README.md`; this file covers infrastructure only
|
||||
— compose, nginx, TLS, the runner, and the runbook.
|
||||
|
||||
Everything runs on a single Raspberry Pi, as Docker containers on one bridge
|
||||
network, behind one nginx.
|
||||
|
||||
---
|
||||
|
||||
## 1. Service topology
|
||||
|
||||
Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on
|
||||
3000/2222, and the liquidsoap harbor port. Everything else is internal.
|
||||
|
||||
```
|
||||
internet
|
||||
|
|
||||
:80 :443| :3000 / :2222 :8001
|
||||
v v v
|
||||
+--------------+ +--------+ +-------------+
|
||||
| nginx | | gitea | | liquidsoap |
|
||||
| (TLS, SPA, | | (git + | | harbor |
|
||||
| reverse | | CI) | | (live DJ) |
|
||||
| proxy) | +--------+ +------+------+
|
||||
+------+-------+ | |
|
||||
| | |
|
||||
--------------------------------------------- | (same container
|
||||
| | | | | | | as icecast2)
|
||||
v v v v v v | |
|
||||
/api/ /radio/ /gitea/ /hasura/ /notes/ /py/ | |
|
||||
backend icecast2 gitea hasura quartz python | |
|
||||
| ^ | | |
|
||||
| | | | |
|
||||
| +------------------|--------------------|---------------+
|
||||
| | |
|
||||
+----------+-----------------+--------------------+
|
||||
v
|
||||
+------+
|
||||
| db | postgres:16
|
||||
+------+ (app database + gitea database)
|
||||
|
||||
vue one-shot build container -> writes vue_dist volume -> nginx serves it
|
||||
certbot no ports; shares ./certbot/conf and ./certbot/www with nginx
|
||||
autoheal no network; watches the docker socket and restarts unhealthy containers
|
||||
```
|
||||
|
||||
### Who listens where
|
||||
|
||||
| Service | Container name | Internal port | Public route | Published to host |
|
||||
|---|---|---|---|---|
|
||||
| nginx | `nginx` | 80, 443 | — | **80, 443** |
|
||||
| backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no |
|
||||
| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no |
|
||||
| hasura | `${HASURA_HOST}` | `${HASURA_PORT}` | `/hasura/` (admin-gated) | no |
|
||||
| quartz (notes) | `${QUARTZ_HOST}` | `${QUARTZ_PORT}` | `/notes/` (admin-gated) | no |
|
||||
| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no |
|
||||
| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** |
|
||||
| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** |
|
||||
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
|
||||
| certbot | `certbot` | — | — | no |
|
||||
| autoheal | `autoheal` | — | — | no |
|
||||
|
||||
Container names come from `.env`, and nginx builds its upstreams from the same
|
||||
variables. **Renaming a `*_HOST` value renames the container and repoints nginx
|
||||
in one step — never change one without the other.**
|
||||
|
||||
### Things nginx does that are easy to miss
|
||||
|
||||
- **Canonical host.** `http://` → `https://`, and apex → `www`. The SPA, the
|
||||
cookies and the CORS rules all assume `www.<DOMAIN>`.
|
||||
- **Prefix stripping.** `/api`, `/radio`, `/gitea`, `/notes`, `/py` are stripped
|
||||
by a `rewrite ... break` before proxying; each upstream serves from `/`.
|
||||
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
|
||||
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
|
||||
backend down (502s until it appears) instead of refusing to start.
|
||||
- **Admin gate.** `/hasura/` and `/notes/` are protected by an `auth_request`
|
||||
subrequest to the backend's `/auth/validate-admin`; a failure redirects to the
|
||||
SPA login. Neither service has any auth of its own at that path.
|
||||
- **Uploads served directly.** `/uploads/` is an alias onto the shared `uploads`
|
||||
volume with `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so
|
||||
user-supplied files cannot execute anything on our origin.
|
||||
- **Rate limits** — see §6.
|
||||
|
||||
---
|
||||
|
||||
## 2. Dev vs prod boot paths
|
||||
|
||||
### Production
|
||||
|
||||
```
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected).
|
||||
2. `nginx` starts, runs `nginx/entrypoint.sh`, which:
|
||||
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
|
||||
- renders `nginx.conf.template` if the cert is there, else
|
||||
`nginx_setup.conf.template`;
|
||||
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
|
||||
nginx either way.
|
||||
3. `certbot` obtains or confirms the certificate, then loops renewing.
|
||||
4. Everything else comes up in parallel; `depends_on` here is the plain list
|
||||
form, which waits only for *start*, not readiness.
|
||||
|
||||
On the Pi this is triggered automatically: `.gitea/workflows/deploy.yaml` runs on
|
||||
every push to `main`, fetches over `ssh://git@localhost:2222`, hard-resets the
|
||||
deploy checkout, and runs `docker compose up -d --build --remove-orphans`.
|
||||
|
||||
### Development
|
||||
|
||||
```
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||
```
|
||||
|
||||
The override layer changes five services and disables one:
|
||||
|
||||
- **vue** — `npm run dev` instead of a one-shot build; `./vue` is bind-mounted
|
||||
for hot reload, with anonymous-volume masks on `/app/node_modules` and
|
||||
`/app/src/wasm` so the image's installed deps and compiled WASM are not hidden
|
||||
by the bind mount. You need neither `node_modules` nor a Rust toolchain on the
|
||||
host.
|
||||
- **nginx** — `DEV_MODE=true`, which makes the entrypoint self-sign a
|
||||
`CN=localhost` certificate (once, kept in `certbot/conf`) and render
|
||||
`nginx_dev.conf.template`: `/` proxies to the Vite dev server, both `:80` and
|
||||
`:443` serve the whole site, no HSTS, no HTTP→HTTPS redirect.
|
||||
- **backend** — `DEV_MODE`, GraphQL playground and introspection on, a localhost
|
||||
Spotify redirect URI, and **`SEED_DB=true`**.
|
||||
- **hasura** — console and dev mode on.
|
||||
- **python** — `uvicorn --reload` with `python/app` bind-mounted.
|
||||
- **certbot** — put in the `disabled` profile, so it never starts. Let's Encrypt
|
||||
cannot validate localhost anyway.
|
||||
|
||||
Visit `http://localhost`.
|
||||
|
||||
**`SEED_DB`** makes the Go backend populate the database with test posts, users
|
||||
and messages at startup. It is set only in the dev override and must never be
|
||||
set on the Pi — it would inject fake content into the live site.
|
||||
|
||||
Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
|
||||
`/api`, `/gitea` and `/radio` to locally running services.
|
||||
|
||||
---
|
||||
|
||||
## 3. TLS: first issuance and renewal
|
||||
|
||||
### The chicken-and-egg
|
||||
|
||||
The production nginx config references
|
||||
`/etc/letsencrypt/live/$DOMAIN/fullchain.pem`, and nginx refuses to start if that
|
||||
file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port
|
||||
80. On a brand-new host neither can go first.
|
||||
|
||||
`nginx_setup.conf.template` breaks the loop: port 80 only, no TLS directives, no
|
||||
upstreams, nothing that can fail to load. It serves
|
||||
`/.well-known/acme-challenge/` from `/var/www/certbot` and 404s everything else,
|
||||
so a half-configured site is never partially exposed.
|
||||
|
||||
**First run on a new domain:**
|
||||
|
||||
1. `docker compose up -d`. nginx logs `Certificates NOT found. Using setup nginx
|
||||
config.`
|
||||
2. certbot runs `certbot certonly --webroot` and writes the certificate into
|
||||
`./certbot/conf` (bind-mounted into both containers — that sharing is what
|
||||
makes the whole thing work).
|
||||
3. **`docker compose restart nginx`.** This step is manual. Nothing watches the
|
||||
cert directory. On restart the entrypoint re-checks, finds the cert, and
|
||||
renders the production config.
|
||||
|
||||
### Renewal
|
||||
|
||||
`certbot/entrypoint.sh` loops `certbot renew` every 12 hours. Renewal is a no-op
|
||||
until the cert is inside its 30-day window, so this is well within Let's Encrypt
|
||||
rate limits — it just means the window is checked twice a day. Certs are valid 90
|
||||
days, so renewal lands around day 60.
|
||||
|
||||
**Caveat worth knowing:** there is no `--deploy-hook`, and the certbot container
|
||||
cannot signal nginx (no docker socket, no shared PID namespace). nginx reads the
|
||||
certificate at startup and holds it in memory, so **a renewed certificate is not
|
||||
served until nginx is reloaded or restarted.** In practice pushes to `main`
|
||||
recreate nginx often enough to hide this. If the site ever serves an expired
|
||||
cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
|
||||
|
||||
---
|
||||
|
||||
## 4. What persists across restarts
|
||||
|
||||
**Named volumes** — survive `docker compose down` and rebuilds; destroyed only by
|
||||
`docker compose down -v` or `docker volume rm`:
|
||||
|
||||
| Volume | Holds | Losing it means |
|
||||
|---|---|---|
|
||||
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata |
|
||||
| `uploads` | User-uploaded files (backend writes, nginx serves) | All uploaded images |
|
||||
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
|
||||
|
||||
**Bind mounts** — live in the repo checkout on the Pi, survive everything short
|
||||
of deleting the directory:
|
||||
|
||||
| Path | Holds | Notes |
|
||||
|---|---|---|
|
||||
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
|
||||
| `./certbot/www` | ACME challenge webroot | Transient by nature |
|
||||
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. |
|
||||
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
|
||||
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
|
||||
| `./logs` | Backend logs | |
|
||||
| `./icecast2/fallback_music` | Radio fallback MP3s | Synced by `sync-secrets.sh`, not git |
|
||||
| `${OBSIDIAN_DIR}` | The Obsidian vault | Read-write to backend, **read-only** to quartz |
|
||||
|
||||
**Ephemeral:** anything else inside a container. Notably the Vue build, the
|
||||
rendered nginx/icecast/quartz configs, and the Gitea runner's downloaded binary
|
||||
are all regenerated.
|
||||
|
||||
---
|
||||
|
||||
## 5. Environment variables
|
||||
|
||||
All configuration lives in **`./.env`** at the repo root, which is gitignored.
|
||||
`.env.example` documents every variable with blank values — start from that.
|
||||
|
||||
Two distinct mechanisms read it, and services use both:
|
||||
|
||||
- **`${VAR}` in `docker-compose.yml`** — substituted by the compose CLI at parse
|
||||
time. Builds container names, published ports, the Hasura database URL.
|
||||
- **`env_file: ./.env`** — injects the whole file into the container. Used by
|
||||
nginx, backend, db, icecast2, quartz, certbot.
|
||||
|
||||
`gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own
|
||||
convention for overriding `app.ini` keys), and `python` receives an explicit
|
||||
three-variable allow-list, so it never sees the database password or any API key.
|
||||
|
||||
**`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two
|
||||
things between this checkout and `adamf@stppi.local:~/deploy/web_server`:
|
||||
`.env`, and `icecast2/fallback_music/*.mp3`. The sync is **bidirectional and
|
||||
resolved by modification time — newer wins, with no merge.** Editing `.env` on
|
||||
both machines silently loses one side's edits. Run it before and after editing.
|
||||
|
||||
An unset variable is not an error: `envsubst` renders it as an empty string,
|
||||
which for a password field means *no password*. After editing `.env`, confirm
|
||||
with `docker compose config`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Rate limits
|
||||
|
||||
Defined once per config in the `http` block, applied per location. Keyed on
|
||||
`$binary_remote_addr` — the client IP in packed form, so each entry is ~64 bytes
|
||||
and a `10m` zone holds roughly 160k IPs. `10m` is a safe round number, not a
|
||||
tuned value.
|
||||
|
||||
`rate` is a **smoothed leaky bucket**, not a per-window counter: `5r/m` means one
|
||||
request every 12 seconds, not five at once. `burst=N` lets N requests queue ahead
|
||||
of that drip, and `nodelay` (used everywhere here) serves those N immediately.
|
||||
So the effective behaviour is *"N instant requests, then throttled to the drip
|
||||
rate"*. Anything beyond the burst gets an immediate **503**.
|
||||
|
||||
| Zone | Rate | Burst | Applied to | Why |
|
||||
|---|---|---|---|---|
|
||||
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
|
||||
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
|
||||
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
|
||||
| `upload` | 5/min | 3 | `/api/messages/upload` | Uploads can be 50MB and hit disk; bounds how fast one IP fills the volume. |
|
||||
| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
|
||||
|
||||
The WebSocket endpoint is deliberately unlimited: a socket is one long-lived
|
||||
request, and a limit there would drop reconnect storms rather than abuse.
|
||||
|
||||
These zones key on the direct client IP, which is correct because nginx is the
|
||||
sole edge. **If a CDN or proxy is ever put in front, they must switch to a
|
||||
trusted `X-Forwarded-For` or every visitor shares one bucket.**
|
||||
|
||||
---
|
||||
|
||||
## 7. Runbook
|
||||
|
||||
All commands run from the deploy checkout on the Pi
|
||||
(`~/deploy/web_server`) unless stated.
|
||||
|
||||
**Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does
|
||||
it. By hand:
|
||||
|
||||
```
|
||||
git pull && docker compose up -d --build --remove-orphans
|
||||
```
|
||||
|
||||
**Rebuild one service** (e.g. after changing only the backend):
|
||||
|
||||
```
|
||||
docker compose up -d --build backend
|
||||
```
|
||||
|
||||
Note: editing `certbot/entrypoint.sh` needs no rebuild (it is bind-mounted over
|
||||
the stock image's entrypoint) — just `docker compose restart certbot`. Editing
|
||||
an nginx **template** does need a rebuild, since templates are `COPY`'d into the
|
||||
image.
|
||||
|
||||
**Apply a new nginx config / pick up a renewed certificate:**
|
||||
|
||||
```
|
||||
docker compose up -d --build nginx # template changed
|
||||
docker compose restart nginx # certificate changed
|
||||
```
|
||||
|
||||
**Renew certificates manually** (then restart nginx so it is actually served):
|
||||
|
||||
```
|
||||
docker compose exec certbot certbot renew --webroot -w /var/www/certbot
|
||||
docker compose restart nginx
|
||||
```
|
||||
|
||||
Add `--dry-run` to test without burning rate limit.
|
||||
|
||||
**Check logs:**
|
||||
|
||||
```
|
||||
docker compose logs -f nginx # follow one service
|
||||
docker compose logs --tail=200 backend
|
||||
docker compose ps # note: `vue` Exited(0) is correct
|
||||
docker compose logs certbot # issuance / renewal outcomes
|
||||
```
|
||||
|
||||
**Reset the database** — destructive; wipes the app database **and Gitea's**:
|
||||
|
||||
```
|
||||
docker compose down
|
||||
docker volume rm web_server_dbdata # confirm the name with `docker volume ls`
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The app schema is recreated by GORM auto-migration on backend start (there are no
|
||||
migration files). **Gitea's database is not auto-created** — the Postgres image
|
||||
only creates `POSTGRES_DB` on first init, so create `${POSTGRES_GITEA_DB}`
|
||||
manually before Gitea will start:
|
||||
|
||||
```
|
||||
docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB"
|
||||
```
|
||||
|
||||
**Sync secrets / fallback music** (from the laptop checkout, not the Pi):
|
||||
|
||||
```
|
||||
./sync-secrets.sh
|
||||
```
|
||||
|
||||
**Set up the CI runner on a fresh Pi:**
|
||||
|
||||
```
|
||||
cd gitea-runner
|
||||
bash download.sh # pulls the arm64 binary
|
||||
# mint a registration token: Gitea -> Site Administration -> Actions -> Runners
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN=... ./run.sh # registers once, then daemonises
|
||||
```
|
||||
|
||||
The runner lives **outside** Docker on purpose: it runs `docker compose up`
|
||||
against this stack, so it cannot be a container in it. Registration is one-shot —
|
||||
`.runner` is the lasting credential; re-registering needs that file deleted *and*
|
||||
a fresh token.
|
||||
|
||||
**Go live on the radio:** point a broadcasting client (e.g. butt) at the Pi on
|
||||
`${LIQUIDSOAP_HARBOR_PORT}` with mount `${LIQUIDSOAP_HARBOR_MOUNT}` and the
|
||||
icecast source password. liquidsoap pre-empts the fallback playlist immediately
|
||||
(`track_sensitive=false`). Disconnect and it falls back to the playlist, then to
|
||||
silence. Adding MP3s to `icecast2/fallback_music/` is picked up live
|
||||
(`reload_mode="watch"`) with no restart.
|
||||
|
||||
**Unhealthy containers** are restarted automatically by `autoheal`, which polls
|
||||
the docker socket every 30s. Only `backend` and `python` define healthchecks, so
|
||||
only they are covered.
|
||||
|
||||
---
|
||||
|
||||
## 8. Known rough edges
|
||||
|
||||
Documented, not fixed — each would change deploy behaviour.
|
||||
|
||||
1. **Renewed certificates are not served until nginx restarts.** No
|
||||
`--deploy-hook` in `certbot/entrypoint.sh`. Fix: add
|
||||
`--deploy-hook "touch /var/www/certbot/.reloadme"` plus a watcher, or give
|
||||
certbot the docker socket to send nginx a `HUP`.
|
||||
2. **First TLS issuance needs a manual `docker compose restart nginx`.** The
|
||||
entrypoint only re-evaluates cert presence at container start.
|
||||
3. **`gitea/config/entrypoint.sh` is an empty, unused file** that would be
|
||||
mounted to the same in-container path as the real wrapper. It is currently
|
||||
shadowed by an explicit file mount — fragile. Deleting it would be safe but
|
||||
is a file removal.
|
||||
4. **The dev nginx template duplicates its `:80` and `:443` server blocks**
|
||||
almost verbatim (~190 lines), so a routing fix must be made twice.
|
||||
5. **`nginx.conf.template` has a `/img/stamps/mine.gif` CORS header allowing
|
||||
only our own origin**, which defeats the point of having the header at all.
|
||||
6. **`certbot/entrypoint.sh` uses unquoted `${EMAIL}` and `${DOMAIN}`.** Inert
|
||||
today (neither contains whitespace) but a latent quoting bug.
|
||||
7. **`UPTIMEKUMA_*` and `WALLABAG_*` are substituted by nginx but no compose
|
||||
service provides them** — leftovers from removed services.
|
||||
8. **`autoheal` mounts the docker socket**, which is effectively root on the
|
||||
host, and uses the `:latest` tag.
|
||||
@@ -1,3 +1,32 @@
|
||||
# =============================================================================
|
||||
# Go backend image — multi-stage: build with the full toolchain, ship a slim
|
||||
# runtime containing one static binary.
|
||||
#
|
||||
# STAGE 1 (golang:1.26)
|
||||
# go.mod/go.sum are copied and downloaded BEFORE the rest of the source, so
|
||||
# the dependency layer is cached and only re-runs when the module files
|
||||
# change — a meaningful saving when building on a Raspberry Pi.
|
||||
#
|
||||
# The `--mount=type=cache` lines are BuildKit cache mounts: the module cache
|
||||
# and the Go build cache persist BETWEEN builds on the host without being
|
||||
# baked into any image layer. This is the single biggest reason a rebuild on
|
||||
# the Pi takes minutes rather than much longer. They require BuildKit, which
|
||||
# is the default in modern `docker compose build`.
|
||||
#
|
||||
# CGO_ENABLED=0 produces a fully static binary with no libc dependency, which
|
||||
# is what lets a golang-built binary run on a different, slimmer base image.
|
||||
#
|
||||
# STAGE 2 (debian:bookworm-slim)
|
||||
# Carries only the binary plus ca-certificates — needed because the backend
|
||||
# makes outbound HTTPS calls (Spotify, Claude, Steam, the Gitea feed) and
|
||||
# would fail certificate verification without a trust store.
|
||||
#
|
||||
# EXPOSE 8080 is documentation only; the port is never published to the host.
|
||||
# nginx reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
|
||||
#
|
||||
# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and
|
||||
# amd64 (a dev laptop) with no platform pin.
|
||||
# =============================================================================
|
||||
FROM golang:1.26 AS builder
|
||||
|
||||
WORKDIR /backend
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# Backend
|
||||
|
||||
The Go API for adam-french.co.uk. It is one process behind nginx, serving a
|
||||
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
|
||||
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea, Anthropic).
|
||||
|
||||
Nginx strips the `/api` prefix before proxying, so a browser request to
|
||||
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
|
||||
sees it.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
main.go wiring: env -> services -> Store -> routes
|
||||
models/models.go GORM entities, which are ALSO the GraphQL object types
|
||||
handlers/ REST endpoints + the shared Store dependency container
|
||||
store.go Store: DB, service handles, and the third-party caches
|
||||
handle_*.go one file per domain
|
||||
services/ stateful collaborators (DB, auth, chat hub, API clients)
|
||||
graph/ GraphQL layer
|
||||
schema/*.graphql source of truth for the schema
|
||||
*.resolvers.go resolver implementations, one per schema file
|
||||
*_helpers.go hand-written mapping helpers (never regenerated)
|
||||
context.go reading identity out of the resolver context
|
||||
middleware.go putting it in
|
||||
doc.go package overview — read this before touching resolvers
|
||||
generated.go GENERATED, do not edit
|
||||
model/models_gen.go GENERATED, do not edit
|
||||
```
|
||||
|
||||
## Request lifecycle
|
||||
|
||||
1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and
|
||||
proxies to this service.
|
||||
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
|
||||
that `ClientIP()` — which the login rate limiter keys on — cannot be
|
||||
spoofed via `X-Forwarded-For`.
|
||||
3. **REST**: the route's middleware chain runs. `AuthMiddlewear` requires a
|
||||
valid access token and stashes the claims in the Gin context;
|
||||
`AdminMiddleware` then requires `admin: true` in those claims. A handler
|
||||
reached through the `admin` group can assume both.
|
||||
4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only
|
||||
*annotates* the request context with the Gin context and, if a valid access
|
||||
token is present, the JWT claims — and then lets everything through. Each
|
||||
resolver authorises itself with `IsAdminFromCtx` / `UserIDFromCtx`.
|
||||
**A resolver that forgets to check is public.**
|
||||
5. Handlers and resolvers both reach the database and the caches through the
|
||||
single `handlers.Store` built in `main`.
|
||||
|
||||
## Auth
|
||||
|
||||
- `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets
|
||||
two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`:
|
||||
- `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary
|
||||
requests authorise without a database hit;
|
||||
- `refresh_token` (365 days) carries only `id`.
|
||||
- `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh
|
||||
token for a new pair, re-reading the user — and therefore the admin flag —
|
||||
from the database.
|
||||
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
|
||||
and will transparently refresh, so returning admins are recognised without a
|
||||
visible re-login.
|
||||
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
|
||||
is revoked server-side, and a token that has already been issued stays valid
|
||||
until it expires. The same is true of demoting an admin: it takes effect on
|
||||
their next refresh, not immediately.
|
||||
|
||||
The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
|
||||
`graph/auth.resolvers.go`) are parallel by design, since the front end uses
|
||||
both. They share `services.Auth` and the rate limiter, but each has its own
|
||||
cookie-writing helper — change one and you must change the other.
|
||||
|
||||
## GraphQL vs REST
|
||||
|
||||
GraphQL is the default and covers essentially all the site's data. REST exists
|
||||
for the things GraphQL cannot do:
|
||||
|
||||
| REST endpoint | why it is not GraphQL |
|
||||
| --- | --- |
|
||||
| `/auth/*` | cookie handling and the status-code-only admin probe |
|
||||
| `/spotify/callback`, `/email/callback` | OAuth providers redirect a *browser* here |
|
||||
| `/messages/upload`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
|
||||
| `/notes/*path` | streams a file download, not JSON |
|
||||
| `/ws` | WebSocket upgrade |
|
||||
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
||||
|
||||
## Services
|
||||
|
||||
Everything is constructed in `main` from environment variables and handed to
|
||||
`handlers.Store`. Nothing here fails start-up: a missing Spotify token, an
|
||||
unconfigured mailbox or an absent Steam key all just leave that feature
|
||||
dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
|
||||
- **database.go** — Postgres via GORM. There are no migration files:
|
||||
`AutoMigrate` is the whole schema story, so it adds tables/columns but never
|
||||
drops or renames, and a new model must be listed there to get a table.
|
||||
- **auth.go** — HS256 JWT minting and verification.
|
||||
- **ratelimit.go** — in-memory per-IP sliding window (5 logins/minute).
|
||||
Process-local and never evicts keys.
|
||||
- **websocket.go** — the chat hub. A package-level singleton: one connection
|
||||
set, one mutex, one DB handle. Public, with admin connections additionally
|
||||
able to see/send private messages and delete.
|
||||
- **spotify.go**, **steam.go**, **gitea.go** — third-party reads. Results are
|
||||
cached on `Store` with TTLs of 1 min (Spotify recent, Gitea) and 5 min
|
||||
(Steam).
|
||||
- **email_sync.go** / **email_imap.go** — the job-application pipeline: fetch
|
||||
recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter
|
||||
it, ask Claude to extract structured data, create or advance a
|
||||
`JobApplication`. Runs on a timer and can be triggered by an admin.
|
||||
- **claude.go** — the shared Anthropic client, used by the email pipeline and
|
||||
by the rowing photo reader.
|
||||
- **notes.go** — path-traversal-safe file lookup for the notes directory.
|
||||
- **seed.go** — dev-only test data. Creates an admin with the password
|
||||
`password`, so it must never run in production (`SEED_DB=true` is set only
|
||||
in `docker-compose.dev.yml`).
|
||||
|
||||
## Regenerating gqlgen
|
||||
|
||||
The `.graphql` files are the source of truth.
|
||||
|
||||
```
|
||||
cd backend && go run github.com/99designs/gqlgen generate
|
||||
```
|
||||
|
||||
This rewrites `graph/generated.go` and `graph/model/models_gen.go` and adds
|
||||
stubs for new fields to the matching `*.resolvers.go`. Existing resolver bodies
|
||||
are preserved, but hand-written code in a regenerated file can be relocated to
|
||||
the end of it — which is why shared helpers live in `*_helpers.go` instead.
|
||||
|
||||
`gqlgen.yml` maps most GraphQL object types directly onto the GORM structs in
|
||||
`models/`, so `graph/model/` holds only input and payload types. Adding a type
|
||||
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
|
||||
generated struct rather than the model you expected.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Soft delete everywhere.** Every model except `ProcessedEmail` has a
|
||||
`gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
|
||||
row out. Rows are never actually removed, and a `uniqueIndex` still collides
|
||||
with deleted rows — a soft-deleted username cannot be reused.
|
||||
- **`Preload` is not lazy.** `Post.Author` is nil unless the query preloads it;
|
||||
there is no error to tell you why the field came back null.
|
||||
- **IDs.** Models use `uint`, GraphQL uses `Int`. That is why nearly every type
|
||||
has a hand-written `ID` resolver doing `int(obj.ID)`.
|
||||
- **`Message.AuthorID` is not a user id.** It is a per-process counter handed
|
||||
out by the chat hub on connect, meaningless across restarts.
|
||||
- **The chat table is capped.** Every insert soft-deletes all but the newest
|
||||
50 messages.
|
||||
- **Store's caches are unsynchronised** and shared by all requests. The races
|
||||
are benign (at worst a duplicate upstream fetch), but do not add a field
|
||||
there that would be unsafe to tear.
|
||||
- **Claude output is parsed as JSON** after stripping a possible markdown code
|
||||
fence, in both `handle_rowing.go` and `email_sync.go`.
|
||||
- **The email pipeline never retries.** A failed email is recorded with action
|
||||
`"error"` so the next sync skips it.
|
||||
- **Authenticating email after start-up does not start the scheduler**, which
|
||||
only checks readiness once — restart, or trigger syncs by hand.
|
||||
- **Introspection and the playground are off** unless `DEV_MODE=true` *and*
|
||||
`GQL_INTROSPECTION` / `GQL_PLAYGROUND` are set.
|
||||
- **No graceful shutdown.** `r.Run` blocks forever and its error is ignored;
|
||||
the container is simply killed.
|
||||
|
||||
## Environment
|
||||
|
||||
| var | purpose |
|
||||
| --- | --- |
|
||||
| `POSTGRES_USER` / `_PASSWORD` / `_DB` / `_HOST` / `_PORT` | database connection |
|
||||
| `BACKEND_PORT` | listen port |
|
||||
| `BACKEND_SECRET` | JWT signing secret |
|
||||
| `BACKEND_ENDPOINT` | this service's public base URL |
|
||||
| `DOMAIN` | auth cookie domain and WebSocket origin allow-list |
|
||||
| `DEV_MODE` | release vs debug Gin; gates the two GraphQL dev flags |
|
||||
| `SEED_DB` | seed dev test data (never in production) |
|
||||
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
|
||||
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
|
||||
| `CLAUDE_API_KEY` | Anthropic API |
|
||||
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
|
||||
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
|
||||
| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) |
|
||||
| `MSGRAPH_CLIENT_ID` / `_SECRET` / `_TENANT_ID` / `_REDIRECT_URI` | Microsoft Graph backend |
|
||||
| `IMAP_HOST` / `_PORT` / `_EMAIL` / `_PASSWORD` | IMAP backend |
|
||||
|
||||
Paths baked into the code, all inside mounted volumes so they survive a
|
||||
container restart: `/backend/logs`, `/backend/notes`, `/backend/uploads`,
|
||||
`/backend/fallback_music`, `/backend/token/` (Spotify and Microsoft Graph
|
||||
OAuth tokens).
|
||||
@@ -20,6 +20,7 @@ func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, e
|
||||
|
||||
// CreateActivity is the resolver for the createActivity field.
|
||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||
// No middleware guards GraphQL, so each mutation checks for itself.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
@@ -38,6 +39,9 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &activities[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Activity, len(activities))
|
||||
for i := range activities {
|
||||
result[i] = &activities[i]
|
||||
|
||||
@@ -17,6 +17,12 @@ import (
|
||||
|
||||
// Login is the resolver for the login field.
|
||||
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
|
||||
// The Gin context is needed for two things GraphQL cannot express: the
|
||||
// client IP for rate limiting, and setting response cookies. It is
|
||||
// smuggled in by AuthContextMiddleware.
|
||||
//
|
||||
// This mutation mirrors handlers.Store.Login; the two share the limiter
|
||||
// and services.Auth, so the same 5/min budget covers both entry points.
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return nil, fmt.Errorf("could not get gin context")
|
||||
@@ -26,6 +32,8 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
|
||||
return nil, fmt.Errorf("too many login attempts, please try again later")
|
||||
}
|
||||
|
||||
// Identical message for unknown user and wrong password, so the API
|
||||
// cannot be used to enumerate usernames.
|
||||
var user models.User
|
||||
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
@@ -40,24 +48,10 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
setAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
|
||||
// The payload carries no token: the tokens only ever travel as HttpOnly
|
||||
// cookies, so client JavaScript never sees them.
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
|
||||
@@ -68,6 +62,9 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
|
||||
return false, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
// Max-age -1 tells the browser to drop the cookies. Nothing is
|
||||
// invalidated server-side, so a token captured beforehand still works
|
||||
// until it expires.
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie("access_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
gc.SetCookie("refresh_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
@@ -97,6 +94,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
// Setting the primary key and calling First with no condition makes GORM
|
||||
// look the row up by that key. Admin status is re-read from the database
|
||||
// here, which is what lets a revoked admin flag take effect on refresh.
|
||||
var user models.User
|
||||
user.ID = uint(userIDF)
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
@@ -108,23 +108,7 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
setAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
@@ -136,6 +120,8 @@ func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
// Read fresh from the database rather than returned from the token
|
||||
// claims, so `me` reflects the current username and admin flag.
|
||||
var user models.User
|
||||
user.ID = userID
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// setAuthCookies writes the access/refresh cookie pair on a GraphQL response.
|
||||
//
|
||||
// This mirrors handlers.Store.setAuthCookies — the two cannot be shared
|
||||
// because importing graph from handlers would be a cycle, so any change to
|
||||
// cookie attributes has to be made in both places or login via REST and login
|
||||
// via GraphQL will disagree.
|
||||
//
|
||||
// gin's SetCookie takes Secure and HttpOnly as its two trailing booleans, both
|
||||
// true here: the cookies never travel over plain HTTP and are invisible to
|
||||
// JavaScript. SameSite=Lax survives a top-level navigation back from an OAuth
|
||||
// provider while still blocking cross-site POSTs. Each max-age mirrors the
|
||||
// lifetime baked into the token itself.
|
||||
//
|
||||
// It lives in its own file rather than in auth.resolvers.go because gqlgen may
|
||||
// relocate hand-written code in the files it regenerates.
|
||||
func setAuthCookies(gc *gin.Context, config *services.AuthConfig, tokens *services.Tokens) {
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
config.Domain,
|
||||
true, true,
|
||||
)
|
||||
}
|
||||
@@ -35,6 +35,9 @@ func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Loaded first so the deleted record can be returned to the client, and
|
||||
// so a missing id is a clean "not found" rather than a silent no-op.
|
||||
// Delete is a soft delete: deleted_at is set and the row stays.
|
||||
var bookmark models.Bookmark
|
||||
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -51,6 +54,9 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
||||
if err := r.Store.DB.Order("category ASC, created_at ASC").Find(&bookmarks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &bookmarks[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Bookmark, len(bookmarks))
|
||||
for i := range bookmarks {
|
||||
result[i] = &bookmarks[i]
|
||||
|
||||
@@ -7,6 +7,17 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// This file is the bridge between Gin's request handling and gqlgen's
|
||||
// resolvers. gqlgen resolvers receive only a context.Context, so
|
||||
// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and
|
||||
// the *gin.Context itself into that context, and these accessors read them
|
||||
// back out.
|
||||
|
||||
// contextKey is a private named type so that these keys can never collide
|
||||
// with a key set by another package — the reason the standard library warns
|
||||
// against using bare strings as context keys. Note the string value
|
||||
// "userClaims" happens to match the key handlers.AuthMiddlewear uses in the
|
||||
// *Gin* context, but the two are unrelated and do not see each other.
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
@@ -14,6 +25,9 @@ const (
|
||||
ginContextKey contextKey = "ginContext"
|
||||
)
|
||||
|
||||
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
|
||||
// is anonymous. nil means "not authenticated": a missing or invalid token is
|
||||
// not an error here, because many queries are public.
|
||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||
if !ok {
|
||||
@@ -22,6 +36,8 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
return claims
|
||||
}
|
||||
|
||||
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
|
||||
// float64 because claims are decoded by encoding/json, hence the conversion.
|
||||
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -34,6 +50,11 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
return uint(idF), true
|
||||
}
|
||||
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. This is
|
||||
// the authorisation check for nearly every mutation — there is no middleware
|
||||
// in front of the GraphQL endpoint, so a resolver that forgets to call this
|
||||
// is public. Admin comes from the token, not the database, so a revoked admin
|
||||
// flag only bites once the access token expires.
|
||||
func IsAdminFromCtx(ctx context.Context) bool {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -43,6 +64,10 @@ func IsAdminFromCtx(ctx context.Context) bool {
|
||||
return ok && admin
|
||||
}
|
||||
|
||||
// GinContextFromCtx returns the underlying *gin.Context, which resolvers need
|
||||
// for things that live outside GraphQL's model: setting auth cookies and
|
||||
// reading the client IP. Returns nil if the middleware was not installed,
|
||||
// which the auth resolvers surface as an error rather than panicking.
|
||||
func GinContextFromCtx(ctx context.Context) *gin.Context {
|
||||
gc, ok := ctx.Value(ginContextKey).(*gin.Context)
|
||||
if !ok {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Package graph is the GraphQL layer: the single POST /graphql endpoint that
|
||||
// serves most of the site's data.
|
||||
//
|
||||
// How the pieces fit:
|
||||
//
|
||||
// - graph/schema/*.graphql is the source of truth. Running
|
||||
// `go run github.com/99designs/gqlgen generate` regenerates generated.go
|
||||
// and model/models_gen.go, and adds stubs for any new field to the
|
||||
// matching *.resolvers.go. Never edit those two generated files.
|
||||
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
|
||||
// structs in backend/models, so model/ holds only input and payload
|
||||
// types. That is also why almost every type has a hand-written ID
|
||||
// resolver: model IDs are uint, GraphQL's Int is a Go int.
|
||||
// - Resolvers reach the database and the third-party caches through
|
||||
// Resolver.Store, the same handlers.Store the REST endpoints use.
|
||||
// - context.go and middleware.go carry the caller's identity from Gin into
|
||||
// the plain context.Context a resolver receives.
|
||||
//
|
||||
// Authorisation, which is the thing most likely to catch out a newcomer:
|
||||
// there is NO middleware guarding this endpoint. AuthContextMiddleware only
|
||||
// annotates the context and lets everything through, so each resolver checks
|
||||
// for itself with IsAdminFromCtx or UserIDFromCtx. A resolver that omits that
|
||||
// check is fully public. The rule of thumb in this schema is that queries are
|
||||
// public and mutations are admin-only, with these exceptions: the job
|
||||
// application and job reference queries are admin-only (they are private
|
||||
// data), the places mutations need only a signed-in user, and the messages
|
||||
// query hides private messages from non-admins rather than refusing.
|
||||
//
|
||||
// The files ending in _helpers.go are hand-written and are not touched by
|
||||
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
|
||||
// them by hand may be moved to the end of the file on the next generate.
|
||||
package graph
|
||||
@@ -38,6 +38,9 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &favorites[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Favorite, len(favorites))
|
||||
for i := range favorites {
|
||||
result[i] = &favorites[i]
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
|
||||
// GiteaFeed is the resolver for the giteaFeed field.
|
||||
func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) {
|
||||
// One-minute cache on the Store, shared by every visitor, so a busy home
|
||||
// page does not hammer the Gitea container.
|
||||
if r.Store.GiteaFeedFresh() {
|
||||
return mapGiteaFeed(r.Store.GiteaFeed), nil
|
||||
}
|
||||
@@ -23,6 +25,10 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed
|
||||
// would dereference it, so return null to the client instead. The cache
|
||||
// is deliberately not written in that case, so an empty feed is retried
|
||||
// on the next request.
|
||||
if feed == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,10 @@ import (
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the
|
||||
// commit message out of the doubly-encoded Content field as it goes. It
|
||||
// dereferences feed, so callers must rule out the (nil, nil) that
|
||||
// FetchLatestFeed returns for an empty feed.
|
||||
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
|
||||
return &model.GiteaFeedItem{
|
||||
AvatarURL: feed.ActUser.AvatarURL,
|
||||
|
||||
@@ -81,6 +81,8 @@ func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppR
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var refs []*models.JobAppReference
|
||||
// created_at is the final tie-break so entries sharing a sort_order (the
|
||||
// default 0) keep a stable, insertion-ordered sequence.
|
||||
if err := r.Store.DB.Order("category ASC, sort_order ASC, created_at ASC").Find(&refs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -43,6 +43,10 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Partial update: every input field is a pointer so that "not supplied"
|
||||
// is distinguishable from "set to empty". A nil field is left untouched;
|
||||
// note this also means a nullable column can never be cleared back to
|
||||
// null through this mutation.
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -79,6 +83,8 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Soft delete straight by id, without loading first — so deleting an id
|
||||
// that does not exist still returns true.
|
||||
if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -87,9 +93,12 @@ func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bo
|
||||
|
||||
// JobApplications is the resolver for the jobApplications field.
|
||||
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
|
||||
// Admin-only even though it is a query: job applications are private.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Find can populate a slice of pointers directly, avoiding the
|
||||
// copy-to-pointers loop the other list resolvers need.
|
||||
var apps []*models.JobApplication
|
||||
if err := r.Store.DB.Order("created_at desc").Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -17,12 +17,21 @@ func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, err
|
||||
}
|
||||
|
||||
// AuthorID is the resolver for the authorId field.
|
||||
// AuthorID is the resolver for the authorId field. The value is the chat
|
||||
// hub's per-connection counter, not a User id — see models.Message.
|
||||
func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) {
|
||||
return int(obj.AuthorID), nil
|
||||
}
|
||||
|
||||
// Messages is the resolver for the messages field.
|
||||
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
|
||||
// Non-admins get the public subset rather than an error, so the chat
|
||||
// history loads for everyone. The same filter is applied to the history
|
||||
// replayed over the WebSocket (services.HandleWebSocket) — change one and
|
||||
// the other must change too.
|
||||
//
|
||||
// Note the ordering differs between the two: newest first here, oldest
|
||||
// first over the socket.
|
||||
var messages []models.Message
|
||||
query := r.Store.DB.Order("created_at DESC")
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
@@ -31,6 +40,9 @@ func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error)
|
||||
if err := query.Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &messages[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Message, len(messages))
|
||||
for i := range messages {
|
||||
result[i] = &messages[i]
|
||||
|
||||
@@ -7,6 +7,18 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// AuthContextMiddleware prepares the request context for the GraphQL handler.
|
||||
//
|
||||
// It always attaches the *gin.Context, and attaches the JWT claims only when a
|
||||
// valid access token is present. Crucially it never rejects a request: a
|
||||
// missing, expired or forged token simply leaves the context anonymous, which
|
||||
// is what lets public queries work and pushes every authorisation decision
|
||||
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
|
||||
// errors are swallowed for exactly that reason.
|
||||
//
|
||||
// Unlike the REST path there is no refresh-token fallback here, so once the
|
||||
// access token expires GraphQL treats the caller as anonymous until the front
|
||||
// end refreshes.
|
||||
func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
|
||||
@@ -19,6 +31,8 @@ func AuthContextMiddleware(auth *services.Auth) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// The context is immutable, so the enriched one has to be written
|
||||
// back onto the request for the gqlgen handler to see it.
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ import (
|
||||
|
||||
// CreatePlace is the resolver for the createPlace field.
|
||||
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
|
||||
// Any signed-in user, not just an admin — places are the one shared,
|
||||
// collaboratively edited list on the site. There is no per-user
|
||||
// ownership, so any signed-in user can edit or delete any place.
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
@@ -43,6 +46,8 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
// Partial update, same pointer-means-supplied convention as job
|
||||
// applications: nil fields are left as they are.
|
||||
var place models.Place
|
||||
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -48,10 +48,14 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
// Admin alone is not enough: a post may only be edited by its author, so
|
||||
// one admin cannot rewrite another's posts.
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
|
||||
// Both fields are non-pointer in the input, so this is a full replace —
|
||||
// omitting one in the mutation blanks it rather than leaving it alone.
|
||||
post.Title = input.Title
|
||||
post.Content = input.Content
|
||||
if err := r.Store.DB.Save(&post).Error; err != nil {
|
||||
@@ -81,6 +85,8 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
return nil, fmt.Errorf("you can only delete your own posts")
|
||||
}
|
||||
|
||||
// Soft delete; the error is dropped, so a failed delete still reports
|
||||
// success to the client.
|
||||
r.Store.DB.Delete(&post)
|
||||
return &post, nil
|
||||
}
|
||||
@@ -92,10 +98,16 @@ func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||
|
||||
// Posts is the resolver for the posts field.
|
||||
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||
// Preload issues a second query for the authors and fills in Post.Author.
|
||||
// Without it the field is nil and the schema's author field resolves to
|
||||
// null — there is no lazy loading and no error to tell you why.
|
||||
var posts []models.Post
|
||||
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &posts[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Post, len(posts))
|
||||
for i := range posts {
|
||||
result[i] = &posts[i]
|
||||
|
||||
@@ -7,6 +7,15 @@ import "adam-french.co.uk/backend/handlers"
|
||||
// It serves as dependency injection for your app, add any dependencies you require
|
||||
// here.
|
||||
|
||||
// Resolver is the root of the GraphQL schema and the only dependency every
|
||||
// resolver has. Rather than listing dependencies individually it holds the
|
||||
// same handlers.Store the REST handlers use, so GraphQL and REST share one
|
||||
// database handle and one set of third-party caches.
|
||||
//
|
||||
// The generated code embeds *Resolver in per-type resolver structs
|
||||
// (queryResolver, mutationResolver, postResolver, ...), which is why those
|
||||
// one-line `struct{ *Resolver }` declarations appear at the bottom of each
|
||||
// resolvers file.
|
||||
type Resolver struct {
|
||||
Store *handlers.Store
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &rows[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.Rowing, len(rows))
|
||||
for i := range rows {
|
||||
result[i] = &rows[i]
|
||||
@@ -30,6 +33,8 @@ func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error
|
||||
}
|
||||
|
||||
// Time is the resolver for the time field.
|
||||
// Time is the resolver for the time field: total session seconds, narrowed
|
||||
// from uint64 to GraphQL's Int.
|
||||
func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||
return int(obj.Time), nil
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Latest activity from the self-hosted Gitea instance, proxied and cached for
|
||||
# one minute by the backend. Resolves to null when the feed is empty.
|
||||
|
||||
type GiteaFeedItem {
|
||||
avatarUrl: String!
|
||||
repoUrl: String!
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
# Job application tracker. Rows come from these mutations or automatically
|
||||
# from the email sync pipeline (backend/services/email_sync.go). These are
|
||||
# private data, so the queries here are admin-only as well as the mutations.
|
||||
#
|
||||
# status is a free-form String, but only the values ranked in
|
||||
# services.statusOrder can be advanced automatically by the email pipeline:
|
||||
# applied, screening, assessment, interviewing, offer, rejected, withdrawn.
|
||||
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
# Chat history. The live chat runs over the WebSocket at /ws, not GraphQL;
|
||||
# this query is the initial page load.
|
||||
#
|
||||
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
|
||||
# User id, and private messages are silently filtered out for non-admins
|
||||
# rather than causing an error.
|
||||
|
||||
type Message {
|
||||
id: ID!
|
||||
content: String!
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Places to go. Unlike most mutations these require only a signed-in user,
|
||||
# not an admin, and there is no per-user ownership: the list is shared.
|
||||
|
||||
type Place {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
# Root of the GraphQL schema.
|
||||
#
|
||||
# Query and Mutation are declared here with no fields; every other file in this
|
||||
# directory adds to them with `extend type Query` / `extend type Mutation`.
|
||||
# That is what lets the schema be split one file per domain, matching the
|
||||
# one-file-per-domain resolver layout (gqlgen.yml uses layout: follow-schema).
|
||||
#
|
||||
# Time is mapped to Go's time.Time by gqlgen's default scalar handling and is
|
||||
# serialised as RFC 3339.
|
||||
#
|
||||
# These files are the source of truth: after editing one, run
|
||||
# go run github.com/99designs/gqlgen generate
|
||||
# from backend/ to regenerate graph/generated.go and graph/model/models_gen.go.
|
||||
# Note that `#` comments like this one are invisible to clients; a `"""` block
|
||||
# would become a schema description and show up in introspection.
|
||||
|
||||
scalar Time
|
||||
|
||||
type Query
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# Spotify "now playing" / "recently played" for the home page. Both resolve to
|
||||
# null / an empty list when the backend has never completed the Spotify OAuth
|
||||
# flow, so the page degrades rather than erroring.
|
||||
|
||||
type SpotifyArtist {
|
||||
name: String!
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Steam presence and recent games for the home page, cached for five minutes.
|
||||
# headerImage is built from the app id rather than returned by Steam's API.
|
||||
|
||||
type SteamGame {
|
||||
appId: Int!
|
||||
name: String!
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
|
||||
// SpotifyListening is the resolver for the spotifyListening field.
|
||||
func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPlaying, error) {
|
||||
// A nil client means the OAuth flow has never been completed. Report that
|
||||
// as null rather than an error so the home page renders without it.
|
||||
if r.Store.SpotifyClient == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -38,6 +40,8 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
|
||||
return []*model.SpotifyRecentItem{}, nil
|
||||
}
|
||||
|
||||
// One-minute cache. This resolver is the only writer of that cache; the
|
||||
// REST /spotify/recent endpoint reads it but never fills it.
|
||||
if r.Store.RecentSongsFresh() {
|
||||
return mapRecentItems(*r.Store.RecentSongs), nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,11 @@ import (
|
||||
"github.com/zmb3/spotify/v2"
|
||||
)
|
||||
|
||||
// Converters from the Spotify library's rich types to the deliberately narrow
|
||||
// GraphQL types — the schema exposes only the handful of fields the home page
|
||||
// renders.
|
||||
|
||||
// mapSpotifyImages keeps just the URLs of a set of album images.
|
||||
func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
|
||||
result := make([]*model.SpotifyImage, len(images))
|
||||
for i, img := range images {
|
||||
@@ -13,6 +18,7 @@ func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
|
||||
return result
|
||||
}
|
||||
|
||||
// mapSpotifyTrack converts a currently-playing track.
|
||||
func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
|
||||
artists := make([]*model.SpotifyArtist, len(track.Artists))
|
||||
for i, a := range track.Artists {
|
||||
@@ -28,6 +34,11 @@ func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
|
||||
}
|
||||
}
|
||||
|
||||
// mapRecentItems converts recently played history entries.
|
||||
//
|
||||
// It rebuilds the track inline instead of calling mapSpotifyTrack because a
|
||||
// RecentlyPlayedItem holds a SimpleTrack, not the FullTrack that function
|
||||
// takes — the duplication is forced by the library's types.
|
||||
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
|
||||
result := make([]*model.SpotifyRecentItem, len(items))
|
||||
for i, item := range items {
|
||||
|
||||
@@ -19,6 +19,8 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Five-minute cache across both Steam calls, which are made together and
|
||||
// expire together.
|
||||
if r.Store.SteamFresh() {
|
||||
return &model.SteamStatus{
|
||||
Online: r.Store.SteamOnline,
|
||||
@@ -36,6 +38,8 @@ func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// PersonaState 0 is offline; every higher value is some flavour of
|
||||
// online. A nil summary (private profile) reads as offline.
|
||||
online := false
|
||||
if summary != nil {
|
||||
online = summary.PersonaState > 0
|
||||
|
||||
@@ -7,6 +7,11 @@ import (
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// mapSteamGames converts Steam API games into the GraphQL shape.
|
||||
//
|
||||
// HeaderImageURL is synthesised rather than returned by the API: Steam's CDN
|
||||
// serves every game's cover art at a predictable path keyed by app id, so
|
||||
// building the URL here saves an extra API call per game.
|
||||
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
|
||||
result := make([]*model.SteamGame, len(games))
|
||||
for i, g := range games {
|
||||
|
||||
@@ -20,6 +20,8 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// Only an existing admin can create accounts — there is no public
|
||||
// sign-up. New users are created non-admin; setUserAdmin promotes them.
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -62,6 +64,8 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
// Guards against the last admin demoting themselves and locking everyone
|
||||
// out of the admin UI.
|
||||
if uint(id) == callerID {
|
||||
return nil, fmt.Errorf("cannot change your own admin status")
|
||||
}
|
||||
@@ -88,6 +92,9 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Copy to a slice of pointers because the schema returns a list of
|
||||
// nullable objects. Taking &users[i] is safe: the slice is never
|
||||
// appended to after this point, so the backing array cannot move.
|
||||
result := make([]*models.User, len(users))
|
||||
for i := range users {
|
||||
result[i] = &users[i]
|
||||
|
||||
@@ -5,16 +5,38 @@ import (
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// This file holds the REST authentication endpoints and the Gin middleware
|
||||
// that guards the other REST routes. GraphQL has its own parallel
|
||||
// implementation of login/logout/refresh in graph/auth.resolvers.go; both
|
||||
// mint the same cookies through services.Auth.
|
||||
//
|
||||
// Cookie model: `access_token` is short-lived and carries id + admin, so most
|
||||
// requests authorise without a database hit; `refresh_token` carries only the
|
||||
// id and is exchanged for a fresh pair. Both are set HttpOnly and Secure, so
|
||||
// JavaScript cannot read them and the browser attaches them automatically.
|
||||
|
||||
// UserCredentials is the JSON body of POST /auth/login. The binding tags make
|
||||
// Gin reject a request missing either field.
|
||||
type UserCredentials struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
// AuthMiddlewear requires a valid access token on a REST route and stashes
|
||||
// the claims for AdminMiddleware to read.
|
||||
//
|
||||
// (The name is misspelled but it is exported and referenced from main.go, so
|
||||
// it is left alone rather than renamed.)
|
||||
//
|
||||
// It deliberately does NOT fall back to the refresh token: an expired access
|
||||
// token yields a 401 and the front end is expected to call /auth/refresh and
|
||||
// retry.
|
||||
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
||||
access_token, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -28,11 +50,20 @@ func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// store claims in Gin context
|
||||
// Stored under a plain string key in the *Gin* context. This is a
|
||||
// different mechanism from graph/context.go, which puts the same claims
|
||||
// into the standard library request context under an unexported typed
|
||||
// key; the two do not see each other's values.
|
||||
ctx.Set("userClaims", claims)
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// AdminMiddleware requires the access token to carry admin=true. It must be
|
||||
// chained after AuthMiddlewear, which is what populates "userClaims"; on its
|
||||
// own it always rejects.
|
||||
//
|
||||
// Admin is read from the token, not the database, so revoking someone's admin
|
||||
// flag only takes effect once their current access token expires.
|
||||
func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
if !exists {
|
||||
@@ -46,6 +77,8 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// A token minted before the admin claim existed simply has no "admin"
|
||||
// key, so a failed type assertion is treated as "not an admin".
|
||||
admin, ok := (*mapClaims)["admin"].(bool)
|
||||
if !ok || !admin {
|
||||
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
@@ -55,6 +88,13 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
|
||||
// decide whether to show admin UI. It answers with a bare status code and no
|
||||
// body: 200 admin, 403 authenticated but not admin, 401 not authenticated.
|
||||
//
|
||||
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
|
||||
// new cookie pair as a side effect, so a returning admin is recognised
|
||||
// without a visible re-login.
|
||||
func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
||||
accessToken, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -83,6 +123,16 @@ func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
||||
ctx.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// tryRefreshAndValidateAdmin re-authenticates from the refresh token.
|
||||
//
|
||||
// The bool does not mean "is an admin" — it means "this function already
|
||||
// wrote the response". It returns true both for a successful admin refresh
|
||||
// (200, new cookies set) and for a valid non-admin (403), and false only when
|
||||
// it could not decide, leaving the caller to send 401. Getting this backwards
|
||||
// would send two status codes for one request.
|
||||
//
|
||||
// Admin status is re-read from the database here, which is what makes the
|
||||
// refresh path pick up a revoked admin flag.
|
||||
func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
refreshToken, err := ctx.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
@@ -99,6 +149,9 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Pre-setting ID and calling First with no explicit condition makes GORM
|
||||
// use the primary key already in the struct as the lookup. Soft-deleted
|
||||
// users are excluded automatically, so a deleted admin fails here.
|
||||
user := models.User{ID: uint(userIDF)}
|
||||
if err := store.DB.First(&user).Error; err != nil {
|
||||
return false
|
||||
@@ -114,6 +167,21 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
store.setAuthCookies(ctx, tokens)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
return true
|
||||
}
|
||||
|
||||
// setAuthCookies writes the access/refresh cookie pair.
|
||||
//
|
||||
// The two trailing booleans of gin's SetCookie are Secure and HttpOnly, both
|
||||
// true here: the cookies are never sent over plain HTTP and are invisible to
|
||||
// JavaScript. SameSite=Lax lets them survive a top-level navigation back from
|
||||
// an OAuth provider while still blocking cross-site POSTs. Each cookie's
|
||||
// max-age mirrors the lifetime baked into the token itself, so the browser
|
||||
// drops it at roughly the moment it stops being accepted.
|
||||
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
@@ -131,11 +199,12 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
return true
|
||||
}
|
||||
|
||||
// CheckToken backs GET /auth/check: it returns the current user for a valid
|
||||
// access token, or 401. If the token is valid but the user no longer exists
|
||||
// it answers 404 and clears the cookies, so the browser stops presenting a
|
||||
// token for a deleted account.
|
||||
func (store *Store) CheckToken(ctx *gin.Context) {
|
||||
access_token, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -149,6 +218,8 @@ func (store *Store) CheckToken(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// JWT claims come back through encoding/json, so every number is a
|
||||
// float64 regardless of the Go type it was signed from.
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(401, gin.H{"error": "unauthorized"})
|
||||
@@ -168,6 +239,11 @@ func (store *Store) CheckToken(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token
|
||||
// for a new cookie pair and returns the user.
|
||||
//
|
||||
// Tokens are not rotated in any revocable sense — the old refresh token stays
|
||||
// valid until it expires, because nothing is tracked server-side.
|
||||
func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
refreshToken, err := ctx.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
@@ -204,28 +280,18 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
ctx.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
store.setAuthCookies(ctx, tokens)
|
||||
|
||||
ctx.JSON(http.StatusAccepted, user)
|
||||
}
|
||||
|
||||
// Login backs POST /auth/login. The user object it returns omits the password
|
||||
// because models.User tags that field `json:"-"`.
|
||||
func (store *Store) Login(ctx *gin.Context) {
|
||||
// Per-IP limit (5/min) on top of nginx's own login rate limit.
|
||||
// ctx.ClientIP is only trustworthy because main.go pins the trusted
|
||||
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
|
||||
// client talking through nginx.
|
||||
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
|
||||
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
|
||||
return
|
||||
@@ -237,6 +303,9 @@ func (store *Store) Login(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Unknown user and wrong password return the identical message, so the
|
||||
// response cannot be used to enumerate usernames. (The timing does
|
||||
// differ, since only the second path runs bcrypt.)
|
||||
user := models.User{}
|
||||
if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
|
||||
@@ -255,33 +324,23 @@ func (store *Store) Login(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
ctx.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
store.setAuthCookies(ctx, tokens)
|
||||
|
||||
ctx.JSON(http.StatusAccepted, user)
|
||||
}
|
||||
|
||||
// Logout backs POST /auth/logout. It only clears the browser's cookies —
|
||||
// the tokens themselves stay cryptographically valid until they expire, so a
|
||||
// copy taken beforehand would still work.
|
||||
func (store *Store) Logout(ctx *gin.Context) {
|
||||
store.removeCookies(ctx)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// removeCookies expires both auth cookies. The max-age of -1 is what tells
|
||||
// the browser to delete them; path, domain and the Secure/HttpOnly flags must
|
||||
// match those used when setting them or the browser keeps the originals.
|
||||
func (store *Store) removeCookies(ctx *gin.Context) {
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
|
||||
@@ -7,7 +7,16 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// REST endpoints for the job-application email pipeline: a manual
|
||||
// admin-triggered sync, and the OAuth redirect target (which has to be REST
|
||||
// because Microsoft redirects a browser to it).
|
||||
|
||||
// TriggerEmailSync backs the admin-only POST /email/sync and runs one sync
|
||||
// synchronously, so the response reflects the result. If the scheduler is
|
||||
// mid-sync the service refuses via TryLock and this returns 500.
|
||||
func (store *Store) TriggerEmailSync(ctx *gin.Context) {
|
||||
// A nil HTTPClient is the service's readiness flag — see
|
||||
// services.EmailSyncService.
|
||||
if store.EmailSync == nil || store.EmailSync.HTTPClient == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"})
|
||||
return
|
||||
@@ -23,6 +32,13 @@ func (store *Store) TriggerEmailSync(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"})
|
||||
}
|
||||
|
||||
// CompleteEmailAuth handles Microsoft's OAuth redirect to
|
||||
// GET /email/callback and stores the resulting token.
|
||||
//
|
||||
// The route is unauthenticated (Microsoft's redirect carries no site cookie),
|
||||
// which is safe only because the code is worthless without the app's client
|
||||
// secret. Note that completing auth here does not start the scheduler, which
|
||||
// only checks readiness at start-up — a restart is needed for that.
|
||||
func (store *Store) CompleteEmailAuth(ctx *gin.Context) {
|
||||
if store.EmailSync == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"})
|
||||
|
||||
@@ -12,18 +12,33 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Attachment upload for the chat. Files land in a directory that nginx serves
|
||||
// directly at /uploads/, so anything written here is publicly reachable by
|
||||
// URL — which is why the extension and content checks below matter.
|
||||
|
||||
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
|
||||
var allowedExtensions = map[string]bool{
|
||||
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true,
|
||||
".mp4": true, ".webm": true, ".mp3": true, ".ogg": true,
|
||||
".pdf": true, ".txt": true,
|
||||
}
|
||||
|
||||
// extensionToMIMEPrefix cross-checks the sniffed content type against the
|
||||
// claimed extension, to stop e.g. HTML being served from a .png URL.
|
||||
//
|
||||
// The audio extensions (.mp3, .ogg) and .gif are deliberately absent:
|
||||
// http.DetectContentType's answers for them are unreliable enough to reject
|
||||
// legitimate files, so a missing entry means "extension allowed, content not
|
||||
// verified".
|
||||
var extensionToMIMEPrefix = map[string]string{
|
||||
".jpg": "image/", ".jpeg": "image/", ".png": "image/", ".gif": "image/", ".webp": "image/",
|
||||
".mp4": "video/", ".webm": "video/",
|
||||
".pdf": "application/pdf", ".txt": "text/",
|
||||
}
|
||||
|
||||
// UploadMessageFile backs POST /messages/upload (login required) and returns
|
||||
// the public URL of the stored file, which the client then sends over the
|
||||
// WebSocket as a message's fileUrl.
|
||||
func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
@@ -49,6 +64,10 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
||||
return
|
||||
}
|
||||
// 512 bytes is exactly what http.DetectContentType inspects; reading more
|
||||
// would be wasted. A single Read may return fewer bytes than asked for,
|
||||
// which is fine — sniffing works on a short prefix — so only a read that
|
||||
// produced nothing at all is an error.
|
||||
buf := make([]byte, 512)
|
||||
n, err := f.Read(buf)
|
||||
f.Close()
|
||||
@@ -64,6 +83,10 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// The uploaded name is discarded entirely in favour of 16 random bytes
|
||||
// from crypto/rand. That kills path traversal and collisions in one go,
|
||||
// and makes the resulting URL unguessable. Only the extension is carried
|
||||
// over, and it has already been checked against the allow-list.
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate filename"})
|
||||
@@ -74,6 +97,9 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
uploadDir := "/backend/uploads/"
|
||||
dest := filepath.Join(uploadDir, filename)
|
||||
|
||||
// Reopened rather than rewound: the earlier handle was closed after
|
||||
// sniffing, and multipart files may be backed by either memory or a temp
|
||||
// file, so a fresh reader is the simplest correct option.
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
||||
|
||||
@@ -7,9 +7,16 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// GetNoteFile serves one file from the notes directory for the admin-only
|
||||
// route GET /notes/*path. The wildcard means `path` arrives with a leading
|
||||
// slash and may contain further slashes, so it has to be validated rather
|
||||
// than trusted — Notes.ParsePath does the containment check.
|
||||
|
||||
func (store *Store) GetNoteFile(ctx *gin.Context) {
|
||||
path := ctx.Param("path")
|
||||
|
||||
// A traversal attempt is reported as 404, not 403, so probing cannot
|
||||
// distinguish a blocked path from a missing one.
|
||||
path, err := store.Notes.ParsePath(path)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
@@ -22,6 +29,9 @@ func (store *Store) GetNoteFile(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// The SPA reads Last-Modified to show a note's edit date. Browsers hide
|
||||
// non-safelisted headers from cross-origin fetch() unless they are listed
|
||||
// in Access-Control-Expose-Headers, hence the second header.
|
||||
ctx.Header("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
|
||||
ctx.Header("Access-Control-Expose-Headers", "Content-Disposition, Last-Modified")
|
||||
|
||||
|
||||
@@ -9,12 +9,27 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Admin management of the radio's fallback music. These handlers only move
|
||||
// files around on disk; the Python service is what actually streams them, and
|
||||
// it picks up the directory contents on its own.
|
||||
//
|
||||
// Disabling a song moves it into a "disabled" subdirectory rather than
|
||||
// deleting it — so presence in that directory IS the disabled flag, and there
|
||||
// is no database state for the radio at all.
|
||||
|
||||
// fallbackMusicDir is a shared volume, also mounted by the radio service.
|
||||
const fallbackMusicDir = "/backend/fallback_music"
|
||||
|
||||
// allowedAudioExtensions is the upload allow-list, keyed by lower-cased
|
||||
// extension. Unlike chat uploads, the content is not sniffed: the route is
|
||||
// admin-only and audio formats sniff unreliably.
|
||||
var allowedAudioExtensions = map[string]bool{
|
||||
".mp3": true, ".ogg": true, ".flac": true, ".wav": true, ".m4a": true, ".opus": true,
|
||||
}
|
||||
|
||||
// UploadRadioSong backs the admin-only POST /radio/upload. Unlike chat
|
||||
// uploads the original filename is kept, because it is what the admin sees in
|
||||
// the song list — hence the sanitisation below.
|
||||
func (store *Store) UploadRadioSong(ctx *gin.Context) {
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
@@ -34,16 +49,22 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// filepath.Base strips any directory component, so "../../etc/passwd"
|
||||
// becomes "passwd". The absolute-path check below is a second, redundant
|
||||
// guard in case Base ever fails to neutralise some input.
|
||||
filename := filepath.Base(file.Filename)
|
||||
dest := filepath.Join(fallbackMusicDir, filename)
|
||||
|
||||
// Verify the resolved path stays within the music directory
|
||||
// The separator is appended before comparing so a sibling directory whose
|
||||
// name merely starts with the same characters cannot pass.
|
||||
absDest, err := filepath.Abs(dest)
|
||||
if err != nil || !strings.HasPrefix(absDest, fallbackMusicDir+string(os.PathSeparator)) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
|
||||
return
|
||||
}
|
||||
|
||||
// Refuse to overwrite. There is a check-then-write race here, but the
|
||||
// route is admin-only and single-user in practice.
|
||||
if _, err := os.Stat(dest); err == nil {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"})
|
||||
return
|
||||
@@ -57,7 +78,11 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"name": filename})
|
||||
}
|
||||
|
||||
// ListRadioSongs backs the admin-only GET /radio/songs, returning both the
|
||||
// enabled songs and those parked in the disabled subdirectory, flagged.
|
||||
func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
// Declared inside the function because it is purely the JSON shape of
|
||||
// this one response.
|
||||
type songInfo struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
@@ -65,6 +90,7 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
Disabled bool `json:"disabled"`
|
||||
}
|
||||
|
||||
// Initialised empty rather than nil so the response is [] and not null.
|
||||
songs := []songInfo{}
|
||||
|
||||
// Read enabled songs
|
||||
@@ -73,6 +99,8 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read music directory"})
|
||||
return
|
||||
}
|
||||
// Skipping directories is also what keeps the "disabled" subdirectory out
|
||||
// of the enabled list; dotfiles skip editor and OS cruft.
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") {
|
||||
continue
|
||||
@@ -89,7 +117,9 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// Read disabled songs
|
||||
// The disabled directory is created lazily by DisableRadioSong, so a read
|
||||
// failure here is normally just "nothing has ever been disabled" and is
|
||||
// ignored rather than reported.
|
||||
disabledDir := filepath.Join(fallbackMusicDir, "disabled")
|
||||
disabledEntries, err := os.ReadDir(disabledDir)
|
||||
if err == nil {
|
||||
@@ -113,7 +143,12 @@ func (store *Store) ListRadioSongs(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"songs": songs})
|
||||
}
|
||||
|
||||
// DisableRadioSong moves a song into the disabled subdirectory so the radio
|
||||
// stops playing it, keeping the file.
|
||||
func (store *Store) DisableRadioSong(ctx *gin.Context) {
|
||||
// filepath.Base neutralises traversal in the :filename route parameter.
|
||||
// It returns "." for an empty input and "/" for "/", neither of which is
|
||||
// a real file, so both are rejected explicitly.
|
||||
filename := filepath.Base(ctx.Param("filename"))
|
||||
if filename == "." || filename == "/" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
|
||||
@@ -141,6 +176,7 @@ func (store *Store) DisableRadioSong(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"disabled": filename})
|
||||
}
|
||||
|
||||
// EnableRadioSong moves a song back out of the disabled subdirectory.
|
||||
func (store *Store) EnableRadioSong(ctx *gin.Context) {
|
||||
filename := filepath.Base(ctx.Param("filename"))
|
||||
if filename == "." || filename == "/" {
|
||||
@@ -163,6 +199,9 @@ func (store *Store) EnableRadioSong(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"enabled": filename})
|
||||
}
|
||||
|
||||
// DeleteRadioSong permanently removes an enabled song. It cannot reach the
|
||||
// disabled subdirectory, so a disabled song must be enabled before it can be
|
||||
// deleted.
|
||||
func (store *Store) DeleteRadioSong(ctx *gin.Context) {
|
||||
filename := filepath.Base(ctx.Param("filename"))
|
||||
if filename == "." || filename == "/" {
|
||||
|
||||
@@ -16,14 +16,25 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Rowing log. The interesting endpoint is CreateRowing: rather than a form,
|
||||
// the admin uploads a photo of the rowing machine display and Claude reads the
|
||||
// numbers off it. The session date comes from the photo's EXIF metadata, which
|
||||
// also doubles as the deduplication key.
|
||||
|
||||
// ExtractedRowingData is the JSON contract for what Claude reads off the
|
||||
// display; the keys must match the prompt in CreateRowing.
|
||||
type ExtractedRowingData struct {
|
||||
TimeMinutes uint64 `json:"timeMinutes"`
|
||||
TimeSeconds uint64 `json:"timeSeconds"`
|
||||
Distance uint64 `json:"distance"`
|
||||
}
|
||||
|
||||
// GetRowing backs the public GET /rowing with every logged session, newest
|
||||
// first.
|
||||
func (store *Store) GetRowing(ctx *gin.Context) {
|
||||
var rowing []models.Rowing
|
||||
// "Created_At" works because Postgres folds unquoted identifiers to lower
|
||||
// case; the column is created_at.
|
||||
if err := store.DB.Order("Created_At DESC").Find(&rowing).Error; err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
@@ -32,6 +43,12 @@ func (store *Store) GetRowing(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, rowing)
|
||||
}
|
||||
|
||||
// CreateRowing backs the admin-only POST /rowing: it takes a photo of the
|
||||
// rowing machine display, dates it from EXIF, has Claude read the time and
|
||||
// distance, sanity-checks the result and stores a session.
|
||||
//
|
||||
// Note it is admin-gated and calls a paid API once per request, so the
|
||||
// validation below exists to catch misreadings rather than hostile input.
|
||||
func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
file, err := ctx.FormFile("image")
|
||||
if err != nil {
|
||||
@@ -46,20 +63,23 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Get the date taken from the EXIF data
|
||||
x, err := exif.Decode(f)
|
||||
// EXIF is required, not optional: it is both the session date and the
|
||||
// duplicate key, so a stripped-metadata image (anything that has been
|
||||
// through most messaging apps) is rejected outright.
|
||||
exifData, err := exif.Decode(f)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"})
|
||||
return
|
||||
}
|
||||
|
||||
dateTaken, err := x.DateTime()
|
||||
dateTaken, err := exifData.DateTime()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no date found in EXIF data"})
|
||||
return
|
||||
}
|
||||
|
||||
// Seek back to start since exif.Decode advanced the cursor
|
||||
// exif.Decode consumed part of the stream, so rewind before reading the
|
||||
// bytes to send to Claude.
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
|
||||
return
|
||||
@@ -77,6 +97,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
"image/gif": true,
|
||||
"image/webp": true,
|
||||
}
|
||||
// This is the browser's claimed type, not a sniffed one; it is passed
|
||||
// straight through to the Anthropic API, so the allow-list is there to
|
||||
// keep the API call well-formed rather than to police the file.
|
||||
mediaType := file.Header.Get("Content-Type")
|
||||
if !allowedMediaTypes[mediaType] {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
|
||||
@@ -84,7 +107,11 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
}
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
|
||||
// Reject duplicates: same EXIF datetime already recorded
|
||||
// Duplicate guard: two photos of the same session share an EXIF capture
|
||||
// time to the second. Checked before the Claude call so a re-upload costs
|
||||
// nothing. Note this reads err == nil as "found" — an actual database
|
||||
// error is indistinguishable from "no match" here and lets the insert
|
||||
// proceed.
|
||||
var existing models.Rowing
|
||||
if err := store.DB.Where("date = ?", dateTaken).First(&existing).Error; err == nil {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": "duplicate entry for this date"})
|
||||
@@ -130,6 +157,8 @@ No text, no markdown, no explanation. Just the JSON object.`),
|
||||
return
|
||||
}
|
||||
|
||||
// Strip a markdown code fence if the model wrapped its JSON in one
|
||||
// despite the prompt. Same defensive dance as in services/email_sync.go.
|
||||
extractedData := ExtractedRowingData{}
|
||||
raw := message.Content[0].Text
|
||||
|
||||
@@ -153,7 +182,10 @@ No text, no markdown, no explanation. Just the JSON object.`),
|
||||
|
||||
totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds
|
||||
|
||||
// Validate for anomalous values
|
||||
// Sanity bounds on what Claude claims to have read. A misread digit
|
||||
// typically lands far outside human rowing performance, and the pace
|
||||
// check catches the case where time and distance are individually
|
||||
// plausible but inconsistent with each other.
|
||||
const (
|
||||
minDistance = 100 // metres
|
||||
maxDistance = 100000 // metres
|
||||
@@ -177,6 +209,9 @@ No text, no markdown, no explanation. Just the JSON object.`),
|
||||
return
|
||||
}
|
||||
|
||||
// Rough calorie estimate from distance alone: roughly 500 kcal per
|
||||
// 7500 m. Not from the machine and not physiologically derived — it is a
|
||||
// display figure only.
|
||||
calories := float64(extractedData.Distance) / 7500.0 * 500.0
|
||||
|
||||
rowing := models.Rowing{
|
||||
|
||||
@@ -11,11 +11,23 @@ import (
|
||||
"github.com/zmb3/spotify/v2"
|
||||
)
|
||||
|
||||
// These REST endpoints predate the equivalent GraphQL queries in
|
||||
// graph/spotify.resolvers.go and are kept for the OAuth callback (which must
|
||||
// be REST, because Spotify redirects a browser to it) and for direct use.
|
||||
|
||||
// CompleteSpotifyAuth handles Spotify's OAuth redirect to
|
||||
// GET /spotify/callback. It swaps the code for a token, saves it so the
|
||||
// authorisation survives restarts, and installs the authenticated client on
|
||||
// the Store — which is how Store.SpotifyClient becomes non-nil without a
|
||||
// restart.
|
||||
func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
|
||||
state := ctx.Query("state")
|
||||
// context.Background, not the request context: the client built below
|
||||
// outlives this request and would otherwise be cancelled when it ends.
|
||||
c := context.Background()
|
||||
// code := c.Query("code")
|
||||
|
||||
// The library pulls the `code` out of the request itself and checks the
|
||||
// state parameter matches the one passed here.
|
||||
token, err := store.SpotifyAuth.Token(c, state, ctx.Request)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
@@ -38,6 +50,9 @@ func (store *Store) CompleteSpotifyAuth(ctx *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// ListeningTo backs GET /spotify/listening with the currently playing track.
|
||||
// A nil client means the OAuth flow has never been completed, reported here
|
||||
// as a 500.
|
||||
func (store *Store) ListeningTo(ctx *gin.Context) {
|
||||
c := ctx.Request.Context()
|
||||
|
||||
@@ -56,6 +71,12 @@ func (store *Store) ListeningTo(ctx *gin.Context) {
|
||||
ctx.JSON(200, playing)
|
||||
}
|
||||
|
||||
// RecentlyPlayed backs GET /spotify/recent.
|
||||
//
|
||||
// It reads the cache but never writes it: only the GraphQL spotifyRecent
|
||||
// resolver populates Store.RecentSongs. So this endpoint serves cached data
|
||||
// only when a GraphQL query happened to fill the cache in the last minute,
|
||||
// and otherwise calls Spotify every time.
|
||||
func (store *Store) RecentlyPlayed(ctx *gin.Context) {
|
||||
if store.SpotifyClient == nil {
|
||||
ctx.JSON(500, gin.H{"error": "Spotify not authenticated"})
|
||||
@@ -79,6 +100,9 @@ func (store *Store) RecentlyPlayed(ctx *gin.Context) {
|
||||
ctx.JSON(200, played)
|
||||
}
|
||||
|
||||
// RecentSongsFresh reports whether the cached recently-played list is within
|
||||
// its one-minute TTL. An empty list counts as stale, so an empty listening
|
||||
// history is re-fetched every time.
|
||||
func (s *Store) RecentSongsFresh() bool {
|
||||
if s.RecentSongs == nil {
|
||||
return false
|
||||
|
||||
@@ -6,6 +6,9 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ConnectWebSocket upgrades GET /ws into a chat connection. The route is
|
||||
// public: anyone may chat, and admin status only adds the ability to see and
|
||||
// send private messages and to delete.
|
||||
func (store *Store) ConnectWebSocket(ctx *gin.Context) {
|
||||
// Work out admin status before upgrading: the browser sends the auth
|
||||
// cookies with the upgrade request, but they are not available afterwards.
|
||||
|
||||
@@ -10,6 +10,18 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Package handlers holds the REST endpoints and the shared Store that every
|
||||
// request handler — and, through graph.Resolver, every GraphQL resolver —
|
||||
// depends on.
|
||||
//
|
||||
// Store is the backend's dependency container: it is built once in main and
|
||||
// passed around by pointer, so the caches on it are shared process-wide.
|
||||
//
|
||||
// Concurrency note: the cache fields below are read and written by concurrent
|
||||
// requests without a mutex. The races are benign in practice (worst case two
|
||||
// requests refresh the same third-party API at once, or one reads a value
|
||||
// being replaced), but this is a deliberate simplification, not an oversight
|
||||
// — do not add a field here that would be unsafe to tear.
|
||||
type Store struct {
|
||||
DB *gorm.DB
|
||||
SpotifyAuth *spotifyauth.Authenticator
|
||||
@@ -20,14 +32,19 @@ type Store struct {
|
||||
LoginLimiter *services.RateLimiter
|
||||
EmailSync *services.EmailSyncService
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
// mean "never fetched" distinctly from "fetched, empty".
|
||||
RecentSongs *[]spotify.RecentlyPlayedItem
|
||||
RecentSongsFetchedAt time.Time
|
||||
|
||||
// Cached latest Gitea activity entry, 1 minute TTL.
|
||||
GiteaHost string
|
||||
GiteaPort string
|
||||
GiteaFeed *services.GiteaFeedResponse
|
||||
GiteaFeedFetchedAt time.Time
|
||||
|
||||
// Cached Steam status and recent games, 5 minute TTL.
|
||||
SteamAPIKey string
|
||||
SteamID string
|
||||
SteamRecentGames []services.SteamRecentGame
|
||||
@@ -35,6 +52,9 @@ type Store struct {
|
||||
SteamFetchedAt time.Time
|
||||
}
|
||||
|
||||
// GiteaFeedFresh reports whether the cached Gitea feed entry is still within
|
||||
// its one-minute TTL. A nil cache is never fresh, so the first request always
|
||||
// hits Gitea.
|
||||
func (s *Store) GiteaFeedFresh() bool {
|
||||
if s.GiteaFeed == nil {
|
||||
return false
|
||||
@@ -42,6 +62,10 @@ func (s *Store) GiteaFeedFresh() bool {
|
||||
return time.Since(s.GiteaFeedFetchedAt) < time.Minute
|
||||
}
|
||||
|
||||
// SteamFresh reports whether the cached Steam data is still within its
|
||||
// five-minute TTL. Note it tests only SteamRecentGames: if Steam legitimately
|
||||
// returns no recent games, the cache never registers as fresh and every
|
||||
// request re-queries the API.
|
||||
func (s *Store) SteamFresh() bool {
|
||||
if s.SteamRecentGames == nil {
|
||||
return false
|
||||
|
||||
+51
-1
@@ -21,7 +21,17 @@ import (
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// Command backend is the Go API for adam-french.co.uk.
|
||||
//
|
||||
// main is the single place everything is wired together: it reads every
|
||||
// setting from the environment, builds the services, packs them into one
|
||||
// handlers.Store, and registers the routes. There are three route groups —
|
||||
// open, `protected` (valid access token) and `admin` (token with admin=true)
|
||||
// — plus the GraphQL endpoint, which does its own per-resolver authorisation
|
||||
// instead of using middleware. See backend/README.md for the wider picture.
|
||||
func main() {
|
||||
// Logs go to both stdout (so `docker compose logs` works) and a file in a
|
||||
// mounted volume (so they survive the container).
|
||||
logsDir := "/backend/logs"
|
||||
logFile, err := os.OpenFile(logsDir+"/go.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
@@ -35,6 +45,10 @@ func main() {
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
// Only the Docker network nginx sits on may set X-Forwarded-For. Without
|
||||
// this pin any client could spoof its IP and defeat the per-IP login rate
|
||||
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
|
||||
// defined in docker-compose.yml.
|
||||
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -50,10 +64,15 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
// Dev only; the seeder creates an admin with a known password.
|
||||
if os.Getenv("SEED_DB") == "true" {
|
||||
services.SeedDatabase(db)
|
||||
}
|
||||
// DOMAIN does double duty: the WebSocket origin allow-list and the auth
|
||||
// cookie domain.
|
||||
domainName := os.Getenv("DOMAIN")
|
||||
// The chat hub is a package-level singleton rather than a value on the
|
||||
// Store, so it is initialised rather than constructed.
|
||||
services.InitWebSocket(db, domainName)
|
||||
|
||||
// SPOTIFY
|
||||
@@ -71,6 +90,9 @@ func main() {
|
||||
|
||||
authSecret := os.Getenv("BACKEND_SECRET")
|
||||
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
||||
// Long-lived by design: this is a personal site with a single admin, and
|
||||
// there is no server-side revocation, so a leaked token stays valid for
|
||||
// its whole lifetime.
|
||||
accessTokenLifetime := 7 * 24 * time.Hour
|
||||
refreshTokenLifetime := 365 * 24 * time.Hour
|
||||
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
|
||||
@@ -87,6 +109,8 @@ func main() {
|
||||
steamID := os.Getenv("STEAM_ID")
|
||||
|
||||
// EMAIL SYNC
|
||||
// An unparseable EMAIL_SYNC_INTERVAL is silently ignored and the 30
|
||||
// minute default stands — a typo here fails quietly.
|
||||
emailSyncInterval := 30 * time.Minute
|
||||
if interval := os.Getenv("EMAIL_SYNC_INTERVAL"); interval != "" {
|
||||
if parsed, err := time.ParseDuration(interval); err == nil {
|
||||
@@ -110,10 +134,16 @@ func main() {
|
||||
}
|
||||
emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient)
|
||||
|
||||
// 5 login attempts per IP per minute, applied by both the REST handler
|
||||
// and the GraphQL login mutation. Nginx rate-limits the login route too.
|
||||
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
||||
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID}
|
||||
|
||||
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||
// the Gin context, so the order in the admin group matters.
|
||||
//
|
||||
// Paths below have no /api prefix: nginx strips it before proxying.
|
||||
protected := r.Group("/", store.AuthMiddlewear)
|
||||
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
||||
|
||||
@@ -146,6 +176,8 @@ func main() {
|
||||
admin.PATCH("/radio/songs/:filename/enable", store.EnableRadioSong)
|
||||
|
||||
// MESSAGES
|
||||
// /ws is deliberately outside the protected group: chat is public, and
|
||||
// the handler checks the cookies itself to decide admin privileges.
|
||||
r.GET("/ws", store.ConnectWebSocket)
|
||||
protected.POST("/messages/upload", store.UploadMessageFile)
|
||||
|
||||
@@ -153,6 +185,12 @@ func main() {
|
||||
admin.GET("/notes/*path", store.GetNoteFile)
|
||||
|
||||
// GRAPHQL
|
||||
// GraphQL is assembled by hand rather than with handler.NewDefaultServer
|
||||
// so the transports and extensions below are explicit.
|
||||
//
|
||||
// Note the whole API is one POST route with no middleware guard:
|
||||
// authorisation happens per resolver via IsAdminFromCtx / UserIDFromCtx,
|
||||
// so a new resolver is PUBLIC until it checks for itself.
|
||||
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
||||
Resolvers: &graph.Resolver{Store: &store},
|
||||
}))
|
||||
@@ -160,12 +198,20 @@ func main() {
|
||||
gqlSrv.AddTransport(transport.Options{})
|
||||
gqlSrv.AddTransport(transport.POST{})
|
||||
gqlSrv.AddTransport(transport.MultipartForm{})
|
||||
// Caches parsed query documents so repeated queries skip parsing.
|
||||
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
|
||||
// Rejects queries above a computed complexity, the standard defence
|
||||
// against a deeply nested query being used to exhaust the server.
|
||||
gqlSrv.Use(extension.FixedComplexityLimit(200))
|
||||
// Introspection and the playground are both off unless DEV_MODE *and*
|
||||
// their own flag are set, so production does not publish its schema.
|
||||
devMode := os.Getenv("DEV_MODE") == "true"
|
||||
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
|
||||
gqlSrv.Use(extension.Introspection{})
|
||||
}
|
||||
// AuthContextMiddleware copies the Gin context and any verified claims
|
||||
// into the request context, which is what resolvers read. The closure is
|
||||
// needed because gqlgen speaks net/http, not gin.
|
||||
r.POST("/graphql", graph.AuthContextMiddleware(auth), func(c *gin.Context) {
|
||||
gqlSrv.ServeHTTP(c.Writer, c.Request)
|
||||
})
|
||||
@@ -180,11 +226,15 @@ func main() {
|
||||
c.JSON(200, gin.H{"message": "Hello World"})
|
||||
})
|
||||
|
||||
// Launch email sync scheduler
|
||||
// The scheduler runs until ctx is cancelled, which in practice only
|
||||
// happens if r.Run returns — there is no signal handling or graceful
|
||||
// shutdown, so the container is simply killed.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go store.EmailSync.StartScheduler(ctx)
|
||||
|
||||
port := os.Getenv("BACKEND_PORT")
|
||||
// Blocks forever; its error is not checked, so a failure to bind the port
|
||||
// exits main silently with status 0.
|
||||
r.Run(fmt.Sprintf(":%s", port))
|
||||
}
|
||||
|
||||
+85
-12
@@ -6,16 +6,42 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Package models holds the GORM entities, which are also the GraphQL object
|
||||
// types: gqlgen.yml maps each GraphQL type straight onto the struct here, so
|
||||
// graph/model/ only contains generated input and payload types. That means
|
||||
// these structs carry three sets of contracts at once — database columns,
|
||||
// JSON field names for the REST endpoints, and the shape resolvers return —
|
||||
// and renaming a field or changing a tag breaks at least one of them.
|
||||
//
|
||||
// Conventions across every model:
|
||||
// - There are no migration files; services.migrateDatabase runs AutoMigrate,
|
||||
// so a model must be listed there to get a table.
|
||||
// - A gorm.DeletedAt field means soft delete: Delete sets deleted_at, and
|
||||
// every subsequent query silently filters those rows out. Rows are never
|
||||
// actually removed, and a uniqueIndex still sees deleted rows, so a
|
||||
// soft-deleted username cannot be reused.
|
||||
// - IDs are uint in Go but Int in GraphQL, which is why nearly every type
|
||||
// has a hand-written ID resolver doing int(obj.ID).
|
||||
|
||||
// User is an account. There is no public sign-up: users are created by an
|
||||
// existing admin through the createUser mutation, or by the dev seeder.
|
||||
type User struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Username string `gorm:"uniqueIndex" json:"username"`
|
||||
Password []byte `json:"-"`
|
||||
Admin bool `json:"admin"`
|
||||
// bcrypt hash, never the plaintext. `json:"-"` keeps it out of REST
|
||||
// responses, and gqlgen.yml marks the GraphQL password field
|
||||
// resolver:false so it is not exposed there either.
|
||||
Password []byte `json:"-"`
|
||||
// Admin gates almost every mutation. It is copied into the access token,
|
||||
// so a change here only takes effect on the user's next token refresh.
|
||||
Admin bool `json:"admin"`
|
||||
}
|
||||
|
||||
// Post is a blog entry. Author is loaded with Preload("Author") by the post
|
||||
// resolvers; without that preload it is nil rather than an error.
|
||||
type Post struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -27,16 +53,27 @@ type Post struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Message is one chat message. The table is capped at 50 rows by the
|
||||
// WebSocket hub, which soft-deletes older ones on every insert.
|
||||
//
|
||||
// Two things to watch: Content is exposed as "text", not "content"; and
|
||||
// AuthorID is a per-process connection counter from the WebSocket hub, NOT a
|
||||
// User ID — chat is pseudonymous and the number is meaningless across
|
||||
// restarts.
|
||||
type Message struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Content string `json:"text"`
|
||||
AuthorID uint `json:"authorId"`
|
||||
FileURL string `json:"fileUrl,omitempty"`
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Content string `json:"text"`
|
||||
AuthorID uint `json:"authorId"`
|
||||
FileURL string `json:"fileUrl,omitempty"`
|
||||
// Private messages are visible only to admins; both the WebSocket
|
||||
// broadcast and the messages query filter on it.
|
||||
Private bool `gorm:"not null;default:false" json:"private"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
}
|
||||
|
||||
// Activity is a "currently doing" entry on the home page. Structurally
|
||||
// identical to Favorite but kept separate so the two lists can diverge.
|
||||
type Activity struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -47,6 +84,7 @@ type Activity struct {
|
||||
Link *string `json:"link"`
|
||||
}
|
||||
|
||||
// Favorite is a "currently enjoying" entry on the home page.
|
||||
type Favorite struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -57,6 +95,13 @@ type Favorite struct {
|
||||
Link *string `json:"link"`
|
||||
}
|
||||
|
||||
// Rowing is one rowing machine session, created by uploading a photo of the
|
||||
// display (see handlers.CreateRowing).
|
||||
//
|
||||
// Date is the photo's EXIF capture time and acts as the deduplication key —
|
||||
// it is not the row's creation time. Time is total seconds; Distance is
|
||||
// metres; TimePer500m is seconds and derived from the other two; Calories is
|
||||
// an estimate computed from distance, not read off the machine.
|
||||
type Rowing struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -68,6 +113,7 @@ type Rowing struct {
|
||||
Calories float64 `json:"calories"`
|
||||
}
|
||||
|
||||
// Bookmark is a link on the bookmarks page, grouped by Category.
|
||||
type Bookmark struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -78,6 +124,9 @@ type Bookmark struct {
|
||||
Link string `gorm:"not null" json:"link"`
|
||||
}
|
||||
|
||||
// JobAppReference is a reusable snippet for filling in job application forms
|
||||
// (a stock answer, a profile link, and so on), grouped by Category and
|
||||
// ordered within it by SortOrder.
|
||||
type JobAppReference struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -89,15 +138,31 @@ type JobAppReference struct {
|
||||
SortOrder int `gorm:"default:0" json:"sortOrder"`
|
||||
}
|
||||
|
||||
// ProcessedEmail records that the email pipeline has already looked at a
|
||||
// message, so it is never classified twice.
|
||||
//
|
||||
// Unlike every other model it has no DeletedAt and so is NOT soft deleted —
|
||||
// the dedup check must see every historical row. Its CreatedAt also drives
|
||||
// the next sync's time window, so the most recent row here is effectively the
|
||||
// pipeline's cursor. A row is written even when classification failed, with
|
||||
// Action "error", which means failures are never retried.
|
||||
type ProcessedEmail struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"`
|
||||
Subject string `gorm:"not null" json:"subject"`
|
||||
Action string `gorm:"not null" json:"action"`
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
// The provider's message id: Microsoft Graph's id on the Graph backend,
|
||||
// the RFC822 Message-ID header on IMAP. Unique, which is what makes the
|
||||
// dedup check safe against a concurrent sync.
|
||||
GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"`
|
||||
Subject string `gorm:"not null" json:"subject"`
|
||||
Action string `gorm:"not null" json:"action"`
|
||||
// The application this email created or updated, if any. A plain nullable
|
||||
// column, not a GORM association — nothing preloads it.
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
}
|
||||
|
||||
// Place is an entry on the places-to-go list. Creating or editing one needs
|
||||
// only a signed-in user, not an admin — the one exception to the
|
||||
// admin-writes-everything rule.
|
||||
type Place struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
@@ -113,6 +178,14 @@ type Place struct {
|
||||
Done bool `gorm:"default:false" json:"done"`
|
||||
}
|
||||
|
||||
// JobApplication is a tracked job application. Rows are created by hand
|
||||
// through GraphQL or automatically by the email pipeline.
|
||||
//
|
||||
// Status is a free-form string, but only the values ranked in
|
||||
// services.statusOrder ("applied", "screening", "assessment",
|
||||
// "interviewing", "offer", "rejected", "withdrawn") can be advanced
|
||||
// automatically; the pipeline matches an existing application on
|
||||
// (Company, JobTitle) compared case-insensitively.
|
||||
type JobApplication struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
|
||||
@@ -8,10 +8,16 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Auth mints and verifies the HS256 JWTs that back the site's login. Tokens
|
||||
// are handed to the browser as HTTP-only cookies (see handlers.Store.Login);
|
||||
// there is no server-side session or token blacklist, so a token stays valid
|
||||
// until it expires even after logout.
|
||||
type Auth struct {
|
||||
Config *AuthConfig
|
||||
}
|
||||
|
||||
// AuthConfig carries the signing secret and cookie/token lifetimes. Domain is
|
||||
// the cookie domain; Endpoint is the backend's public base URL.
|
||||
type AuthConfig struct {
|
||||
Secret []byte
|
||||
Domain string
|
||||
@@ -20,17 +26,26 @@ type AuthConfig struct {
|
||||
Endpoint string
|
||||
}
|
||||
|
||||
// Tokens is a freshly minted access/refresh token pair, both already signed.
|
||||
type Tokens struct {
|
||||
AccessToken string
|
||||
RefreshToken string
|
||||
}
|
||||
|
||||
// InitAuth builds the Auth service from config.
|
||||
func InitAuth(config *AuthConfig) *Auth {
|
||||
auth := Auth{Config: config}
|
||||
|
||||
return &auth
|
||||
}
|
||||
|
||||
// GenerateJWT issues an access/refresh pair for user.
|
||||
//
|
||||
// The access token carries the authorisation data the API needs (id, admin)
|
||||
// so that most requests can be authorised without touching the database. The
|
||||
// refresh token deliberately carries only the id: admin status is re-read
|
||||
// from the database when refreshing, so revoking someone's admin flag takes
|
||||
// effect on their next refresh rather than only when they log in again.
|
||||
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
|
||||
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"username": user.Username,
|
||||
@@ -57,10 +72,20 @@ func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
|
||||
return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil
|
||||
}
|
||||
|
||||
// keyFunc supplies the HMAC secret to the JWT parser. The token argument is
|
||||
// ignored because only one key is ever in use; VerifyJWT separately pins the
|
||||
// algorithm, which is what actually prevents the "alg: none"/algorithm
|
||||
// confusion attack.
|
||||
func (auth *Auth) keyFunc(_ *jwt.Token) (any, error) {
|
||||
return auth.Config.Secret, nil
|
||||
}
|
||||
|
||||
// VerifyJWT parses and validates a signed token, returning its claims.
|
||||
// Expiry is checked by the jwt library. Note the *jwt.MapClaims return: a
|
||||
// pointer to a map is unusual, but every caller in this codebase expects it,
|
||||
// so the type is part of the internal contract. Numeric claims come back as
|
||||
// float64 because that is what encoding/json produces, hence the
|
||||
// `(*claims)["id"].(float64)` conversions at the call sites.
|
||||
func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
|
||||
token, err := jwt.Parse(tokenStr, auth.keyFunc, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
||||
if err != nil {
|
||||
|
||||
@@ -5,11 +5,20 @@ import (
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
)
|
||||
|
||||
// ClaudeConfig holds the Anthropic API credentials.
|
||||
type ClaudeConfig struct {
|
||||
APIKey string
|
||||
}
|
||||
|
||||
// InitClaude builds the shared Anthropic client. It is used in two places:
|
||||
// reading a rowing machine display from a photo (handlers.CreateRowing) and
|
||||
// classifying job-application emails (EmailSyncService.processEmail).
|
||||
//
|
||||
// No validation happens here: with an empty or wrong API key construction
|
||||
// still succeeds and the failure only surfaces on the first request.
|
||||
func InitClaude(config *ClaudeConfig) *anthropic.Client {
|
||||
// anthropic.NewClient returns a value, not a pointer, so take its address
|
||||
// to share one client across every caller.
|
||||
client := anthropic.NewClient(option.WithAPIKey(config.APIKey))
|
||||
return &client
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SQLConfig holds the PostgreSQL connection parameters, all read from the
|
||||
// environment in main.
|
||||
type SQLConfig struct {
|
||||
User string
|
||||
Password string
|
||||
@@ -16,6 +18,9 @@ type SQLConfig struct {
|
||||
Port string
|
||||
}
|
||||
|
||||
// connectToPostgreSQL opens the GORM connection. sslmode=disable is safe
|
||||
// only because Postgres is reachable exclusively on the private Docker
|
||||
// network, never over the internet.
|
||||
func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf(
|
||||
"user=%s password=%s dbname=%s host=%s port=%s sslmode=disable",
|
||||
@@ -30,6 +35,12 @@ func connectToPostgreSQL(config *SQLConfig) (*gorm.DB, error) {
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// migrateDatabase brings the schema up to date. This project has no
|
||||
// migration files: GORM's AutoMigrate is the only schema source, so it will
|
||||
// add tables, columns and indexes but never drop or rename anything. Removing
|
||||
// a field from a model therefore leaves the column behind, and a renamed
|
||||
// field appears as a brand-new column with no data. Any model added to
|
||||
// models.go must also be listed here or its table will never be created.
|
||||
func migrateDatabase(db *gorm.DB) error {
|
||||
err := db.AutoMigrate(
|
||||
&models.User{},
|
||||
@@ -51,6 +62,7 @@ func migrateDatabase(db *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// InitDatabase connects to Postgres and runs the auto-migration.
|
||||
func InitDatabase(config *SQLConfig) (*gorm.DB, error) {
|
||||
db, err := connectToPostgreSQL(config)
|
||||
if err != nil {
|
||||
|
||||
@@ -15,6 +15,17 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file is a hand-rolled IMAP client, used as an alternative mail source
|
||||
// to Microsoft Graph. It exists because the Graph path needs an Azure app
|
||||
// registration and admin consent, while IMAP needs only an app password.
|
||||
//
|
||||
// It implements the bare minimum of RFC 3501 — LOGIN, SELECT, SEARCH, FETCH,
|
||||
// LOGOUT — by matching on string prefixes rather than parsing IMAP's grammar
|
||||
// properly. It works against Outlook and similar servers with the response
|
||||
// shapes seen in practice; it is not a general-purpose IMAP client.
|
||||
|
||||
// IMAPConfig holds the mailbox credentials. Password is an app password, not
|
||||
// an account password.
|
||||
type IMAPConfig struct {
|
||||
Host string
|
||||
Port string
|
||||
@@ -27,9 +38,15 @@ type IMAPConfig struct {
|
||||
type imapClient struct {
|
||||
conn net.Conn
|
||||
reader *bufio.Reader
|
||||
tag atomic.Int64
|
||||
// tag numbers the commands. IMAP allows several in flight at once
|
||||
// identified by tag; this client never does that, so the atomic is
|
||||
// belt-and-braces rather than load-bearing.
|
||||
tag atomic.Int64
|
||||
}
|
||||
|
||||
// imapDial opens an implicit-TLS IMAP connection (port 993 style, TLS from the
|
||||
// first byte — there is no STARTTLS support here) and consumes the server
|
||||
// greeting, which arrives unsolicited before any command.
|
||||
func imapDial(addr string) (*imapClient, error) {
|
||||
conn, err := tls.Dial("tcp", addr, nil)
|
||||
if err != nil {
|
||||
@@ -47,21 +64,31 @@ func imapDial(addr string) (*imapClient, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Close drops the TCP connection. Callers normally send LOGOUT first.
|
||||
func (c *imapClient) Close() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// nextTag returns the next command tag, e.g. "A0001". The width is cosmetic:
|
||||
// past 9999 the tags simply get longer, and they stay unique.
|
||||
func (c *imapClient) nextTag() string {
|
||||
return fmt.Sprintf("A%04d", c.tag.Add(1))
|
||||
}
|
||||
|
||||
// readLine reads one CRLF-terminated protocol line with the terminator
|
||||
// stripped. There is no read deadline anywhere in this client, so an
|
||||
// unresponsive server can block a sync until the TCP connection itself fails.
|
||||
func (c *imapClient) readLine() (string, error) {
|
||||
line, err := c.reader.ReadString('\n')
|
||||
return strings.TrimRight(line, "\r\n"), err
|
||||
}
|
||||
|
||||
// sendCommand sends a tagged command and reads lines until the tagged response.
|
||||
// Returns all untagged response lines and the final tagged status line.
|
||||
// sendCommand sends a tagged command and reads lines until the line beginning
|
||||
// with that tag, which is the server's final status for the command.
|
||||
// Everything before it is an untagged ("* ...") response and is returned.
|
||||
//
|
||||
// This must not be used for FETCH: it reads line by line and would mistake the
|
||||
// bytes of a literal for protocol lines. Use sendFetch instead.
|
||||
func (c *imapClient) sendCommand(cmd string) (untagged []string, status string, err error) {
|
||||
tag := c.nextTag()
|
||||
_, err = fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
@@ -87,7 +114,8 @@ func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
|
||||
if err != nil {
|
||||
return untagged, err
|
||||
}
|
||||
// Status line is like: A0001 OK ... or A0001 NO ...
|
||||
// Status line is "<tag> OK ..." on success, "<tag> NO ..." or
|
||||
// "<tag> BAD ..." otherwise; only the second field matters.
|
||||
parts := strings.SplitN(status, " ", 3)
|
||||
if len(parts) < 2 || parts[1] != "OK" {
|
||||
return untagged, fmt.Errorf("command %q failed: %s", cmd, status)
|
||||
@@ -95,7 +123,10 @@ func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
|
||||
return untagged, nil
|
||||
}
|
||||
|
||||
// fetchLiteral reads an IMAP literal {N}\r\n followed by N bytes.
|
||||
// readLiteral reads exactly size bytes of an IMAP literal, i.e. the payload
|
||||
// announced by a trailing "{N}" on the preceding line. It must read by byte
|
||||
// count rather than by line because the payload is arbitrary binary data that
|
||||
// will itself contain CRLFs.
|
||||
func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
buf := make([]byte, size)
|
||||
_, err := io.ReadFull(c.reader, buf)
|
||||
@@ -105,8 +136,15 @@ func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// sendFetch sends a FETCH command and collects the full response including literals.
|
||||
// Returns raw response lines (with literals inlined after their header lines).
|
||||
// sendFetch sends a FETCH and collects its response, handling literals.
|
||||
//
|
||||
// The returned slice interleaves protocol lines with literal payloads: when a
|
||||
// line ends in "{N}" the next entry is the N bytes that followed it. The
|
||||
// caller (fetchEmailsIMAP) relies on that pairing.
|
||||
//
|
||||
// The literal is detected with LastIndex("{") plus a "}" suffix rather than a
|
||||
// real parse, so a line whose text merely ends in braces could be misread —
|
||||
// tolerable because only FETCH responses reach this code.
|
||||
func (c *imapClient) sendFetch(cmd string) ([]string, error) {
|
||||
tag := c.nextTag()
|
||||
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
@@ -158,7 +196,11 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
// Quote the password to handle special characters
|
||||
// %q wraps the password in double quotes and backslash-escapes any quote
|
||||
// or backslash inside it, which happens to be exactly IMAP's quoted-string
|
||||
// syntax. The username is NOT quoted: an address needs no escaping.
|
||||
// Note this sends the password in a LOGIN command, so it is only safe
|
||||
// because the connection is TLS from the first byte.
|
||||
quotedPass := fmt.Sprintf("%q", s.Config.IMAP.Password)
|
||||
if _, err := c.sendCommandOK(fmt.Sprintf("LOGIN %s %s", s.Config.IMAP.Email, quotedPass)); err != nil {
|
||||
return nil, fmt.Errorf("IMAP login: %w", err)
|
||||
@@ -168,14 +210,19 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
return nil, fmt.Errorf("IMAP select INBOX: %w", err)
|
||||
}
|
||||
|
||||
// SEARCH SINCE uses date only (no time), per IMAP spec
|
||||
// SEARCH SINCE has day granularity only — the time of day is not
|
||||
// expressible — so this always over-fetches back to midnight of `since`.
|
||||
// Harmless: SyncEmails deduplicates by message id. The date must be in
|
||||
// IMAP's dd-Mon-yyyy form, hence this exact layout string.
|
||||
dateStr := since.UTC().Format("02-Jan-2006")
|
||||
untagged, err := c.sendCommandOK(fmt.Sprintf("SEARCH SINCE %s", dateStr))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP search: %w", err)
|
||||
}
|
||||
|
||||
// Parse sequence numbers from "* SEARCH 1 2 3 ..."
|
||||
// Parse sequence numbers from "* SEARCH 1 2 3 ...". parts[2:] skips the
|
||||
// "*" and "SEARCH" tokens; a bare "* SEARCH" (no matches) has len 2 and
|
||||
// is skipped by the length test.
|
||||
var seqNums []string
|
||||
for _, line := range untagged {
|
||||
if strings.HasPrefix(line, "* SEARCH") {
|
||||
@@ -194,13 +241,18 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
|
||||
log.Printf("[EmailSync/IMAP] Found %d messages since %s", len(seqNums), dateStr)
|
||||
|
||||
// Every matching message is fetched in one command with a comma-separated
|
||||
// sequence set, and each full body is held in memory. A mailbox with a
|
||||
// very busy day could make this large — there is no batching.
|
||||
seqSet := strings.Join(seqNums, ",")
|
||||
fetchLines, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP fetch: %w", err)
|
||||
}
|
||||
|
||||
// Parse fetched messages - literals contain the raw RFC822 message
|
||||
// Pair each "... BODY[] {N}" header line with the literal that sendFetch
|
||||
// stored immediately after it. A message that fails to parse is logged and
|
||||
// skipped rather than failing the whole sync.
|
||||
var messages []graphMessage
|
||||
for i := 0; i < len(fetchLines); i++ {
|
||||
line := fetchLines[i]
|
||||
@@ -208,7 +260,11 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
if strings.Contains(line, "BODY[]") && strings.HasSuffix(line, "}") {
|
||||
if i+1 < len(fetchLines) {
|
||||
raw := fetchLines[i+1]
|
||||
i++ // skip the literal
|
||||
// Advance past the literal so its contents are never
|
||||
// examined as a protocol line. Note this is a C-style loop
|
||||
// precisely so i can be advanced here; a range loop could
|
||||
// not do it.
|
||||
i++
|
||||
gm, err := parseRawEmail(raw)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
|
||||
@@ -219,11 +275,16 @@ func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, err
|
||||
}
|
||||
}
|
||||
|
||||
// LOGOUT errors are ignored: the emails are already in hand and the
|
||||
// deferred Close will drop the connection regardless.
|
||||
c.sendCommand("LOGOUT")
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// parseRawEmail parses an RFC822 email into a graphMessage.
|
||||
// parseRawEmail parses a raw RFC822 message into the same graphMessage struct
|
||||
// the Graph API path produces, so everything downstream is source-agnostic.
|
||||
// An unparseable Date falls back to now, and a missing From leaves both name
|
||||
// and address empty rather than failing.
|
||||
func parseRawEmail(raw string) (graphMessage, error) {
|
||||
msg, err := mail.ReadMessage(strings.NewReader(raw))
|
||||
if err != nil {
|
||||
@@ -266,7 +327,16 @@ func parseRawEmail(raw string) (graphMessage, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// extractTextBody pulls the text/plain or text/html content from a message body.
|
||||
// extractTextBody pulls readable content out of a message body, preferring
|
||||
// text/plain and falling back to text/html.
|
||||
//
|
||||
// It recurses into nested multipart parts by re-wrapping the part's bytes in a
|
||||
// synthetic mail.Header carrying just its Content-Type — a shortcut that works
|
||||
// because this function only ever reads Content-Type.
|
||||
//
|
||||
// Quoted-printable and base64 transfer encodings are NOT decoded, so a
|
||||
// base64-encoded body reaches Claude as base64. Read errors on a part are
|
||||
// swallowed and the part is skipped.
|
||||
func extractTextBody(header mail.Header, body io.Reader) string {
|
||||
contentType := header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
@@ -326,7 +396,9 @@ func extractTextBody(header mail.Header, body io.Reader) string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// decodeHeader decodes RFC 2047 encoded header values.
|
||||
// decodeHeader decodes RFC 2047 encoded-words (the "=?UTF-8?Q?...?=" form
|
||||
// used for non-ASCII subjects), returning the input unchanged if it is not
|
||||
// encoded or cannot be decoded.
|
||||
func decodeHeader(s string) string {
|
||||
dec := new(mime.WordDecoder)
|
||||
decoded, err := dec.DecodeHeader(s)
|
||||
|
||||
+137
-11
@@ -21,8 +21,18 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// This file is the job-application email pipeline. On a timer it fetches
|
||||
// recent mail (via Microsoft Graph or plain IMAP), keeps the ones that look
|
||||
// recruitment-related, asks Claude to turn each into structured data, and
|
||||
// creates or advances a models.JobApplication row. Every email it has looked
|
||||
// at is recorded as a models.ProcessedEmail so it is never handled twice.
|
||||
|
||||
// MSGRAPH_TOKEN_JSON_PATH lives in a Docker volume so the OAuth refresh token
|
||||
// survives restarts, exactly like the Spotify token.
|
||||
const MSGRAPH_TOKEN_JSON_PATH = "/backend/token/msgraph_token.json"
|
||||
|
||||
// EmailSyncConfig configures the pipeline. Backend picks the mail source;
|
||||
// anything other than "graph" or "imap" leaves the service permanently idle.
|
||||
type EmailSyncConfig struct {
|
||||
Backend string // "graph" or "imap"
|
||||
ClientID string
|
||||
@@ -34,22 +44,38 @@ type EmailSyncConfig struct {
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// EmailSyncService owns the sync pipeline.
|
||||
type EmailSyncService struct {
|
||||
Config *EmailSyncConfig
|
||||
OAuthConfig *oauth2.Config
|
||||
Config *EmailSyncConfig
|
||||
OAuthConfig *oauth2.Config
|
||||
// HTTPClient doubles as the readiness flag: nil means "not configured or
|
||||
// not yet authenticated", and both the scheduler and the manual-trigger
|
||||
// handler refuse to run while it is nil. On the Graph backend it is a
|
||||
// real token-injecting client; on the IMAP backend it is set to
|
||||
// http.DefaultClient purely so this check passes (IMAP never uses it).
|
||||
HTTPClient *http.Client
|
||||
DB *gorm.DB
|
||||
ClaudeClient *anthropic.Client
|
||||
mu sync.Mutex
|
||||
// mu is used with TryLock, not Lock: it makes a sync a no-op while
|
||||
// another one is running rather than queueing behind it, so the manual
|
||||
// admin trigger cannot pile up on top of the scheduled run.
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Microsoft Graph API response types
|
||||
|
||||
// Microsoft Graph API response types. The IMAP backend parses raw RFC822
|
||||
// messages into these same structs (see parseRawEmail) so that everything
|
||||
// downstream of fetchEmails is backend-agnostic.
|
||||
|
||||
// graphMessagesResponse is one page of /me/messages; NextLink is Graph's
|
||||
// cursor for the next page and is empty on the last one.
|
||||
type graphMessagesResponse struct {
|
||||
Value []graphMessage `json:"value"`
|
||||
NextLink string `json:"@odata.nextLink"`
|
||||
}
|
||||
|
||||
// graphMessage is a single email.
|
||||
type graphMessage struct {
|
||||
ID string `json:"id"`
|
||||
Subject string `json:"subject"`
|
||||
@@ -59,15 +85,18 @@ type graphMessage struct {
|
||||
BodyPreview string `json:"bodyPreview"`
|
||||
}
|
||||
|
||||
// graphFrom wraps the sender, which Graph nests one level deep.
|
||||
type graphFrom struct {
|
||||
EmailAddress graphEmailAddress `json:"emailAddress"`
|
||||
}
|
||||
|
||||
// graphEmailAddress is a display name plus address.
|
||||
type graphEmailAddress struct {
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
// graphBody is the message body; ContentType is "html" or "text".
|
||||
type graphBody struct {
|
||||
ContentType string `json:"contentType"`
|
||||
Content string `json:"content"`
|
||||
@@ -75,6 +104,9 @@ type graphBody struct {
|
||||
|
||||
// Claude response type
|
||||
|
||||
// EmailAnalysis is the JSON contract Claude is asked to return; the keys here
|
||||
// must stay in step with emailClassificationPrompt at the bottom of this file.
|
||||
// Pointer fields are the ones Claude is allowed to answer null for.
|
||||
type EmailAnalysis struct {
|
||||
IsJobEmail bool `json:"isJobEmail"`
|
||||
Action string `json:"action"`
|
||||
@@ -89,6 +121,12 @@ type EmailAnalysis struct {
|
||||
|
||||
// Email filtering config
|
||||
|
||||
// Cheap pre-filter, applied before any Claude call so that the bulk of a
|
||||
// mailbox never costs an API request. It is intentionally over-inclusive:
|
||||
// false positives are cheap (Claude rejects them), false negatives are not
|
||||
// (the email is never looked at again once its window has passed).
|
||||
|
||||
// subjectKeywords match case-insensitively anywhere in the subject line.
|
||||
var subjectKeywords = []string{
|
||||
"application", "interview", "offer", "rejected", "assessment",
|
||||
"applied", "candidate", "position", "role", "hiring",
|
||||
@@ -96,6 +134,8 @@ var subjectKeywords = []string{
|
||||
"next steps", "coding challenge", "take-home",
|
||||
}
|
||||
|
||||
// senderDomains are applicant-tracking systems; mail from any of them is
|
||||
// considered job-related whatever the subject says.
|
||||
var senderDomains = []string{
|
||||
"greenhouse.io", "lever.co", "workday.com", "myworkday.com",
|
||||
"ashbyhq.com", "smartrecruiters.com", "icims.com",
|
||||
@@ -105,6 +145,11 @@ var senderDomains = []string{
|
||||
|
||||
// Status progression order
|
||||
|
||||
// statusOrder ranks the application lifecycle so updates can only move an
|
||||
// application forwards (see updateJobApplication). A status missing from this
|
||||
// map is treated as unknown and never applied. Note that "rejected" and
|
||||
// "withdrawn" sit at the top, so once an application reaches them nothing can
|
||||
// move it back.
|
||||
var statusOrder = map[string]int{
|
||||
"applied": 0,
|
||||
"screening": 1,
|
||||
@@ -117,6 +162,9 @@ var statusOrder = map[string]int{
|
||||
|
||||
// Token persistence
|
||||
|
||||
// SaveMSGraphToken persists an OAuth token to disk with 0600 permissions.
|
||||
// Like the Spotify equivalent it copies into a local struct so the on-disk
|
||||
// shape does not depend on the oauth2 package's own JSON tags.
|
||||
func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
||||
data := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
@@ -142,6 +190,8 @@ func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
||||
return os.WriteFile(path, jsonBytes, 0600)
|
||||
}
|
||||
|
||||
// LoadMSGraphToken reads a token written by SaveMSGraphToken. A missing file
|
||||
// is reported as an error and means "not yet authenticated".
|
||||
func LoadMSGraphToken(path string) (*oauth2.Token, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
@@ -174,6 +224,18 @@ type persistingTokenSource struct {
|
||||
lastToken *oauth2.Token
|
||||
}
|
||||
|
||||
// Token returns a valid token, refreshing through the wrapped source when
|
||||
// needed and writing any new token back to disk.
|
||||
//
|
||||
// Without this wrapper the oauth2 client would refresh happily in memory but
|
||||
// the file on disk would keep the original refresh token; Microsoft rotates
|
||||
// refresh tokens, so after the original expired the service would have to be
|
||||
// re-authorised by hand on the next restart.
|
||||
//
|
||||
// There is no mutex here even though oauth2's client may call Token from
|
||||
// several goroutines. In practice syncs are serialised by EmailSyncService.mu
|
||||
// so concurrent calls do not arise; the worst case if they ever did is a
|
||||
// duplicate write of the same token.
|
||||
func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
tok, err := p.base.Token()
|
||||
if err != nil {
|
||||
@@ -189,6 +251,12 @@ func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// InitEmailSync builds the service and, for the Graph backend, restores a
|
||||
// saved OAuth session. It never fails: a misconfigured or unauthenticated
|
||||
// service is returned with a nil HTTPClient, which leaves the pipeline idle
|
||||
// while the rest of the backend starts normally. For Graph, the authorisation
|
||||
// URL is printed to the container log for a one-off manual sign-in that
|
||||
// lands on GET /email/callback.
|
||||
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, claudeClient *anthropic.Client) *EmailSyncService {
|
||||
svc := &EmailSyncService{
|
||||
Config: config,
|
||||
@@ -264,7 +332,13 @@ func (s *EmailSyncService) CompleteAuth(ctx context.Context, code string) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartScheduler runs SyncEmails on a recurring interval.
|
||||
// StartScheduler runs SyncEmails immediately and then on every tick until ctx
|
||||
// is cancelled. It is meant to be run in its own goroutine and returns
|
||||
// straight away when the service is disabled or unauthenticated.
|
||||
//
|
||||
// Because readiness is only checked once here, authenticating later via
|
||||
// /email/callback does NOT start the scheduler; the backend has to be
|
||||
// restarted, or syncs triggered by hand through POST /email/sync.
|
||||
func (s *EmailSyncService) StartScheduler(ctx context.Context) {
|
||||
if !s.Config.Enabled {
|
||||
log.Println("[EmailSync] Disabled, skipping scheduler")
|
||||
@@ -300,11 +374,17 @@ func (s *EmailSyncService) StartScheduler(ctx context.Context) {
|
||||
|
||||
// SyncEmails is the main pipeline: fetch, filter, dedup, classify, create/update.
|
||||
func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
// TryLock, so a manual trigger during a scheduled run is rejected
|
||||
// immediately instead of blocking a request for minutes.
|
||||
if !s.mu.TryLock() {
|
||||
return fmt.Errorf("sync already in progress")
|
||||
}
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// Registered after the unlock defer, therefore it runs BEFORE it: the
|
||||
// panic is absorbed here and the mutex is still released afterwards.
|
||||
// A recovered panic makes SyncEmails return nil, so the caller sees a
|
||||
// successful sync — the log line is the only evidence.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("[EmailSync] PANIC recovered: %v", r)
|
||||
@@ -313,7 +393,13 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
|
||||
log.Println("[EmailSync] Starting sync...")
|
||||
|
||||
// Determine the time window: use the most recent ProcessedEmail timestamp, or default to 24h ago
|
||||
// Window start = when the last email was *processed*, not when it was
|
||||
// received. Those differ by up to one sync interval, which is deliberate:
|
||||
// it overlaps the windows so nothing that arrived mid-sync is missed. The
|
||||
// overlap re-fetches a few emails, and the ProcessedEmail dedup below is
|
||||
// what stops them being handled twice. On a cold database (no processed
|
||||
// emails at all) it falls back to the last 24 hours, so the pipeline
|
||||
// never tries to ingest an entire mailbox.
|
||||
since := time.Now().Add(-24 * time.Hour)
|
||||
var latest models.ProcessedEmail
|
||||
if err := s.DB.Order("created_at DESC").First(&latest).Error; err == nil {
|
||||
@@ -342,7 +428,10 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
continue
|
||||
}
|
||||
|
||||
// Process this email
|
||||
// A failed email is still recorded (with action "error") so the next
|
||||
// sync skips it rather than retrying — and, importantly, so it does
|
||||
// not hold the window open. The trade-off is that a transient Claude
|
||||
// outage permanently drops those emails.
|
||||
action, jobAppID, processErr := s.processEmail(ctx, email)
|
||||
if processErr != nil {
|
||||
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
|
||||
@@ -379,7 +468,8 @@ func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchEmails retrieves emails since the given time using the configured backend.
|
||||
// fetchEmails retrieves emails since the given time using the configured
|
||||
// backend, normalising both into []graphMessage.
|
||||
func (s *EmailSyncService) fetchEmails(ctx context.Context, since time.Time) ([]graphMessage, error) {
|
||||
if s.Config.Backend == "imap" {
|
||||
return s.fetchEmailsIMAP(since)
|
||||
@@ -399,6 +489,8 @@ func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time
|
||||
"$orderby": {"receivedDateTime asc"},
|
||||
}
|
||||
|
||||
// Graph paginates with @odata.nextLink, which already carries every query
|
||||
// parameter, so the loop below only builds this first URL by hand.
|
||||
nextURL := fmt.Sprintf("https://graph.microsoft.com/v1.0/me/messages?%s", params.Encode())
|
||||
|
||||
for nextURL != "" {
|
||||
@@ -415,6 +507,8 @@ func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
// Status is checked before the read error so that a non-200 reports
|
||||
// Graph's own error body rather than a generic read failure.
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("Graph API returned %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
@@ -446,6 +540,9 @@ func (s *EmailSyncService) filterEmails(emails []graphMessage) []graphMessage {
|
||||
return matched
|
||||
}
|
||||
|
||||
// matchesFilter reports whether an email looks job-related on subject or
|
||||
// sender alone. See subjectKeywords for why this errs towards including too
|
||||
// much.
|
||||
func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
|
||||
subjectLower := strings.ToLower(email.Subject)
|
||||
for _, kw := range subjectKeywords {
|
||||
@@ -498,6 +595,10 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
return "", nil, fmt.Errorf("empty response from Claude")
|
||||
}
|
||||
|
||||
// Only the first content block is read, and the prompt asks for bare JSON,
|
||||
// but models still wrap output in a markdown fence often enough that it is
|
||||
// stripped defensively here. The two TrimPrefix calls are ordered so that
|
||||
// "```json" is removed first and a plain "```" otherwise.
|
||||
raw := message.Content[0].Text
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
@@ -518,7 +619,11 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
// Try to find an existing job application
|
||||
// Applications are identified by (company, job title) compared
|
||||
// case-insensitively — there is no external id to match on. Claude
|
||||
// wording the same role slightly differently therefore creates a second
|
||||
// application rather than updating the first. The most recent match wins
|
||||
// when there are several.
|
||||
var existing models.JobApplication
|
||||
found := s.DB.Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
|
||||
analysis.Company, analysis.JobTitle).
|
||||
@@ -537,6 +642,7 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
// createJobApplication inserts a new application from Claude's analysis.
|
||||
func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) {
|
||||
app := models.JobApplication{
|
||||
Company: analysis.Company,
|
||||
@@ -547,6 +653,8 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string
|
||||
Notes: analysis.Notes,
|
||||
}
|
||||
|
||||
// The prompt asks for YYYY-MM-DD but full RFC3339 comes back often enough
|
||||
// to be worth trying first; an unparseable date is dropped silently.
|
||||
if analysis.AppliedAt != nil {
|
||||
if t, err := time.Parse(time.RFC3339, *analysis.AppliedAt); err == nil {
|
||||
app.AppliedAt = &t
|
||||
@@ -567,6 +675,10 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string
|
||||
return "created", &app.ID, nil
|
||||
}
|
||||
|
||||
// updateJobApplication advances an existing application's status, but only
|
||||
// ever forwards through statusOrder. Emails commonly arrive out of order (a
|
||||
// delayed "thanks for applying" after an interview invite), and this is what
|
||||
// stops a stale email dragging an application backwards.
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
newOrder, newExists := statusOrder[analysis.Status]
|
||||
currentOrder, currentExists := statusOrder[existing.Status]
|
||||
@@ -596,7 +708,13 @@ func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication,
|
||||
return "updated", &existing.ID, nil
|
||||
}
|
||||
|
||||
// cleanEmailBody strips HTML and truncates the email body for Claude.
|
||||
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
|
||||
// Claude, cutting token cost and noise.
|
||||
//
|
||||
// The HTML handling is a regex tag-strip, not a parser: fine for extracting
|
||||
// prose, but it would mangle inline <script>/<style> content and mis-handle
|
||||
// tags inside attribute values. That is acceptable because the output is only
|
||||
// ever read by a language model, never rendered.
|
||||
func cleanEmailBody(content string, contentType string) string {
|
||||
text := content
|
||||
|
||||
@@ -625,7 +743,9 @@ func cleanEmailBody(content string, contentType string) string {
|
||||
text = nlRegex.ReplaceAllString(text, "\n\n")
|
||||
text = strings.TrimSpace(text)
|
||||
|
||||
// Remove common signatures
|
||||
// Cut everything from the first signature marker onwards. The idx > 0
|
||||
// test (not >= 0) means a body that begins with a marker is left alone,
|
||||
// which avoids blanking the whole message.
|
||||
sigPatterns := []string{
|
||||
"\n-- \n",
|
||||
"\nSent from my iPhone",
|
||||
@@ -649,7 +769,8 @@ func cleanEmailBody(content string, contentType string) string {
|
||||
}
|
||||
text = strings.Join(cleaned, "\n")
|
||||
|
||||
// Truncate to ~4000 characters
|
||||
// Cap the prompt size. This slices by bytes, so a cut can land mid-rune
|
||||
// and leave an invalid UTF-8 tail; harmless for a model prompt.
|
||||
if len(text) > 4000 {
|
||||
text = text[:4000]
|
||||
}
|
||||
@@ -657,6 +778,8 @@ func cleanEmailBody(content string, contentType string) string {
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
// truncate caps a string at maxLen bytes (not runes) before it is stored in
|
||||
// ProcessedEmail.Subject.
|
||||
func truncate(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
@@ -664,6 +787,9 @@ func truncate(s string, maxLen int) string {
|
||||
return s[:maxLen]
|
||||
}
|
||||
|
||||
// emailClassificationPrompt must stay in sync with the EmailAnalysis struct:
|
||||
// every key it names is a field there, and the status values it lists are the
|
||||
// keys of statusOrder.
|
||||
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
|
||||
|
||||
Return ONLY a JSON object with these exact keys:
|
||||
|
||||
@@ -8,23 +8,35 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file talks to the self-hosted Gitea instance over the private Docker
|
||||
// network to surface "what did Adam push most recently" on the home page.
|
||||
// The response is cached by the caller (handlers.Store, 1 minute TTL).
|
||||
|
||||
// GiteaFeedCommit is one commit inside a push event's Content payload.
|
||||
// The capitalised JSON keys are Gitea's, not a typo.
|
||||
type GiteaFeedCommit struct {
|
||||
Message string `json:"Message"`
|
||||
}
|
||||
|
||||
// GiteaFeedContent is the shape of the JSON *string* stored in
|
||||
// GiteaFeedResponse.Content for push events; see ParseCommitMessage.
|
||||
type GiteaFeedContent struct {
|
||||
Commits []GiteaFeedCommit `json:"Commits"`
|
||||
}
|
||||
|
||||
// GiteaFeedUser is the acting user on a feed entry.
|
||||
type GiteaFeedUser struct {
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
}
|
||||
|
||||
// GiteaFeedRepo is the repository a feed entry belongs to.
|
||||
type GiteaFeedRepo struct {
|
||||
FullName string `json:"full_name"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
}
|
||||
|
||||
// GiteaFeedResponse is a single Gitea activity feed entry. Only the fields
|
||||
// the front end renders are declared; the rest of the payload is discarded.
|
||||
type GiteaFeedResponse struct {
|
||||
ActUser GiteaFeedUser `json:"act_user"`
|
||||
Repo GiteaFeedRepo `json:"repo"`
|
||||
@@ -33,6 +45,13 @@ type GiteaFeedResponse struct {
|
||||
Created time.Time `json:"created"`
|
||||
}
|
||||
|
||||
// FetchLatestFeed returns the single most recent public activity entry for
|
||||
// user "adamf", or (nil, nil) when the feed is empty — callers must handle
|
||||
// that nil-without-error case.
|
||||
//
|
||||
// The username is hard-coded and the call is plain HTTP with no token: this
|
||||
// only ever reaches the Gitea container over the internal Docker network,
|
||||
// where the public feed needs no authentication.
|
||||
func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
|
||||
url := fmt.Sprintf("http://%s:%s/api/v1/users/adamf/activities/feeds?limit=1", host, port)
|
||||
|
||||
@@ -60,6 +79,11 @@ func FetchLatestFeed(host, port string) (*GiteaFeedResponse, error) {
|
||||
return &items[0], nil
|
||||
}
|
||||
|
||||
// ParseCommitMessage pulls the first commit message out of a feed entry's
|
||||
// Content field, which Gitea delivers as JSON encoded inside a JSON string
|
||||
// (so it needs a second Unmarshal). Non-push events have Content in a
|
||||
// different shape entirely, so any parse failure is intentionally swallowed
|
||||
// and reported as "no commit message".
|
||||
func ParseCommitMessage(content string) string {
|
||||
var c GiteaFeedContent
|
||||
if err := json.Unmarshal([]byte(content), &c); err != nil {
|
||||
|
||||
@@ -7,21 +7,35 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// NotesConfig points at the directory of markdown notes mounted into the
|
||||
// container.
|
||||
type NotesConfig struct {
|
||||
Dir string
|
||||
}
|
||||
|
||||
// Notes serves files out of a single directory, guarding against path
|
||||
// traversal. It is admin-only at the route level (see main.go).
|
||||
type Notes struct {
|
||||
Config NotesConfig
|
||||
}
|
||||
|
||||
// InitNotes builds the Notes service.
|
||||
func InitNotes(config *NotesConfig) *Notes {
|
||||
return &Notes{
|
||||
Config: *config,
|
||||
}
|
||||
}
|
||||
|
||||
// ParsePath resolves a user-supplied request path to an absolute path inside
|
||||
// the notes directory, or returns an error if it would escape.
|
||||
//
|
||||
// The traversal guard is the prefix check at the end. filepath.Join already
|
||||
// cleans "..", but the separator is appended to baseDir before comparing so
|
||||
// that a sibling directory whose name merely starts with the same characters
|
||||
// (e.g. /backend/notes-private next to /backend/notes) cannot pass the check.
|
||||
func (notes *Notes) ParsePath(path string) (string, error) {
|
||||
// The route is /notes/*path, so a bare /notes/ arrives as "" or "/";
|
||||
// treat both as a request for the wiki index.
|
||||
if path == "" || path == "/" {
|
||||
path = "Index.md"
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
// Package services holds the backend's stateful collaborators: the database
|
||||
// handle, JWT signing, the chat WebSocket hub, third-party API clients
|
||||
// (Spotify, Steam, Gitea, Claude) and the email-sync pipeline. Handlers and
|
||||
// GraphQL resolvers reach them through handlers.Store.
|
||||
package services
|
||||
|
||||
import (
|
||||
@@ -5,13 +9,24 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary
|
||||
// string (in practice the client IP). It is process-local: restarting the
|
||||
// backend clears every window, and a multi-replica deployment would limit
|
||||
// per replica rather than globally. Nginx applies its own rate limits in
|
||||
// front of this, so this layer is a second line of defence, not the only one.
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
mu sync.Mutex
|
||||
// attempts holds the timestamps of recent allowed attempts per key.
|
||||
// Keys are never evicted, so memory grows with the number of distinct
|
||||
// client IPs seen since start-up; acceptable for a personal site, but
|
||||
// worth knowing before reusing this elsewhere.
|
||||
attempts map[string][]time.Time
|
||||
max int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
// NewRateLimiter returns a limiter allowing at most max calls to Allow per
|
||||
// key within any window-length period.
|
||||
func NewRateLimiter(max int, window time.Duration) *RateLimiter {
|
||||
return &RateLimiter{
|
||||
attempts: make(map[string][]time.Time),
|
||||
@@ -20,6 +35,9 @@ func NewRateLimiter(max int, window time.Duration) *RateLimiter {
|
||||
}
|
||||
}
|
||||
|
||||
// Allow records an attempt for key and reports whether it is within the
|
||||
// limit. A rejected attempt is deliberately NOT recorded, so a caller that
|
||||
// keeps hammering does not extend its own lockout indefinitely.
|
||||
func (rl *RateLimiter) Allow(key string) bool {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
@@ -27,7 +45,11 @@ func (rl *RateLimiter) Allow(key string) bool {
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-rl.window)
|
||||
|
||||
// Remove expired entries
|
||||
// Filter in place: slicing to [:0] reuses the existing backing array, so
|
||||
// the append below overwrites the old timestamps instead of allocating a
|
||||
// new slice on every request. Safe here because we only ever write an
|
||||
// element at an index we have already read past. A missing key yields a
|
||||
// nil slice, and nil[:0] is legal and yields nil.
|
||||
valid := rl.attempts[key][:0]
|
||||
for _, t := range rl.attempts[key] {
|
||||
if t.After(cutoff) {
|
||||
|
||||
@@ -9,7 +9,13 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SeedDatabase populates an empty database with demo content for local
|
||||
// development. It is called from main only when SEED_DB=true, which
|
||||
// docker-compose.dev.yml sets; it must never run in production because it
|
||||
// creates an admin account with the password "password".
|
||||
func SeedDatabase(db *gorm.DB) {
|
||||
// "Any user exists" is the whole idempotency check — if the users table
|
||||
// has a row, nothing is seeded, even if the other tables were emptied.
|
||||
var user models.User
|
||||
if db.First(&user).Error == nil {
|
||||
log.Println("Database already has data, skipping seed")
|
||||
@@ -23,11 +29,14 @@ func SeedDatabase(db *gorm.DB) {
|
||||
log.Fatal("Failed to hash seed password:", err)
|
||||
}
|
||||
|
||||
// Dev-only credentials: testuser / password.
|
||||
testUser := models.User{
|
||||
Username: "testuser",
|
||||
Password: hashedPassword,
|
||||
Admin: true,
|
||||
}
|
||||
// GORM writes the generated primary key back into testUser, which the
|
||||
// posts below then reference as their author.
|
||||
db.Create(&testUser)
|
||||
|
||||
posts := []models.Post{
|
||||
|
||||
@@ -13,6 +13,10 @@ import (
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// SpotifyConfig holds the OAuth app credentials. AuthState is the fixed
|
||||
// `state` value used in the authorisation URL; because the flow is only ever
|
||||
// driven by hand by the site owner, it is a constant rather than a
|
||||
// per-request nonce.
|
||||
type SpotifyConfig struct {
|
||||
AuthState string
|
||||
RedirectURL string
|
||||
@@ -20,8 +24,15 @@ type SpotifyConfig struct {
|
||||
ClientSecret string
|
||||
}
|
||||
|
||||
// SPOTIFY_TOKEN_JSON_PATH is inside a Docker volume, so the refresh token
|
||||
// survives container restarts and the OAuth dance only has to be done once.
|
||||
const SPOTIFY_TOKEN_JSON_PATH = "/backend/token/spotify_token.json"
|
||||
|
||||
// SaveSpotifyToken persists an OAuth token to disk.
|
||||
//
|
||||
// It copies the fields into a local anonymous struct rather than marshalling
|
||||
// oauth2.Token directly, so the on-disk format stays stable regardless of what
|
||||
// the oauth2 package adds to its own struct or its JSON tags.
|
||||
func SaveSpotifyToken(path string, tok *oauth2.Token) error {
|
||||
data := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
@@ -48,6 +59,9 @@ func SaveSpotifyToken(path string, tok *oauth2.Token) error {
|
||||
return os.WriteFile(path, jsonBytes, 0600)
|
||||
}
|
||||
|
||||
// LoadSpotifyToken reads a token previously written by SaveSpotifyToken.
|
||||
// A missing file returns an error, which callers treat as "not yet
|
||||
// authenticated" rather than a fault.
|
||||
func LoadSpotifyToken(path string) (*oauth2.Token, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
@@ -75,6 +89,14 @@ func LoadSpotifyToken(path string) (*oauth2.Token, error) {
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// InitSpotifyAuth builds the OAuth authenticator and, if a saved token
|
||||
// exists, an authenticated client.
|
||||
//
|
||||
// Start-up never fails on Spotify problems: when there is no token or the
|
||||
// refresh is rejected it prints the authorisation URL to the container log
|
||||
// and returns a nil client. Every Spotify handler and resolver therefore has
|
||||
// to nil-check Store.SpotifyClient. Visiting that URL sends the browser to
|
||||
// /spotify/callback, which fills the client in at runtime.
|
||||
func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotify.Client) {
|
||||
auth := spotifyauth.New(
|
||||
spotifyauth.WithRedirectURL(config.RedirectURL),
|
||||
@@ -106,7 +128,18 @@ func InitSpotifyAuth(config *SpotifyConfig) (*spotifyauth.Authenticator, *spotif
|
||||
return auth, client
|
||||
}
|
||||
|
||||
// RefreshClient exchanges a stored token for a fresh one and returns a client
|
||||
// using it.
|
||||
//
|
||||
// Spotify may issue a new refresh token during this exchange, so the result is
|
||||
// written straight back to disk; the write error is ignored because a failed
|
||||
// save only costs a re-authentication later, and failing the whole start-up
|
||||
// over it would be worse. The returned client also holds the token source
|
||||
// internally and keeps refreshing on its own — but those later refreshes are
|
||||
// NOT persisted, so after a long uptime the file on disk can be stale.
|
||||
func RefreshClient(auth *spotifyauth.Authenticator, token *oauth2.Token) (*spotify.Client, error) {
|
||||
// context.Background rather than a request context: the resulting client
|
||||
// is long-lived and must outlive whichever request triggered this.
|
||||
ctx := context.Background()
|
||||
|
||||
token, err := auth.RefreshToken(ctx, token)
|
||||
|
||||
@@ -8,6 +8,12 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file wraps the two public Steam Web API endpoints used by the home
|
||||
// page. Results are cached by the caller (handlers.Store, 5 minute TTL) to
|
||||
// stay well inside Steam's rate limits.
|
||||
|
||||
// SteamRecentGame is one game from GetRecentlyPlayedGames. Playtimes are in
|
||||
// minutes.
|
||||
type SteamRecentGame struct {
|
||||
AppID int `json:"appid"`
|
||||
Name string `json:"name"`
|
||||
@@ -15,6 +21,8 @@ type SteamRecentGame struct {
|
||||
PlaytimeForever int `json:"playtime_forever"`
|
||||
}
|
||||
|
||||
// SteamRecentGamesResponse mirrors Steam's envelope, which wraps everything
|
||||
// in a "response" object.
|
||||
type SteamRecentGamesResponse struct {
|
||||
Response struct {
|
||||
TotalCount int `json:"total_count"`
|
||||
@@ -22,16 +30,26 @@ type SteamRecentGamesResponse struct {
|
||||
} `json:"response"`
|
||||
}
|
||||
|
||||
// SteamPlayerSummary is the subset of GetPlayerSummaries we care about.
|
||||
// PersonaState is Steam's online status enum: 0 = offline, anything higher
|
||||
// is some flavour of online (online, busy, away, snooze, looking to trade or
|
||||
// play), which is why the caller treats "> 0" as online.
|
||||
type SteamPlayerSummary struct {
|
||||
PersonaState int `json:"personastate"`
|
||||
}
|
||||
|
||||
// SteamPlayerSummariesResponse mirrors Steam's response envelope.
|
||||
type SteamPlayerSummariesResponse struct {
|
||||
Response struct {
|
||||
Players []SteamPlayerSummary `json:"players"`
|
||||
} `json:"response"`
|
||||
}
|
||||
|
||||
// FetchRecentlyPlayedGames returns the three most recently played games.
|
||||
//
|
||||
// Steam answers with HTTP 200 and an empty envelope for a private profile or
|
||||
// a bad key, so an empty slice and no error is the normal "nothing to show"
|
||||
// result rather than a failure.
|
||||
func FetchRecentlyPlayedGames(apiKey, steamID string) ([]SteamRecentGame, error) {
|
||||
url := fmt.Sprintf("https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v1/?key=%s&steamid=%s&count=3", apiKey, steamID)
|
||||
|
||||
@@ -55,6 +73,8 @@ func FetchRecentlyPlayedGames(apiKey, steamID string) ([]SteamRecentGame, error)
|
||||
return result.Response.Games, nil
|
||||
}
|
||||
|
||||
// FetchPlayerSummary returns the profile's online status, or (nil, nil) when
|
||||
// Steam returns no players (private or unknown profile).
|
||||
func FetchPlayerSummary(apiKey, steamID string) (*SteamPlayerSummary, error) {
|
||||
url := fmt.Sprintf("https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=%s&steamids=%s", apiKey, steamID)
|
||||
|
||||
|
||||
@@ -12,10 +12,27 @@ import (
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// This file is the chat hub behind GET /ws. It is deliberately a package-level
|
||||
// singleton (one process, one chat room) rather than an injectable type, so the
|
||||
// connection set, the database handle and the allowed origin all live in
|
||||
// package vars initialised once by InitWebSocket.
|
||||
|
||||
// maxMessages is both the size of the history replayed to a new client and the
|
||||
// number of rows kept in the database: every insert trims older messages.
|
||||
const maxMessages = 50
|
||||
|
||||
// allowedDomain is the site's domain, set by InitWebSocket and read by
|
||||
// Upgrader.CheckOrigin. It is a package var because the Upgrader is one too.
|
||||
var allowedDomain string
|
||||
|
||||
// Upgrader turns the HTTP request into a WebSocket.
|
||||
//
|
||||
// CheckOrigin is the only cross-origin defence on this endpoint: the browser
|
||||
// sends cookies with a WebSocket handshake regardless of origin and there is
|
||||
// no preflight, so without this check any site could open a socket as a
|
||||
// logged-in visitor. Default gorilla behaviour (same-host only) is too strict
|
||||
// here because the site is reached as both example.com and www.example.com,
|
||||
// and "localhost" is allowed for the Vite dev server.
|
||||
var Upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
@@ -35,12 +52,21 @@ var Upgrader = websocket.Upgrader{
|
||||
|
||||
var (
|
||||
// clients maps each open connection to whether it belongs to an admin.
|
||||
clients = make(map[*websocket.Conn]bool)
|
||||
mu sync.Mutex
|
||||
wsDB *gorm.DB
|
||||
clients = make(map[*websocket.Conn]bool)
|
||||
// mu guards clients AND serialises the write-then-broadcast sequence, so
|
||||
// that two concurrent senders cannot interleave and deliver messages to
|
||||
// different clients in different orders.
|
||||
mu sync.Mutex
|
||||
wsDB *gorm.DB
|
||||
// nextAuthorID is a per-process counter handed out on connect. It is NOT
|
||||
// a user id and has no meaning across restarts: the chat is pseudonymous,
|
||||
// and the front end only uses it to colour/group consecutive messages
|
||||
// from the same connection.
|
||||
nextAuthorID uint
|
||||
)
|
||||
|
||||
// Per-connection flood limit, separate from services.RateLimiter because it
|
||||
// counts frames on one socket rather than requests from one IP.
|
||||
const (
|
||||
rateLimitWindow = time.Second
|
||||
rateLimitMaxMsgs = 10
|
||||
@@ -70,6 +96,8 @@ type wsHistoryEvent struct {
|
||||
Messages []models.Message `json:"messages"`
|
||||
}
|
||||
|
||||
// InitWebSocket wires the package-level hub to the database and the origin
|
||||
// allow-list. Call it once, before serving.
|
||||
func InitWebSocket(database *gorm.DB, domain string) {
|
||||
wsDB = database
|
||||
allowedDomain = domain
|
||||
@@ -80,6 +108,11 @@ func InitWebSocket(database *gorm.DB, domain string) {
|
||||
func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
defer conn.Close()
|
||||
|
||||
// Registration, history read and history send all happen under one lock.
|
||||
// That is the point: it guarantees the client is already in `clients`
|
||||
// before its snapshot is taken, so a message broadcast concurrently is
|
||||
// either in the history or delivered afterwards — never dropped in the
|
||||
// gap, and never delivered before the history that would overwrite it.
|
||||
mu.Lock()
|
||||
clients[conn] = isAdmin
|
||||
nextAuthorID++
|
||||
@@ -99,11 +132,15 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// Fixed-window flood limit. Over-limit frames are dropped silently with
|
||||
// no error to the client and without resetting the window.
|
||||
msgCount := 0
|
||||
windowStart := time.Now()
|
||||
|
||||
for {
|
||||
var incoming wsIncoming
|
||||
// Any read error — clean close, network drop or malformed JSON —
|
||||
// ends the connection; there is no attempt to resynchronise.
|
||||
if err := conn.ReadJSON(&incoming); err != nil {
|
||||
break
|
||||
}
|
||||
@@ -135,10 +172,18 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
|
||||
mu.Lock()
|
||||
wsDB.Create(&msg)
|
||||
// Keep only the newest maxMessages rows. This is a soft delete
|
||||
// (models.Message has gorm.DeletedAt), so the rows stay in the table
|
||||
// with deleted_at set and GORM filters them out of later reads; the
|
||||
// table therefore grows forever even though the chat does not.
|
||||
// The subquery is itself soft-delete filtered, so already-trimmed
|
||||
// rows are not re-deleted.
|
||||
wsDB.Where("id NOT IN (?)",
|
||||
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
|
||||
).Delete(&models.Message{})
|
||||
|
||||
// Deleting from a map while ranging over it is explicitly allowed in
|
||||
// Go, so pruning dead clients inline here is safe.
|
||||
for client, clientAdmin := range clients {
|
||||
if msg.Private && !clientAdmin {
|
||||
continue
|
||||
|
||||
@@ -1,10 +1,73 @@
|
||||
#!/bin/sh
|
||||
# =============================================================================
|
||||
# certbot entrypoint — obtains the TLS certificate once, then renews forever.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# 1. One blocking `certonly` run to get (or confirm) a certificate for the
|
||||
# apex domain and its www alias.
|
||||
# 2. Then loops forever: `certbot renew` every 12 hours.
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# Production only. docker-compose.dev.yml puts this service in the `disabled`
|
||||
# profile, so `docker compose -f docker-compose.yml -f docker-compose.dev.yml
|
||||
# up` never starts it and dev uses nginx's self-signed localhost cert instead.
|
||||
#
|
||||
# HOW VALIDATION WORKS (--webroot)
|
||||
# Let's Encrypt HTTP-01: certbot writes a challenge token into
|
||||
# /var/www/certbot/.well-known/acme-challenge/ and Let's Encrypt fetches it
|
||||
# over plain HTTP on port 80. certbot itself listens on nothing — nginx is
|
||||
# the server that answers. /var/www/certbot is the ./certbot/www bind mount,
|
||||
# mounted into BOTH containers, which is what makes this work. Every nginx
|
||||
# template (including the bootstrap nginx_setup.conf) serves that path.
|
||||
# See nginx/entrypoint.sh for the first-issuance chicken-and-egg ordering.
|
||||
#
|
||||
# CERT STORAGE / SHARING
|
||||
# /etc/letsencrypt is the ./certbot/conf bind mount, also mounted read-write
|
||||
# into nginx. That directory is the private key material — it is gitignored
|
||||
# and must never be committed.
|
||||
#
|
||||
# RENEWAL TIMING AND THE RELOAD SIGNAL
|
||||
# `certbot renew` is a no-op unless the cert is within 30 days of expiry, so
|
||||
# running it every 12h is safe and well inside Let's Encrypt's rate limits —
|
||||
# it just means the renewal window is checked twice a day rather than once a
|
||||
# month. Certificates are valid 90 days, so a renewal lands ~day 60.
|
||||
#
|
||||
# IMPORTANT CAVEAT: there is NO --deploy-hook here, and this container cannot
|
||||
# signal nginx (no docker socket, no shared PID namespace). nginx loads the
|
||||
# certificate files at startup and keeps them in memory, so a freshly renewed
|
||||
# certificate is NOT picked up until nginx is reloaded or restarted. In
|
||||
# practice the site is redeployed often enough (the Gitea Actions deploy
|
||||
# workflow runs `docker compose up -d --build` on every push to main, which
|
||||
# recreates nginx) that this has not bitten — but on a quiet month it could.
|
||||
# See DEPLOYMENT.md "Renew certificates" for the manual reload, and the
|
||||
# proposal to add a reload hook.
|
||||
#
|
||||
# ENV VARS REQUIRED (from ./.env via `env_file`)
|
||||
# DOMAIN apex domain; both $DOMAIN and www.$DOMAIN go on one certificate,
|
||||
# filed under --cert-name $DOMAIN so the path nginx expects
|
||||
# (/etc/letsencrypt/live/$DOMAIN/) is stable regardless of which
|
||||
# name certbot would otherwise have chosen.
|
||||
# EMAIL registration/expiry-notice address for the ACME account.
|
||||
#
|
||||
# FLAGS WORTH KNOWING
|
||||
# --agree-tos --non-interactive never prompt; required in a container.
|
||||
# --expand if a cert already exists under this name but
|
||||
# covers a different set of names, replace it
|
||||
# rather than erroring out.
|
||||
#
|
||||
# ASSUMES EXISTS
|
||||
# /var/www/certbot (shared ACME webroot, served by nginx on port 80)
|
||||
# /etc/letsencrypt (persistent cert store, shared with nginx)
|
||||
# Port 80 reachable from the public internet for $DOMAIN and www.$DOMAIN.
|
||||
# =============================================================================
|
||||
|
||||
certbot certonly --webroot -w /var/www/certbot \
|
||||
--email ${EMAIL} \
|
||||
-d ${DOMAIN} -d www.${DOMAIN} \
|
||||
--cert-name ${DOMAIN} \
|
||||
--agree-tos --non-interactive --expand;
|
||||
|
||||
# Exit promptly on `docker compose stop` instead of sitting out the 12h sleep.
|
||||
trap exit TERM;
|
||||
|
||||
while :; do
|
||||
|
||||
@@ -1,22 +1,70 @@
|
||||
# =============================================================================
|
||||
# docker-compose.dev.yml — local development OVERRIDE layer.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# This file is never used alone. It is merged on top of docker-compose.yml:
|
||||
# docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||
# Compose merges per-key: `environment` entries are added to (not replacing)
|
||||
# the base ones, while `command` and `ports` are replaced wholesale. Anything
|
||||
# not mentioned here keeps its production definition.
|
||||
#
|
||||
# WHAT CHANGES vs PRODUCTION
|
||||
# - vue : one-shot `vite build` becomes the long-running Vite dev server
|
||||
# with the source bind-mounted for hot reload.
|
||||
# - backend : dev flags on, including database seeding.
|
||||
# - nginx : DEV_MODE=true, which makes its entrypoint render
|
||||
# nginx_dev.conf.template and self-sign a localhost certificate.
|
||||
# - hasura : console and dev mode enabled so the GraphQL console is usable.
|
||||
# - python : uvicorn --reload with the app source bind-mounted.
|
||||
# - certbot : disabled entirely.
|
||||
#
|
||||
# HOW TO REACH IT
|
||||
# http://localhost (HTTPS also works on :443 with the self-signed cert, which
|
||||
# the browser will warn about — that is expected).
|
||||
#
|
||||
# NOT USED ON THE PI. The deploy workflow runs plain `docker compose up`.
|
||||
# =============================================================================
|
||||
|
||||
services:
|
||||
vue:
|
||||
# Replaces the one-shot `vite build`: the container now stays up serving
|
||||
# the Vite dev server on :5173, which nginx_dev.conf proxies `/` to.
|
||||
command: ["npm", "run", "dev"]
|
||||
volumes:
|
||||
- ./vue:/app
|
||||
# The two bare paths are ANONYMOUS-VOLUME MASKS, not typos. Binding
|
||||
# ./vue over /app would otherwise hide the node_modules and WASM
|
||||
# output that were installed/built *inside* the image. Declaring
|
||||
# them as anonymous volumes re-exposes the image's copies on top of
|
||||
# the bind mount, so `npm ci` and wasm-pack results survive and the
|
||||
# host does not need node_modules or a Rust toolchain at all.
|
||||
- /app/node_modules
|
||||
- /app/src/wasm
|
||||
environment:
|
||||
- NODE_ENV=development
|
||||
backend:
|
||||
environment:
|
||||
# Spotify requires an exact redirect URI match, so dev needs its own
|
||||
# (and this localhost URI must be registered in the Spotify app).
|
||||
- SPOTIFY_REDIRECT_URI=https://localhost/api/spotify/callback
|
||||
# GraphQL playground + introspection: convenient locally, and off in
|
||||
# production so the schema is not published to the world.
|
||||
- GQL_PLAYGROUND=true
|
||||
- GQL_INTROSPECTION=true
|
||||
- DEV_MODE=true
|
||||
# SEED_DB=true makes the backend populate the database with test
|
||||
# posts/users/messages on startup (services/ seeding). Safe here
|
||||
# because dev uses a throwaway local dbdata volume; it is NEVER set
|
||||
# in production — seeding a live database would inject fake content.
|
||||
- SEED_DB=true
|
||||
nginx:
|
||||
environment:
|
||||
# The single switch that selects nginx_dev.conf.template and the
|
||||
# self-signed localhost certificate. See nginx/entrypoint.sh.
|
||||
- DEV_MODE=true
|
||||
# Same mapping as the base file; restated because compose replaces the
|
||||
# `ports` list rather than merging it, so omitting it here would be fine
|
||||
# but restating it makes the dev surface explicit.
|
||||
ports:
|
||||
- 80:80
|
||||
- 443:443
|
||||
@@ -25,9 +73,18 @@ services:
|
||||
HASURA_GRAPHQL_ENABLE_CONSOLE: "true"
|
||||
HASURA_GRAPHQL_DEV_MODE: "true"
|
||||
python:
|
||||
# Same command as the Dockerfile's CMD plus --reload, paired with the
|
||||
# source bind mount below so editing python/app/ restarts uvicorn.
|
||||
# ${PYTHON_PORT} here is interpolated by the compose CLI from ./.env,
|
||||
# not by the container's shell.
|
||||
command: ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PYTHON_PORT:-8000} --root-path /py --reload"]
|
||||
volumes:
|
||||
- ./python/app:/app/app
|
||||
certbot:
|
||||
# Profiles are opt-in: a service with a profile is only started when
|
||||
# that profile is explicitly requested. Nothing ever requests
|
||||
# "disabled", so this is the idiomatic way to switch a service off in an
|
||||
# override file. Dev gets TLS from nginx's self-signed cert instead, and
|
||||
# Let's Encrypt could not validate localhost anyway.
|
||||
profiles:
|
||||
- disabled
|
||||
|
||||
+171
-3
@@ -1,19 +1,82 @@
|
||||
# =============================================================================
|
||||
# docker-compose.yml — production topology for the whole site.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# Defines every container, the single bridge network they share, and the
|
||||
# named volumes that survive restarts. This file alone IS production:
|
||||
# docker compose up --build
|
||||
# Dev layers docker-compose.dev.yml on top of it (see that file).
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# On the Raspberry Pi, via the Gitea Actions deploy workflow
|
||||
# (.gitea/workflows/deploy.yaml) on every push to main, and by hand.
|
||||
#
|
||||
# ENV VARS
|
||||
# Everything interpolated as ${VAR} below is read by the docker compose CLI
|
||||
# from ./.env at the repo root (which is gitignored — see sync-secrets.sh for
|
||||
# how it is distributed to the Pi). Note the two distinct mechanisms:
|
||||
# - ${VAR} in this file -> substituted by compose when parsing
|
||||
# - `env_file: ./.env` -> the whole file injected into the container
|
||||
# Many services need both: the container name comes from substitution, the
|
||||
# app config from env_file.
|
||||
#
|
||||
# Required by this file: POSTGRES_{USER,PASSWORD,DB,PORT,HOST},
|
||||
# POSTGRES_GITEA_DB, BACKEND_HOST, HASURA_HOST, HASURA_GRAPHQL_ADMIN_SECRET,
|
||||
# ICECAST_HOST, QUARTZ_HOST, GITEA_HOST, OBSIDIAN_DIR, and the GITEA_*
|
||||
# secrets. PYTHON_HOST/PYTHON_PORT/TFL_APP_KEY/LIQUIDSOAP_HARBOR_PORT have
|
||||
# inline defaults.
|
||||
#
|
||||
# NAMING CONVENTION / WHY container_name IS SET FROM env
|
||||
# Service discovery is by container name on app-network. nginx builds its
|
||||
# upstreams from the same ${*_HOST} variables (nginx/entrypoint.sh), so
|
||||
# naming the containers from .env keeps the proxy and the containers in sync
|
||||
# from one source of truth. Renaming a *_HOST value renames the container AND
|
||||
# repoints nginx at it — do not change one without the other.
|
||||
#
|
||||
# WHAT IS PUBLISHED TO THE HOST
|
||||
# Only nginx (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor
|
||||
# port. Everything else is reachable only from inside app-network, which is
|
||||
# why the backend, db, hasura, quartz and python have no `ports:` — they are
|
||||
# deliberately not exposed and are reached through nginx.
|
||||
# =============================================================================
|
||||
|
||||
networks:
|
||||
# One flat bridge network; every service resolves every other by container
|
||||
# name via docker's embedded DNS at 172.28.0.11 (nginx configs point their
|
||||
# `resolver` there). The subnet is pinned explicitly so it cannot collide
|
||||
# with the Pi's LAN range or wander between compose versions.
|
||||
app-network:
|
||||
driver: bridge
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.28.0.0/16
|
||||
|
||||
# PERSISTENT vs EPHEMERAL state
|
||||
# Named volumes below survive `docker compose down` and container rebuilds;
|
||||
# they are only destroyed by `docker compose down -v` or an explicit
|
||||
# `docker volume rm`. Bind mounts (./gitea/data, ./backend/token, ./logs,
|
||||
# ./certbot/conf) live in the repo checkout on the Pi and survive everything
|
||||
# short of deleting the directory. Anything inside a container's own
|
||||
# filesystem is ephemeral and gone on rebuild.
|
||||
volumes:
|
||||
# Postgres database
|
||||
# Postgres database — PERSISTENT. Holds the app DB *and* the Gitea DB.
|
||||
# Deleting this wipes posts, users, messages and every git repo's metadata.
|
||||
dbdata:
|
||||
# File upload
|
||||
# File upload — PERSISTENT. Written by the backend at /backend/uploads,
|
||||
# served read-only by nginx at /uploads/. Shared so nginx can serve user
|
||||
# uploads without proxying through the Go process.
|
||||
uploads:
|
||||
# Vue build
|
||||
# Vue build — EPHEMERAL in spirit but a named volume for handoff: the
|
||||
# one-shot `vue` container writes the built SPA here and exits; nginx mounts
|
||||
# it at /etc/nginx/html and serves it. Repopulated on every rebuild.
|
||||
vue_dist:
|
||||
|
||||
services:
|
||||
# One-shot build container, NOT a long-running service. `vite build` writes
|
||||
# the SPA into the shared vue_dist volume and the container exits 0. That
|
||||
# exit is expected — `docker compose ps` showing vue as Exited is healthy.
|
||||
# In dev this same service is overridden to run the Vite dev server instead
|
||||
# (docker-compose.dev.yml) and does stay up.
|
||||
vue:
|
||||
build:
|
||||
context: ./vue
|
||||
@@ -24,6 +87,18 @@ services:
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
# The only public entrypoint. Terminates TLS, serves the SPA, reverse-proxies
|
||||
# everything else. Its config is chosen at container start — see
|
||||
# nginx/entrypoint.sh for the DEV_MODE / cert-present / bootstrap decision.
|
||||
#
|
||||
# START ORDERING: these `depends_on` entries are the plain list form, which
|
||||
# only waits for each container to be *created and started*, NOT for it to be
|
||||
# ready or healthy. That is deliberate — nginx's `resolver 127.0.0.11` means
|
||||
# upstreams are resolved per-request, so a late-starting backend produces a
|
||||
# temporary 502 rather than a failed nginx boot. The one ordering nginx
|
||||
# genuinely cares about (the Vue build finishing) is handled by the polling
|
||||
# loop in its entrypoint, because depends_on cannot express "wait for a
|
||||
# one-shot container to exit successfully" here.
|
||||
nginx:
|
||||
build:
|
||||
context: ./nginx
|
||||
@@ -45,11 +120,21 @@ services:
|
||||
- 80:80
|
||||
- 443:443
|
||||
volumes:
|
||||
# Shared with certbot: the cert store nginx reads and certbot writes.
|
||||
# PERSISTENT, and private key material — gitignored, never commit.
|
||||
- ./certbot/conf:/etc/letsencrypt
|
||||
# Shared with certbot: the ACME HTTP-01 challenge webroot. certbot drops
|
||||
# tokens in, nginx serves them on port 80.
|
||||
- ./certbot/www:/var/www/certbot
|
||||
- uploads:/uploads
|
||||
# The SPA written by the one-shot `vue` container.
|
||||
- vue_dist:/etc/nginx/html
|
||||
|
||||
# Obtains the cert once, then renews every 12h forever. Disabled in dev via
|
||||
# the `disabled` profile in docker-compose.dev.yml. Note this is the stock
|
||||
# certbot image with our script bind-mounted over the entrypoint, so editing
|
||||
# certbot/entrypoint.sh takes effect on restart with no rebuild. Version is
|
||||
# pinned so a certbot release cannot change behaviour under us on redeploy.
|
||||
certbot:
|
||||
image: certbot/certbot:v3.1.0
|
||||
container_name: certbot
|
||||
@@ -76,11 +161,24 @@ services:
|
||||
env_file:
|
||||
- ./.env
|
||||
volumes:
|
||||
# PERSISTENT, and the subtle one: the Spotify OAuth refresh token is
|
||||
# written here as spotify_token.json. Without this bind mount the token
|
||||
# would live in the container filesystem and be destroyed on every
|
||||
# rebuild, forcing a manual re-authorisation of Spotify after each
|
||||
# deploy. Gitignored (it is a credential).
|
||||
- ./backend/token/:/backend/token
|
||||
# The Obsidian vault on the host, read by the backend for the notes API.
|
||||
# Same directory is mounted read-only into quartz to build the notes site.
|
||||
- ${OBSIDIAN_DIR}:/backend/notes
|
||||
- ./logs:/backend/logs
|
||||
# Same named volume nginx serves at /uploads/ — backend writes, nginx reads.
|
||||
- uploads:/backend/uploads
|
||||
# Shared with icecast2, which plays these as the radio fallback playlist;
|
||||
# the backend reads them to report what is queued.
|
||||
- ./icecast2/fallback_music:/backend/fallback_music
|
||||
# Reported to docker (and therefore to autoheal, below), which restarts the
|
||||
# container after 3 consecutive failures ~90s apart. start_period gives the
|
||||
# Go process 10s to bind before failures start counting.
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:8080/"]
|
||||
interval: 30s
|
||||
@@ -88,6 +186,13 @@ services:
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
# Watchdog: docker itself marks a container `unhealthy` but never acts on it.
|
||||
# autoheal polls the docker socket and restarts anything that goes unhealthy.
|
||||
# AUTOHEAL_CONTAINER_LABEL=all means "watch every container that defines a
|
||||
# healthcheck" (i.e. backend and python) rather than only labelled ones.
|
||||
# It mounts the docker socket, which is effectively root on the host — that
|
||||
# is the price of the feature; keep the image pinned-ish and trusted.
|
||||
# Deliberately NOT on app-network: it talks only to the socket.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal:latest
|
||||
container_name: autoheal
|
||||
@@ -99,6 +204,12 @@ services:
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
# Single Postgres instance serving TWO databases: ${POSTGRES_DB} for the Go
|
||||
# backend and ${POSTGRES_GITEA_DB} for Gitea. The postgres image only creates
|
||||
# POSTGRES_DB on first init, so the Gitea database was created by hand once;
|
||||
# a from-scratch restore must `createdb` it before Gitea will start.
|
||||
# Schema for the app DB comes from GORM auto-migration at backend start —
|
||||
# there are no migration files.
|
||||
db:
|
||||
image: postgres:16
|
||||
container_name: "${POSTGRES_HOST}"
|
||||
@@ -110,6 +221,11 @@ services:
|
||||
volumes:
|
||||
- dbdata:/var/lib/postgresql/data
|
||||
|
||||
# Admin-only DB browser, reached at /hasura/. Console and dev mode are OFF in
|
||||
# production (turned on by the dev override). It is additionally gated in
|
||||
# nginx by an `auth_request` subrequest to the backend's /auth/validate-admin,
|
||||
# so an admin cookie is required before the request ever reaches Hasura —
|
||||
# the admin secret alone is not the only line of defence.
|
||||
hasura:
|
||||
image: hasura/graphql-engine:v2.44.0
|
||||
container_name: "${HASURA_HOST}"
|
||||
@@ -125,6 +241,17 @@ services:
|
||||
HASURA_GRAPHQL_DEV_MODE: "false"
|
||||
HASURA_GRAPHQL_ENABLED_LOG_TYPES: "startup, http-log, webhook-log, websocket-log, query-log"
|
||||
|
||||
# Internet radio: one container running BOTH icecast2 (the streaming server
|
||||
# listeners connect to, proxied at /radio/) and liquidsoap (the source that
|
||||
# feeds it). See icecast2/entrypoint.sh.
|
||||
#
|
||||
# This is the only non-nginx service that publishes a host port, and it has
|
||||
# to: LIQUIDSOAP_HARBOR_PORT is the live-DJ input. A broadcasting client
|
||||
# (e.g. butt) connects straight to the Pi on that port with the icecast
|
||||
# source password and pre-empts the fallback playlist. It is NOT proxied
|
||||
# through nginx because it is a raw source protocol, not HTTP the SPA uses.
|
||||
# Note the host:container mapping uses the same variable on both sides, so
|
||||
# the published port always matches what liquidsoap actually binds.
|
||||
icecast2:
|
||||
build:
|
||||
context: ./icecast2
|
||||
@@ -140,6 +267,11 @@ services:
|
||||
ports:
|
||||
- "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}"
|
||||
|
||||
# Quartz renders the Obsidian vault into the notes site at /notes/ (also
|
||||
# behind the nginx admin auth_request). The vault is mounted READ-ONLY so a
|
||||
# bug in Quartz can never write into the real notes. Quartz is run in
|
||||
# `build --serve` watch mode, so edits to the vault on the host appear
|
||||
# without restarting the container.
|
||||
quartz:
|
||||
build:
|
||||
context: ./quartz
|
||||
@@ -153,6 +285,13 @@ services:
|
||||
volumes:
|
||||
- ${OBSIDIAN_DIR}:/quartz/content:ro
|
||||
|
||||
# FastAPI side-service, proxied at /py/ with the prefix stripped by nginx.
|
||||
# ROOT_PATH=/py tells FastAPI it is mounted under a prefix so the generated
|
||||
# OpenAPI/Swagger URLs (/py/docs) are correct even though the app's own
|
||||
# routes are written relative to /.
|
||||
# Note this service uses `environment:` with an explicit allow-list rather
|
||||
# than `env_file: ./.env` — it only gets the three variables it needs and
|
||||
# never sees the database password, Spotify secrets, or API keys.
|
||||
python:
|
||||
build:
|
||||
context: ./python
|
||||
@@ -172,6 +311,22 @@ services:
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
# Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI
|
||||
# server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to
|
||||
# main, executed by the act_runner that lives outside docker (gitea-runner/).
|
||||
#
|
||||
# ROOTLESS image: runs as an unprivileged user, so config lives in /etc/gitea
|
||||
# and data in /var/lib/gitea (not /data as in the root image) — that is why
|
||||
# the bind mounts look unlike most Gitea compose examples.
|
||||
#
|
||||
# The GITEA__section__KEY environment convention is Gitea's own: each maps to
|
||||
# an app.ini key and overrides the file at runtime, which is how the secrets
|
||||
# stay in .env instead of in the committed app.ini.template.
|
||||
#
|
||||
# entrypoint is overridden to run our wrapper (which materialises app.ini
|
||||
# from the template on first boot) before handing off to Gitea's real
|
||||
# docker-entrypoint.sh. dumb-init is kept as PID 1 for correct signal/zombie
|
||||
# handling, exactly as the stock image does it.
|
||||
gitea:
|
||||
image: docker.gitea.com/gitea:1.25.4-rootless
|
||||
container_name: "${GITEA_HOST}"
|
||||
@@ -191,13 +346,26 @@ services:
|
||||
- USER_GID=1000
|
||||
restart: always
|
||||
volumes:
|
||||
# PERSISTENT: repositories, LFS objects, avatars, sessions. The git data
|
||||
# itself. (Gitea's *relational* data is in Postgres, not here.)
|
||||
- ./gitea/data:/var/lib/gitea
|
||||
# PERSISTENT: app.ini is generated into this host directory on first boot
|
||||
# and then edited by Gitea itself, so it is gitignored — only the
|
||||
# template is committed.
|
||||
- ./gitea/config:/etc/gitea
|
||||
# Mounted over the config dir so the wrapper script is available at the
|
||||
# path the overridden entrypoint points at.
|
||||
- ./gitea/entrypoint.sh:/etc/gitea/entrypoint.sh:ro
|
||||
# Match the Pi's clock/zone so commit and CI timestamps are local time.
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
ports:
|
||||
# 2222 = Gitea's *built-in* SSH server (the rootless image cannot use 22).
|
||||
# Clones use ssh://git@host:2222/... — including the deploy workflow,
|
||||
# which fetches from ssh://git@localhost:2222.
|
||||
- "2222:2222"
|
||||
# 3000 = HTTP, published directly as well as proxied at /gitea/, because
|
||||
# the act_runner registers against http://localhost:3000 from the host.
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
@@ -1,4 +1,33 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# gitea-runner/download.sh — fetch the act_runner binary for this machine.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# Downloads the correct act_runner release asset for the host CPU and drops
|
||||
# it next to this script as ./act_runner (gitignored — a binary, not source).
|
||||
#
|
||||
# WHY IT IS A SCRIPT AND NOT A CONTAINER
|
||||
# The runner executes the deploy workflow, which itself runs
|
||||
# `docker compose up -d --build` against this stack. Running it inside the
|
||||
# stack would mean a container restarting its own parent mid-job. So the
|
||||
# runner lives OUTSIDE docker, directly on the Pi, and is the one moving part
|
||||
# of this repo that docker compose does not manage.
|
||||
#
|
||||
# ARCHITECTURE SELECTION (the Raspberry Pi bit)
|
||||
# uname -m decides the asset. aarch64 is the 64-bit Pi OS case and is what
|
||||
# this deployment actually uses; armv7l covers a 32-bit Pi OS install and
|
||||
# x86_64 covers running the same script on a dev laptop. An unknown arch is a
|
||||
# hard error rather than a silent wrong download.
|
||||
#
|
||||
# VERSION is pinned so a runner upgrade is an explicit commit, never a surprise
|
||||
# on a re-run. Bump it here, delete ./act_runner, and re-run to upgrade.
|
||||
#
|
||||
# SCRIPT_DIR is resolved so the binary always lands beside the script even when
|
||||
# invoked from another directory.
|
||||
#
|
||||
# USAGE: bash gitea-runner/download.sh (run.sh calls it automatically if the
|
||||
# binary is missing)
|
||||
# =============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
VERSION="0.2.11"
|
||||
|
||||
+47
-1
@@ -1,5 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# =============================================================================
|
||||
# gitea-runner/run.sh — register (once) and then run the Gitea Actions runner.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# 1. Downloads the act_runner binary if it is not already present.
|
||||
# 2. Blocks until Gitea answers on http://localhost:3000.
|
||||
# 3. Registers with Gitea the first time only.
|
||||
# 4. execs the runner daemon in the foreground.
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# On the Pi, outside docker, as a long-lived process (systemd unit or nohup).
|
||||
# It must be started from THIS directory: the script uses relative paths
|
||||
# (./act_runner, .runner) and `act_runner daemon` looks for .runner in the
|
||||
# current working directory.
|
||||
#
|
||||
# WHY IT WAITS FOR PORT 3000
|
||||
# On a Pi reboot this process and the docker stack race. Registering or
|
||||
# starting the daemon against a Gitea that is not up yet fails permanently
|
||||
# rather than retrying, so the loop polls (forever, by design — there is no
|
||||
# sensible timeout when the answer is "wait longer") until Gitea responds.
|
||||
# It targets localhost:3000, the port docker-compose.yml publishes directly,
|
||||
# NOT the public /gitea/ path through nginx — so the runner keeps working
|
||||
# even while TLS or nginx is broken.
|
||||
#
|
||||
# THE REGISTRATION TOKEN (one-shot, and easy to get wrong)
|
||||
# GITEA_RUNNER_REGISTRATION_TOKEN comes from ./.env and is generated in the
|
||||
# Gitea web UI (Site Administration -> Actions -> Runners -> Create new
|
||||
# runner). It is a single-use enrolment token, NOT a lasting credential:
|
||||
# registration exchanges it for a permanent runner identity written to the
|
||||
# .runner file (gitignored — that file IS the real credential).
|
||||
#
|
||||
# The `if [ ! -f .runner ]` guard is what makes this idempotent. Once .runner
|
||||
# exists the token is never used again and may safely be stale in .env. To
|
||||
# re-register a runner you must delete .runner AND mint a FRESH token in the
|
||||
# UI — reusing the old one will fail.
|
||||
#
|
||||
# --labels self-hosted must match `runs-on: self-hosted` in
|
||||
# .gitea/workflows/*.yaml, or jobs queue forever with no runner picking them up.
|
||||
#
|
||||
# ENV VARS
|
||||
# GITEA_RUNNER_REGISTRATION_TOKEN required for first registration only
|
||||
# GITEA_RUNNER_NAME optional, defaults to "pi-runner"
|
||||
# (this script does not source .env itself — export them or use an
|
||||
# EnvironmentFile in the systemd unit)
|
||||
#
|
||||
# Diagnostics go to stderr so stdout stays clean for the daemon's own output.
|
||||
# =============================================================================
|
||||
if [ ! -f ./act_runner ]; then
|
||||
echo "act_runner binary not found. Downloading..." >&2
|
||||
bash "$(dirname "$0")/download.sh"
|
||||
|
||||
@@ -1,3 +1,35 @@
|
||||
; =============================================================================
|
||||
; app.ini.template — seed configuration for Gitea, copied to app.ini on the
|
||||
; FIRST boot on a host by gitea/entrypoint.sh and never touched again after.
|
||||
;
|
||||
; IMPORTANT: editing this file does nothing to a running install. Gitea owns
|
||||
; ./gitea/config/app.ini (it rewrites it from the web UI) and that real file is
|
||||
; gitignored because it accumulates generated secrets.
|
||||
;
|
||||
; SECRET FIELDS ARE DELIBERATELY BLANK HERE
|
||||
; LFS_JWT_SECRET, PASSWD, SECRET_KEY and JWT_SECRET are empty on purpose so
|
||||
; nothing sensitive is committed. Real values arrive at runtime as
|
||||
; GITEA__section__KEY environment variables from ./.env (see
|
||||
; docker-compose.yml), which override app.ini. SECRET_KEY is the exception —
|
||||
; Gitea generates one itself on first run and writes it into the live app.ini.
|
||||
;
|
||||
; SETTINGS WORTH KNOWING
|
||||
; ROOT_URL must match the public path nginx serves Gitea at (/gitea/), or
|
||||
; every link, clone URL and OAuth redirect Gitea emits will be wrong.
|
||||
; START_SSH_SERVER = true with SSH_PORT 2222: the rootless image cannot bind
|
||||
; 22 and cannot use the host's sshd, so Gitea runs its own Go SSH server.
|
||||
; 2222 is published in docker-compose.yml; the deploy workflow clones over
|
||||
; ssh://git@localhost:2222.
|
||||
; REVERSE_PROXY_LIMIT = 1 / TRUSTED_PROXIES = * : trust exactly one hop of
|
||||
; X-Forwarded-For, i.e. our nginx, so Gitea logs real client IPs. This is
|
||||
; only safe because nginx is the sole edge.
|
||||
; INSTALL_LOCK = true skips the first-run web installer.
|
||||
; DISABLE_REGISTRATION = true — single-user instance; nobody can sign up.
|
||||
; OFFLINE_MODE = true — no calls out to gravatar/CDNs.
|
||||
; DB_TYPE postgres pointing at the shared `db` container, in its own database
|
||||
; alongside the app's. WORK_PATH/APP_DATA_PATH are /var/lib/gitea, the
|
||||
; rootless image's layout (the root image uses /data instead).
|
||||
; =============================================================================
|
||||
APP_NAME = Gitea: Git with a cup of tea
|
||||
RUN_USER = git
|
||||
RUN_MODE = prod
|
||||
|
||||
@@ -1,4 +1,42 @@
|
||||
#!/bin/sh
|
||||
# =============================================================================
|
||||
# gitea entrypoint wrapper — materialise app.ini on first boot, then hand off.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# Gitea refuses to start without /etc/gitea/app.ini, but app.ini is a live
|
||||
# file: Gitea rewrites it when you change settings in the web UI, and it ends
|
||||
# up holding generated secrets (SECRET_KEY, INTERNAL_TOKEN, ...). So it is
|
||||
# gitignored and NOT committed. Only app.ini.template is in git, with the
|
||||
# secret fields left blank. This script copies the template into place the
|
||||
# first time the container ever runs on a host, then gets out of the way.
|
||||
#
|
||||
# The `if [ ! -f ]` guard is the important part: on every subsequent boot the
|
||||
# real app.ini already exists in the ./gitea/config bind mount and is left
|
||||
# completely alone. Editing app.ini.template therefore has NO effect on an
|
||||
# existing install — you must edit ./gitea/config/app.ini directly (or delete
|
||||
# it to re-seed, which loses any UI-made settings).
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# Container start. docker-compose.yml overrides gitea's entrypoint to
|
||||
# ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"], keeping dumb-init
|
||||
# as PID 1 for signal handling exactly as the stock image does, and inserting
|
||||
# this script ahead of Gitea's own docker-entrypoint.sh.
|
||||
#
|
||||
# WHERE THE SECRETS ACTUALLY COME FROM
|
||||
# Not from the template. docker-compose.yml passes GITEA__section__KEY
|
||||
# environment variables (database credentials, LFS_JWT_SECRET,
|
||||
# INTERNAL_TOKEN, OAUTH2 JWT_SECRET) sourced from ./.env; Gitea applies those
|
||||
# over whatever app.ini says. That is why the template can safely ship with
|
||||
# those fields empty.
|
||||
#
|
||||
# ASSUMES EXISTS
|
||||
# /etc/gitea - bind mount of ./gitea/config (persistent, gitignored)
|
||||
# /etc/gitea/app.ini.template - committed, lives in that same directory
|
||||
# /usr/local/bin/docker-entrypoint.sh - Gitea's real entrypoint
|
||||
#
|
||||
# `exec` replaces this shell so Gitea inherits PID and receives signals
|
||||
# directly instead of through a lingering parent.
|
||||
# =============================================================================
|
||||
set -e
|
||||
|
||||
# Generate app.ini from template if it doesn't already exist
|
||||
|
||||
@@ -1,3 +1,31 @@
|
||||
# =============================================================================
|
||||
# Radio image — liquidsoap base with icecast2 added on top.
|
||||
#
|
||||
# BASE CHOICE: savonet/liquidsoap:v2.3.2, pinned. Liquidsoap is by far the
|
||||
# harder of the two to install (OCaml toolchain, many audio codecs), so the
|
||||
# image starts from the official liquidsoap build and adds icecast2 from apt,
|
||||
# rather than the other way round. Both daemons then run in one container so
|
||||
# liquidsoap can reach icecast on localhost — see icecast2/entrypoint.sh.
|
||||
#
|
||||
# PACKAGES
|
||||
# icecast2 the streaming server itself
|
||||
# gettext provides `envsubst` for rendering the two config templates
|
||||
# media-types the /etc/mime.types database; without it icecast serves the
|
||||
# stream and its status pages with wrong content types
|
||||
#
|
||||
# THE USER SWITCH: apt needs root, so the image switches to root, installs,
|
||||
# creates an unprivileged `radio` user, chowns everything the two daemons will
|
||||
# need to write (icecast config, its logs, the music dir, the liquidsoap config
|
||||
# dir) and then drops back to `radio` for the rest. Neither daemon runs as
|
||||
# root, which is also why icecast.xml sets <chroot>0</chroot> — an unprivileged
|
||||
# process cannot chroot anyway.
|
||||
#
|
||||
# The chown of /music matters even though it is mounted read-only at runtime:
|
||||
# the mount inherits ownership from the host, and the directory must exist
|
||||
# before the mount lands.
|
||||
#
|
||||
# The apt install is Debian-based and multi-arch; no platform pin needed on the Pi.
|
||||
# =============================================================================
|
||||
FROM savonet/liquidsoap:v2.3.2
|
||||
USER root
|
||||
RUN apt-get update \
|
||||
|
||||
@@ -1,12 +1,62 @@
|
||||
#!/bin/bash
|
||||
# =============================================================================
|
||||
# icecast2 entrypoint — runs the streaming server AND its audio source together.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# This one container holds two cooperating daemons:
|
||||
# icecast2 - the HTTP streaming server listeners connect to. nginx
|
||||
# proxies /radio/ to it.
|
||||
# liquidsoap - the *source*: it decides what audio to play and pushes a
|
||||
# single MP3 stream into icecast's mount point.
|
||||
# They are colocated because liquidsoap connects to icecast over
|
||||
# host="localhost" (see stream.liq.template) — no network hop, and the source
|
||||
# password never leaves the container.
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# Container start (ENTRYPOINT), in both dev and production.
|
||||
#
|
||||
# THE TEMPLATING STEP
|
||||
# Both configs are rendered by bare `envsubst` (no allow-list) because unlike
|
||||
# the nginx templates, neither icecast.xml nor stream.liq has any legitimate
|
||||
# dollar-token of its own — every ${VAR} in them is meant to be substituted,
|
||||
# so an unrestricted envsubst is safe here. NOTE the consequence: any
|
||||
# referenced variable that is unset silently becomes an empty string, which
|
||||
# for a password field means "empty password" rather than an error.
|
||||
#
|
||||
# STARTUP ORDER AND THE sleep 2
|
||||
# liquidsoap's output.icecast connects to icecast as a client on startup and
|
||||
# there is no readiness check available, so the script backgrounds icecast,
|
||||
# waits a fixed 2 seconds for it to bind its port, then starts liquidsoap.
|
||||
# It is a race, not a guarantee — but `fallible=true` in stream.liq means
|
||||
# liquidsoap retries the connection rather than dying if it loses.
|
||||
#
|
||||
# PROCESS SUPERVISION
|
||||
# `wait -n` returns as soon as EITHER daemon exits. We then kill whatever is
|
||||
# still running and exit 1, so a half-dead container (icecast up, liquidsoap
|
||||
# dead = silence forever) becomes a full crash that docker's
|
||||
# `restart: always` will recycle. Exiting non-zero is deliberate.
|
||||
#
|
||||
# ENV VARS REQUIRED (from ./.env)
|
||||
# ICECAST_SOURCE_PASSWORD shared by icecast (accepts) and liquidsoap (sends)
|
||||
# ICECAST_RELAY_PASSWORD for relay clients
|
||||
# ICECAST_ADMIN_USER / ICECAST_ADMIN_PASSWORD icecast web admin
|
||||
# ICECAST_HOST / ICECAST_PORT / ICECAST_MOUNT listener-facing stream
|
||||
# LIQUIDSOAP_HARBOR_MOUNT / LIQUIDSOAP_HARBOR_PORT live DJ input
|
||||
#
|
||||
# ASSUMES EXISTS
|
||||
# /music - read-only bind mount of ./icecast2/fallback_music, the fallback
|
||||
# playlist. If it is empty the stream falls through to silence.
|
||||
# =============================================================================
|
||||
set -e
|
||||
|
||||
envsubst < /etc/icecast2/icecast.xml.template > /etc/icecast2/icecast.xml
|
||||
envsubst < /etc/liquidsoap/stream.liq.template > /etc/liquidsoap/stream.liq
|
||||
|
||||
icecast2 -c /etc/icecast2/icecast.xml &
|
||||
# Give icecast time to bind before liquidsoap tries to connect as a source.
|
||||
sleep 2
|
||||
liquidsoap /etc/liquidsoap/stream.liq &
|
||||
# Exit as soon as either daemon dies, then take the other down with it.
|
||||
wait -n
|
||||
kill $(jobs -p) 2>/dev/null || true
|
||||
exit 1
|
||||
|
||||
@@ -1,3 +1,34 @@
|
||||
<!--
|
||||
=============================================================================
|
||||
icecast.xml.template — icecast2 server config.
|
||||
|
||||
RENDERED BY icecast2/entrypoint.sh with bare envsubst into
|
||||
/etc/icecast2/icecast.xml at container start. Every VAR placeholder comes from ./.env,
|
||||
which is how the four passwords stay out of git. An unset variable becomes an
|
||||
EMPTY password rather than an error, so verify .env is complete after any
|
||||
change to it.
|
||||
|
||||
THE FOUR CREDENTIALS, and who uses each:
|
||||
source-password - liquidsoap uses it to push the stream in, and the live
|
||||
DJ client uses the same value against the liquidsoap
|
||||
harbor port. Anyone with it can take over the station.
|
||||
relay-password - for a downstream icecast relaying this stream.
|
||||
admin-user /
|
||||
admin-password - the icecast web admin UI. Reachable through the /radio/
|
||||
proxy, so treat it as internet-facing.
|
||||
|
||||
OTHER NOTES:
|
||||
<alias source="/" destination="/status.xsl"/> makes the bare /radio/ URL
|
||||
show the status page instead of a 404.
|
||||
<sources>2</sources> is the minimum that works: one slot for the liquidsoap
|
||||
output and one spare for a reconnect overlapping the old connection.
|
||||
Lowering it to 1 causes reconnect failures.
|
||||
<chroot>0</chroot> — no chroot, because the container already provides the
|
||||
isolation and the process does not run as root.
|
||||
Listener cap is 100, which is far above what a Raspberry Pi's uplink can
|
||||
actually sustain; it is a safety ceiling, not a target.
|
||||
=============================================================================
|
||||
-->
|
||||
<icecast>
|
||||
<authentication>
|
||||
<source-password>${ICECAST_SOURCE_PASSWORD}</source-password>
|
||||
|
||||
@@ -1,3 +1,41 @@
|
||||
# =============================================================================
|
||||
# stream.liq.template — liquidsoap source script for the internet radio.
|
||||
#
|
||||
# RENDERED BY icecast2/entrypoint.sh with bare envsubst into
|
||||
# /etc/liquidsoap/stream.liq at container start. Every VAR placeholder below comes from
|
||||
# ./.env; an unset one silently becomes an empty string.
|
||||
#
|
||||
# WHAT IT BUILDS, bottom of the fallback chain upward:
|
||||
# blank() - digital silence; the last resort so the mount is never dropped.
|
||||
# music - the fallback playlist read from the /music bind mount
|
||||
# (./icecast2/fallback_music on the host). reload_mode="watch"
|
||||
# means adding or removing an MP3 on the host is picked up live,
|
||||
# with no container restart.
|
||||
# live - a *harbor* input: liquidsoap itself listens on
|
||||
# LIQUIDSOAP_HARBOR_PORT and accepts an incoming source
|
||||
# connection. This is the "go live" path — a broadcasting client
|
||||
# on the LAN/internet connects with ICECAST_SOURCE_PASSWORD and
|
||||
# starts talking. It is the one reason icecast2 publishes a host
|
||||
# port in docker-compose.yml.
|
||||
#
|
||||
# fallback(track_sensitive=false, [live, music, blank()])
|
||||
# Picks the first available source in list order, so a live DJ pre-empts
|
||||
# the playlist automatically. track_sensitive=false is the important flag:
|
||||
# it makes the switch happen IMMEDIATELY rather than politely waiting for
|
||||
# the current track to finish — otherwise going live could take minutes.
|
||||
#
|
||||
# amplify(0.7, ...) - a fixed -3dB or so trim, because the fallback MP3s are
|
||||
# mastered loud and were clipping against the live input.
|
||||
#
|
||||
# OUTPUT
|
||||
# Pushes to icecast on localhost (same container) at ICECAST_MOUNT, which is
|
||||
# what nginx exposes at /radio/. fallible=true tells liquidsoap this output
|
||||
# is allowed to fail and be retried, instead of aborting the script — that is
|
||||
# what makes the `sleep 2` startup race in the entrypoint survivable.
|
||||
#
|
||||
# settings.server.telnet := false — the liquidsoap control socket is off; there
|
||||
# is no interactive way to poke the running stream.
|
||||
# =============================================================================
|
||||
settings.server.telnet := false
|
||||
|
||||
music = playlist("/music", mode="randomize", reload_mode="watch")
|
||||
|
||||
@@ -1,3 +1,27 @@
|
||||
# =============================================================================
|
||||
# nginx image — the public edge. Stock nginx plus two tools and three templates.
|
||||
#
|
||||
# BASE: nginx:1.27, pinned to a minor version. Official nginx images are
|
||||
# multi-arch, so the same tag resolves to the arm64 build on the Raspberry Pi
|
||||
# with no platform pin needed — that is why there is no `--platform` anywhere
|
||||
# in this repo.
|
||||
#
|
||||
# WHY THE EXTRA PACKAGES
|
||||
# gettext-base provides `envsubst`, which entrypoint.sh uses to render a
|
||||
# config template. Not in the base image.
|
||||
# openssl used by entrypoint.sh to mint the self-signed localhost
|
||||
# certificate in DEV_MODE only. Installed unconditionally
|
||||
# because there is one image for both dev and production.
|
||||
#
|
||||
# `rm -rf /etc/nginx/html/*` clears the stock "Welcome to nginx" page, since
|
||||
# that directory is where the vue_dist volume gets mounted and a leftover
|
||||
# index.html there would be served if the Vue build ever failed.
|
||||
#
|
||||
# apt lists are deleted in the SAME RUN layer so they never end up in the image.
|
||||
#
|
||||
# NO nginx.conf IS COPIED IN. All three templates are, and entrypoint.sh picks
|
||||
# one at container start. See nginx/entrypoint.sh for that decision.
|
||||
# =============================================================================
|
||||
FROM nginx:1.27
|
||||
RUN rm -rf /etc/nginx/html/* && \
|
||||
apt-get update && apt-get install -y gettext-base openssl && \
|
||||
|
||||
+105
-7
@@ -1,14 +1,99 @@
|
||||
#!/bin/sh
|
||||
# =============================================================================
|
||||
# nginx entrypoint — picks one of three nginx configs at container start.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# nginx.conf is not shipped in the image. Instead three *templates* are baked
|
||||
# in (see nginx/Dockerfile) and this script renders exactly one of them to
|
||||
# /etc/nginx/nginx.conf before starting nginx in the foreground.
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# Every time the `nginx` container starts (ENTRYPOINT). It is therefore also
|
||||
# the thing that re-evaluates "do we have certificates yet?" on each restart.
|
||||
#
|
||||
# WHICH CONFIG IS CHOSEN (the three-way decision)
|
||||
# 1. DEV_MODE=true -> nginx_dev.conf.template
|
||||
# Local development. Certbot is disabled (docker-compose.dev.yml puts it
|
||||
# in the `disabled` profile), so there can never be a real certificate.
|
||||
# We mint a throwaway self-signed cert for CN=localhost so the :443
|
||||
# server block still has something to load, and proxy `/` to the Vite
|
||||
# dev server (vue:5173) instead of serving built files from disk.
|
||||
# 2. Real cert exists for $DOMAIN -> nginx.conf.template
|
||||
# Steady-state production: HTTP->HTTPS redirect, apex->www redirect,
|
||||
# SPA served from /etc/nginx/html, everything else reverse-proxied.
|
||||
# 3. No cert yet -> nginx_setup.conf.template
|
||||
# The bootstrap case. See CHICKEN-AND-EGG below.
|
||||
#
|
||||
# CHICKEN-AND-EGG: nginx_setup.conf vs certbot first issuance
|
||||
# Let's Encrypt HTTP-01 validation requires a working HTTP server on port 80
|
||||
# that serves /.well-known/acme-challenge/. But nginx.conf.template references
|
||||
# /etc/letsencrypt/live/$DOMAIN/fullchain.pem in its `ssl_certificate`
|
||||
# directives, and nginx refuses to start if that file is missing. So on a
|
||||
# brand-new host nginx cannot use the production config, and certbot cannot
|
||||
# get a certificate without nginx. The setup config breaks the loop: it is a
|
||||
# minimal port-80-only server that serves the ACME webroot and 404s
|
||||
# everything else — no TLS, no upstreams, nothing that can fail to load.
|
||||
# Order of events on a fresh machine:
|
||||
# a. nginx starts with nginx_setup.conf (port 80, ACME webroot only).
|
||||
# b. certbot container runs `certbot certonly --webroot`, writes the cert
|
||||
# into the shared ./certbot/conf volume.
|
||||
# c. nginx is restarted (manually, or by a redeploy) — this script re-runs,
|
||||
# now finds the cert, and renders the production config.
|
||||
# Step (c) is NOT automatic. A first deploy on a new domain needs one manual
|
||||
# `docker compose restart nginx` after certbot succeeds.
|
||||
#
|
||||
# THE envsubst TEMPLATING PATTERN
|
||||
# The templates are plain nginx configs containing $VARIABLES. Two different
|
||||
# kinds of $VAR live in the same file:
|
||||
# - build-time vars we want substituted: $DOMAIN, $BACKEND_HOST, ...
|
||||
# - runtime nginx vars that must survive: $host, $remote_addr, $uri,
|
||||
# $http_upgrade, $proxy_add_x_forwarded_for, $binary_remote_addr, ...
|
||||
# Bare `envsubst` would replace *every* $NAME it recognises and blank out the
|
||||
# nginx runtime variables, producing a config that silently forwards empty
|
||||
# headers. Passing an explicit SHELL-FORMAT list (the '${A} ${B} ...' string
|
||||
# below) restricts envsubst to exactly those names and leaves every other
|
||||
# $token untouched. That is why the list is in SINGLE quotes: it must reach
|
||||
# envsubst as a literal '${DOMAIN} ${BACKEND_HOST} ...' string, not be
|
||||
# expanded by the shell first.
|
||||
#
|
||||
# ENV VARS REQUIRED (all from ./.env via `env_file` in docker-compose.yml)
|
||||
# DOMAIN apex domain, e.g. example.com
|
||||
# BACKEND_HOST / BACKEND_PORT Go API container name and port
|
||||
# BACKEND_ENDPOINT URL prefix the API is mounted at (e.g. /api)
|
||||
# ICECAST_HOST / ICECAST_PORT radio stream upstream
|
||||
# GITEA_HOST / GITEA_PORT git server upstream
|
||||
# HASURA_HOST / HASURA_PORT Hasura console upstream
|
||||
# QUARTZ_HOST / QUARTZ_PORT notes site upstream
|
||||
# PYTHON_HOST / PYTHON_PORT FastAPI upstream (defaulted below)
|
||||
# UPTIMEKUMA_* / WALLABAG_* substituted but not currently referenced by
|
||||
# any template; kept so adding those services
|
||||
# back needs no entrypoint change.
|
||||
# DEV_MODE "true" only via docker-compose.dev.yml
|
||||
#
|
||||
# ASSUMES EXISTS
|
||||
# /etc/letsencrypt (bind mount of ./certbot/conf, shared with certbot)
|
||||
# /var/www/certbot (bind mount of ./certbot/www, the ACME webroot)
|
||||
# /uploads (named volume `uploads`, shared with the backend)
|
||||
# /etc/nginx/html (named volume `vue_dist`, written by the one-shot `vue`
|
||||
# build container in production)
|
||||
# =============================================================================
|
||||
set -e
|
||||
|
||||
# Defaults for optional services so envsubst never leaves an empty upstream
|
||||
export PYTHON_HOST="${PYTHON_HOST:-python}"
|
||||
export PYTHON_PORT="${PYTHON_PORT:-8000}"
|
||||
|
||||
# The envsubst allow-list, defined once and reused by both full-config branches
|
||||
# so the two lists cannot drift apart. It MUST stay single-quoted here and be
|
||||
# passed as "$ENVSUBST_VARS" (one argument) below.
|
||||
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${UPTIMEKUMA_HOST} ${UPTIMEKUMA_PORT} ${WALLABAG_HOST} ${WALLABAG_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
|
||||
|
||||
# Check if DEV_MODE
|
||||
if [ "$DEV_MODE" = "true" ]; then
|
||||
echo "Dev mode. Generating self-signed certificate for HTTPS."
|
||||
CERT_DIR="/etc/letsencrypt/live/localhost"
|
||||
# Generated once and kept in the certbot/conf bind mount, so restarts reuse
|
||||
# the same cert and the browser's "accept this exception" sticks.
|
||||
if [ ! -f "$CERT_DIR/fullchain.pem" ]; then
|
||||
mkdir -p "$CERT_DIR"
|
||||
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
|
||||
@@ -17,38 +102,51 @@ if [ "$DEV_MODE" = "true" ]; then
|
||||
-subj "/CN=localhost" 2>/dev/null
|
||||
fi
|
||||
# In dev mode, so use nginx_dev.conf.template
|
||||
envsubst '${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${UPTIMEKUMA_HOST} ${UPTIMEKUMA_PORT} ${WALLABAG_HOST} ${WALLABAG_PORT} ${PYTHON_HOST} ${PYTHON_PORT}' \
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx_dev.conf.template \
|
||||
>/etc/nginx/nginx.conf
|
||||
elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
||||
echo "Certificates found. Using production nginx config."
|
||||
# In production with certificates already existing, so use nginx.conf.template
|
||||
envsubst '${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${UPTIMEKUMA_HOST} ${UPTIMEKUMA_PORT} ${WALLABAG_HOST} ${WALLABAG_PORT} ${PYTHON_HOST} ${PYTHON_PORT}' \
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx.conf.template \
|
||||
>/etc/nginx/nginx.conf
|
||||
else
|
||||
echo "Certificates NOT found. Using setup nginx config."
|
||||
# In production with no certificates, so use nginx_setup.conf.template and will need restart after generation
|
||||
# Only ${DOMAIN} is substituted: the setup config has no upstreams at all.
|
||||
envsubst '${DOMAIN}' </etc/nginx/nginx_setup.conf.template >/etc/nginx/nginx.conf
|
||||
fi
|
||||
|
||||
# Ensure upload directory is traversable by nginx worker
|
||||
# Ensure upload directory is traversable by nginx worker.
|
||||
# `uploads` is a named volume shared with the backend, which creates it with
|
||||
# the backend's umask; nginx runs its workers as a different user and needs
|
||||
# +x on the directory to serve files out of it via the /uploads/ alias.
|
||||
# `|| true` because on a read-only or foreign-owned mount this is not fatal.
|
||||
chmod 755 /uploads 2>/dev/null || true
|
||||
|
||||
# Wait for Vue assets in production mode
|
||||
# Wait for Vue assets in production mode.
|
||||
# The `vue` service is a ONE-SHOT build container: it runs `vite build` into the
|
||||
# shared `vue_dist` volume and exits. `depends_on: vue` only waits for it to
|
||||
# start, not to finish, so on a cold build nginx can come up before index.html
|
||||
# exists and would 404 the whole site. Poll for up to 120s, then start anyway
|
||||
# (a running nginx that 404s is still better than a crash loop, and the assets
|
||||
# appear moments later). In dev mode there are no built assets at all — `/` is
|
||||
# proxied to the Vite dev server — so the wait is skipped.
|
||||
if [ "$DEV_MODE" != "true" ]; then
|
||||
echo "Waiting for Vue assets..."
|
||||
elapsed=0
|
||||
while [ ! -f /etc/nginx/html/index.html ] && [ $elapsed -lt 120 ]; do
|
||||
vue_build_timeout=120
|
||||
while [ ! -f /etc/nginx/html/index.html ] && [ "$elapsed" -lt "$vue_build_timeout" ]; do
|
||||
sleep 1
|
||||
elapsed=$((elapsed + 1))
|
||||
done
|
||||
if [ ! -f /etc/nginx/html/index.html ]; then
|
||||
echo "WARNING: Vue assets not found after 120s, starting nginx anyway"
|
||||
echo "WARNING: Vue assets not found after ${vue_build_timeout}s, starting nginx anyway"
|
||||
else
|
||||
echo "Vue assets ready."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Start nginx
|
||||
# Start nginx in the foreground so it is PID 1 and docker can signal/restart it.
|
||||
nginx -g 'daemon off;'
|
||||
|
||||
@@ -1,3 +1,31 @@
|
||||
# =============================================================================
|
||||
# nginx.conf.template — PRODUCTION config (steady state, certificates present).
|
||||
#
|
||||
# WHEN IT IS USED
|
||||
# Rendered to /etc/nginx/nginx.conf by nginx/entrypoint.sh when DEV_MODE is
|
||||
# not "true" AND a real certificate exists at
|
||||
# /etc/letsencrypt/live/<DOMAIN>/. The other two templates cover dev
|
||||
# (nginx_dev.conf.template) and first-boot bootstrap
|
||||
# (nginx_setup.conf.template).
|
||||
#
|
||||
# TEMPLATING
|
||||
# Only the names in the envsubst allow-list in nginx/entrypoint.sh are
|
||||
# substituted: DOMAIN, BACKEND_HOST/PORT/ENDPOINT, ICECAST_*, GITEA_*,
|
||||
# HASURA_*, QUARTZ_*, PYTHON_*, UPTIMEKUMA_*, WALLABAG_*. Every other dollar
|
||||
# token in this file is an nginx RUNTIME variable (host, remote_addr, uri,
|
||||
# http_upgrade, proxy_add_x_forwarded_for, binary_remote_addr, request_uri,
|
||||
# scheme, http_cookie) and must be left alone — that restriction is the whole
|
||||
# reason the allow-list exists.
|
||||
#
|
||||
# SERVER BLOCKS (three, in order)
|
||||
# 1. :80 any name -> serves the ACME challenge, 301s everything else to
|
||||
# https://www.DOMAIN. Certbot renewal depends on this
|
||||
# block staying reachable on plain HTTP.
|
||||
# 2. :443 apex -> TLS terminates, then 301s to the www host, so there
|
||||
# is exactly one canonical origin (important: cookies,
|
||||
# CORS and the SPA all assume www).
|
||||
# 3. :443 www -> the real site.
|
||||
# =============================================================================
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
@@ -9,10 +37,58 @@ http {
|
||||
server_tokens off;
|
||||
charset utf-8;
|
||||
|
||||
# Docker's embedded DNS. Required because upstreams are referenced through
|
||||
# `set $upstream_* ...` variables below; using a variable in proxy_pass
|
||||
# makes nginx resolve the name PER REQUEST instead of once at startup.
|
||||
# That is the trick that lets nginx boot even when a backend container is
|
||||
# down or not yet created (it 502s until the container appears, rather than
|
||||
# refusing to start with "host not found in upstream"). valid=10s caps how
|
||||
# long a stale container IP can be cached after a redeploy.
|
||||
resolver 127.0.0.11 valid=10s;
|
||||
|
||||
# Caps request bodies; must be >= the largest allowed chat image upload or
|
||||
# nginx rejects with 413 before the backend ever sees the request.
|
||||
client_max_body_size 50M;
|
||||
|
||||
# ---- Rate limiting -------------------------------------------------------
|
||||
# Each zone is a shared-memory table keyed by $binary_remote_addr (the
|
||||
# client IP in packed 4/16-byte form rather than a string — that is why
|
||||
# "binary": it makes each entry ~64 bytes instead of ~128). 10m therefore
|
||||
# holds roughly 160k distinct IPs, far more than this site will ever see;
|
||||
# 10m is simply the safe round number, not a tuned value. If a zone fills,
|
||||
# nginx evicts the oldest entries and logs a warning.
|
||||
#
|
||||
# `rate` is enforced as a smoothed leaky bucket, not a per-minute counter:
|
||||
# 5r/m means one request allowed every 12 seconds, not 5 at once then
|
||||
# nothing. `burst=N` at the use site allows N requests to queue ahead of
|
||||
# that drip, and `nodelay` (used everywhere here) serves those N
|
||||
# immediately rather than spacing them out — so the practical behaviour is
|
||||
# "N instant requests, then throttled to the drip rate". Anything over the
|
||||
# burst gets 503 immediately.
|
||||
#
|
||||
# Chosen limits and why:
|
||||
# login 5r/m burst=3 - brute-force defence on password auth. A human
|
||||
# mistyping gets 3 instant tries, then one every
|
||||
# 12s. Painless for a real user, useless for a
|
||||
# credential-stuffing script.
|
||||
# api 30r/s burst=20 - generous; a normal SPA page load fans out to
|
||||
# several API calls and must never be throttled.
|
||||
# This is an abuse ceiling, not a quota.
|
||||
# graphql 10r/s burst=10 - tighter than REST because a single GraphQL
|
||||
# query can be arbitrarily expensive to resolve.
|
||||
# (Production only; the dev template omits it.)
|
||||
# upload 5r/m burst=3 - uploads are 50MB-capable and hit disk; this
|
||||
# bounds how fast one IP can fill the volume.
|
||||
# hotel_search 3r/m burst=2 - each request holds an upstream call to
|
||||
# Travelodge/TfL for up to a few minutes and the
|
||||
# Python side has a single search slot, so this is
|
||||
# really concurrency protection, not abuse
|
||||
# protection.
|
||||
#
|
||||
# NOTE: the key is the direct client IP. Since nginx is the edge here (no
|
||||
# CDN or upstream proxy in front), that is correct. If anything is ever put
|
||||
# in front, these zones must switch to a trusted X-Forwarded-For or every
|
||||
# visitor will share one bucket.
|
||||
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
||||
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
|
||||
limit_req_zone $binary_remote_addr zone=graphql:10m rate=10r/s;
|
||||
@@ -24,6 +100,9 @@ http {
|
||||
|
||||
access_log /var/log/nginx/access.log compact;
|
||||
|
||||
# nginx's bundled mime.types has no entry for .mjs, so ES modules would be
|
||||
# served as application/octet-stream and browsers refuse to execute them.
|
||||
# This adds the missing mapping without editing the shipped mime.types.
|
||||
types {
|
||||
text/javascript mjs;
|
||||
}
|
||||
@@ -110,6 +189,12 @@ http {
|
||||
add_header Cache-Control "public";
|
||||
}
|
||||
|
||||
# User-uploaded files, served straight off the shared `uploads` volume
|
||||
# so the Go process never has to stream them. Because these are
|
||||
# attacker-supplied bytes on our own origin, three headers neutralise
|
||||
# them: nosniff stops content-type guessing, Content-Disposition inline
|
||||
# keeps them from being treated as downloads, and the locked-down CSP
|
||||
# means even an uploaded .html can run no script and load no resource.
|
||||
location /uploads/ {
|
||||
alias /uploads/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
@@ -117,6 +202,9 @@ http {
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
# SPA fallback: serve the file if it exists, otherwise hand index.html
|
||||
# to the browser so Vue Router can resolve the path client-side. This
|
||||
# is what makes deep links like /notes-page or /admin work on refresh.
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
@@ -127,10 +215,19 @@ http {
|
||||
access_log off;
|
||||
}
|
||||
|
||||
# Belt-and-braces: HTTP-01 validation always happens on port 80 (the
|
||||
# :80 block above), so this duplicate on :443 never actually serves a
|
||||
# challenge. Harmless, and kept in case a future challenge type or a
|
||||
# redirect chain lands here. Note it is a regex location (~), so it
|
||||
# matches the path anywhere in the URI, not just at the start.
|
||||
location ~ /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
# One-off: this GIF is a "web stamp" other people's sites hot-link, so
|
||||
# it needs an explicit CORS header. Ironically the origin allowed is our
|
||||
# own, which means cross-origin embedders are not actually permitted —
|
||||
# see the proposals in DEPLOYMENT.md before changing it.
|
||||
location = /img/stamps/mine.gif {
|
||||
add_header Access-Control-Allow-Origin "https://www.$DOMAIN";
|
||||
expires 7d;
|
||||
@@ -142,10 +239,49 @@ http {
|
||||
add_header Cache-Control "public";
|
||||
}
|
||||
|
||||
# ---- Backend API -----------------------------------------------------
|
||||
# Two patterns repeat through every proxied location below:
|
||||
#
|
||||
# 1. THE PREFIX-STRIP REWRITE
|
||||
# rewrite ^<PREFIX>/(.*)$ /$1 break;
|
||||
# The public URL carries a prefix (/api, /radio, /gitea, /notes,
|
||||
# /py) but the upstream service serves its routes from /. The
|
||||
# rewrite strips the prefix and `break` stops rewrite processing so
|
||||
# the request stays in this location and goes to proxy_pass with the
|
||||
# rewritten URI. (This is why proxy_pass here has no trailing path —
|
||||
# with a variable upstream, nginx would not do the strip for us.)
|
||||
# The bare `location <PREFIX>` blocks that 301 to `<PREFIX>/` exist
|
||||
# only so a user typing /gitea without the slash lands correctly.
|
||||
#
|
||||
# 2. THE FOUR FORWARDING HEADERS
|
||||
# Host preserve the browser's hostname so the app
|
||||
# builds correct absolute URLs and cookies.
|
||||
# X-Real-IP the true client IP (the upstream otherwise
|
||||
# sees only nginx's container IP).
|
||||
# X-Forwarded-For appends the client to any existing chain.
|
||||
# X-Forwarded-Proto tells the app the ORIGINAL request was
|
||||
# https even though this hop is plain http.
|
||||
# Without it the backend would issue
|
||||
# non-Secure cookies and http:// redirects,
|
||||
# breaking auth behind TLS termination.
|
||||
#
|
||||
# Ordering matters: nginx picks the longest matching prefix location,
|
||||
# so the specific /ws, /auth/login, /messages/upload and /graphql blocks
|
||||
# win over the catch-all <PREFIX>/ block regardless of file order.
|
||||
location $BACKEND_ENDPOINT {
|
||||
return 301 $BACKEND_ENDPOINT/;
|
||||
}
|
||||
|
||||
# WebSocket endpoint (live chat / activity feed).
|
||||
# The three lines that make an upgrade work, and why each is needed:
|
||||
# proxy_http_version 1.1 - HTTP/1.0 has no Upgrade mechanism at all.
|
||||
# Upgrade $http_upgrade - hop-by-hop headers are NOT forwarded by
|
||||
# Connection "upgrade" default, so they must be re-set by hand.
|
||||
# Note the Connection value is hardcoded rather than using the usual
|
||||
# $connection_upgrade map: this location only ever serves websockets, so
|
||||
# there is no plain-HTTP case to fall back to.
|
||||
# Deliberately NOT rate limited — a websocket is one long-lived request
|
||||
# and a limit_req here would drop reconnect storms, not abuse.
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
@@ -295,6 +431,20 @@ http {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# ---- Admin gate for /hasura/ and /notes/ ------------------------------
|
||||
# `auth_request` makes nginx fire a subrequest here before serving the
|
||||
# real one; a 2xx lets it through, 401/403 triggers error_page ->
|
||||
# @auth_denied -> redirect to the SPA login. This puts the Go backend's
|
||||
# session cookie in front of two services that have no idea it exists.
|
||||
# internal; - unreachable from outside, subrequest only.
|
||||
# proxy_pass_request_body off + Content-Length ""
|
||||
# - the subrequest must not replay the
|
||||
# original body (it could be a 50MB
|
||||
# upload); clearing Content-Length stops
|
||||
# the backend waiting for a body that is
|
||||
# not coming.
|
||||
# Cookie $http_cookie - the whole point: forward the session
|
||||
# cookie so the backend can validate it.
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
|
||||
@@ -1,3 +1,36 @@
|
||||
# =============================================================================
|
||||
# nginx_dev.conf.template — LOCAL DEVELOPMENT config.
|
||||
#
|
||||
# WHEN IT IS USED
|
||||
# Rendered by nginx/entrypoint.sh whenever DEV_MODE=true, which is set only
|
||||
# by docker-compose.dev.yml. Never used on the Pi.
|
||||
#
|
||||
# HOW IT DIFFERS FROM nginx.conf.template
|
||||
# - `/` is proxied to the Vite dev server at vue:5173 instead of serving
|
||||
# built files from disk. The Upgrade/Connection headers on that block are
|
||||
# for Vite's HMR websocket, not for the app.
|
||||
# - No HTTP->HTTPS redirect and no apex->www redirect: BOTH :80 and :443
|
||||
# serve the full site, so http://localhost just works. The two server
|
||||
# blocks are therefore near-identical copies of each other (see the
|
||||
# duplication note in DEPLOYMENT.md).
|
||||
# - TLS uses the self-signed /etc/letsencrypt/live/localhost/ certificate that
|
||||
# the entrypoint generates, not a Let's Encrypt one. Browsers will warn.
|
||||
# - No HSTS or other security headers — HSTS on localhost would poison the
|
||||
# browser for every other localhost project on the machine.
|
||||
# - No `graphql` rate-limit zone (the production template has one); GraphQL
|
||||
# falls under the general `api` limit here.
|
||||
# - No /assets/, /fonts/, /img/ cache-control blocks: Vite serves those and
|
||||
# long cache lifetimes would defeat hot reload.
|
||||
#
|
||||
# TEMPLATING
|
||||
# Same envsubst allow-list as production. Every other dollar token is an
|
||||
# nginx runtime variable and must survive substitution untouched.
|
||||
#
|
||||
# For the rate-limit reasoning, the prefix-strip rewrite, the four forwarding
|
||||
# headers, the websocket upgrade block and the auth_request admin gate, see the
|
||||
# fully-annotated equivalents in nginx.conf.template — the mechanics here are
|
||||
# identical.
|
||||
# =============================================================================
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,33 @@
|
||||
# =============================================================================
|
||||
# nginx_setup.conf.template — BOOTSTRAP config, used exactly once per host.
|
||||
#
|
||||
# WHEN IT IS USED
|
||||
# Rendered by nginx/entrypoint.sh in production when NO certificate exists
|
||||
# yet at /etc/letsencrypt/live/<DOMAIN>/.
|
||||
#
|
||||
# WHY IT EXISTS (the chicken-and-egg)
|
||||
# The production config cannot start without a certificate file, and certbot
|
||||
# cannot obtain a certificate without an HTTP server answering Let's
|
||||
# Encrypt's HTTP-01 challenge on port 80. This config is the smallest thing
|
||||
# that breaks that loop: port 80 only, no TLS directives, no upstreams,
|
||||
# nothing that can fail to load. It serves the ACME webroot and 404s
|
||||
# everything else so the half-configured site is never partially exposed.
|
||||
#
|
||||
# LIFECYCLE
|
||||
# 1. nginx starts here.
|
||||
# 2. certbot succeeds and writes the certificate into the shared volume.
|
||||
# 3. nginx must be RESTARTED for the entrypoint to re-check and switch to
|
||||
# nginx.conf.template. This step is manual:
|
||||
# docker compose restart nginx
|
||||
# Nothing watches the cert directory and flips automatically.
|
||||
#
|
||||
# TEMPLATING
|
||||
# Only ${DOMAIN} is substituted for this file (a separate, shorter envsubst
|
||||
# call in the entrypoint) because there are no upstreams to fill in.
|
||||
#
|
||||
# ASSUMES: /var/www/certbot is bind-mounted and shared with the certbot
|
||||
# container; port 80 is reachable from the public internet.
|
||||
# =============================================================================
|
||||
events {
|
||||
worker_connections 1024; # required, can be minimal
|
||||
}
|
||||
|
||||
@@ -1,3 +1,29 @@
|
||||
# =============================================================================
|
||||
# FastAPI side-service image.
|
||||
#
|
||||
# requirements.txt is copied and installed before the app source so the
|
||||
# dependency layer is cached across code changes. --no-cache-dir keeps pip's
|
||||
# download cache out of the image (this one is a plain layer, not a BuildKit
|
||||
# cache mount, because the dependency set is small).
|
||||
#
|
||||
# PYTHONDONTWRITEBYTECODE stops .pyc files being written into the image and the
|
||||
# dev bind mount; PYTHONUNBUFFERED makes logs appear in `docker logs`
|
||||
# immediately instead of sitting in a buffer — both are standard for
|
||||
# containerised Python and the second one matters for debugging.
|
||||
#
|
||||
# ROOT_PATH=/py: nginx proxies /py/ and STRIPS the prefix, so the app's routes
|
||||
# are written relative to /. --root-path tells FastAPI it is nonetheless
|
||||
# mounted under a prefix, so the OpenAPI schema and Swagger UI emit correct
|
||||
# /py/... URLs. Without it, /py/docs loads but cannot call anything.
|
||||
#
|
||||
# The CMD is a `sh -c` form on purpose: it needs the shell to expand
|
||||
# ${PYTHON_PORT} and ${ROOT_PATH} at runtime, which the exec form cannot do.
|
||||
# Both have defaults here so the image runs standalone; docker compose normally
|
||||
# supplies them.
|
||||
#
|
||||
# EXPOSE 8000 is documentation only — the port is not published; nginx reaches
|
||||
# it over app-network.
|
||||
# =============================================================================
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# Python API service
|
||||
|
||||
A small FastAPI app (`app/main.py`) served by uvicorn on port 8000 inside the
|
||||
`python` container. Most of it is one feature: **cheap Travelodge finder** —
|
||||
given a London location and dates it pulls live room prices from Travelodge and
|
||||
adds the cost of getting there from a chosen station on TfL, so you can rank
|
||||
hotels by what the night *actually* costs, not just the room.
|
||||
|
||||
## Layout
|
||||
|
||||
| File | Role |
|
||||
| --- | --- |
|
||||
| `app/main.py` | HTTP skin: request models/validation, response cache, one-at-a-time guard, NDJSON framing, route handlers |
|
||||
| `app/travelodge.py` | All the real work: upstream calls, caching, rate limiting, fare maths, the two search generators |
|
||||
| `app/__init__.py` | Empty; makes `app` a package so `app.main:app` resolves |
|
||||
|
||||
`travelodge.py` never imports FastAPI and can be driven from a plain script.
|
||||
|
||||
## Endpoints
|
||||
|
||||
Paths below are as the service sees them; from a browser prefix everything with
|
||||
`/py` (see *Behind nginx*).
|
||||
|
||||
| Method | Path | What it does |
|
||||
| --- | --- | --- |
|
||||
| GET | `/` | Index message |
|
||||
| GET | `/health` | Liveness: `{"status": "ok", "time": ...}` |
|
||||
| GET | `/hello/{name}` | Demo route |
|
||||
| GET | `/hotels/origins` | The built-in origin stations the UI offers |
|
||||
| POST | `/hotels/search` | Blocking search; returns once every shortlisted hotel is priced |
|
||||
| POST | `/hotels/search/stream` | Same search as NDJSON progress lines |
|
||||
| POST | `/hotels/scan/stream` | Cheapest night across a date range, NDJSON |
|
||||
|
||||
Interactive schema: `/py/docs` (Swagger UI), `/py/openapi.json`.
|
||||
|
||||
### Streaming format
|
||||
|
||||
The stream endpoints return `application/x-ndjson`: one JSON object per line,
|
||||
no SSE framing. Read a line, parse it, apply it. `exclude_none=True` is set, so
|
||||
**absent keys mean null**.
|
||||
|
||||
`/hotels/search/stream` emits:
|
||||
|
||||
1. `hotels` — every shortlisted hotel with its room price and an estimated
|
||||
cycling time; transport columns are still null and `route` reads `pricing…`.
|
||||
2. `transport` — one line per hotel as TfL answers; patch that row by `code`.
|
||||
3. `done` — final summary plus all rows sorted by total.
|
||||
|
||||
`/hotels/scan/stream` emits `scan` (all candidate nights, pending), then a
|
||||
`night` per date, then a `transport` per **unique hotel code** (apply it to
|
||||
every night containing that code — transport is priced once and reused), then
|
||||
`done`.
|
||||
|
||||
An `error` line ends a failed stream. Streams are always HTTP 200: the response
|
||||
starts before the work does, so failures cannot become a status code. The
|
||||
blocking `/hotels/search` is the exception — it returns 429 when a search is
|
||||
already running and 502 on upstream failure.
|
||||
|
||||
Only **one** live search or scan runs process-wide at a time (the TfL budget
|
||||
can't be shared), and identical requests are cached for 10 minutes.
|
||||
|
||||
## Behind nginx
|
||||
|
||||
`nginx/nginx.conf.template` proxies `/py/` to this container and **strips the
|
||||
prefix**, so routes here are written relative to `/`. `--root-path /py` (set on
|
||||
the uvicorn command line via `ROOT_PATH`) is what keeps the generated docs and
|
||||
OpenAPI URLs correct behind that rewrite.
|
||||
|
||||
The hotel routes get their own nginx location with `proxy_buffering off` and a
|
||||
300s read timeout, because otherwise nginx would hold the whole NDJSON stream
|
||||
until it finished. The app also sends `X-Accel-Buffering: no` as a belt-and-
|
||||
braces version of the same thing. The internal deadlines in `travelodge.py`
|
||||
(200s for a search, 240s for a scan) exist to finish *before* that 300s cut, and
|
||||
return partial results with `summary.truncated = true` instead of dying.
|
||||
|
||||
Env vars (from `docker-compose.yml`): `PYTHON_PORT`, `ROOT_PATH`, and the
|
||||
optional `TFL_APP_KEY` (see below). Dev mode mounts `python/app` and runs
|
||||
uvicorn with `--reload`.
|
||||
|
||||
## Running locally
|
||||
|
||||
Inside the whole stack:
|
||||
|
||||
```
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||
# http://localhost/py/docs
|
||||
```
|
||||
|
||||
Or just this service:
|
||||
|
||||
```
|
||||
cd python
|
||||
python3 -m venv .venv && . .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
uvicorn app.main:app --reload --port 8000
|
||||
# http://localhost:8000/docs (no /py prefix when run directly)
|
||||
```
|
||||
|
||||
Dependencies are `fastapi`, `uvicorn[standard]` and `requests` — nothing else.
|
||||
|
||||
## How the pricing works
|
||||
|
||||
1. Search Travelodge for the location and dates, following pagination, and drop
|
||||
hotels with no availability, no price, or no coordinates.
|
||||
2. Keep the cheapest `top` (search) or `per_night` (scan) of them.
|
||||
3. For each, ask TfL for the fastest route *and* a bus-only route at the given
|
||||
departure time. Pick the cheapest that isn't slower than `max_travel_min`.
|
||||
4. Apply a Railcard discount (1/3 off, rounded to 5p) to off-peak rail/tube
|
||||
fares only — never buses. The return leg is assumed to be the same journey
|
||||
the next morning at off-peak rates.
|
||||
5. Rank by room + round-trip transport. Cycling time is shown alongside.
|
||||
|
||||
### Fragility — read this before debugging "no prices"
|
||||
|
||||
Both upstreams are JSON APIs, not HTML, so there are no CSS selectors to break —
|
||||
but the **key names play exactly that role** and neither API is a public,
|
||||
documented contract for this use:
|
||||
|
||||
- Travelodge's `/api/v2/hotel` is the feed its own search page calls. The query
|
||||
parameters (`q`, `checkIn`, `rooms[0][adults]`, the undocumented
|
||||
`action=hotel_amend`, and `pagination=false`, which only hides the pagination
|
||||
metadata and does *not* return everything in one page) and the response keys
|
||||
read in `normalise_hotel` are whatever the site sends today.
|
||||
- A browser `User-Agent` is sent because the edge throttles obviously scripted
|
||||
clients. If everything starts coming back empty or 403, bump it first.
|
||||
- Every field read is tolerant — a renamed key yields `None`, not an exception.
|
||||
So a shape change looks like *"every hotel is unavailable"*, not a 502.
|
||||
- TfL fares come from `fare.fares[].cost/peak/offPeak/chargeLevel`. Off-peak is
|
||||
detected by substring-matching `chargeLevel` for "off" *or* the cost equalling
|
||||
the off-peak price, because that field's spelling has moved around.
|
||||
- Pagination stops when a batch of pages returns nothing new or comes back
|
||||
short, with `TL_MAX_START` as a hard backstop.
|
||||
|
||||
There is no scraping of pages behind a login and no attempt to book anything,
|
||||
but this is still an undocumented internal API being polled from a public web
|
||||
page — check Travelodge's terms before pointing it at anything heavier.
|
||||
|
||||
### TfL rate limit
|
||||
|
||||
Anonymous callers get 50 requests/min from a single IP; with a `TFL_APP_KEY` it
|
||||
is 500/min. A search spends 2–3 requests per hotel, so the anonymous tier is the
|
||||
binding constraint and is what the single-search-slot guard protects. Setting
|
||||
`TFL_APP_KEY` also switches cycling times from a distance-based estimate to real
|
||||
TfL cycle routing (`cycle_source` tells you which you're looking at).
|
||||
|
||||
## Frontend
|
||||
|
||||
Consumed by `vue/src/views/hotels/`:
|
||||
|
||||
- `SingleStayPanel.vue` → `POST /py/hotels/search/stream`
|
||||
- `CheapestNightPanel.vue` → `POST /py/hotels/scan/stream`
|
||||
- `useHotelForm.js` → `GET /py/hotels/origins`
|
||||
- `hotelsStream.js` — the NDJSON reader (splits on newlines, skips a malformed
|
||||
line rather than aborting the search)
|
||||
|
||||
The Pydantic field names and JSON keys in `main.py` are that contract; renaming
|
||||
one breaks the UI silently.
|
||||
+138
-7
@@ -4,6 +4,21 @@ Nginx proxies https://www.<DOMAIN>/py/... to this container and strips the
|
||||
/py prefix, so routes here are defined relative to "/". FastAPI's root_path
|
||||
(set via --root-path on the uvicorn command line) keeps the generated docs
|
||||
at /py/docs working behind the proxy.
|
||||
|
||||
Endpoints
|
||||
GET / service index
|
||||
GET /health liveness probe
|
||||
GET /hello/{name} demo route
|
||||
GET /hotels/origins the known travel origins the UI offers
|
||||
POST /hotels/search blocking cheapest-Travelodge search
|
||||
POST /hotels/search/stream same search, streamed as NDJSON
|
||||
POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON
|
||||
|
||||
All the hotel work lives in `travelodge`; this module is the HTTP skin around
|
||||
it - request validation, a response cache, the one-search-at-a-time guard, and
|
||||
the NDJSON framing. Consumed by vue/src/views/hotels/ (SingleStayPanel.vue,
|
||||
CheapestNightPanel.vue, useHotelForm.js), which fetch these paths with the /py
|
||||
prefix. Field names in the models below are part of that contract.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -28,26 +43,33 @@ app = FastAPI(
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
"""Liveness payload: a fixed status string and the server's UTC time."""
|
||||
|
||||
status: str
|
||||
time: datetime
|
||||
|
||||
|
||||
class Greeting(BaseModel):
|
||||
"""A single human-readable message."""
|
||||
|
||||
message: str
|
||||
|
||||
|
||||
@app.get("/", response_model=Greeting, summary="Service index")
|
||||
def index() -> Greeting:
|
||||
"""Point a curious caller at the docs (which live at /py/docs via nginx)."""
|
||||
return Greeting(message="Python API is running. See /py/docs for the schema.")
|
||||
|
||||
|
||||
@app.get("/health", response_model=Health, summary="Liveness check")
|
||||
def health() -> Health:
|
||||
"""Liveness check; always 200 while the process is up."""
|
||||
return Health(status="ok", time=datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@app.get("/hello/{name}", response_model=Greeting, summary="Greet a caller")
|
||||
def hello(name: str) -> Greeting:
|
||||
"""Echo a greeting back. Demo route, nothing depends on it."""
|
||||
return Greeting(message=f"Hello, {name}!")
|
||||
|
||||
|
||||
@@ -60,12 +82,18 @@ MAX_CHILDREN = 8
|
||||
MAX_SCAN_DAYS = travelodge.SCAN_MAX_DAYS
|
||||
CACHE_TTL_S = 10 * 60
|
||||
|
||||
# Only one live search or scan may run at a time, process-wide. A run can spend
|
||||
# the entire anonymous TfL budget (50 requests/min), so two concurrent runs
|
||||
# would simply starve each other into rate-limit backoff. Callers that find the
|
||||
# slot taken get an immediate "try again" rather than queueing.
|
||||
_search_slot = threading.Semaphore(1)
|
||||
_cache_lock = threading.Lock()
|
||||
_cache: dict = {} # key -> (expires_at, response dict)
|
||||
|
||||
|
||||
class Origin(BaseModel):
|
||||
"""One selectable travel origin, as offered to the UI's dropdown."""
|
||||
|
||||
key: str
|
||||
name: str
|
||||
lat: float
|
||||
@@ -120,6 +148,12 @@ class HotelRequestBase(BaseModel):
|
||||
return v.strip()
|
||||
|
||||
def shared_kwargs(self) -> dict:
|
||||
"""Translate the validated request into travelodge.run_* keyword args.
|
||||
|
||||
Parsing runs a second time here (the validators above only checked
|
||||
validity and discarded the result), which is cheap and keeps the model
|
||||
holding exactly what the client sent.
|
||||
"""
|
||||
origin_name, origin = travelodge.parse_origin(self.origin)
|
||||
return {
|
||||
"location": self.location,
|
||||
@@ -134,6 +168,8 @@ class HotelRequestBase(BaseModel):
|
||||
|
||||
|
||||
class HotelSearchRequest(HotelRequestBase):
|
||||
"""One stay on known dates: rank hotels by room price plus transport."""
|
||||
|
||||
checkin: date = Field(..., description="Check-in date (today or later)")
|
||||
checkout: Optional[date] = Field(None, description="Check-out date; overrides nights")
|
||||
nights: int = Field(1, ge=1, le=14, description="Used when checkout is not given")
|
||||
@@ -141,6 +177,14 @@ class HotelSearchRequest(HotelRequestBase):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_dates(self):
|
||||
"""Resolve checkout/nights into a consistent pair and bound the stay.
|
||||
|
||||
`checkout` wins when both are given; otherwise it is derived from
|
||||
`nights`. Both fields are then written back so downstream code can
|
||||
trust either one. `date.today()` is the server's local date, so a user
|
||||
in another timezone can be refused a checkin that is still valid for
|
||||
them.
|
||||
"""
|
||||
if self.checkin < date.today():
|
||||
raise ValueError("checkin must be today or later")
|
||||
checkout = self.checkout or self.checkin + timedelta(days=self.nights)
|
||||
@@ -154,6 +198,8 @@ class HotelSearchRequest(HotelRequestBase):
|
||||
|
||||
|
||||
class HotelScanRequest(HotelRequestBase):
|
||||
"""A range of candidate check-in dates: find the cheapest night to stay."""
|
||||
|
||||
start: date = Field(..., description="First candidate check-in date (today or later)")
|
||||
end: date = Field(..., description=f"Last candidate check-in date, at most {MAX_SCAN_DAYS} days after start")
|
||||
weekdays: list[int] = Field(
|
||||
@@ -166,6 +212,11 @@ class HotelScanRequest(HotelRequestBase):
|
||||
@field_validator("weekdays")
|
||||
@classmethod
|
||||
def _check_weekdays(cls, v: list[int]) -> list[int]:
|
||||
"""Validate and de-duplicate the weekday filter, preserving input order.
|
||||
|
||||
Order is preserved (rather than using a set) so the echoed summary and
|
||||
the cache key stay deterministic for a given request body.
|
||||
"""
|
||||
days = []
|
||||
for d in v:
|
||||
if d < 0 or d > 6:
|
||||
@@ -178,6 +229,12 @@ class HotelScanRequest(HotelRequestBase):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _check_dates(self):
|
||||
"""Bound the range and reject one that no candidate date can satisfy.
|
||||
|
||||
The final check actually enumerates the candidates, so a range like
|
||||
"Mondays only" over a Tuesday-to-Thursday window fails here with a clear
|
||||
message instead of producing an empty scan.
|
||||
"""
|
||||
if self.start < date.today():
|
||||
raise ValueError("start must be today or later")
|
||||
if self.end < self.start:
|
||||
@@ -190,6 +247,14 @@ class HotelScanRequest(HotelRequestBase):
|
||||
|
||||
|
||||
class HotelRow(BaseModel):
|
||||
"""One hotel in a result list.
|
||||
|
||||
Prices are pounds. Transport fields are None until the matching "transport"
|
||||
event arrives, and `route` carries the reason when they stay None ("pricing…",
|
||||
"no TfL fare found", "not priced (time limit)"). Field names are consumed
|
||||
verbatim by the Vue frontend - do not rename.
|
||||
"""
|
||||
|
||||
code: Optional[str] = None
|
||||
name: Optional[str] = None
|
||||
lat: Optional[float] = None
|
||||
@@ -216,6 +281,9 @@ class HotelRow(BaseModel):
|
||||
|
||||
|
||||
class HotelSearchSummary(BaseModel):
|
||||
"""Counts and echoed parameters for a search; `truncated` means the time
|
||||
budget ran out before every shortlisted hotel was priced."""
|
||||
|
||||
location: str
|
||||
checkin: date
|
||||
checkout: date
|
||||
@@ -238,6 +306,8 @@ class HotelSearchSummary(BaseModel):
|
||||
|
||||
|
||||
class HotelSearchResponse(BaseModel):
|
||||
"""Final result of the blocking search endpoint."""
|
||||
|
||||
summary: HotelSearchSummary
|
||||
rows: list[HotelRow]
|
||||
cached: bool = False
|
||||
@@ -245,6 +315,7 @@ class HotelSearchResponse(BaseModel):
|
||||
|
||||
@app.get("/hotels/origins", response_model=list[Origin], summary="Known origin stations")
|
||||
def hotel_origins() -> list[Origin]:
|
||||
"""List the built-in origin stations the UI offers (plus free "lat,lon")."""
|
||||
return [Origin(key=k, name=n, lat=lat, lon=lon) for k, (n, lat, lon) in travelodge.ORIGINS.items()]
|
||||
|
||||
|
||||
@@ -277,6 +348,8 @@ class TransportFields(BaseModel):
|
||||
|
||||
|
||||
class NightRow(BaseModel):
|
||||
"""One candidate night in a scan, with its cheapest hotels."""
|
||||
|
||||
checkin: date
|
||||
checkout: date
|
||||
status: str = Field("pending", description='"pending", "ok", "failed" or "skipped"')
|
||||
@@ -289,6 +362,9 @@ class NightRow(BaseModel):
|
||||
|
||||
|
||||
class HotelScanSummary(BaseModel):
|
||||
"""Counts and echoed parameters for a scan; `truncated` means some nights
|
||||
were skipped or some hotels left unpriced when time ran out."""
|
||||
|
||||
location: str
|
||||
start: date
|
||||
end: date
|
||||
@@ -326,7 +402,8 @@ class HotelScanEvent(BaseModel):
|
||||
detail: Optional[str] = None
|
||||
|
||||
|
||||
def _cache_get(key):
|
||||
def _cache_get(key: str):
|
||||
"""Return a cached response payload for `key`, or None if absent/expired."""
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
hit = _cache.get(key)
|
||||
@@ -335,7 +412,12 @@ def _cache_get(key):
|
||||
return None
|
||||
|
||||
|
||||
def _cache_put(key, result):
|
||||
def _cache_put(key: str, result: dict) -> None:
|
||||
"""Cache a completed response for CACHE_TTL_S, sweeping expired entries.
|
||||
|
||||
The sweep is the only eviction: the cache is unbounded between sweeps, which
|
||||
is fine because the one-at-a-time guard caps how fast entries can be added.
|
||||
"""
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
expired = [k for k, (exp, _) in _cache.items() if exp <= now]
|
||||
@@ -370,7 +452,14 @@ def _guarded(run, make_error):
|
||||
|
||||
|
||||
def _search_events(req: HotelSearchRequest):
|
||||
"""Yield HotelSearchEvent objects for a request, serving from cache when possible."""
|
||||
"""Yield HotelSearchEvent objects for a request, serving from cache when possible.
|
||||
|
||||
A cache hit replays a two-line stream ("hotels" then "done") carrying the
|
||||
finished result, so the client's streaming reader needs no special case; the
|
||||
`cached` flag is the only difference it can observe. The key is the
|
||||
canonical JSON of the whole validated request, which makes it exact but also
|
||||
means a cosmetically different body (a different `top`, say) misses.
|
||||
"""
|
||||
key = "search:" + json.dumps(req.model_dump(mode="json"), sort_keys=True)
|
||||
hit = _cache_get(key)
|
||||
if hit:
|
||||
@@ -379,6 +468,9 @@ def _search_events(req: HotelSearchRequest):
|
||||
return
|
||||
|
||||
def run():
|
||||
# run_search yields 3-tuples except for "transport", which is a 2-tuple
|
||||
# of (kind, row) - hence the shape test before unpacking. Only the final
|
||||
# "done" event is worth caching.
|
||||
gen = travelodge.run_search(
|
||||
checkin=req.checkin,
|
||||
checkout=req.checkout,
|
||||
@@ -398,7 +490,11 @@ def _search_events(req: HotelSearchRequest):
|
||||
|
||||
|
||||
def _scan_events(req: HotelScanRequest):
|
||||
"""Yield HotelScanEvent objects for a scan, serving from cache when possible."""
|
||||
"""Yield HotelScanEvent objects for a scan, serving from cache when possible.
|
||||
|
||||
As with searches, a cache hit is replayed as a "scan" line followed by
|
||||
"done" so the client parses it exactly like a live stream.
|
||||
"""
|
||||
key = "scan:" + json.dumps(req.model_dump(mode="json"), sort_keys=True)
|
||||
hit = _cache_get(key)
|
||||
if hit:
|
||||
@@ -442,7 +538,18 @@ _SCAN_DESCRIPTION = (
|
||||
)
|
||||
|
||||
|
||||
def _ndjson(events):
|
||||
def _ndjson(events) -> StreamingResponse:
|
||||
"""Frame an iterable of Pydantic events as newline-delimited JSON.
|
||||
|
||||
NDJSON rather than SSE: the client just splits on "\n" and JSON-parses each
|
||||
line, with no event-type framing to strip. `exclude_none=True` keeps the
|
||||
lines small, so absent keys must be treated as null by the reader.
|
||||
|
||||
X-Accel-Buffering: no is essential - without it nginx buffers the whole
|
||||
response and the user sees nothing until the search finishes, defeating the
|
||||
point of streaming. Cache-Control: no-cache stops any intermediary storing
|
||||
a partial stream.
|
||||
"""
|
||||
return StreamingResponse(
|
||||
(ev.model_dump_json(exclude_none=True) + "\n" for ev in events),
|
||||
media_type="application/x-ndjson",
|
||||
@@ -458,6 +565,17 @@ def _ndjson(events):
|
||||
responses={429: {"description": "Another search is already running"}, 502: {"description": "Upstream API failed"}},
|
||||
)
|
||||
def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse:
|
||||
"""Run a search to completion and return the final result.
|
||||
|
||||
Drains the same event generator the streaming endpoint uses and keeps only
|
||||
the "done" event. Because the status code must be chosen before anything is
|
||||
written, an "error" event becomes an HTTPException here: 429 when the single
|
||||
search slot was busy, 502 for anything upstream.
|
||||
|
||||
Raises:
|
||||
HTTPException: 429 (busy) or 502 (upstream failure, or a stream that
|
||||
ended without a result).
|
||||
"""
|
||||
final = None
|
||||
for ev in _search_events(req):
|
||||
if ev.event == "error":
|
||||
@@ -482,7 +600,13 @@ def hotel_search(req: HotelSearchRequest) -> HotelSearchResponse:
|
||||
response_class=StreamingResponse,
|
||||
responses={200: {"content": {"application/x-ndjson": {"schema": HotelSearchEvent.model_json_schema()}}}},
|
||||
)
|
||||
def hotel_search_stream(req: HotelSearchRequest):
|
||||
def hotel_search_stream(req: HotelSearchRequest) -> StreamingResponse:
|
||||
"""Stream the search as NDJSON.
|
||||
|
||||
Always 200: the response starts before the work does, so failures (including
|
||||
the busy-slot case that the blocking endpoint reports as 429) arrive as a
|
||||
final "error" line instead of a status code.
|
||||
"""
|
||||
return _ndjson(_search_events(req))
|
||||
|
||||
|
||||
@@ -499,5 +623,12 @@ def hotel_search_stream(req: HotelSearchRequest):
|
||||
response_class=StreamingResponse,
|
||||
responses={200: {"content": {"application/x-ndjson": {"schema": HotelScanEvent.model_json_schema()}}}},
|
||||
)
|
||||
def hotel_scan_stream(req: HotelScanRequest):
|
||||
def hotel_scan_stream(req: HotelScanRequest) -> StreamingResponse:
|
||||
"""Stream the cheapest-night scan as NDJSON.
|
||||
|
||||
Transport is emitted once per unique hotel code, not once per row: the
|
||||
client is expected to apply each "transport" line to every night containing
|
||||
that code. Like the search stream this is always 200, with failures carried
|
||||
as a final "error" line.
|
||||
"""
|
||||
return _ndjson(_scan_events(req))
|
||||
|
||||
+406
-43
@@ -28,6 +28,33 @@ Method
|
||||
of the outbound.
|
||||
5. Rank by room + round-trip transport. Cycling time is reported separately
|
||||
(TfL cycle routing with an app key, otherwise a distance-based estimate).
|
||||
|
||||
Fragility
|
||||
Neither API is a documented public contract for this use. Travelodge's
|
||||
/api/v2/hotel endpoint is the JSON feed its own search page calls; the query
|
||||
parameter names ("q", "checkIn", "rooms[0][adults]", the undocumented
|
||||
"action=hotel_amend") and the response field names consumed in
|
||||
`normalise_hotel` are whatever the site happens to send today. If Travelodge
|
||||
reshapes its search page, every price here silently becomes None rather than
|
||||
raising. Same for TfL's fare JSON: `price_journey` reads `fare.fares[].cost`
|
||||
/ `peak` / `offPeak` / `chargeLevel`, and falls back to "no fare found" if the
|
||||
shape changes. There is no HTML parsing anywhere in this module - both
|
||||
upstreams are JSON - so there are no CSS/XPath selectors to break, but the
|
||||
key names play the same role.
|
||||
|
||||
Concurrency
|
||||
Everything here is thread-based (requests is blocking), not asyncio. Module
|
||||
state - the two response caches, the rate limiters and the shared
|
||||
requests.Session - is process-global and guarded by plain locks, so it is
|
||||
shared across concurrent FastAPI requests. main.py additionally allows only
|
||||
one live search at a time, which is what keeps the TfL budget spendable by a
|
||||
single run.
|
||||
|
||||
Time budgets
|
||||
Every network path takes an optional `deadline` (a time.monotonic() value).
|
||||
Passing it down instead of using a wall-clock timeout lets a long run degrade
|
||||
gracefully: work already done is returned with summary["truncated"] = True
|
||||
instead of the whole request dying at the nginx 300s proxy timeout.
|
||||
"""
|
||||
|
||||
import math
|
||||
@@ -43,6 +70,11 @@ import requests
|
||||
TL_API = "https://www.travelodge.co.uk/api/v2/hotel"
|
||||
TL_SITE = "https://www.travelodge.co.uk"
|
||||
TFL_API = "https://api.tfl.gov.uk/Journey/JourneyResults/{frm}/to/{to}"
|
||||
# A browser User-Agent is sent because Travelodge's edge rejects or throttles
|
||||
# obviously-scripted clients (python-requests/x.y). The Chrome version is
|
||||
# arbitrary and is never checked for freshness; if requests start coming back
|
||||
# as 403 or as a challenge page, this is the first thing to bump. The same
|
||||
# headers are reused for TfL, where they are harmless.
|
||||
HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Safari/537.36",
|
||||
"Accept": "application/json",
|
||||
@@ -101,6 +133,11 @@ TFL_CACHE_TTL_S = 2 * 60 * 60
|
||||
CYCLE_ROUTE_FACTOR = 1.3
|
||||
CYCLE_KMH = 14.0
|
||||
|
||||
# One process-wide Session so TLS handshakes and any cookies the upstreams set
|
||||
# are reused across requests (a fresh Session per call roughly doubles latency).
|
||||
# pool_maxsize must cover the widest possible fan-out - TfL workers plus every
|
||||
# scan date worker running its own batch of Travelodge page fetches - otherwise
|
||||
# urllib3 starts discarding connections and logging pool-full warnings.
|
||||
_session = requests.Session()
|
||||
_session.mount(
|
||||
"https://",
|
||||
@@ -115,8 +152,23 @@ class UpstreamError(Exception):
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Input parsing
|
||||
# --------------------------------------------------------------------------- #
|
||||
def parse_guests(spec):
|
||||
"""'2,2+1' -> [(2, 0), (2, 1)] (list of (adults, children) per room)."""
|
||||
def parse_guests(spec: str) -> list[tuple[int, int]]:
|
||||
"""Parse the compact guests string into per-room occupancy.
|
||||
|
||||
Comma separates rooms, "+" separates adults from children within a room,
|
||||
so '2,2+1' -> [(2, 0), (2, 1)]: two rooms, the second with one child.
|
||||
|
||||
Args:
|
||||
spec: user-supplied guests string, e.g. "1", "2+1", "2,2+2".
|
||||
|
||||
Returns:
|
||||
One (adults, children) tuple per room, in the order given. The index of
|
||||
each tuple becomes the ``rooms[i][...]`` index in the Travelodge query.
|
||||
|
||||
Raises:
|
||||
ValueError: empty spec, non-numeric part, a room with no adult, or a
|
||||
negative child count.
|
||||
"""
|
||||
rooms = []
|
||||
for part in spec.split(","):
|
||||
part = part.strip()
|
||||
@@ -134,8 +186,25 @@ def parse_guests(spec):
|
||||
return rooms
|
||||
|
||||
|
||||
def parse_origin(spec):
|
||||
"""Return (name, (lat, lon)) for an ORIGINS key or a 'lat,lon' string."""
|
||||
def parse_origin(spec: str) -> tuple[str, tuple[float, float]]:
|
||||
"""Resolve an origin to a display name and coordinates.
|
||||
|
||||
Args:
|
||||
spec: either a key of :data:`ORIGINS` (case-insensitive) or a raw
|
||||
"lat,lon" pair.
|
||||
|
||||
Returns:
|
||||
(display name, (lat, lon)). For raw coordinates the display name is the
|
||||
coordinates re-formatted to 4 decimal places (~11m), which is both the
|
||||
label shown to the user and a stable cache-key component.
|
||||
|
||||
Raises:
|
||||
ValueError: unknown station, unparseable coordinates, or coordinates
|
||||
outside :data:`LONDON_BOX`. The box check exists because TfL's
|
||||
journey planner will happily route from anywhere in the country and
|
||||
burn the rate-limit budget on journeys this tool cannot price
|
||||
sensibly.
|
||||
"""
|
||||
key = spec.strip().lower()
|
||||
if key in ORIGINS:
|
||||
name, lat, lon = ORIGINS[key]
|
||||
@@ -155,7 +224,24 @@ def parse_origin(spec):
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Travelodge
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _fetch_page(params, start, deadline=None):
|
||||
def _fetch_page(params: dict, start: int, deadline: float | None = None) -> list[dict]:
|
||||
"""Fetch one page of Travelodge search results.
|
||||
|
||||
Args:
|
||||
params: the shared query parameters built by :func:`fetch_hotels`.
|
||||
start: zero-based offset of the first result wanted; the API paginates
|
||||
by offset, not page number, in steps of :data:`TL_PAGE_SIZE`.
|
||||
deadline: time.monotonic() value; the socket timeout is shortened so a
|
||||
hung page cannot outlive the caller's budget.
|
||||
|
||||
Returns:
|
||||
The raw ``results`` array, or [] when the key is missing - an empty page
|
||||
is the only signal the API gives that pagination is exhausted.
|
||||
|
||||
Raises:
|
||||
UpstreamError: transport failure, non-2xx status, or a body that is not
|
||||
JSON (which in practice means a challenge/error HTML page).
|
||||
"""
|
||||
p = dict(params, start=start)
|
||||
timeout = 30
|
||||
if deadline is not None:
|
||||
@@ -165,14 +251,33 @@ def _fetch_page(params, start, deadline=None):
|
||||
r.raise_for_status()
|
||||
return r.json().get("results") or []
|
||||
except (requests.RequestException, ValueError, AttributeError) as e:
|
||||
# ValueError covers r.json() on a non-JSON body; AttributeError covers a
|
||||
# JSON body that is a list or scalar rather than an object (no .get).
|
||||
raise UpstreamError(f"Travelodge search failed: {e}") from e
|
||||
|
||||
|
||||
def fetch_hotels(location, checkin, checkout, rooms, deadline=None):
|
||||
"""Return list of hotel dicts from the Travelodge search API (all pages).
|
||||
def fetch_hotels(location, checkin, checkout, rooms, deadline=None) -> list[dict]:
|
||||
"""Return the raw hotel dicts for a search, following pagination.
|
||||
|
||||
rooms: list of (adults, children) tuples, one per room.
|
||||
deadline: time.monotonic() value after which page requests are cut short.
|
||||
Args:
|
||||
location: free-text search string, passed straight through as ``q``.
|
||||
checkin, checkout: :class:`datetime.date`; the API wants ISO dates.
|
||||
rooms: list of (adults, children) tuples from :func:`parse_guests`.
|
||||
deadline: time.monotonic() value limiting each page request.
|
||||
|
||||
Returns:
|
||||
Hotel dicts in API order, de-duplicated by ``code``. Order matters: it
|
||||
is the site's own relevance ranking and later sorts are stable, so ties
|
||||
on price keep the site's ordering.
|
||||
|
||||
Raises:
|
||||
UpstreamError: propagated from :func:`_fetch_page`.
|
||||
|
||||
Note:
|
||||
``action=hotel_amend`` is an undocumented parameter copied from the
|
||||
site's own XHR; without it the endpoint answers differently. Likewise
|
||||
``pagination=false`` does *not* disable paging - it only suppresses the
|
||||
pagination metadata block - which is why the offset loop below exists.
|
||||
"""
|
||||
params = {
|
||||
"pagination": "false",
|
||||
@@ -185,9 +290,11 @@ def fetch_hotels(location, checkin, checkout, rooms, deadline=None):
|
||||
params[f"rooms[{i}][adults]"] = adults
|
||||
params[f"rooms[{i}][children]"] = children
|
||||
|
||||
hotels, seen = [], set()
|
||||
hotels: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def absorb(results):
|
||||
def absorb(results: list[dict]) -> bool:
|
||||
"""Append hotels not seen before; return True if any were new."""
|
||||
new = [h for h in results if h.get("code") and h.get("code") not in seen]
|
||||
for h in new:
|
||||
seen.add(h["code"])
|
||||
@@ -199,6 +306,11 @@ def fetch_hotels(location, checkin, checkout, rooms, deadline=None):
|
||||
if not absorb(first) or len(first) < TL_PAGE_SIZE:
|
||||
return hotels
|
||||
|
||||
# Fetch TL_PAGE_BATCH pages at a time and stop on the first batch that is
|
||||
# either short (a page with fewer than TL_PAGE_SIZE results is the last one)
|
||||
# or wholly duplicate. Requesting speculatively overshoots by up to a batch,
|
||||
# but a strictly sequential walk of ~50 pages would blow the time budget.
|
||||
# TL_MAX_START is a hard stop in case the API ever pages forever.
|
||||
start = TL_PAGE_SIZE
|
||||
with ThreadPoolExecutor(max_workers=TL_PAGE_BATCH) as ex:
|
||||
while start <= TL_MAX_START:
|
||||
@@ -217,7 +329,17 @@ def fetch_hotels(location, checkin, checkout, rooms, deadline=None):
|
||||
return hotels
|
||||
|
||||
|
||||
def normalise_hotel(h):
|
||||
def normalise_hotel(h: dict) -> dict:
|
||||
"""Map one raw Travelodge hotel dict onto this service's stable field names.
|
||||
|
||||
This is the single place where upstream key names are read, so it is the
|
||||
only file location that needs changing when Travelodge renames a field.
|
||||
Every lookup is tolerant: a renamed or missing key yields None (or False)
|
||||
rather than an exception, so a shape change degrades into "no price"
|
||||
instead of a 502. ``minPrice`` is the cheapest bookable room for the whole
|
||||
stay in pounds (already a number, no currency string to parse), and
|
||||
``hotelUrl`` is site-relative so :data:`TL_SITE` is prefixed here.
|
||||
"""
|
||||
return {
|
||||
"code": h.get("code"),
|
||||
"name": h.get("title"),
|
||||
@@ -242,6 +364,9 @@ def hotels_for(location, checkin, checkout, rooms, deadline=None):
|
||||
|
||||
Failures are not cached. Callers must treat the returned dicts as read-only.
|
||||
"""
|
||||
# Case/whitespace-insensitive location so "Central London" and
|
||||
# "central london " share one cache entry; rooms must be hashable, hence
|
||||
# the tuple.
|
||||
key = (location.strip().lower(), checkin, checkout, tuple(rooms))
|
||||
now = time.monotonic()
|
||||
with _tl_cache_lock:
|
||||
@@ -249,6 +374,9 @@ def hotels_for(location, checkin, checkout, rooms, deadline=None):
|
||||
if hit and hit[0] > now:
|
||||
return hit[1]
|
||||
|
||||
# Deliberately outside the lock: a slow upstream fetch must not block other
|
||||
# threads reading the cache. Two threads racing on the same key both fetch
|
||||
# and the second write wins, which is harmless.
|
||||
hotels = [normalise_hotel(h) for h in fetch_hotels(location, checkin, checkout, rooms, deadline=deadline)]
|
||||
|
||||
with _tl_cache_lock:
|
||||
@@ -256,8 +384,10 @@ def hotels_for(location, checkin, checkout, rooms, deadline=None):
|
||||
expired = [k for k, (exp, _) in _tl_cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
del _tl_cache[k]
|
||||
# Bounded, not LRU: dicts preserve insertion order, so evicting the
|
||||
# first key drops the oldest *written* entry regardless of recent reads.
|
||||
while len(_tl_cache) >= TL_CACHE_MAX:
|
||||
del _tl_cache[next(iter(_tl_cache))] # oldest insertion
|
||||
del _tl_cache[next(iter(_tl_cache))]
|
||||
_tl_cache[key] = (now + TL_CACHE_TTL_S, hotels)
|
||||
return hotels
|
||||
|
||||
@@ -265,15 +395,27 @@ def hotels_for(location, checkin, checkout, rooms, deadline=None):
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Geometry
|
||||
# --------------------------------------------------------------------------- #
|
||||
def haversine_km(a, b):
|
||||
def haversine_km(a: tuple[float, float], b: tuple[float, float]) -> float:
|
||||
"""Great-circle distance in km between two (lat, lon) points in degrees.
|
||||
|
||||
6371.0 km is the mean Earth radius; at London scale the error from assuming
|
||||
a sphere is far smaller than the road-winding fudge applied on top.
|
||||
"""
|
||||
lat1, lon1 = map(math.radians, a)
|
||||
lat2, lon2 = map(math.radians, b)
|
||||
h = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
|
||||
return 2 * 6371.0 * math.asin(math.sqrt(h))
|
||||
|
||||
|
||||
def estimate_cycle(origin, dest):
|
||||
"""(minutes, km) for cycling from origin to dest, from straight-line distance."""
|
||||
def estimate_cycle(origin: tuple[float, float], dest: tuple[float, float]) -> tuple[int, float]:
|
||||
"""Estimate (minutes, km) for a cycle journey without calling TfL.
|
||||
|
||||
Straight-line distance is inflated by :data:`CYCLE_ROUTE_FACTOR` (roads do
|
||||
not go in straight lines) and divided by :data:`CYCLE_KMH`, a relaxed urban
|
||||
pace that absorbs traffic lights. Both constants are hand-tuned guesses, not
|
||||
measurements; they are only used when no TFL_APP_KEY is configured. Minutes
|
||||
are clamped to at least 1 so a hotel next to the origin never reads "0 min".
|
||||
"""
|
||||
km = haversine_km(origin, dest) * CYCLE_ROUTE_FACTOR
|
||||
return max(1, round(km / CYCLE_KMH * 60)), round(km, 1)
|
||||
|
||||
@@ -281,7 +423,14 @@ def estimate_cycle(origin, dest):
|
||||
# --------------------------------------------------------------------------- #
|
||||
# TfL
|
||||
# --------------------------------------------------------------------------- #
|
||||
def round_5p(pence):
|
||||
def round_5p(pence: float) -> int:
|
||||
"""Round a pence amount to the nearest 5p.
|
||||
|
||||
TfL quotes every discounted fare in whole 5p steps, so a raw 1/3-off
|
||||
multiplication has to be snapped back onto that grid to match what the
|
||||
passenger is actually charged. Python's banker's rounding applies at exact
|
||||
half-steps (2.5p), which is a sub-penny discrepancy and ignored.
|
||||
"""
|
||||
return int(5 * round(pence / 5.0))
|
||||
|
||||
|
||||
@@ -292,6 +441,18 @@ def price_journey(journey, adults=1, railcard_holders=1):
|
||||
|
||||
adults: number of fare-paying adults. railcard_holders: how many of them
|
||||
get 1/3 off off-peak rail fares (0 = nobody has a railcard).
|
||||
|
||||
All money is integer pence, straight from TfL - no currency strings are
|
||||
parsed and no floats are introduced until the final division by 100 in
|
||||
:func:`_transport_fields`, which keeps the arithmetic exact.
|
||||
|
||||
Children are not counted: the caller passes adults only, on the assumption
|
||||
that under-11s travel free on TfL.
|
||||
|
||||
The return leg is modelled, not fetched. It is assumed to be the same route
|
||||
made the next morning at an off-peak time, so it is priced at the outbound
|
||||
fare's ``offPeak`` value. That is optimistic for an early-morning return
|
||||
into zone 1, which is a real peak fare.
|
||||
"""
|
||||
railcard_holders = max(0, min(adults, railcard_holders))
|
||||
full_fare = adults - railcard_holders
|
||||
@@ -304,6 +465,9 @@ def price_journey(journey, adults=1, railcard_holders=1):
|
||||
if not non_walk: # walking only
|
||||
return 0, 0, "walk"
|
||||
|
||||
# TfL omits the fare block entirely for some journeys (e.g. ones involving
|
||||
# a mode it cannot price). Returning None makes the caller drop this option
|
||||
# rather than treat it as free.
|
||||
if not fare or not fare.get("fares"):
|
||||
return None
|
||||
|
||||
@@ -311,6 +475,11 @@ def price_journey(journey, adults=1, railcard_holders=1):
|
||||
for f in fare["fares"]:
|
||||
cost = f.get("cost") or 0
|
||||
peak, offpeak = f.get("peak") or 0, f.get("offPeak") or 0
|
||||
# Two independent bus tests, because TfL is inconsistent about which
|
||||
# it provides: a fare with neither a peak nor an off-peak price is a
|
||||
# flat bus fare by construction, and otherwise the tap records name the
|
||||
# mode outright. Getting this wrong would apply a Railcard discount to
|
||||
# a bus fare, which does not exist.
|
||||
is_bus = (peak == 0 and offpeak == 0) or any(
|
||||
(t.get("tapDetails") or {}).get("modeType") == "Bus" for t in (f.get("taps") or [])
|
||||
)
|
||||
@@ -319,6 +488,13 @@ def price_journey(journey, adults=1, railcard_holders=1):
|
||||
out += cost * adults
|
||||
ret += cost * adults
|
||||
else:
|
||||
# Railcards give 1/3 off *off-peak* rail/tube fares only, so the
|
||||
# outbound is discounted only when this fare is off-peak. That is
|
||||
# detected two ways because chargeLevel is free text that has
|
||||
# historically read "Off Peak", "Off-peak" or been absent: a
|
||||
# substring match on "off", or the cost simply equalling the
|
||||
# off-peak price. The return is always treated as off-peak (see the
|
||||
# docstring), so it is always discounted for railcard holders.
|
||||
level = (f.get("chargeLevel") or "").lower()
|
||||
out_full = cost
|
||||
ret_full = offpeak or cost # next-day return assumed off-peak
|
||||
@@ -327,7 +503,9 @@ def price_journey(journey, adults=1, railcard_holders=1):
|
||||
out += out_full * full_fare + out_disc * railcard_holders
|
||||
ret += ret_full * full_fare + ret_disc * railcard_holders
|
||||
|
||||
# short human summary of the route
|
||||
# Short human summary of the route, e.g. "rail > tube Victoria". Walking
|
||||
# legs are dropped as noise, and "national-rail" is shortened purely to fit
|
||||
# the column in the UI.
|
||||
parts = []
|
||||
for l in legs:
|
||||
m = (l.get("mode") or {}).get("id")
|
||||
@@ -342,13 +520,28 @@ def price_journey(journey, adults=1, railcard_holders=1):
|
||||
class RateLimiter:
|
||||
"""Sliding-window limiter: at most `per_minute` acquisitions in any 60s."""
|
||||
|
||||
def __init__(self, per_minute):
|
||||
def __init__(self, per_minute: int) -> None:
|
||||
"""Args: per_minute: maximum acquisitions allowed in any 60s window."""
|
||||
self.per_minute = per_minute
|
||||
self._times = deque()
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def acquire(self, deadline=None):
|
||||
"""Block until a slot is free. Returns False if `deadline` would pass first."""
|
||||
def acquire(self, deadline: float | None = None) -> bool:
|
||||
"""Block until a slot is free.
|
||||
|
||||
Args:
|
||||
deadline: time.monotonic() value; if the wait would run past it,
|
||||
give up immediately instead of sleeping.
|
||||
|
||||
Returns:
|
||||
True when a slot was taken, False when the deadline would pass
|
||||
first (the caller should then abandon the request).
|
||||
|
||||
The sleep is capped at 1s per iteration rather than sleeping the full
|
||||
computed wait, so that a slot freed by another thread finishing early is
|
||||
picked up promptly, and so the deadline is re-checked often. The lock is
|
||||
released before sleeping - holding it would serialise every waiter.
|
||||
"""
|
||||
while True:
|
||||
with self._lock:
|
||||
now = time.monotonic()
|
||||
@@ -367,7 +560,12 @@ _limiters = {}
|
||||
_limiters_lock = threading.Lock()
|
||||
|
||||
|
||||
def _limiter(app_key):
|
||||
def _limiter(app_key: str | None) -> RateLimiter:
|
||||
"""Return the shared limiter for the rate that `app_key` unlocks.
|
||||
|
||||
Limiters are keyed by rate, not by key, so every caller at a given tier
|
||||
shares one 60s window - which is the point, since TfL counts per source IP.
|
||||
"""
|
||||
rate = TFL_RATE_KEYED if app_key else TFL_RATE_ANON
|
||||
with _limiters_lock:
|
||||
lim = _limiters.get(rate)
|
||||
@@ -389,8 +587,28 @@ def sleep_within(seconds, deadline):
|
||||
return True
|
||||
|
||||
|
||||
def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=None):
|
||||
"""Journeys from TfL for one origin/destination/time/mode, cached and rate limited."""
|
||||
def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=None) -> list[dict]:
|
||||
"""Journeys from TfL for one origin/destination/time/mode, cached and rate limited.
|
||||
|
||||
Args:
|
||||
frm, to: (lat, lon) tuples; TfL accepts raw coordinates in the path.
|
||||
when: naive :class:`datetime` of the intended departure, London local
|
||||
time (TfL interprets it as such; no timezone is sent).
|
||||
extra: additional query parameters, e.g. ``{"mode": "bus,walking"}`` to
|
||||
force a bus-only route or ``{"mode": "cycle"}`` for cycle routing.
|
||||
app_key: TfL API key from the TFL_APP_KEY env var, or None for the
|
||||
anonymous tier.
|
||||
retries: attempts before giving up.
|
||||
deadline: time.monotonic() value bounding the whole call.
|
||||
|
||||
Returns:
|
||||
The ``journeys`` array, or [] on any failure. This function never
|
||||
raises: a missing route and a dead API look the same to the caller, who
|
||||
simply ends up with no priced option for that hotel. That is deliberate
|
||||
- one flaky lookup should not abort a 40-hotel search - but it does mean
|
||||
a total TfL outage shows up in the UI as "no TfL fare found" rather than
|
||||
as an error.
|
||||
"""
|
||||
params = {
|
||||
"date": when.strftime("%Y%m%d"),
|
||||
"time": when.strftime("%H%M"),
|
||||
@@ -399,6 +617,9 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
|
||||
}
|
||||
if extra:
|
||||
params.update(extra)
|
||||
# Coordinates are rounded to 5dp (~1m) so that floating-point noise in
|
||||
# otherwise identical requests still hits the cache. app_key is excluded
|
||||
# from the key on purpose: the route and fare do not depend on it.
|
||||
key = (round(frm[0], 5), round(frm[1], 5), round(to[0], 5), round(to[1], 5), params["date"], params["time"],
|
||||
tuple(sorted((extra or {}).items())))
|
||||
now = time.monotonic()
|
||||
@@ -412,6 +633,14 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
|
||||
url = TFL_API.format(frm=f"{frm[0]},{frm[1]}", to=f"{to[0]},{to[1]}")
|
||||
limiter = _limiter(app_key)
|
||||
journeys = None
|
||||
# Retry policy, all deadline-aware (a skipped sleep means the deadline is
|
||||
# too close, so stop rather than hammer):
|
||||
# network error -> wait 2s
|
||||
# 429 rate limited -> linear backoff, 5s then 10s then 15s
|
||||
# 5xx -> wait 2s
|
||||
# any other non-200 (notably 300 "disambiguation", meaning TfL wants the
|
||||
# caller to pick between candidate locations) -> treat as "no route",
|
||||
# do not retry, and cache the empty result
|
||||
for attempt in range(retries):
|
||||
remaining = TFL_TIMEOUT_S if deadline is None else deadline - time.monotonic()
|
||||
if remaining < 1 or not limiter.acquire(deadline):
|
||||
@@ -439,9 +668,15 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
|
||||
journeys = []
|
||||
break
|
||||
|
||||
# journeys is still None only if every attempt was abandoned; return empty
|
||||
# without caching so a later, less rushed call can try again. An empty list
|
||||
# from a *successful* response is cached - "no route" is a real answer.
|
||||
if journeys is None:
|
||||
return [] # gave up: don't cache a failure
|
||||
return []
|
||||
with _tfl_cache_lock:
|
||||
# Sweep expired entries only once the cache is large, so the common path
|
||||
# stays O(1); TFL_CACHE_TTL_S is long because journey times and fares
|
||||
# for a fixed date/time do not change.
|
||||
if len(_tfl_cache) > 5000:
|
||||
expired = [k for k, (exp, _) in _tfl_cache.items() if exp <= now]
|
||||
for k in expired:
|
||||
@@ -450,14 +685,40 @@ def tfl_journeys(frm, to, when, extra=None, app_key=None, retries=3, deadline=No
|
||||
return journeys
|
||||
|
||||
|
||||
# Two journey queries per hotel, because TfL's default "LeastTime" answer is
|
||||
# usually a tube fare and the cheapest option is very often a slower bus. The
|
||||
# bus query has to name "walking" alongside "bus" or TfL refuses routes that
|
||||
# need a walk to the stop.
|
||||
TRANSPORT_QUERIES = (("fast", None), ("bus", {"mode": "bus,walking"}))
|
||||
CYCLE_QUERY = {"mode": "cycle"}
|
||||
|
||||
|
||||
def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, app_key=None, deadline=None, pool=None):
|
||||
"""Cheapest acceptable round-trip transport to a hotel. Returns dict or None.
|
||||
"""Cheapest acceptable round-trip transport to a hotel.
|
||||
|
||||
Runs the fast and bus-only TfL queries concurrently on `pool` when given.
|
||||
Args:
|
||||
origin: (lat, lon) of the journey start.
|
||||
hotel: normalised hotel dict; only lat/lon are read.
|
||||
when: departure datetime for the outbound leg.
|
||||
adults, railcard_holders: party makeup, passed to :func:`price_journey`.
|
||||
max_minutes: routes slower than this are rejected - unless *every*
|
||||
route is slower, in which case the fastest is kept so the hotel
|
||||
still gets a price rather than vanishing from the results.
|
||||
app_key: TfL key or None.
|
||||
deadline: time.monotonic() budget.
|
||||
pool: optional executor; the two queries are independent, so running
|
||||
them concurrently halves the latency per hotel. Note this pool is
|
||||
shared with the caller's other work, so it must never be sized 1 or
|
||||
the map below can deadlock behind its own parent task.
|
||||
|
||||
Returns:
|
||||
The chosen option as a dict with keys ``kind`` ("fast"/"bus"),
|
||||
``outbound_p``, ``return_p``, ``total_p`` (integer pence), ``minutes``,
|
||||
``route``, plus ``fastest_*`` fields describing the quickest option so
|
||||
the UI can show the speed/price trade-off. None if nothing was priceable.
|
||||
|
||||
Ties are broken by duration, so two equally cheap routes resolve to the
|
||||
quicker one.
|
||||
"""
|
||||
dest = (hotel["lat"], hotel["lon"])
|
||||
|
||||
@@ -498,9 +759,23 @@ def best_transport(origin, hotel, when, adults, railcard_holders, max_minutes, a
|
||||
|
||||
|
||||
def cycle_time(origin, hotel, when, app_key, deadline=None, journeys=None):
|
||||
"""(minutes, km, source) for cycling to the hotel. TfL routing only with an app key.
|
||||
"""(minutes, km, source) for cycling to the hotel.
|
||||
|
||||
`journeys` may carry an already-fetched TfL cycle response to avoid a second call.
|
||||
Real TfL cycle routing is used only when an app key is configured, because
|
||||
it costs a third rate-limited request per hotel and the anonymous 50/min
|
||||
budget is already spent on fares; without a key this falls straight back to
|
||||
:func:`estimate_cycle`. ``source`` is "tfl" or "estimate" so the UI can say
|
||||
which it is showing.
|
||||
|
||||
Args:
|
||||
journeys: an already-fetched cycle response, so the caller can start the
|
||||
request early and overlap it with the fare lookups.
|
||||
|
||||
Returns:
|
||||
(minutes, km, source). The km comes from summing per-leg ``distance``
|
||||
values, which TfL reports in metres; if that sum is zero (the field is
|
||||
sometimes absent) the straight-line estimate is used for distance while
|
||||
keeping TfL's duration.
|
||||
"""
|
||||
dest = (hotel["lat"], hotel["lon"])
|
||||
est_min, est_km = estimate_cycle(origin, dest)
|
||||
@@ -518,6 +793,9 @@ def cycle_time(origin, hotel, when, app_key, deadline=None, journeys=None):
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Search
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Every transport column blanked out. Splatted into a row to reset it, so
|
||||
# adding a transport field means adding it here too or it will leak a stale
|
||||
# value from a previous night when rows are reused in a scan.
|
||||
_UNPRICED = {
|
||||
"transport_out": None,
|
||||
"transport_return": None,
|
||||
@@ -532,7 +810,14 @@ _UNPRICED = {
|
||||
TIME_LIMIT_ROUTE = "not priced (time limit)"
|
||||
|
||||
|
||||
def _transport_fields(hotel, t):
|
||||
def _transport_fields(hotel: dict, t: dict | None) -> dict:
|
||||
"""Convert a :func:`best_transport` result into the row's output columns.
|
||||
|
||||
Pence become pounds here (the only place), and ``total`` is room price plus
|
||||
round-trip transport, rounded to 2dp for display. When `t` is None every
|
||||
transport column is None and ``route`` carries the reason, which is what the
|
||||
UI renders in place of a price.
|
||||
"""
|
||||
if not t:
|
||||
return dict(_UNPRICED, route="no TfL fare found")
|
||||
return {
|
||||
@@ -548,13 +833,31 @@ def _transport_fields(hotel, t):
|
||||
}
|
||||
|
||||
|
||||
def sort_rows(rows):
|
||||
def sort_rows(rows: list[dict]) -> None:
|
||||
"""Sort rows in place by total cost, unpriced rows last.
|
||||
|
||||
``r["total"] is None`` sorts False(0) before True(1), so priced rows come
|
||||
first; ``or 0`` then keeps the comparison from hitting None. Room price is
|
||||
the tiebreak.
|
||||
"""
|
||||
rows.sort(key=lambda r: (r["total"] is None, r["total"] or 0, r["room_price"]))
|
||||
|
||||
|
||||
def _shortlist(hotels, max_miles, top):
|
||||
"""(available, shortlist): bookable, priced, geocoded hotels within max_miles
|
||||
sorted by room price, and the cheapest `top` of them."""
|
||||
def _shortlist(hotels: list[dict], max_miles: float | None, top: int) -> tuple[list[dict], list[dict]]:
|
||||
"""Filter and rank hotels, then take the cheapest `top`.
|
||||
|
||||
Hotels are dropped unless they are bookable, have a price, and have
|
||||
coordinates - the last because a hotel without lat/lon cannot be routed and
|
||||
would crash the TfL step. ``distance_from_search_mi`` is Travelodge's own
|
||||
distance from the searched location (miles, not from the travel origin),
|
||||
and a missing value is treated as 0 so it survives the filter rather than
|
||||
being silently excluded.
|
||||
|
||||
Returns:
|
||||
(all qualifying hotels sorted by room price, the cheapest `top` of them).
|
||||
Only the shortlist gets transport priced, which is what bounds the
|
||||
number of TfL calls.
|
||||
"""
|
||||
avail = [h for h in hotels if h["available"] and h["room_price"] and h["lat"] is not None and h["lon"] is not None]
|
||||
if max_miles is not None:
|
||||
avail = [h for h in avail if (h["distance_from_search_mi"] or 0) <= max_miles]
|
||||
@@ -562,8 +865,15 @@ def _shortlist(hotels, max_miles, top):
|
||||
return avail, avail[:top]
|
||||
|
||||
|
||||
def _make_row(h, origin):
|
||||
"""Result row for a hotel: unpriced transport plus an estimated cycle time."""
|
||||
def _make_row(h: dict, origin: tuple[float, float]) -> dict:
|
||||
"""Build the initial result row for a hotel.
|
||||
|
||||
Transport columns start blank with route "pricing…" - the stream emits these
|
||||
rows immediately so the UI can render the hotel list while TfL is still
|
||||
being queried, then patches each row in place when its "transport" event
|
||||
arrives. The cycle estimate is cheap and local, so it is filled in up front
|
||||
and only overwritten later if TfL cycle routing is available.
|
||||
"""
|
||||
row = dict(h, **_UNPRICED, route="pricing…")
|
||||
est_min, est_km = estimate_cycle(origin, (h["lat"], h["lon"]))
|
||||
row.update({"cycle_minutes": est_min, "cycle_km": est_km, "cycle_source": "estimate"})
|
||||
@@ -576,6 +886,22 @@ def _price_hotels(hotels, origin, depart_dt, adults, railcard_holders, max_trave
|
||||
Generator of (code, transport_or_None, cycle_or_None, timed_out) in the order
|
||||
TfL answers. Owns the worker pools; leftover work is cancelled if the
|
||||
consumer stops early.
|
||||
|
||||
Two pools, not one: `hotel_pool` runs at most TFL_HOTEL_WORKERS hotels at a
|
||||
time and each of those tasks submits its own sub-queries to the larger
|
||||
`tfl_pool`. Sharing one pool would let the hotel tasks fill every slot and
|
||||
then block waiting for sub-tasks that can never be scheduled - a classic
|
||||
executor deadlock.
|
||||
|
||||
`timed_out` distinguishes "TfL has no fare for this hotel" from "we ran out
|
||||
of time before asking", which the caller surfaces as summary["truncated"].
|
||||
Note it is inferred from the clock at completion time rather than reported
|
||||
by the worker, so it can misattribute a genuine no-fare result that happens
|
||||
to land after the deadline.
|
||||
|
||||
The cancel loop in `finally` is best-effort - it only stops tasks that have
|
||||
not started - and the `with` blocks still join running workers, so an
|
||||
abandoned stream takes up to one in-flight TfL timeout to unwind.
|
||||
"""
|
||||
with ThreadPoolExecutor(max_workers=TFL_WORKERS) as tfl_pool, \
|
||||
ThreadPoolExecutor(max_workers=TFL_HOTEL_WORKERS) as hotel_pool:
|
||||
@@ -605,7 +931,8 @@ def _price_hotels(hotels, origin, depart_dt, adults, railcard_holders, max_trave
|
||||
f.cancel()
|
||||
|
||||
|
||||
def _apply_transport(row, t, cyc, timed_out):
|
||||
def _apply_transport(row: dict, t: dict | None, cyc: tuple | None, timed_out: bool) -> dict:
|
||||
"""Merge one hotel's transport and cycle results into its row, in place."""
|
||||
row.update(_transport_fields(row, t))
|
||||
if timed_out:
|
||||
row["route"] = TIME_LIMIT_ROUTE
|
||||
@@ -614,13 +941,24 @@ def _apply_transport(row, t, cyc, timed_out):
|
||||
return row
|
||||
|
||||
|
||||
def _party(rooms, railcard_holders):
|
||||
def _party(rooms: list[tuple[int, int]], railcard_holders: int) -> tuple[int, int, int]:
|
||||
"""Totals for the booking: (adults, children, railcard holders).
|
||||
|
||||
Railcard holders are clamped to the number of adults so an over-stated
|
||||
value cannot discount more fares than there are payers.
|
||||
"""
|
||||
adults = sum(a for a, _ in rooms)
|
||||
children = sum(c for _, c in rooms)
|
||||
return adults, children, max(0, min(adults, railcard_holders))
|
||||
|
||||
|
||||
def _depart_dt(day, depart):
|
||||
def _depart_dt(day: date, depart: str) -> datetime:
|
||||
"""Combine a check-in date with an "HH:MM" string into a naive datetime.
|
||||
|
||||
Naive on purpose: TfL reads the date/time as London local time, so
|
||||
attaching a timezone here would only invite a double conversion. The format
|
||||
is already validated by the Pydantic model in main.py.
|
||||
"""
|
||||
hh, mm = map(int, depart.split(":"))
|
||||
return datetime(day.year, day.month, day.day, hh, mm)
|
||||
|
||||
@@ -699,9 +1037,15 @@ def run_search(
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Date-range scan
|
||||
# --------------------------------------------------------------------------- #
|
||||
def candidate_checkins(start, end, weekdays, nights):
|
||||
"""[(checkin, checkout)] for every day start..end (inclusive) whose weekday
|
||||
(0=Mon) is in `weekdays`, each for a stay of `nights` nights."""
|
||||
def candidate_checkins(start: date, end: date, weekdays, nights: int) -> list[tuple[date, date]]:
|
||||
"""Enumerate candidate (checkin, checkout) pairs for a date-range scan.
|
||||
|
||||
Every day from `start` to `end` inclusive whose weekday (0=Mon, matching
|
||||
:meth:`date.weekday`) is in `weekdays` becomes a check-in, with check-out
|
||||
`nights` days later. Note the checkout may fall past `end` - `end` bounds
|
||||
the check-in date, not the stay. main.py also calls this during validation
|
||||
purely to reject a range that matches no weekday.
|
||||
"""
|
||||
out = []
|
||||
day = start
|
||||
while day <= end:
|
||||
@@ -711,7 +1055,13 @@ def candidate_checkins(start, end, weekdays, nights):
|
||||
return out
|
||||
|
||||
|
||||
def _copy_night(n):
|
||||
def _copy_night(n: dict) -> dict:
|
||||
"""Two-level copy of a night before yielding it.
|
||||
|
||||
The generator keeps mutating `night_list` after each event, so both the
|
||||
night dict and its hotel rows must be copied or the caller's already-emitted
|
||||
JSON would change underneath it.
|
||||
"""
|
||||
return dict(n, hotels=[dict(r) for r in n["hotels"]])
|
||||
|
||||
|
||||
@@ -840,6 +1190,10 @@ def run_scan(
|
||||
|
||||
# Phase 2: one TfL price per unique hotel. Hotels that are cheapest on some
|
||||
# night go first, since they are the likely winners if time runs out.
|
||||
# A hotel can appear on many nights; it is priced once. Its ordering key is
|
||||
# its best (lowest) position in any night's list, tiebroken by price, so
|
||||
# hotels that top some night get their fares first and a truncated scan
|
||||
# still has the likely winners priced.
|
||||
index = {} # code -> ((best rank, min room price), row)
|
||||
for n in night_list:
|
||||
for rank, row in enumerate(n["hotels"]):
|
||||
@@ -855,6 +1209,9 @@ def run_scan(
|
||||
ordered, origin, depart_dt, adults, railcard_holders, max_travel_min, app_key, deadline
|
||||
):
|
||||
base = index[code][1]
|
||||
# Transport here is night-independent, so there is no room price to add:
|
||||
# a dummy 0 is passed and the resulting "total" discarded. Each night
|
||||
# computes its own total in phase 3.
|
||||
fields = _transport_fields({"room_price": 0}, t)
|
||||
fields.pop("total", None)
|
||||
if timed_out:
|
||||
@@ -863,6 +1220,8 @@ def run_scan(
|
||||
if cyc:
|
||||
fields["cycle_minutes"], fields["cycle_km"], fields["cycle_source"] = cyc
|
||||
else:
|
||||
# No TfL cycle result: keep the local estimate already on the row,
|
||||
# since these fields are copied wholesale onto every night's copy.
|
||||
fields.update({k: base[k] for k in ("cycle_minutes", "cycle_km", "cycle_source")})
|
||||
fields["code"] = code
|
||||
transport[code] = fields
|
||||
@@ -875,6 +1234,7 @@ def run_scan(
|
||||
continue
|
||||
for row in n["hotels"]:
|
||||
fields = transport.get(row["code"])
|
||||
# Missing means phase 2 ran out of time before reaching this hotel.
|
||||
if fields is None:
|
||||
row["route"] = TIME_LIMIT_ROUTE
|
||||
continue
|
||||
@@ -888,6 +1248,9 @@ def run_scan(
|
||||
n["best_code"] = best["code"]
|
||||
n["best_room"] = min(r["room_price"] for r in n["hotels"])
|
||||
|
||||
# Cheapest night first; nights with no total (failed, skipped, or unpriced)
|
||||
# fall to the bottom, ordered by best room price and then by date so the
|
||||
# list is still deterministic.
|
||||
night_list.sort(
|
||||
key=lambda n: (
|
||||
n["best_total"] is None,
|
||||
|
||||
@@ -1,3 +1,27 @@
|
||||
# =============================================================================
|
||||
# Quartz image — builds the Obsidian notes site.
|
||||
#
|
||||
# HOW THE SOURCE IS OBTAINED: Quartz is not an npm package you depend on, it is
|
||||
# an application you clone and configure. So the image `git clone`s the
|
||||
# upstream repo at build time, which is why `git` is installed. --depth 1
|
||||
# --branch pins to an exact tag (QUARTZ_VERSION, overridable as a build ARG)
|
||||
# and fetches no history — a shallow clone is much faster on a Pi and the
|
||||
# history is of no use here.
|
||||
#
|
||||
# Because this clone happens at build time, upstream Quartz is only updated
|
||||
# when the image is rebuilt with a bumped QUARTZ_VERSION. The tag pin is the
|
||||
# thing stopping an upstream change from breaking the notes site on a routine
|
||||
# redeploy.
|
||||
#
|
||||
# gettext-base supplies `envsubst` for rendering quartz.config.ts from its
|
||||
# template at container start (see quartz/entrypoint.sh).
|
||||
#
|
||||
# quartz.config.ts.template and quartz.layout.ts are copied in AFTER the clone
|
||||
# so they land on top of the upstream defaults — layout is used as-is, config
|
||||
# is templated at runtime because it needs DOMAIN.
|
||||
#
|
||||
# node:22-slim is multi-arch, so this builds unchanged on the Pi.
|
||||
# =============================================================================
|
||||
FROM node:22-slim
|
||||
|
||||
RUN apt-get update \
|
||||
|
||||
@@ -1,4 +1,38 @@
|
||||
#!/bin/sh
|
||||
# =============================================================================
|
||||
# quartz entrypoint — render the config, then build-and-serve the notes site.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# Quartz turns the Obsidian vault into a static site. Its config is a
|
||||
# TypeScript file that has to know the public base URL, which is only known
|
||||
# at runtime, so quartz.config.ts is generated from a template on each start.
|
||||
#
|
||||
# THE envsubst ALLOW-LIST
|
||||
# Only ${DOMAIN} is substituted. This matters more here than elsewhere: the
|
||||
# template is TypeScript and full of `${...}` -shaped syntax and dollar signs
|
||||
# that must NOT be touched. Restricting envsubst to a single name guarantees
|
||||
# it can only ever rewrite the one intended line (baseUrl).
|
||||
#
|
||||
# WHY build --serve RATHER THAN A STATIC BUILD
|
||||
# --serve leaves Quartz running as an HTTP server AND watching the content
|
||||
# directory, so editing a note in Obsidian on the host re-renders the site
|
||||
# live with no container restart. The vault is bind-mounted READ-ONLY
|
||||
# (docker-compose.yml), so Quartz can watch it but never write to it.
|
||||
# The trade-off is that this is a long-running Node process on a Pi rather
|
||||
# than pre-built static files nginx could serve for free.
|
||||
#
|
||||
# ACCESS CONTROL
|
||||
# None here — Quartz is wide open on its port inside app-network. The site is
|
||||
# private because nginx gates /notes/ behind an `auth_request` admin check
|
||||
# before proxying. Never publish this container's port to the host.
|
||||
#
|
||||
# ENV VARS
|
||||
# DOMAIN required; becomes baseUrl "www.<DOMAIN>/notes"
|
||||
# QUARTZ_PORT optional, defaults to 8080; must match the QUARTZ_PORT nginx
|
||||
# builds its upstream from, or /notes/ 502s.
|
||||
#
|
||||
# `exec` so the Node process becomes PID 1 and receives docker's signals.
|
||||
# =============================================================================
|
||||
set -e
|
||||
|
||||
envsubst '${DOMAIN}' \
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
// =============================================================================
|
||||
// quartz.config.ts.template — Quartz site config, rendered to quartz.config.ts
|
||||
// by quartz/entrypoint.sh at container start.
|
||||
//
|
||||
// ONLY the DOMAIN placeholder is substituted (envsubst is given a one-name allow-list), so
|
||||
// every other dollar sign and backtick-template-looking construct in this
|
||||
// TypeScript file survives untouched. That restriction is deliberate: a bare
|
||||
// envsubst over a .ts file would corrupt it.
|
||||
//
|
||||
// baseUrl must keep pointing at www.<DOMAIN>/notes — it has to match the path nginx
|
||||
// proxies (/notes/) or every internal link, the sitemap and the RSS feed point
|
||||
// at the wrong place.
|
||||
//
|
||||
// enableSPA / enablePopovers are off because this site is embedded under a
|
||||
// path inside another SPA; Quartz's own client-side router would fight with it.
|
||||
//
|
||||
// ignorePatterns keeps "private", "templates" and ".obsidian" out of the build
|
||||
// — the vault is mounted whole, so this list is the only thing stopping
|
||||
// private notes being published. Check it before adding vault folders.
|
||||
//
|
||||
// This file is committed with real content (no secrets). quartz.layout.ts sits
|
||||
// alongside it and is COPY'd in by quartz/Dockerfile without templating.
|
||||
// =============================================================================
|
||||
import { QuartzConfig } from "./quartz/cfg"
|
||||
import * as Plugin from "./quartz/plugins"
|
||||
|
||||
|
||||
@@ -1,3 +1,35 @@
|
||||
# =============================================================================
|
||||
# Vue frontend image — compiles Rust to WASM, then builds the SPA.
|
||||
#
|
||||
# THIS IS A BUILD CONTAINER, NOT A SERVER. In production the container runs
|
||||
# `vite build` into /output (the shared vue_dist volume) and EXITS. nginx then
|
||||
# serves those files. Seeing `vue` as Exited(0) in `docker compose ps` is the
|
||||
# success case, not a failure. The dev override replaces the CMD with the Vite
|
||||
# dev server, and then it does stay running.
|
||||
#
|
||||
# STAGE 1 — WASM
|
||||
# Builds crates/stp_wasm with wasm-pack into src/wasm. Only that crate
|
||||
# directory is copied in, so touching Vue source never invalidates the (slow)
|
||||
# Rust layer. The two cache mounts persist the cargo registry and the Rust
|
||||
# target directory between builds on the host — on a Raspberry Pi this turns
|
||||
# a very long compile into an incremental one. src/wasm is gitignored: it is
|
||||
# generated, never committed.
|
||||
#
|
||||
# STAGE 2 — Vue
|
||||
# package.json + package-lock.json are copied first so `npm ci` is cached
|
||||
# independently of source changes; the npm cache is also a BuildKit cache
|
||||
# mount. `npm ci` (not `npm install`) installs exactly the lockfile, so a
|
||||
# rebuild can never silently pick up a different dependency version.
|
||||
# `make` and `git` are installed because some npm dependencies build native
|
||||
# code or resolve git URLs during install.
|
||||
#
|
||||
# --emptyOutDir is required: /output is a mounted volume, and vite refuses to
|
||||
# clear a directory outside the project root without it. Without the flag,
|
||||
# stale assets from a previous build would accumulate and be served.
|
||||
#
|
||||
# Note stage 2 is not named and is the final stage; both base images are
|
||||
# multi-arch so this builds on the Pi unchanged.
|
||||
# =============================================================================
|
||||
# Stage 1: Build WASM from Rust
|
||||
FROM rust:slim AS wasm-builder
|
||||
RUN rustup target add wasm32-unknown-unknown \
|
||||
|
||||
+136
@@ -18,6 +18,142 @@ The Vite dev server proxies API requests:
|
||||
- `/api` -> `http://localhost:8080` (Go backend)
|
||||
- `/gitea` -> `http://localhost:3000` (Gitea)
|
||||
- `/radio` -> `http://localhost:8000` (Icecast2)
|
||||
- `/py` -> `http://localhost:8000` (FastAPI; the `/py` prefix is stripped, as nginx does in production)
|
||||
|
||||
## Structure
|
||||
|
||||
```
|
||||
src/
|
||||
main.js entry point — awaits the wasm init, then mounts <App>
|
||||
App.vue empty shell; all chrome lives in the layouts
|
||||
router/index.js route table + the single admin route guard
|
||||
graphql.js the entire GraphQL client (one axios POST)
|
||||
layouts/ DefaultLayout (dark, navbar+footer) and CVLayout (light, print)
|
||||
stores/ Pinia stores
|
||||
components/ reusable UI — text/, input/, util/, borders/, elle/
|
||||
views/ page components, one directory per area
|
||||
assets/styles.css design tokens + base styles (see Styling)
|
||||
js/ small shared helpers
|
||||
wasm/ GENERATED by `npm run build:wasm`; gitignored, do not edit
|
||||
crates/stp_wasm the Rust source for the above
|
||||
```
|
||||
|
||||
## Routing
|
||||
|
||||
Two layout shells, defined in `src/router/index.js`:
|
||||
|
||||
| Path | Layout | Notes |
|
||||
| --- | --- | --- |
|
||||
| `/` | DefaultLayout | Landing page (statically imported — it's the first paint) |
|
||||
| `/stp` | DefaultLayout | The personal home page: the widget grid |
|
||||
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin` |
|
||||
| `/automata`, `/hotels`, `/shrines/*` | DefaultLayout | |
|
||||
| `/cv`, `/cv/jobs` | CVLayout | Light print theme; `/cv/jobs` is admin-only |
|
||||
| `/stp2` | (none) | Bare full-bleed mock, deliberately outside both layouts |
|
||||
| `:pathMatch(.*)*` | DefaultLayout | 404 |
|
||||
|
||||
Everything except the landing page is a dynamic `import()`, so Vite gives each
|
||||
view its own chunk.
|
||||
|
||||
Route `name`s are contracts used by `RouterLink`/`router.push` — renaming one
|
||||
breaks every link to it.
|
||||
|
||||
**The admin guard** (`router.beforeEach`) has one subtlety: the admin flag comes
|
||||
from the `me` field of the home-data query, which arrives asynchronously.
|
||||
Navigating straight to `/admin` on a cold load would otherwise read an empty
|
||||
user and bounce a real admin to the login page, so the guard first awaits
|
||||
`homeData.loaded` via a self-stopping watcher.
|
||||
|
||||
## Data flow
|
||||
|
||||
There is no GraphQL cache or codegen. `src/graphql.js` is a single function:
|
||||
|
||||
```js
|
||||
const data = await gql(`query { ... }`, variables);
|
||||
```
|
||||
|
||||
It POSTs to `/api/graphql` and throws on an error response with no data. Auth
|
||||
rides along in **HTTP-only cookies** set by the Go backend, so nothing here
|
||||
touches tokens — the request just has to be same-origin (nginx in production,
|
||||
the Vite proxy in dev).
|
||||
|
||||
**`stores/homeData.js` is the hub.** It issues *one* query for everything the
|
||||
`/stp` page needs (posts, favourites, activities, Spotify, rowing, bookmarks,
|
||||
Gitea feed, Steam status, current user) instead of letting a dozen widgets each
|
||||
fire their own request. That fetch is kicked off as a side effect of the first
|
||||
`useHomeDataStore()` call, so no component has to start it.
|
||||
|
||||
The other stores are thin views over it:
|
||||
|
||||
| Store | Role |
|
||||
| --- | --- |
|
||||
| `homeData` | the one query; owns `loaded` / `error` |
|
||||
| `auth` | current user; mirrors `homeData.me`, plus login/logout mutations |
|
||||
| `posts`, `favorites`, `activity`, `songs`, `steam` | mirror one slice of `homeData` via an `immediate` watch, and keep a placeholder value until real data arrives |
|
||||
| `places` | independent CRUD; sign-in only, so it is fetched lazily |
|
||||
| `messages` | the chat WebSocket — not GraphQL at all |
|
||||
| `models` | dormant; not imported anywhere |
|
||||
|
||||
The mirroring watches are `immediate` on purpose: a store created *after*
|
||||
`homeData` has already loaded would never see the existing value otherwise.
|
||||
|
||||
## Component conventions
|
||||
|
||||
- Layout and one-off tweaks go in Tailwind utilities; reach for a scoped
|
||||
`<style>` only for what utilities can't express (`grid-template-areas`,
|
||||
keyframes, media-query-specific layouts).
|
||||
- Never hard-code a colour — use a token. The one exception is `<canvas>`
|
||||
drawing (`views/automata/MobileAutomata.vue`), which cannot read CSS
|
||||
variables.
|
||||
- Home widgets: title goes in `<Header>`; admin create forms use
|
||||
`<CreateToggle v-model="showCreate">` in the header's `#action` slot and
|
||||
render the form inside `<Modal v-model="showCreate">`.
|
||||
- Admin create forms are loaded with `defineAsyncComponent`, so a visitor who
|
||||
is not signed in never downloads them.
|
||||
- Create forms emit `done` / `cancel` and never close themselves — the host
|
||||
decides what to dismiss and refresh.
|
||||
- Animation loops (`Headline`, `Intro2`, `Stamps`, `AutoScroll`, `Elle`) keep
|
||||
their state in plain `let`s and write to the DOM directly. Putting per-frame
|
||||
state in a `ref` would queue a Vue re-render 30–60 times a second. They also
|
||||
cache measurements in a `ResizeObserver` rather than reading `offsetWidth` in
|
||||
the rAF callback, which forces a synchronous layout every frame.
|
||||
|
||||
## Dev vs production
|
||||
|
||||
- **Dev** (`npm run dev`): Vite serves the SPA and proxies `/api`, `/gitea`,
|
||||
`/radio` and `/py` (see the table above and `vite.config.js`). The `/py`
|
||||
proxy strips the prefix, matching what nginx does in production.
|
||||
- **Production** (`npm run build`): `dist/` is built into the nginx container
|
||||
and served as static files, with nginx doing the same reverse-proxying.
|
||||
|
||||
Note `npm run build` runs `build:wasm` first, which needs **wasm-pack** on the
|
||||
PATH. If you only want the Vue bundle and `src/wasm/` is already populated,
|
||||
`npx vite build` skips that step.
|
||||
|
||||
## Live vs legacy views
|
||||
|
||||
Several files are kept around but not reachable. Each carries a `STATUS:` note
|
||||
in its header comment; the summary:
|
||||
|
||||
| File | Status |
|
||||
| --- | --- |
|
||||
| `views/home/Home.vue` | live (`/stp`) — imports **Intro2** and **Gym2** |
|
||||
| `views/home/Intro.vue` | superseded by `Intro2.vue`; not imported |
|
||||
| `views/home/Gym.vue` | superseded by `Gym2.vue`; not imported |
|
||||
| `views/home2/Home2.vue` | reachable at `/stp2`, but a static mock and unlinked |
|
||||
| `views/home/BadApple.vue` | unfinished ASCII video player; not imported |
|
||||
| `views/CV/CVProgramming.vue` | live — the only CV template listed in `CV.vue` |
|
||||
| `views/CV/CV{General,Backend,Frontend,Security,Electrical,Hospitality,Analyst,Temp}.vue` | commented out of `CV.vue`'s list; unreachable |
|
||||
| `views/unused/CoverLetters.vue` | **live** despite the directory — it is the "Cover Letter" tab on `/cv` |
|
||||
| `views/unused/Notes.vue` | no route points at it; not imported |
|
||||
| `components/util/wasm/AutoScroll.vue` | Rust port of the JS AutoScroll; not imported |
|
||||
| `components/util/{MusicPlayer,ObjectTable}.vue` | not imported |
|
||||
| `components/elle/Elle.vue`, `components/borders/UtenaFrame.vue` | decorative; not imported |
|
||||
| `stores/models.js`, `js/mobile-automata.mjs` | not imported |
|
||||
|
||||
Nothing in this list is dead weight the build ships — unimported files are
|
||||
tree-shaken out. They are kept deliberately; don't delete without asking.
|
||||
|
||||
|
||||
## Styling
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Root component. Deliberately empty: all chrome lives in the layout components
|
||||
* (layouts/DefaultLayout.vue, layouts/CVLayout.vue) that the router mounts.
|
||||
*/
|
||||
import { RouterView } from "vue-router";
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Fake waybar status bar (a nod to the author's Linux setup) for DefaultLayout.
|
||||
*
|
||||
* Everything except the clock is hard-coded decoration — CPU/MEM/DISK/NET/BAT are
|
||||
* not real readings. `.hide-sm` drops them on narrow screens.
|
||||
*/
|
||||
import { ref, onMounted, onUnmounted } from "vue";
|
||||
|
||||
const clock = ref("");
|
||||
|
||||
@@ -1,4 +1,14 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Top bar for DefaultLayout: an "UP" breadcrumb button and a scrolling marquee.
|
||||
*
|
||||
* `parentPath` strips the last path segment, so /shrines/gto -> /shrines and any
|
||||
* one-segment route -> "/". It is null only at the root, which is what hides the
|
||||
* button on the landing page.
|
||||
*
|
||||
* The kaomoji are joined into one long string and handed to <Headline>, which
|
||||
* duplicates and scrolls it — see Headline.vue for why one string and not a list.
|
||||
*/
|
||||
import Headline from "@/components/text/Headline.vue";
|
||||
import { computed } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
<!--
|
||||
Decorative frame: four counter-rotating flowers around the slotted content.
|
||||
Each corner sets its own `--start` angle so the four are permanently offset by
|
||||
90 degrees while sharing one keyframe animation.
|
||||
STATUS: not imported anywhere.
|
||||
-->
|
||||
<template>
|
||||
<div class="container">
|
||||
<img src="/img/borders/utena.png" class="flower tl antirotate" />
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Decorative animated colour bars. STATUS: not imported anywhere.
|
||||
*
|
||||
* Two known problems if it is ever revived: the call
|
||||
* `generateOffsets((150, 15, 10))` uses the comma operator, so it passes a single
|
||||
* argument 10 as `width` and the other two defaults apply; and animate() logs to
|
||||
* the console on every frame.
|
||||
*/
|
||||
import { ref, onMounted, useTemplateRef, onUnmounted } from "vue";
|
||||
import { getRandomColor } from "@/js/utils";
|
||||
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
<!--
|
||||
The site's standard button. Wraps a native <button>, so all attributes and
|
||||
listeners (including @click) fall through to it via Vue's attribute inheritance.
|
||||
-->
|
||||
<script setup></script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Sliding on/off switch. v-model via the explicit modelValue prop +
|
||||
* update:modelValue emit pair (rather than defineModel) because ToggleHeader
|
||||
* needs to pass the value down and intercept the event.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
|
||||
const props = defineProps({
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Infinite horizontal marquee. Renders its slot twice side by side and
|
||||
* translates the pair left; when the offset passes one copy's width it wraps by
|
||||
* adding that width back, so the seam is never visible.
|
||||
*
|
||||
* The offset is a plain `let`, not a ref, and the transform is written straight
|
||||
* to element.style — a reactive ref here would queue a Vue re-render on every one
|
||||
* of the 60 frames per second. The width is measured once and re-measured by a
|
||||
* ResizeObserver rather than read each frame, because reading offsetWidth in the
|
||||
* rAF callback forces a layout on every frame.
|
||||
*/
|
||||
import { onMounted, useTemplateRef, onUnmounted } from "vue";
|
||||
|
||||
const container = useTemplateRef("container");
|
||||
@@ -54,6 +65,8 @@ onUnmounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- The slot is rendered twice: the second copy fills the gap the first
|
||||
leaves as it scrolls off, which is what makes the loop seamless. -->
|
||||
<div class="root">
|
||||
<div class="container" ref="container">
|
||||
<div ref="item1">
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Link styled to sit inside running prose (bold italic, no underline). Same
|
||||
* `to` vs `href` and auto-`rel` behaviour as Link.vue.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
|
||||
const props = defineProps({
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Standard link. Renders a <RouterLink> when given `to`, a plain <a> when given
|
||||
* `href`. `bare` drops the styling (used where the parent styles the anchor).
|
||||
* External `target="_blank"` links get rel="noopener noreferrer" automatically.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
|
||||
const props = defineProps({
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
<!--
|
||||
Padded <p>. Exists purely so prose spacing is defined in one place.
|
||||
-->
|
||||
<template>
|
||||
<p class="p-1">
|
||||
<slot />
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Section header with a show/hide switch, used by LinkTable's collapsible mode.
|
||||
*
|
||||
* The whole bar is clickable: the click handler forwards to the inner
|
||||
* <ToggleButton>'s DOM node via its $el. The button itself is
|
||||
* `pointer-events-none` with `@click.stop`, so a direct click on it cannot fire
|
||||
* the handler twice.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import ToggleButton from "@/components/input/ToggleButton.vue";
|
||||
|
||||
|
||||
@@ -10,6 +10,16 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
/**
|
||||
* Scroll container that drifts its own content up and down forever, pausing at
|
||||
* each end. Used by the Favorites and Consumption widgets.
|
||||
*
|
||||
* Position is kept as a 0..1 fraction so it survives content resizing. On the
|
||||
* edges it is clamped to 0.999 / 0.001 rather than exactly 1 / 0 so the next
|
||||
* tick's `reachedBottom` / `reachedTop` test doesn't immediately fire again and
|
||||
* re-trigger the pause. scrollHeight is measured by a ResizeObserver instead of
|
||||
* being read every frame, which would force a layout 60 times a second.
|
||||
*/
|
||||
import { useTemplateRef, onMounted, onBeforeUnmount } from "vue";
|
||||
|
||||
const container = useTemplateRef("container");
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The chat widget: message list, composer, file attach, admin delete and an
|
||||
* admins-only "private" mode. Drives stores/messages.js and is mounted in the
|
||||
* right-hand sidebar of views/home/Home.vue.
|
||||
*
|
||||
* Owns the socket lifecycle — connect() on mount, disconnect() on unmount — so
|
||||
* the socket exists only while the widget is on screen.
|
||||
*/
|
||||
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
|
||||
import Button from "@/components/input/Button.vue";
|
||||
import ToggleButton from "@/components/input/ToggleButton.vue";
|
||||
@@ -17,6 +25,8 @@ const fileInput = ref(null);
|
||||
const isAdmin = computed(() => !!authStore.user.admin);
|
||||
const sendPrivate = ref(false);
|
||||
|
||||
// Autoscroll only when the reader is already at the bottom: scrolling up to
|
||||
// read history must not be yanked back down by an incoming message.
|
||||
const isNearBottom = ref(true);
|
||||
const SCROLL_THRESHOLD = 100;
|
||||
let resizeObserver = null;
|
||||
@@ -45,6 +55,7 @@ function goToBottom() {
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
// nextTick: scrollHeight is only correct once Vue has patched the new row in.
|
||||
watch(
|
||||
() => messages.value.length,
|
||||
() => {
|
||||
@@ -91,12 +102,20 @@ function isVideoUrl(url) {
|
||||
return /\.(mp4|webm|ogg|mov)$/i.test(url);
|
||||
}
|
||||
|
||||
/** Only render attachments the backend served from its own upload directory —
|
||||
* the fileUrl arrives over the socket and is otherwise attacker-controlled. */
|
||||
function isSafeFileUrl(url) {
|
||||
return typeof url === "string" && url.startsWith("/uploads/");
|
||||
}
|
||||
|
||||
// NOTE: a module-level /g regex carries `lastIndex` between calls. It is safe
|
||||
// here only because parseMessageParts() below always runs exec() to completion
|
||||
// (exec returns null, resetting lastIndex) before returning. An early return
|
||||
// from that loop would make the next message parse from the wrong offset.
|
||||
const urlRegex = /(https?:\/\/[^\s<]+)/g;
|
||||
|
||||
/** Split message text into alternating {type:'text'|'link', value} parts so
|
||||
* URLs can be rendered as anchors without using v-html. */
|
||||
function parseMessageParts(text) {
|
||||
const parts = [];
|
||||
let lastIndex = 0;
|
||||
@@ -126,6 +145,9 @@ onMounted(() => {
|
||||
});
|
||||
}
|
||||
|
||||
// Images and videos load after their row is inserted and change its height,
|
||||
// which the length watcher above has already missed. Observing the inner
|
||||
// wrapper catches those late reflows.
|
||||
if (messagesInner.value) {
|
||||
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
|
||||
resizeObserver.observe(messagesInner.value);
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Sidebar widget showing the most recent Gitea action, read straight from
|
||||
* homeData.gitFeed (the backend proxies and caches the Gitea API).
|
||||
*/
|
||||
import { useHomeDataStore } from "@/stores/homeData";
|
||||
import { storeToRefs } from "pinia";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Renders a list of {name, link, type} either as stacked link buttons
|
||||
* (variant="list") or as a two-column table (variant="table").
|
||||
*
|
||||
* Passing `title` wraps the whole thing in a collapsible <ToggleHeader>.
|
||||
* Used by the Bookmarks, Favorites, Consumption and Links widgets.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import Link from "@/components/text/Link.vue";
|
||||
import ToggleHeader from "@/components/text/ToggleHeader.vue";
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Renders a markdown string, with KaTeX maths support, into sanitised HTML.
|
||||
*
|
||||
* The v-html is safe only because DOMPurify strips scripts and event handlers
|
||||
* from markdown-it's output first — post content is admin-authored but still
|
||||
* untrusted input. Used by the Feed widget.
|
||||
*/
|
||||
import MarkdownIt from "markdown-it";
|
||||
import { katex } from "@mdit/plugin-katex";
|
||||
import DOMPurify from "dompurify";
|
||||
|
||||
@@ -14,6 +14,9 @@ function onKeydown(e) {
|
||||
if (e.key === "Escape") open.value = false;
|
||||
}
|
||||
|
||||
// The Escape listener is attached only while open, so several modals on one
|
||||
// page can't all react to a single keypress. `immediate` covers a modal that
|
||||
// mounts already open.
|
||||
watch(
|
||||
open,
|
||||
(isOpen) => {
|
||||
@@ -30,6 +33,8 @@ onUnmounted(() => window.removeEventListener("keydown", onKeydown));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- Teleported to <body> so the backdrop escapes any ancestor with
|
||||
overflow/transform/z-index that would otherwise clip or trap it. -->
|
||||
<Teleport to="body">
|
||||
<div v-if="open" class="modal-backdrop" @click.self="open = false">
|
||||
<div class="modal bdr-1" :style="{ maxWidth: props.maxWidth }">
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user