Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ad600469a | ||
|
|
8b902350ad | ||
|
|
3764ea9c0b | ||
|
|
299b5f5224 | ||
|
|
af50e6c8ab | ||
|
|
810d3118b3 | ||
|
|
b832dd68b4 | ||
|
|
d3f722d077 | ||
|
|
71344a1f8d | ||
|
|
307268fbea | ||
|
|
2786bce022 | ||
|
|
26f312e307 | ||
|
|
b8670246a8 | ||
|
|
94eaa8e239 | ||
|
|
f8d48ba9af | ||
|
|
5827fb3ddd | ||
|
|
6dd15414e9 | ||
|
|
76735f0552 | ||
|
|
d843b0baf1 | ||
|
|
8d7606bbe8 | ||
|
|
e25fbbab96 |
@@ -0,0 +1,34 @@
|
||||
# .deprecated
|
||||
|
||||
STATUS: nothing in here is live. No compose file, nginx template or script
|
||||
references this directory. It is kept, not deleted, in line with the repo's
|
||||
"legacy is kept" convention; the full history is also in git.
|
||||
|
||||
## quartz/
|
||||
|
||||
The static-site build that used to serve `/notes/`. Replaced by the read-only
|
||||
`silverbullet-public` service (PR #6). Its compose service and nginx route were
|
||||
removed at that point; only the build context survives here.
|
||||
|
||||
## hasura/
|
||||
|
||||
Admin-only DB console that was proxied at `/hasura/`.
|
||||
|
||||
- `docker-compose.hasura.yml` — the service, verbatim.
|
||||
- `nginx-locations.conf` — the upstream variable and `location` blocks that
|
||||
were in both `nginx.conf.template` and `nginx_dev_common.conf.template`.
|
||||
|
||||
To bring it back: layer the compose file
|
||||
(`docker compose -f docker-compose.yml -f .deprecated/hasura/docker-compose.hasura.yml up`),
|
||||
paste the nginx blocks back into both templates, re-add `${HASURA_HOST}
|
||||
${HASURA_PORT}` to `ENVSUBST_VARS` in `nginx/entrypoint.sh`, and set
|
||||
`HASURA_HOST`, `HASURA_PORT` and `HASURA_GRAPHQL_ADMIN_SECRET` in `.env`. Dev
|
||||
mode additionally set `HASURA_GRAPHQL_ENABLE_CONSOLE` and
|
||||
`HASURA_GRAPHQL_DEV_MODE` to `"true"`.
|
||||
|
||||
## autoheal/
|
||||
|
||||
Watchdog that restarted any container docker marked `unhealthy` (only `backend`
|
||||
and `python` define healthchecks). It mounts the docker socket, which is
|
||||
effectively root on the host. To bring it back, layer
|
||||
`docker-compose.autoheal.yml` the same way as above.
|
||||
@@ -0,0 +1,27 @@
|
||||
# STATUS: deprecated — not part of the stack. See ../README.md for how to bring
|
||||
# it back. Kept verbatim from docker-compose.yml.
|
||||
services:
|
||||
# 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. Because of that the image is pinned BY DIGEST,
|
||||
# not by a floating tag: `:latest` meant any future push to Docker Hub would
|
||||
# silently gain root on the Pi at the next `docker compose pull`/`up`. The
|
||||
# digest below is a multi-arch index (it includes linux/arm64, which is what
|
||||
# the Pi pulls) and was the content of `willfarrell/autoheal:latest` at the
|
||||
# time of pinning. To bump it: pull the new tag, `docker image inspect
|
||||
# willfarrell/autoheal:<tag> --format '{{index .RepoDigests 0}}'`, and paste
|
||||
# the digest here — never go back to a bare tag.
|
||||
# Deliberately NOT on app-network: it talks only to the socket.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal@sha256:4ce976e9033b41426d44633295d6a08f9bc5929b27866352d91b31d4f6b26447
|
||||
container_name: autoheal
|
||||
restart: always
|
||||
environment:
|
||||
- AUTOHEAL_CONTAINER_LABEL=all
|
||||
- AUTOHEAL_INTERVAL=30
|
||||
- AUTOHEAL_START_PERIOD=60
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
@@ -0,0 +1,23 @@
|
||||
# STATUS: deprecated — not part of the stack. See ../README.md for how to bring
|
||||
# it back. Kept verbatim from docker-compose.yml, so it still relies on that
|
||||
# file's `db` service and `app-network`, and must be layered on top of it.
|
||||
services:
|
||||
# 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}"
|
||||
restart: always
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
|
||||
HASURA_GRAPHQL_ADMIN_SECRET: "${HASURA_GRAPHQL_ADMIN_SECRET}"
|
||||
HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
|
||||
HASURA_GRAPHQL_DEV_MODE: "false"
|
||||
HASURA_GRAPHQL_ENABLED_LOG_TYPES: "startup, http-log, webhook-log, websocket-log, query-log"
|
||||
@@ -0,0 +1,21 @@
|
||||
# STATUS: deprecated. The /hasura/ blocks removed from nginx.conf.template and
|
||||
# nginx_dev_common.conf.template (identical in both). See ../README.md.
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
+37
-10
@@ -5,18 +5,28 @@
|
||||
# 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.
|
||||
# names and published ports are built.
|
||||
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
|
||||
# variables inside that container. nginx, backend, db, icecast2,
|
||||
# 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.
|
||||
# explicit `environment:` allow-list, so it never sees the database password
|
||||
# or any API key other than the two it uses (TFL_APP_KEY, CLAUDE_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).
|
||||
# On the Pi, keys and settings can also be changed from the admin panel's
|
||||
# Environment tab, which rewrites this file in place (previous version kept
|
||||
# as .env.bak) and restarts what reads the change. See "Editing from the
|
||||
# admin panel" in DEPLOYMENT.md.
|
||||
#
|
||||
# ADDING A VARIABLE
|
||||
# Add it to backend/services/env_registry.json as well. That file decides
|
||||
# whether the admin panel shows it, whether it is editable there, and which
|
||||
# services are restarted when it changes; a backend test fails if the two
|
||||
# lists differ.
|
||||
#
|
||||
# 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,
|
||||
@@ -87,6 +97,23 @@ IMAP_PASSWORD=
|
||||
EMAIL_SYNC_INTERVAL=
|
||||
EMAIL_SYNC_ENABLED=
|
||||
|
||||
# --- Job leads (backend) -----------------------------------------------------
|
||||
# The lead fetcher polls the sources listed on /cv/leads and files new
|
||||
# postings in the leads inbox. JOB_LEADS_ENABLED=true runs it on a timer;
|
||||
# "Check now" on that page works whether or not it is set. JOB_LEADS_INTERVAL
|
||||
# is a Go duration (default 6h). Scoring uses CLAUDE_API_KEY, above.
|
||||
# The board sources (Greenhouse, Lever, Ashby) need no key. The two search
|
||||
# sources do, both free:
|
||||
# Adzuna: https://developer.adzuna.com/ (an application id and a key)
|
||||
# Reed: https://www.reed.co.uk/developers/jobseeker
|
||||
# A search source whose key is blank reports that on the page; nothing else
|
||||
# is affected.
|
||||
JOB_LEADS_ENABLED=
|
||||
JOB_LEADS_INTERVAL=
|
||||
ADZUNA_APP_ID=
|
||||
ADZUNA_APP_KEY=
|
||||
REED_API_KEY=
|
||||
|
||||
# --- 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.
|
||||
@@ -154,17 +181,17 @@ DOMAIN=
|
||||
EMAIL=
|
||||
|
||||
# --- Third-party API keys (backend) ------------------------------------------
|
||||
# CLAUDE_API_KEY is used by the python service, which makes every Claude call
|
||||
# in the stack: the rowing photo reader, the job posting reader and the email
|
||||
# pipeline's classifier. The backend no longer calls Claude itself.
|
||||
CLAUDE_API_KEY=
|
||||
# Which model those calls use: claude-haiku-4-5 (cheapest), claude-sonnet-5-5
|
||||
# (the default when blank) or claude-opus-5-5. Editable on the admin panel's
|
||||
# Environment tab, which restarts the python service to apply it.
|
||||
CLAUDE_MODEL=
|
||||
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.
|
||||
|
||||
@@ -1,20 +1,170 @@
|
||||
name: Deploy with Docker Compose
|
||||
# =============================================================================
|
||||
# deploy.yaml — test every push; deploy pushes to main that pass.
|
||||
#
|
||||
# TWO JOBS
|
||||
# test runs on every push, to any branch: `go vet` + `go test` for the
|
||||
# backend and pytest for the Python service. These are the same
|
||||
# checks as `make check-backend` and `make check-python`.
|
||||
# deploy runs only for refs/heads/main, and only if `test` passed
|
||||
# (`needs: test`). Before this gate existed every push to main went
|
||||
# straight to the live site.
|
||||
#
|
||||
# WHERE THIS RUNS, AND WHAT THAT RULES OUT
|
||||
# A self-hosted act_runner on the Pi itself, in HOST mode (see
|
||||
# gitea-runner/run.sh): steps are shell commands on the Pi, not in a job
|
||||
# container. So:
|
||||
# - No host toolchains are assumed. The Pi is known to have git and docker
|
||||
# and nothing else; Go and Python run inside `docker run` containers
|
||||
# pinned to the same base images as backend/Dockerfile (golang:1.26) and
|
||||
# python/Dockerfile (python:3.12-slim). Bump them together.
|
||||
# - No `actions/checkout`. It is a JavaScript action and would need Node on
|
||||
# the host. The source is fetched with plain git instead, from the same
|
||||
# local Gitea SSH remote the deploy step has always used.
|
||||
#
|
||||
# THE LIVE DIRECTORY IS NOT TOUCHED UNTIL TESTS PASS
|
||||
# The site runs out of /home/adamf/deploy/web_server. The test job never
|
||||
# goes near it: it fetches into a separate bare cache repo and exports the
|
||||
# pushed commit to a scratch directory. Only the deploy job, after `test`
|
||||
# is green, does the `git reset --hard` there.
|
||||
#
|
||||
# NOT TESTED HERE: THE VUE BUILD
|
||||
# Deliberately skipped. `docker compose up --build` in the deploy job
|
||||
# already runs the full frontend build (wasm-pack + vite) while building the
|
||||
# vue image, and a failed image build aborts `up` BEFORE any container is
|
||||
# replaced, so the old site keeps serving. Building it a second time here
|
||||
# would cost the Pi several minutes per push to learn nothing new. The same
|
||||
# reasoning does not hold for Go and Python: their images build fine with
|
||||
# failing tests, which is exactly why those are gated here.
|
||||
#
|
||||
# NO pull_request TRIGGER
|
||||
# `push` with no branch filter already covers every branch, including the
|
||||
# head branch of any PR in this repo, so adding pull_request would run the
|
||||
# suite twice per push on a machine with little CPU to spare.
|
||||
# =============================================================================
|
||||
name: Test and deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: self-hosted
|
||||
env:
|
||||
# The commit and ref this push delivered. Passed through env rather
|
||||
# than interpolated into the scripts so a branch name can never be
|
||||
# parsed as shell.
|
||||
SHA: ${{ github.sha }}
|
||||
REF: ${{ github.ref }}
|
||||
REMOTE: ssh://git@localhost:2222/adamf/web_server.git
|
||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||
# Bare repo kept between runs so each fetch is incremental (the
|
||||
# history is ~140MB; a fresh clone per push would be slow on the
|
||||
# Pi's SD card). Lives outside the deploy directory on purpose.
|
||||
CACHE: /home/adamf/.cache/web_server-ci/repo.git
|
||||
# This run's source tree, exported from the cache and removed in
|
||||
# the last step. Keyed by commit so two runs cannot share a tree.
|
||||
SRC: /home/adamf/.cache/web_server-ci/src-${{ github.sha }}
|
||||
steps:
|
||||
- name: Export the pushed commit to a scratch directory
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
mkdir -p "$(dirname "$CACHE")"
|
||||
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
|
||||
# Fetch the pushed ref, then export the exact pushed commit.
|
||||
# Using $SHA rather than FETCH_HEAD means that if the branch
|
||||
# has moved on since this run was queued we still test the
|
||||
# commit this run is about, not a newer one.
|
||||
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
|
||||
rm -rf "$SRC"
|
||||
mkdir -p "$SRC"
|
||||
# `git archive` gives a clean tree of tracked files only: no
|
||||
# .git, and nothing left over from an earlier run.
|
||||
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
|
||||
# Do not rely on the shell having pipefail: if the archive
|
||||
# half failed, make sure that is noticed here.
|
||||
test -f "$SRC/backend/go.mod"
|
||||
test -f "$SRC/python/requirements-dev.txt"
|
||||
echo "Exported $SHA ($REF) to $SRC"
|
||||
|
||||
# The whole repo is mounted, not just backend/, because
|
||||
# services/env_manager_test.go reads ../../.env.example to check
|
||||
# it against env_registry.json. Read-only: tests write only to
|
||||
# t.TempDir(), and a read-only mount means the container (root)
|
||||
# cannot leave root-owned files in $SRC that the clean-up step,
|
||||
# running as the runner user, could not delete.
|
||||
#
|
||||
# The two named volumes are the Go module cache and build cache.
|
||||
# Without them every run would re-download every dependency and
|
||||
# recompile gorm, gin and gqlgen from scratch — minutes on a Pi.
|
||||
# They survive `docker image prune` and the weekly maintenance
|
||||
# job; `docker volume rm web_server_ci_gomod web_server_ci_gobuild`
|
||||
# resets them if they ever go bad.
|
||||
- name: Backend - go vet and go test
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm \
|
||||
-v "$SRC":/src:ro \
|
||||
-w /src/backend \
|
||||
-v web_server_ci_gomod:/go/pkg/mod \
|
||||
-v web_server_ci_gobuild:/root/.cache/go-build \
|
||||
golang:1.26 \
|
||||
sh -c 'go vet ./... && go test ./...'
|
||||
|
||||
# requirements-dev.txt pulls in requirements.txt plus pytest. The
|
||||
# install is repeated every run (the container is thrown away) but
|
||||
# the pip cache volume means it is unpacking cached wheels, not
|
||||
# downloading. Read-only source for the same reason as above, so
|
||||
# bytecode and the pytest cache are switched off rather than left
|
||||
# to fail noisily.
|
||||
- name: Python - pytest
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm \
|
||||
-v "$SRC":/src:ro \
|
||||
-w /src/python \
|
||||
-v web_server_ci_pip:/root/.cache/pip \
|
||||
-e PYTHONDONTWRITEBYTECODE=1 \
|
||||
python:3.12-slim \
|
||||
sh -c 'pip install --quiet --disable-pip-version-check --root-user-action=ignore -r requirements-dev.txt && python -m pytest tests -q -p no:cacheprovider'
|
||||
|
||||
# always(): a failed test must not leave a source tree behind per
|
||||
# push. The cache repo is kept; only this run's export goes.
|
||||
- name: Remove the scratch directory
|
||||
if: always()
|
||||
shell: bash
|
||||
run: rm -rf "$SRC"
|
||||
|
||||
deploy:
|
||||
# Both conditions matter: `needs` makes a red test job skip this one,
|
||||
# and the `if` keeps pushes to other branches from deploying at all.
|
||||
needs: test
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Pull changes
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||
SHA: ${{ github.sha }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
git config --global --add safe.directory /home/adamf/deploy/web_server
|
||||
git fetch ssh://git@localhost:2222/adamf/web_server.git main
|
||||
# Deploy only the commit the test job just passed. If main
|
||||
# has moved on since this run started, FETCH_HEAD is a newer
|
||||
# commit that THIS run never tested — stop, and let that
|
||||
# commit's own run test and deploy it. Failing (rather than
|
||||
# resetting to $SHA anyway) also means re-running an old run
|
||||
# can never roll the site back to an old commit.
|
||||
if [ "$(git rev-parse FETCH_HEAD)" != "$SHA" ]; then
|
||||
echo "main is at $(git rev-parse FETCH_HEAD), but this run tested $SHA."
|
||||
echo "Not deploying: the run for the newer commit will."
|
||||
exit 1
|
||||
fi
|
||||
git reset --hard FETCH_HEAD
|
||||
|
||||
- name: Run docker compose up
|
||||
@@ -22,7 +172,10 @@ jobs:
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
COMPOSE_BAKE: "false"
|
||||
run: docker compose up -d --build --remove-orphans
|
||||
# The lock is shared with env-apply/apply.py, so a deploy and a
|
||||
# .env change made from the admin panel cannot run compose at
|
||||
# the same time.
|
||||
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Prune unused Docker resources
|
||||
run: docker image prune -f
|
||||
|
||||
@@ -21,17 +21,28 @@ jobs:
|
||||
- name: Autoremove obsolete packages
|
||||
run: sudo apt-get -y autoremove --purge
|
||||
|
||||
# Both compose steps below take env-apply/run/lock, the same flock
|
||||
# deploy.yaml and env-apply/apply.py hold while they run compose.
|
||||
# Without it this weekly job could recreate containers at the same
|
||||
# moment a .env edit from the admin panel is being applied (or a
|
||||
# deploy is mid-build), and two `compose up`s racing over the same
|
||||
# project can each recreate a container the other just started,
|
||||
# ending with services built against a half-written .env. flock
|
||||
# blocks until the other holder finishes, so the job waits rather
|
||||
# than fails. The lock is taken per step, not across both: nothing
|
||||
# needs pull and up to be atomic, and holding it for less time
|
||||
# keeps an admin-panel change from waiting behind a long pull.
|
||||
- name: Pull latest base images
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
run: docker compose pull
|
||||
run: flock env-apply/run/lock docker compose pull
|
||||
|
||||
- name: Rebuild and restart containers
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
run: docker compose up -d --build --remove-orphans
|
||||
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Prune unused Docker images
|
||||
run: docker image prune -af
|
||||
|
||||
@@ -4,6 +4,11 @@ certbot/conf
|
||||
certbot/www
|
||||
backend/token/
|
||||
.env
|
||||
.env.bak
|
||||
|
||||
# Admin panel -> host hand-off (request and status files, holds secrets)
|
||||
env-apply/run/*
|
||||
!env-apply/run/.gitkeep
|
||||
|
||||
gitea/data/*
|
||||
gitea/config/app.ini
|
||||
@@ -19,6 +24,10 @@ gitea-runner/nohup.out
|
||||
# Python bytecode
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
|
||||
# Virtualenv `make check-python` builds on demand from python/requirements-dev.txt
|
||||
/.venv/
|
||||
|
||||
# Generated WASM output
|
||||
vue/src/wasm/
|
||||
|
||||
@@ -4,6 +4,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## Build & Run Commands
|
||||
|
||||
### Check everything
|
||||
|
||||
```
|
||||
make check
|
||||
```
|
||||
|
||||
Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, and `docker compose config` for both compose files. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing.
|
||||
|
||||
### Full stack (dev mode, HTTP only)
|
||||
|
||||
```
|
||||
@@ -24,7 +32,7 @@ docker compose up --build
|
||||
cd vue && npm run dev
|
||||
```
|
||||
|
||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
||||
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`; the targets default to `localhost:8080`, `:3000`, `:8000` and `:8000` and are overridden with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (shell or `vue/.env.local`). Compose publishes none of the backend, Python or Icecast ports to the host, and `/py` and `/radio` share a default, so set these to wherever the services really are — see the comment in `vue/vite.config.js`.
|
||||
|
||||
### Frontend build
|
||||
|
||||
@@ -32,6 +40,8 @@ Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`
|
||||
cd vue && npm run build
|
||||
```
|
||||
|
||||
`npm run build` compiles the Rust crate first and needs `wasm-pack`. `npm run build:js` (plain `vite build`) is the check to use when only the JS changed and `src/wasm/` already exists.
|
||||
|
||||
### Regenerate GraphQL (after editing schema files)
|
||||
|
||||
```
|
||||
@@ -48,26 +58,28 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
|
||||
|
||||
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode).
|
||||
|
||||
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`.
|
||||
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **Every Claude call in the stack lives here**, behind four internal routes: `/internal/rowing/read` (behind `POST /api/rowing`), `/internal/jobs/extract` (behind `POST /api/jobs/capture/extract`), `/internal/jobs/score` (behind the job-lead pipeline) and `/internal/email/classify` (behind the email sync). The Go backend calls them directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting for all four, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), chosen on the admin panel's Environment tab; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
|
||||
|
||||
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min).
|
||||
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks.
|
||||
|
||||
## Backend Structure
|
||||
|
||||
- `main.go` — entry point: wires up DB, services, router
|
||||
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, ClaudeClient, Auth, etc. Passed to all handlers
|
||||
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, Auth, EmailSync, etc. Passed to all handlers
|
||||
- `handlers/handle_*.go` — REST handlers grouped by domain
|
||||
- `graph/schema/*.graphql` — GraphQL schema files (source of truth)
|
||||
- `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout)
|
||||
- `graph/generated.go` — auto-generated by gqlgen, do not edit
|
||||
- `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit
|
||||
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing)
|
||||
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, Claude client, DB seeding
|
||||
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, JobApplication, JobSource, JobLead, …)
|
||||
- `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns)
|
||||
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), job status vocabulary (`job_status.go`), the job-lead pipeline (`job_leads.go`, `job_sources.go`), the tracker upsert (`job_upsert.go`), DB seeding. There is no Claude client in Go any more
|
||||
|
||||
## Frontend Structure
|
||||
|
||||
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
|
||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData
|
||||
- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status
|
||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, jobApplications, jobAppReferences, jobSources, jobLeads, jobSearchProfile. `createCrudStore.js` is the factory behind places, jobApplications, jobAppReferences and jobSources; `createMirrorStore.js` is the one behind the home-page slices
|
||||
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines)
|
||||
- `src/components/` — reusable UI components
|
||||
- `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`.
|
||||
@@ -75,11 +87,16 @@ 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` (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`.
|
||||
- **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. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded).
|
||||
- **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`.
|
||||
- **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`.
|
||||
- **Job status is one vocabulary.** `enum JobStatus` in `graph/schema/job_application.graphql` is what GraphQL accepts, and a test ties it to `services.statusOrder`. Three copies are *not* checked and must be edited by hand with it: the classifier prompt in `python/app/email_classify.py`, `vue/src/views/CV/jobStatus.js`, and `STATUS_LABELS` in the userscript.
|
||||
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
|
||||
- **Job capture**: `vue/public/job-capture.user.js` is a Violentmonkey userscript, served by the site and installed from `/cv/jobs`, that adds the posting open in the browser to the tracker. It calls the three `/api/jobs/capture` REST routes with a bearer token because cookies do not travel from other origins. The token is generated on the admin panel and stored hashed in `backend/token/job_capture_token.json`; there is no env var for it. Bump its `@version` on every edit or installed copies will not update. See "Job capture" in `backend/README.md`.
|
||||
- **Job leads**: `/cv/leads` is an inbox of postings the backend finds itself. `services/job_leads.go` polls each `JobSource` (Greenhouse, Lever and Ashby boards; Adzuna and Reed searches), files new postings as `JobLead` rows, keyword-filters them and has Claude score the survivors against the single `JobSearchProfile` row. A lead reaches the tracker only by promotion, through `services.UpsertJobApplication` — the same upsert the capture endpoint uses. `JobLead` is not soft deleted: a dismissed lead has to stay a row or the next poll re-adds it. The timer is off unless `JOB_LEADS_ENABLED=true`; "Check now" works either way. See "Job leads" in `backend/README.md`.
|
||||
- **Environment tab**: `/admin` → Environment edits `.env` on the Pi. The backend never touches the file: it validates the edit and writes `env-apply/run/request.json`; `env-apply/apply.py`, run on the host by a systemd path unit (`env-apply/install.sh`), rewrites `.env` and recreates only the services that read the change. `backend/services/env_registry.json` is the single list of variables — **add new variables there as well as `.env.example`** (a test enforces it); a variable the Python service reads must also be added to the `python` service's explicit `environment:` list in `docker-compose.yml`, which a second test checks against the registry, with `editable: false` for anything that renames a container, moves a port or is only read at first init. Secrets are write-only: no endpoint returns one. See "Environment tab" in `backend/README.md`.
|
||||
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
|
||||
- **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.
|
||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field) — except `ProcessedEmail` and `JobLead`, whose dedup must see history, and the single-row `JobSearchProfile`. Note that a `uniqueIndex` still collides with soft-deleted rows.
|
||||
|
||||
## Further documentation
|
||||
|
||||
|
||||
+104
-27
@@ -29,13 +29,13 @@ Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on
|
||||
--------------------------------------------- | (same container
|
||||
| | | | | | | as icecast2)
|
||||
v v v v v v | |
|
||||
/api/ /radio/ /gitea/ /hasura/ /notes/ /py/ | |
|
||||
backend icecast2 gitea hasura sb-pub python | |
|
||||
| ^ | | |
|
||||
| | | | |
|
||||
| +------------------|--------------------|---------------+
|
||||
| | |
|
||||
+----------+-----------------+--------------------+
|
||||
/api/ /radio/ /gitea/ /sb/ /notes/ /py/ | |
|
||||
backend icecast2 gitea sb sb-pub python | |
|
||||
| ^ | |
|
||||
| | | |
|
||||
| +---------------------------------------|---------------+
|
||||
| |
|
||||
+----------+--------------------------------------+
|
||||
v
|
||||
+------+
|
||||
| db | postgres:16
|
||||
@@ -43,7 +43,6 @@ backend icecast2 gitea hasura sb-pub python | |
|
||||
|
||||
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
|
||||
@@ -53,7 +52,6 @@ backend icecast2 gitea hasura sb-pub python | |
|
||||
| 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 |
|
||||
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no |
|
||||
| silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
|
||||
| silverbullet-git | n/a | n/a | none (timer loop) | no |
|
||||
@@ -62,7 +60,6 @@ backend icecast2 gitea hasura sb-pub python | |
|
||||
| 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
|
||||
@@ -80,7 +77,7 @@ in one step — never change one without the other.**
|
||||
- **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/`, `/sb/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request`
|
||||
- **Admin gate.** `/sb/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request`
|
||||
subrequest to the backend's `/auth/validate-admin`; a failure redirects to the
|
||||
SPA login. None of these services has any auth of its own at that path.
|
||||
- **Public notes privacy boundary.** `/notes/` is public, and the only thing
|
||||
@@ -88,8 +85,8 @@ in one step — never change one without the other.**
|
||||
nginx deny blocks. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its
|
||||
file *list*; direct `/.fs/` fetches and server-rendered page URLs still serve
|
||||
them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without
|
||||
adding it to the deny regex in both nginx templates publishes it. See the
|
||||
comment above `location /notes/` in `nginx.conf.template`.
|
||||
adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the
|
||||
comment above `location /notes/` in `nginx_routes.conf.template`.
|
||||
- **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.
|
||||
@@ -116,9 +113,30 @@ docker compose up --build
|
||||
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`.
|
||||
On the Pi this is triggered automatically by `.gitea/workflows/deploy.yaml`,
|
||||
which has two jobs:
|
||||
|
||||
- **`test`** runs on every push to any branch. It exports the pushed commit
|
||||
(never the deploy checkout) and runs the backend's `go vet` + `go test` in
|
||||
`golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build is
|
||||
not repeated here: the image build in the deploy step does it, and a failed
|
||||
build leaves the old containers running.
|
||||
- **`deploy`** runs only on `main`, only after `test` passes, and only if the
|
||||
tested commit is still the tip of `main` (so an older run cannot deploy a
|
||||
newer, untested commit). It fetches over `ssh://git@localhost:2222`,
|
||||
hard-resets the deploy checkout, and runs
|
||||
`docker compose up -d --build --remove-orphans` under the
|
||||
`env-apply/run/lock` flock.
|
||||
|
||||
The test job keeps state on the Pi outside the deploy checkout: a bare
|
||||
repository cache at `/home/adamf/.cache/web_server-ci/` and three named
|
||||
volumes (`web_server_ci_gomod`, `web_server_ci_gobuild`, `web_server_ci_pip`).
|
||||
The weekly maintenance workflow's `docker image prune -af` removes the two
|
||||
toolchain images, so the first run after it pulls them again; the volumes
|
||||
survive. Maintenance takes the same flock around its compose steps.
|
||||
|
||||
`make check` runs the same checks locally, plus the Vue build and compose
|
||||
validation — run it before pushing, since a red `test` job blocks the deploy.
|
||||
|
||||
### Development
|
||||
|
||||
@@ -139,7 +157,6 @@ The override layer changes five services and disables one:
|
||||
`: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.
|
||||
@@ -214,7 +231,8 @@ of deleting the directory:
|
||||
|---|---|---|
|
||||
| `./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. |
|
||||
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) and the **job capture token hash** (`job_capture_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild, and the capture userscript a new token from the admin panel. |
|
||||
| `./env-apply/run` | The admin panel's queued `.env` change (`request.json`) and the host's report on it (`status.json`) | Gitignored. Transient, but must be owned by the deploy user, not root — see §5. |
|
||||
| `./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 | |
|
||||
@@ -235,13 +253,21 @@ All configuration lives in **`./.env`** at the repo root, which is gitignored.
|
||||
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.
|
||||
time. Builds container names and published ports.
|
||||
- **`env_file: ./.env`** — injects the whole file into the container. Used by
|
||||
nginx, backend, db, icecast2, 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.
|
||||
allow-list, so it never sees the database password or any API key other than
|
||||
the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`, plus `CLAUDE_MODEL`,
|
||||
which picks the model). The Python service
|
||||
makes every Claude call in the stack — rowing photo reader, job posting reader,
|
||||
job lead scorer and email classifier — so it is the only container that reads `CLAUDE_API_KEY`;
|
||||
the backend receives it through `env_file` but no longer uses it. A new
|
||||
variable for the Python service has to be added to that allow-list as well as
|
||||
`.env.example` and `backend/services/env_registry.json`; backend tests fail if
|
||||
the three disagree.
|
||||
|
||||
**`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two
|
||||
things between this checkout and `adamf@stppi.local:~/deploy/web_server`:
|
||||
@@ -253,6 +279,36 @@ 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`.
|
||||
|
||||
### Editing from the admin panel
|
||||
|
||||
The **Environment** tab at `/admin` edits `.env` on the Pi without SSH. API
|
||||
keys, OAuth client settings, the email settings and the generated secrets are
|
||||
editable; anything that would rename a container, move a port or lock the
|
||||
backend out of Postgres is shown read-only.
|
||||
|
||||
The backend cannot write `.env` or reach Docker. It queues the change in
|
||||
`./env-apply/run/request.json`, and a systemd path unit on the host runs
|
||||
`env-apply/apply.py`, which:
|
||||
|
||||
1. rewrites `.env` atomically, keeping comments and order, with the previous
|
||||
version saved as **`.env.bak`**;
|
||||
2. runs `docker compose config -q` and restores the backup if compose rejects
|
||||
the file;
|
||||
3. recreates only the services that read the changed variables, plus the
|
||||
backend (`docker compose up -d --no-deps --force-recreate …`);
|
||||
4. writes the outcome to `status.json`, which the panel is polling.
|
||||
|
||||
Only those services are recreated because nginx, db, icecast2 and certbot load
|
||||
the whole file too; a plain `up -d` would restart Postgres for a Steam key.
|
||||
They pick the new file up at the next deploy, which is harmless.
|
||||
|
||||
**The watcher is installed once per host** — see the runbook. Without it the
|
||||
panel still queues the change and says nothing has picked it up.
|
||||
|
||||
A change made this way makes the Pi's `.env` the newer copy, so the next
|
||||
`./sync-secrets.sh` pulls it down to the laptop. The newer-wins caveat above
|
||||
still applies: do not also edit the local copy before syncing.
|
||||
|
||||
---
|
||||
|
||||
## 6. Rate limits
|
||||
@@ -297,6 +353,24 @@ it. By hand:
|
||||
git pull && docker compose up -d --build --remove-orphans
|
||||
```
|
||||
|
||||
**Install the `.env` watcher** (once per host; lets the admin panel's
|
||||
Environment tab apply changes):
|
||||
|
||||
```
|
||||
./env-apply/install.sh # asks for sudo
|
||||
systemctl status web-server-env-apply.path # should be active (waiting)
|
||||
journalctl -u web-server-env-apply.service # one entry per applied change
|
||||
```
|
||||
|
||||
Run it as the user that owns the checkout. `env-apply/run` must belong to that
|
||||
user: if Docker created it first it is root-owned, and the script fixes that.
|
||||
To apply a queued change by hand, or undo one:
|
||||
|
||||
```
|
||||
python3 env-apply/apply.py # apply what the panel queued
|
||||
cp .env.bak .env && docker compose up -d # roll back the last change
|
||||
```
|
||||
|
||||
**Rebuild one service** (e.g. after changing only the backend):
|
||||
|
||||
```
|
||||
@@ -377,9 +451,10 @@ icecast source password. liquidsoap pre-empts the fallback playlist immediately
|
||||
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.
|
||||
**Unhealthy containers are not restarted automatically.** `backend` and `python`
|
||||
define healthchecks, but the `autoheal` watchdog that acted on them was retired
|
||||
(`.deprecated/autoheal`), so `unhealthy` is only visible in `docker ps`.
|
||||
`restart: always` still brings back a container whose process exits.
|
||||
|
||||
---
|
||||
|
||||
@@ -397,13 +472,15 @@ Documented, not fixed — each would change deploy behaviour.
|
||||
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.
|
||||
4. **The two `/uploads/` location blocks are still written twice** — once in
|
||||
`nginx.conf.template` and once in `nginx_dev_common.conf.template` —
|
||||
because production adds security headers inside an auth-gated block. Every
|
||||
other proxied route lives once in `nginx_routes.conf.template`, which both
|
||||
configs include; the `auth_request` lines on `/uploads/private/` are the
|
||||
one thing that must be kept in step by hand.
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# =============================================================================
|
||||
# Makefile — one place for the commands that verify and run this repo.
|
||||
#
|
||||
# WHY THIS FILE EXISTS
|
||||
# The stack is four toolchains (Go, Python, Node, Docker) and the command
|
||||
# that checks each one used to live only in a gitignored notes file. `make
|
||||
# check` is the single thing to run before pushing; .gitea/workflows/
|
||||
# deploy.yaml runs the same backend and Python checks (in containers, since
|
||||
# the Pi runner has no host toolchains) before it deploys.
|
||||
#
|
||||
# WHAT IT NEEDS ON THE HOST
|
||||
# check-backend / generate Go (the version in backend/go.mod)
|
||||
# check-python python3 with the venv module
|
||||
# check-vue Node + `npm install` done in vue/, and the
|
||||
# generated vue/src/wasm/ directory (see below)
|
||||
# check-compose / dev Docker with the compose plugin
|
||||
# Nothing here installs a toolchain; a missing one fails that target only.
|
||||
#
|
||||
# Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in
|
||||
# its own shell, so the directory change cannot leak into the next line.
|
||||
# =============================================================================
|
||||
|
||||
# `make` with no arguments prints the target list rather than running checks.
|
||||
.DEFAULT_GOAL := help
|
||||
|
||||
# Overridable: `make check-python PYTHON=python3.12` to match the image.
|
||||
PYTHON ?= python3
|
||||
|
||||
# The virtualenv for the Python checks. At the repo root rather than inside
|
||||
# python/, because python/ is a docker build context and a venv there would be
|
||||
# sent to the daemon on every build. Gitignored (/.venv/).
|
||||
VENV := .venv
|
||||
|
||||
# Written after a successful install. Being a file target that depends on both
|
||||
# requirements files, it is what makes `check-python` re-install when either
|
||||
# changes and skip the install otherwise.
|
||||
VENV_STAMP := $(VENV)/.installed
|
||||
|
||||
.PHONY: help check check-backend check-python check-vue check-compose generate dev
|
||||
|
||||
help:
|
||||
@echo "Targets:"
|
||||
@echo " make check run every check below"
|
||||
@echo " make check-backend go vet + go test in backend/"
|
||||
@echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)"
|
||||
@echo " make check-vue vite build of vue/ into a throwaway directory"
|
||||
@echo " make check-compose validate docker-compose.yml, alone and with the dev override"
|
||||
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit"
|
||||
@echo " make dev build and run the dev stack (http://localhost)"
|
||||
|
||||
# Run with `make -k check` to keep going past the first failing area.
|
||||
check: check-backend check-python check-vue check-compose
|
||||
|
||||
check-backend:
|
||||
cd backend && go vet ./... && go test ./...
|
||||
|
||||
# requirements-dev.txt `-r`-includes requirements.txt, so one install covers
|
||||
# the app's dependencies and pytest. The venv is recreated from scratch
|
||||
# whenever a requirements file changes: upgrading in place would leave behind
|
||||
# packages that were removed from the files, and the check would keep passing
|
||||
# on a dependency the image no longer has.
|
||||
$(VENV_STAMP): python/requirements.txt python/requirements-dev.txt
|
||||
rm -rf $(VENV)
|
||||
$(PYTHON) -m venv $(VENV)
|
||||
$(VENV)/bin/python -m pip install --quiet --upgrade pip
|
||||
$(VENV)/bin/python -m pip install --quiet -r python/requirements-dev.txt
|
||||
touch $@
|
||||
|
||||
check-python: $(VENV_STAMP)
|
||||
cd python && ../$(VENV)/bin/python -m pytest tests -q
|
||||
|
||||
# `npx vite build`, NOT `npm run build`: the npm script first runs wasm-pack to
|
||||
# compile the Rust crate, which needs a Rust toolchain most machines (and the
|
||||
# Pi) do not have. The Vite half alone is enough to catch a broken import or
|
||||
# template.
|
||||
#
|
||||
# It does still need the OUTPUT of that Rust step, vue/src/wasm/, which is
|
||||
# generated and gitignored — so a fresh clone has none and Vite would fail with
|
||||
# a bare "could not resolve ../wasm/..." error. The guards below say what is
|
||||
# actually wrong instead.
|
||||
#
|
||||
# The build goes to a temp directory that is removed afterwards (success or
|
||||
# failure), so the check never leaves a vue/dist behind or overwrites one.
|
||||
check-vue:
|
||||
@test -d vue/src/wasm || { \
|
||||
echo "check-vue: vue/src/wasm/ is missing."; \
|
||||
echo " It is the generated (gitignored) output of the Rust crate in vue/crates/"; \
|
||||
echo " and the Vite build imports it. Create it with wasm-pack:"; \
|
||||
echo " cd vue && npm run build:wasm"; \
|
||||
echo " (needs a Rust toolchain; the vue image builds it for you, see vue/Dockerfile)."; \
|
||||
exit 1; }
|
||||
@test -d vue/node_modules || { \
|
||||
echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \
|
||||
exit 1; }
|
||||
@out=$$(mktemp -d) && trap 'rm -rf "$$out"' EXIT && \
|
||||
cd vue && npx vite build --outDir "$$out" --emptyOutDir
|
||||
|
||||
# Validates the compose files: YAML, schema, and that every ${VAR} they
|
||||
# interpolate resolves to something usable.
|
||||
#
|
||||
# With a real .env present this is simply `docker compose config -q`.
|
||||
#
|
||||
# Without one (a CI checkout, a fresh clone) two things break, and
|
||||
# `--env-file .env.example` fixes neither:
|
||||
# - several services declare `env_file: ./.env`, and compose refuses to load
|
||||
# the project if that file does not exist;
|
||||
# - .env.example has blank values, and OBSIDIAN_DIR is used as a bind-mount
|
||||
# source, where an empty string is a hard "invalid spec" error.
|
||||
# So in that case the files are validated against a temporary PROJECT
|
||||
# DIRECTORY holding a copy of .env.example as its .env, with a placeholder for
|
||||
# OBSIDIAN_DIR. `config` only resolves paths, it does not need them to exist,
|
||||
# so the build contexts not being under the temp directory is fine. Nothing is
|
||||
# written to the repo, and a real .env is never created by accident.
|
||||
check-compose:
|
||||
@set -e; \
|
||||
if [ -f .env ]; then \
|
||||
pd="."; \
|
||||
else \
|
||||
echo "check-compose: no .env, validating against .env.example"; \
|
||||
pd=$$(mktemp -d); trap 'rm -rf "$$pd"' EXIT; \
|
||||
cp .env.example "$$pd/.env"; \
|
||||
echo "OBSIDIAN_DIR=/placeholder/obsidian" >> "$$pd/.env"; \
|
||||
fi; \
|
||||
echo "docker compose -f docker-compose.yml config -q"; \
|
||||
docker compose --project-directory "$$pd" -f docker-compose.yml config -q; \
|
||||
echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \
|
||||
docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q
|
||||
|
||||
# Rewrites backend/graph/generated.go and graph/model/models_gen.go from
|
||||
# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
|
||||
generate:
|
||||
cd backend && go run github.com/99designs/gqlgen generate
|
||||
|
||||
# Dev stack: HTTP only, seeded database, Vite hot reload behind nginx.
|
||||
dev:
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||
@@ -27,8 +27,6 @@ silverbullet (3000) ── Obsidian Notes Editor (SilverBullet 2.11.0)
|
||||
silverbullet-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY)
|
||||
silverbullet-git ── Commits/pushes notes edits to the notes repo
|
||||
python (8000) ── Python API (FastAPI)
|
||||
hasura (8080) ── Hasura GraphQL Engine (Docker profile: hasura)
|
||||
autoheal ── Auto-restart unhealthy containers
|
||||
certbot ── SSL Certificate Management (disabled in dev)
|
||||
```
|
||||
|
||||
@@ -57,11 +55,10 @@ certbot ── SSL Certificate Management (disabled in dev)
|
||||
- Printable CV with role-specific sections
|
||||
- Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
|
||||
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
|
||||
- Hasura GraphQL console (admin-only)
|
||||
- Admin-gated routes: `/notes`, `/sb`, `/hasura` require admin JWT via Nginx `auth_request`
|
||||
- Admin-gated routes: `/notes`, `/sb` require admin JWT via Nginx `auth_request`
|
||||
- Landing page with animated stamps section
|
||||
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
|
||||
- Backend healthcheck with autoheal container for automatic recovery
|
||||
- Backend healthcheck (reported in `docker ps`; nothing restarts on it)
|
||||
|
||||
## Pages
|
||||
|
||||
@@ -183,13 +180,12 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
|
||||
| `/api` | backend:8080 | API (rate limited: 30r/s) |
|
||||
| `/radio` | icecast:8000 | Audio streaming |
|
||||
| `/gitea` | gitea:3000 | Git service |
|
||||
| `/hasura` | hasura:8080 | GraphQL console + WebSocket (admin-only) |
|
||||
| `/notes` | silverbullet-public:3000 | Obsidian notes (public, read-only) |
|
||||
| `/sb` | silverbullet:3000 | Obsidian notes editor (admin-only) |
|
||||
| `/py` | python:8000 | Python API (FastAPI; docs at `/py/docs`) |
|
||||
| `/uploads` | local alias | User-uploaded files |
|
||||
|
||||
`/hasura` and `/sb` are protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
|
||||
`/sb` is protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
|
||||
|
||||
### Deprecated Endpoints
|
||||
|
||||
@@ -246,12 +242,9 @@ Create a `.env` file in the project root. All services read from this file.
|
||||
| `LIQUIDSOAP_HARBOR_PORT` | Liquidsoap harbor port (e.g. `8005`) |
|
||||
| `DOMAIN` | Production domain name |
|
||||
| `EMAIL` | Email for Let's Encrypt registration |
|
||||
| `CLAUDE_API_KEY` | Anthropic Claude API key |
|
||||
| `CLAUDE_API_KEY` | Anthropic Claude API key (read by the Python service, which makes every Claude call) |
|
||||
| `STEAM_API_KEY` | Steam Web API key |
|
||||
| `STEAM_ID` | Steam user ID |
|
||||
| `HASURA_GRAPHQL_ADMIN_SECRET` | Hasura admin secret |
|
||||
| `HASURA_HOST` | Hasura hostname (use `hasura` for Docker) |
|
||||
| `HASURA_PORT` | Hasura port (typically `8080`) |
|
||||
| `PYTHON_HOST` | Python API hostname (defaults to `python`) |
|
||||
| `PYTHON_PORT` | Python API port (defaults to `8000`) |
|
||||
| `SEED_DB` | Set to `true` to seed test data on startup |
|
||||
@@ -319,7 +312,6 @@ This:
|
||||
- Disables certbot
|
||||
- Seeds the database with test data (`SEED_DB=true`)
|
||||
- Enables GraphQL playground and introspection
|
||||
- Enables Hasura console and dev mode
|
||||
|
||||
Visit `http://localhost` to test.
|
||||
|
||||
@@ -329,7 +321,17 @@ Visit `http://localhost` to test.
|
||||
cd vue && npm run dev
|
||||
```
|
||||
|
||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
||||
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets default to `localhost:8080`, `:3000`, `:8000` and `:8000`; override them with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (see the comment in `vue/vite.config.js` — compose does not publish the backend, Python or Icecast ports to the host).
|
||||
|
||||
### Checks
|
||||
|
||||
```sh
|
||||
make check
|
||||
```
|
||||
|
||||
Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build and `docker compose config` validation. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`.
|
||||
|
||||
The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass.
|
||||
|
||||
## Untracked Files
|
||||
|
||||
|
||||
+2
-2
@@ -46,8 +46,8 @@ FROM debian:bookworm-slim
|
||||
|
||||
# wget is not just for humans: the compose healthcheck probes the server with
|
||||
# `wget -qO- http://localhost:8080/`, and without it in the image every probe
|
||||
# fails as "executable file not found" — Docker then marks the container
|
||||
# unhealthy and autoheal kills it in a ~90s restart loop.
|
||||
# fails as "executable file not found" and Docker marks the container
|
||||
# unhealthy.
|
||||
RUN apt-get update \
|
||||
&& apt-get install --yes --no-install-recommends ca-certificates wget \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
+373
-16
@@ -2,7 +2,8 @@
|
||||
|
||||
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).
|
||||
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
|
||||
that needs Claude is asked of the Python service, not called from here.
|
||||
|
||||
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
|
||||
@@ -18,9 +19,11 @@ handlers/ REST endpoints + the shared Store dependency container
|
||||
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
|
||||
schema/*.graphql source of truth for the schema, including who may call what
|
||||
*.resolvers.go resolver implementations, one per schema file
|
||||
*_helpers.go hand-written mapping helpers (never regenerated)
|
||||
directives.go @admin / @signedIn: the authorisation checks, written once
|
||||
directives_test.go fails when a mutation is added without one
|
||||
context.go reading identity out of the resolver context
|
||||
middleware.go putting it in
|
||||
doc.go package overview — read this before touching resolvers
|
||||
@@ -41,9 +44,10 @@ graph/ GraphQL layer
|
||||
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.**
|
||||
token is present, the JWT claims — and then lets everything through. A
|
||||
field is guarded by a directive on it in the schema, `@admin` or
|
||||
`@signedIn`, which runs before the resolver. **A field with neither is
|
||||
public.** See [GraphQL authorisation](#graphql-authorisation).
|
||||
5. Handlers and resolvers both reach the database and the caches through the
|
||||
single `handlers.Store` built in `main`.
|
||||
|
||||
@@ -70,6 +74,96 @@ The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
|
||||
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 authorisation
|
||||
|
||||
Who may call a field is written in the schema, on the field:
|
||||
|
||||
```graphql
|
||||
extend type Query {
|
||||
bookmarks: [Bookmark!]! # public
|
||||
places: [Place!]! @signedIn # any signed-in user
|
||||
users: [User!]! @admin # admins only
|
||||
}
|
||||
```
|
||||
|
||||
| directive | passes when | error otherwise |
|
||||
| --- | --- | --- |
|
||||
| `@admin` | the access token's `admin` claim is true | `admin access required` |
|
||||
| `@signedIn` | there is a valid access token at all | `authentication required` |
|
||||
| *(none)* | always | — |
|
||||
|
||||
Both are declared in `graph/schema/schema.graphql`, implemented once in
|
||||
`graph/directives.go`, and handed to gqlgen in `main.go`
|
||||
(`graph.Config{Directives: graph.Directives()}`). gqlgen calls the directive
|
||||
before the resolver; on an error the resolver never runs and the client gets
|
||||
that message for the field. The two strings are shown as-is by the front end,
|
||||
so they are part of the API. If the `Directives` line were ever dropped from
|
||||
`main.go` the guarded fields would all fail (`directive admin is not
|
||||
implemented`), not open.
|
||||
|
||||
This replaced an `if !IsAdminFromCtx(ctx) { return ... }` that was pasted into
|
||||
the top of every guarded resolver, where leaving it out was invisible. Now a
|
||||
guarded resolver has no check in it, and the absence of a guard is something a
|
||||
test can see.
|
||||
|
||||
**What is guarded.** Queries are public and mutations are `@admin`, except:
|
||||
|
||||
- `login`, `logout`, `refreshToken` — public; they are how a session starts
|
||||
and ends.
|
||||
- `createPlace`, `updatePlace`, `deletePlace` and the `places` query —
|
||||
`@signedIn`. Places are a shared list with no per-user ownership.
|
||||
- `users`, `user`, `jobApplications`, `jobApplication`, `jobAppReferences` —
|
||||
queries, but `@admin`: private data.
|
||||
|
||||
**What a directive cannot say stays in the resolver**, using `IsAdminFromCtx` /
|
||||
`UserIDFromCtx` from `graph/context.go`:
|
||||
|
||||
- `updatePost` / `deletePost` are `@admin` *and* require the caller to be the
|
||||
post's author; `setUserAdmin` refuses to change the caller's own flag.
|
||||
- `me` has no directive: it returns its own `unauthorized` error.
|
||||
- `messages` has no directive: it filters private messages out for non-admins
|
||||
instead of refusing.
|
||||
- `spotifyNeedsReauth` has no directive: it is `false` for non-admins.
|
||||
|
||||
**The safety net** is `graph/directives_test.go`, which walks the parsed
|
||||
schema:
|
||||
|
||||
- every `Mutation` field must carry `@admin` or `@signedIn`, unless it is in
|
||||
the `publicMutations` list in that file (the three above). A new mutation
|
||||
with no directive fails the build's tests until one or the other is done;
|
||||
- the `@signedIn` mutations and the guarded queries are pinned by name, so
|
||||
loosening `@admin` to `@signedIn`, or dropping a guard from a private query,
|
||||
has to be done in the test as well;
|
||||
- the directive functions are unit-tested, and a handful of operations are run
|
||||
through the real executable schema to pin the messages on the wire.
|
||||
|
||||
One caveat: the test reads the `.graphql` files, but enforcement is in
|
||||
`generated.go`. Adding a directive to an existing field does nothing until
|
||||
gqlgen is re-run.
|
||||
|
||||
## Adding an entity
|
||||
|
||||
1. **Model** — add the struct to `models/models.go` with `ID uint`
|
||||
(`gorm:"primarykey"`) and a `gorm.DeletedAt`, and list it in `AutoMigrate`
|
||||
in `services/database.go`. There are no migration files.
|
||||
2. **Schema** — add `graph/schema/<name>.graphql` with the type, its inputs,
|
||||
and `extend type Query` / `extend type Mutation`. Put `@admin` or
|
||||
`@signedIn` on every mutation, and on any query that is not for the public.
|
||||
Use `#` comments, not `"""` descriptions.
|
||||
3. **Binding** — map the type onto the model in `gqlgen.yml`, with
|
||||
`deletedAt: resolver: false`. Without the entry gqlgen generates a second,
|
||||
unrelated struct in `graph/model/`.
|
||||
4. **Generate** — `go run github.com/99designs/gqlgen generate` (below). This
|
||||
creates `graph/<name>.resolvers.go` with a stub per query and mutation.
|
||||
5. **Resolvers** — fill the stubs in. Do not write an auth check; the
|
||||
directive has run. Do not write an `ID` resolver; `ID uint` binds by itself
|
||||
(see [IDs](#gotchas)). Put commentary inside the function bodies, since
|
||||
gqlgen rewrites what is above the signature. A delete should load the row
|
||||
first and return an error for a missing id, as the existing ones do.
|
||||
6. **Test** — `go test ./...`. `directives_test.go` will tell you if a
|
||||
mutation was left unguarded; if you added a guarded *query*, add it to the
|
||||
pinned list there.
|
||||
|
||||
## GraphQL vs REST
|
||||
|
||||
GraphQL is the default and covers essentially all the site's data. REST exists
|
||||
@@ -83,6 +177,179 @@ for the things GraphQL cannot do:
|
||||
| `/notes/*path` | streams a file download, not JSON |
|
||||
| `/ws` | WebSocket upgrade |
|
||||
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
||||
| `/admin/env`, `/admin/logs`, `/admin/capture-token` | process environment and files on disk, not the data model |
|
||||
| `/jobs/capture`, `/jobs/capture/status`, `/jobs/capture/extract` | called by a userscript on other sites' origins, where the `SameSite=Lax` auth cookies are never sent; they take a bearer token instead |
|
||||
|
||||
### Environment tab
|
||||
|
||||
`handlers/handle_env.go` and `services/env_manager.go` let the admin panel
|
||||
change `.env` on the Pi without SSH. The backend never reads or writes the
|
||||
file and has no Docker access: it validates an edit and leaves it for the
|
||||
host, which is the part trusted to act.
|
||||
|
||||
- **`services/env_registry.json`** lists every variable in `.env.example`
|
||||
with its group, kind, whether it is editable, and the compose services that
|
||||
read it. It is embedded in the binary and read from the checkout by the host
|
||||
script, so one file decides what the panel offers and what the host accepts.
|
||||
A test fails if it and `.env.example` disagree.
|
||||
- **The `python` service is a third place.** It is the one container given an
|
||||
explicit `environment:` list in `docker-compose.yml` instead of the whole
|
||||
`.env`, so that it never holds the database password or the JWT secret. A
|
||||
new Python variable therefore goes in the registry (with `python` in its
|
||||
`services`), in `.env.example`, *and* in that list.
|
||||
`TestEnvRegistryMatchesComposePythonEnvironment` reads the compose file and
|
||||
fails if a variable the registry says python reads is not passed to it, or
|
||||
if an editable variable passed to it does not list `python`. Locked
|
||||
variables carry no `services` and are exempt (`PYTHON_PORT` is one).
|
||||
- `GET /admin/env` — the registry plus state from this process's own
|
||||
environment. A secret's value is never sent, only "set" and, for values of
|
||||
12+ characters, the last four.
|
||||
- `PUT /admin/env` — `{"set": {NAME: value}, "generate": [NAME]}`; `""`
|
||||
clears. The whole batch is validated first. Control characters are refused
|
||||
because `.env` is line oriented: a newline would let an edit to an allowed
|
||||
variable write a second, arbitrary one. Generated values (32 random bytes,
|
||||
hex) are returned once.
|
||||
- The change is written to `/backend/env-apply/request.json` (`./env-apply/run`
|
||||
on the host), `0600` and chowned to that directory's owner so the
|
||||
unprivileged host user can read it. `env-apply/apply.py` claims it, rewrites
|
||||
`.env`, recreates the affected services and writes `status.json`.
|
||||
- `GET /admin/env/status` — `idle`, `pending`, `applying`, `applied` or
|
||||
`failed`. `watcher: false` means a request has sat unclaimed for 15 seconds,
|
||||
i.e. nothing on the host is watching. `DELETE /admin/env/pending` withdraws
|
||||
an unclaimed request.
|
||||
|
||||
The backend is always among the recreated services, because the values the
|
||||
panel shows are the ones this process started with.
|
||||
|
||||
### Job capture
|
||||
|
||||
`handlers/handle_job_capture.go` is the server half of the browser userscript
|
||||
(`vue/public/job-capture.user.js`, installed from the tracker page) that adds
|
||||
the posting open in the browser to the job tracker.
|
||||
|
||||
- **Auth** is `Authorization: Bearer <token>`, checked by
|
||||
`CaptureTokenMiddleware`. The token opens these three routes and nothing
|
||||
else — it cannot read the tracker or reach GraphQL. **With no token
|
||||
generated the routes are off (503)**; that never means "no auth".
|
||||
- **The token is generated in the admin panel**, not set in `.env`
|
||||
(`services/capture_token.go`; `GET`/`POST`/`DELETE /admin/capture-token`,
|
||||
cookie-authenticated like the rest of the admin group). It is 32 random
|
||||
bytes, shown once; only its SHA-256 is kept, in
|
||||
`/backend/token/job_capture_token.json` beside the OAuth tokens, so it
|
||||
survives restarts and rebuilds. There is one token at a time: generating
|
||||
again replaces it, which is how a leaked one is rotated.
|
||||
- `GET /jobs/capture/status?url=` — is this posting already tracked, and at
|
||||
what status. Drives the script's badge.
|
||||
- `POST /jobs/capture/extract` — page text in, `{jobTitle, company, location,
|
||||
notes}` out, read by Claude through the Python service
|
||||
(`/internal/jobs/extract`, see [Calling the Python service](#calling-the-python-service)).
|
||||
Stores nothing.
|
||||
- `POST /jobs/capture` — an **upsert**. A posting is matched by its canonical
|
||||
URL (`services.CanonicalJobURL` strips tracking parameters and folds LinkedIn's
|
||||
several URL shapes into one), then by `(company, job title)` the way the
|
||||
email pipeline matches (`services.UpsertJobApplication`, shared with lead
|
||||
promotion). A repeat capture only ever adds: status moves
|
||||
forwards, empty fields are filled, nothing is overwritten.
|
||||
|
||||
The upsert is what keeps this and the email pipeline from making two rows for
|
||||
one application. It is not watertight: the pipeline still matches on the exact
|
||||
title, so a posting captured as "Senior Engineer" whose confirmation email
|
||||
says "Senior Engineer (Platform)" becomes a second row.
|
||||
|
||||
### Job leads
|
||||
|
||||
Where the tracker records applications, this finds postings. It is GraphQL
|
||||
throughout (`graph/schema/job_lead.graphql`, all `@admin`) with the work in
|
||||
`services/job_leads.go` and `services/job_sources.go`; the page is `/cv/leads`.
|
||||
|
||||
- **Three tables.** `JobSource` is one thing to poll: a company's board on
|
||||
Greenhouse, Lever or Ashby (public JSON, no key), or a keyword search on
|
||||
Adzuna or Reed (keys in `.env`). `JobLead` is one posting found. It is
|
||||
**not soft deleted**, like `ProcessedEmail`: the unique index on
|
||||
`(source_kind, external_id)` is the dedup, and it only keeps a dismissed
|
||||
lead dismissed if that lead is still a row. `JobSearchProfile` is a single
|
||||
row: the profile text, three keyword lists and a minimum score.
|
||||
- **A run** (`JobLeadService.Run`) is fetch → store → pre-filter → score.
|
||||
Every enabled source is polled; one failing records its error on the source
|
||||
and the rest carry on. Postings not seen before become leads; ones already
|
||||
known only have `last_seen_at` moved. A posting whose canonical URL is
|
||||
already in the tracker is filed as `promoted`, linked to that application,
|
||||
so the inbox never offers it.
|
||||
- **The pre-filter** is keywords on the title and location, no Claude. It
|
||||
exists because a company board is mostly irrelevant, and it decides which
|
||||
leads are shown and which cost a call. `matched` is recomputed for every
|
||||
inbox lead on each run, so editing the keywords applies to old leads too.
|
||||
- **Scoring** sends each matched, unscored lead and the profile text to the
|
||||
Python service's `/internal/jobs/score`. At most 40 a run, newest first; a
|
||||
lead Claude cannot score is retried on three runs and then left. With an
|
||||
empty profile nothing is scored. If scoring is unavailable (no API key,
|
||||
Python down) the run stops scoring without spending an attempt on any lead.
|
||||
- **Scoring the backlog.** The `scoreJobLeads` mutation
|
||||
(`JobLeadService.ScoreAll`, "Score unscored" on the page) scores every
|
||||
matched, unscored lead with no cap and without polling any source. It is
|
||||
for the backlog a first poll of several boards leaves behind, or leads
|
||||
that arrived before the profile was written. A lead that fails is tried
|
||||
once per press. It stops after an hour; pressing again continues.
|
||||
- **Rescoring.** The `rescoreJobLeads` mutation (`RescoreAll`, "Rescore all"
|
||||
on the page) scores every matched inbox lead again, for after the profile
|
||||
or `CLAUDE_MODEL` has changed. It does not wipe scores first: a lead keeps
|
||||
its old score until the new one is saved, and `scored_at` is what marks a
|
||||
lead as done by this job. A job that fails partway leaves a mix of old and
|
||||
new scores, and pressing again starts over.
|
||||
- **When it runs.** `JOB_LEADS_ENABLED=true` starts a timer
|
||||
(`JOB_LEADS_INTERVAL`, default `6h`); it does not run at start-up, so a
|
||||
deploy spends nothing. The `runJobLeadSync` mutation starts a run in a
|
||||
goroutine and returns at once, whether or not the timer is on, and
|
||||
`jobLeadSyncStatus` reports on it (and on `scoreJobLeads` and
|
||||
`rescoreJobLeads`; only one of the three jobs runs at a time) — a run can take minutes, so unlike
|
||||
`POST /email/sync` it does not hold the request open. The status is in
|
||||
memory and resets on restart.
|
||||
- **Promotion** (`promoteJobLead`) is the only way a lead reaches the tracker.
|
||||
It calls `services.UpsertJobApplication` with status `saved`, the lead's
|
||||
text and a notes line carrying the score — the same upsert as the capture
|
||||
endpoint, so a posting captured from the browser in the meantime is linked
|
||||
to, not duplicated.
|
||||
|
||||
The Adzuna and Reed response structs were written from the providers'
|
||||
documentation, not against live responses (they need keys). If one of those
|
||||
sources reports a decode error or zero results, compare its struct in
|
||||
`job_sources.go` with a real reply first. Adzuna only returns a snippet of
|
||||
each description, so its leads are scored on less text.
|
||||
|
||||
Most of this needs Postgres and has no unit test: what is tested is the
|
||||
fetchers (against stub servers), the pre-filter, how a fetched posting becomes
|
||||
a row, and the scoring call.
|
||||
|
||||
## Calling the Python service
|
||||
|
||||
Every Claude call the site makes lives in the Python service; this backend has
|
||||
no Anthropic client and does not read `CLAUDE_API_KEY`. It reaches four
|
||||
internal routes directly over the Docker network
|
||||
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
|
||||
nginx, which answers 404 for `/py/internal/`:
|
||||
|
||||
| route | caller | sends | gets back |
|
||||
| --- | --- | --- | --- |
|
||||
| `/internal/rowing/read` | `POST /rowing` (`handlers/handle_rowing.go`) | `{media_type, data}` (image, base64) | `{timeMinutes, timeSeconds, distance}` |
|
||||
| `/internal/jobs/extract` | `POST /jobs/capture/extract` (`handlers/handle_job_capture.go`) | `{url, title, text}` | `{jobTitle, company, location, notes}` |
|
||||
| `/internal/jobs/score` | the lead pipeline (`services/job_leads.go`) | `{profile, jobTitle, company, location, description}` | `{score, reasons}` |
|
||||
| `/internal/email/classify` | the email pipeline (`services/email_sync.go`) | `{message}` | `EmailAnalysis` (below) |
|
||||
|
||||
All four go through one function, `services.CallPython[T]` in
|
||||
`services/python_call.go`: marshal the body, POST it, decode a 200 into `T`.
|
||||
It has the one HTTP client (two-minute timeout, above the Python side's own
|
||||
worst case of a retried Claude call) and the one rule for failures:
|
||||
|
||||
- a **502 whose `detail` is a string** is a message the route wrote for a
|
||||
person ("failed to parse image data"). It comes back as a
|
||||
`*services.PythonError`, and the two HTTP handlers relay it to the browser;
|
||||
- **anything else** — connection refused, a 422 (its `detail` is a list), a
|
||||
503 for an unset `CLAUDE_API_KEY`, a reply that will not decode — is an
|
||||
ordinary error. Callers log it and show something generic.
|
||||
|
||||
It lives in `services` because both `handlers` and `services` need it and
|
||||
`handlers` already imports `services`. A new internal route needs only a
|
||||
request struct, a reply struct and a one-line call.
|
||||
|
||||
## Services
|
||||
|
||||
@@ -105,15 +372,73 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
(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.
|
||||
it, have each survivor classified, create or advance a `JobApplication`.
|
||||
Runs on a timer and can be triggered by an admin.
|
||||
|
||||
The classification is the Python service's `/internal/email/classify`,
|
||||
which owns the prompt, the Claude call and the parsing of the model's
|
||||
reply. Go sends one string — `Subject:`, `From:` and `Date:` lines, a blank
|
||||
line, the cleaned body (capped at 4,000 bytes; the whole message at the
|
||||
200,000 characters Python accepts) — and gets back `EmailAnalysis`:
|
||||
`isJobEmail`, `action`, `company`, `jobTitle`, `status`, and the nullable
|
||||
`location`, `url`, `appliedAt`, `notes`. Everything either side of that
|
||||
call is unchanged and still here: the pre-filter, dedup, retry accounting,
|
||||
matching on (company, job title), and the forward-only status rule. Any
|
||||
failure of the call, whatever its status code, is a failed attempt at that
|
||||
email.
|
||||
- **job_leads.go** / **job_sources.go** — the job-lead pipeline. See
|
||||
[Job leads](#job-leads).
|
||||
- **job_upsert.go** — `UpsertJobApplication`, the one way a posting is added
|
||||
to the tracker without duplicating a row: used by the capture endpoint and
|
||||
by promoting a lead.
|
||||
- **python_call.go** — `CallPython`, the one way to reach the Python service's
|
||||
internal routes. See [Calling the Python service](#calling-the-python-service).
|
||||
- **job_status.go** — how the `JobStatus` GraphQL enum is read and written.
|
||||
See [Job status](#job-status).
|
||||
- **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`).
|
||||
|
||||
## Job status
|
||||
|
||||
A job application's status is one of eight lowercase strings: `saved`,
|
||||
`applied`, `screening`, `assessment`, `interviewing`, `offer`, `rejected`,
|
||||
`withdrawn`. The list is `statusOrder` in `services/email_sync.go`, which also
|
||||
ranks them — the email pipeline and the capture endpoint only ever move a row
|
||||
forwards through it (`services.StatusAdvances`).
|
||||
|
||||
GraphQL knows the same list as `enum JobStatus`
|
||||
(`graph/schema/job_application.graphql`), used for `JobApplication.status` and
|
||||
both inputs. `TestJobStatusEnumMatchesStatusOrder` in
|
||||
`services/job_status_test.go` parses the schema file and fails unless the enum
|
||||
and the map hold the same statuses in the same order, so adding a status means
|
||||
editing both. (The classifier prompt in the Python service, the tracker page
|
||||
and the userscript list them too, and nothing checks those.)
|
||||
|
||||
The enum is bound in `gqlgen.yml` to `services.MarshalJobStatus` /
|
||||
`UnmarshalJobStatus` instead of a generated Go type, for two reasons:
|
||||
|
||||
- **The column stays a `string`.** `models.JobApplication.Status` binds as it
|
||||
is; there is no migration and no conversion in the pipeline.
|
||||
- **Input is strict, output is lenient.** A mutation with a status outside the
|
||||
list is refused (`"hired" is not a valid JobStatus`) — nothing is coerced to
|
||||
`applied` any more. But a row already holding something else, such as the
|
||||
Title Case values the tracker once wrote, must not break reads: `status` is
|
||||
non-null, so a serialisation error on one row would null the entire
|
||||
`jobApplications` list. On the way out a value that matches once trimmed and
|
||||
lowercased is sent in its canonical form, and anything else is sent exactly
|
||||
as stored for the tracker to display and correct.
|
||||
|
||||
On the wire nothing changed from when the field was a `String`: the client
|
||||
sends `"applied"` as a JSON string variable and reads back `"applied"`. (An
|
||||
enum does differ for a status written *inline* in a query document, which must
|
||||
now be `status: applied`, unquoted. The front end only uses variables.)
|
||||
|
||||
`services.NormalizeStatus`, which trims, lowercases and falls back to
|
||||
`applied`, is still what the email pipeline and `POST /jobs/capture` use on
|
||||
values that do not come through GraphQL.
|
||||
|
||||
## Regenerating gqlgen
|
||||
|
||||
The `.graphql` files are the source of truth.
|
||||
@@ -122,6 +447,10 @@ The `.graphql` files are the source of truth.
|
||||
cd backend && go run github.com/99designs/gqlgen generate
|
||||
```
|
||||
|
||||
If that stops with `missing go.sum entry ... urfave/cli`, the generator's own
|
||||
dependencies are not in `go.sum`. `go get github.com/99designs/gqlgen@<the
|
||||
version in go.mod>` adds them.
|
||||
|
||||
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
|
||||
@@ -132,6 +461,14 @@ the end of it — which is why shared helpers live in `*_helpers.go` instead.
|
||||
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
|
||||
generated struct rather than the model you expected.
|
||||
|
||||
Two scalar-level bindings in `gqlgen.yml` are worth knowing about: `ID` lists
|
||||
both `graphql.IntID` and `graphql.UintID` (see IDs under Gotchas), and
|
||||
`JobStatus` points at the hand-written marshaller described above.
|
||||
|
||||
If you delete a field or stop needing a resolver, delete the resolver function
|
||||
by hand before regenerating; otherwise gqlgen keeps it, commented out, in a
|
||||
warning block at the end of the file.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Soft delete everywhere.** Every model except `ProcessedEmail` has a
|
||||
@@ -140,8 +477,18 @@ generated struct rather than the model you expected.
|
||||
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)`.
|
||||
- **IDs.** Models use `uint`; the schema uses `ID`. `gqlgen.yml` binds `ID` to
|
||||
`graphql.IntID` *and* `graphql.UintID`, so a model's `ID uint` field is
|
||||
served directly — there are no `ID` resolvers, and a new type does not need
|
||||
one. `IntID` is listed first, which is why resolver *arguments* are still
|
||||
`id int`. Both write an id as a quoted decimal string (`"12"`) and accept a
|
||||
string or a number, so the wire format is the same either way. Other
|
||||
unsigned fields are not IDs and still have resolvers: `Message.authorId`,
|
||||
`Rowing.time`, `Rowing.distance`.
|
||||
- **Deletes error on a missing id.** Every delete mutation loads the row
|
||||
first. `deleteJobApplication` and `deleteJobAppReference` return `Boolean!`
|
||||
rather than the row, so the only value they ever return is `true`; a wrong
|
||||
id is a `record not found` error, not `false`.
|
||||
- **`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
|
||||
@@ -149,9 +496,10 @@ generated struct rather than the model you expected.
|
||||
- **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 — via the shared `services.StripMarkdownFence`, used by both
|
||||
`handle_rowing.go` and `email_sync.go`.
|
||||
- **Claude's output is never parsed here.** Prompts, the markdown-fence
|
||||
stripping and the JSON parsing are all in the Python service; this side
|
||||
receives typed JSON or an error (see
|
||||
[Calling the Python service](#calling-the-python-service)).
|
||||
- **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.**
|
||||
A failed email is recorded with action `"error"` and an attempt counter;
|
||||
while it has attempts left the next sync reprocesses it and updates the same
|
||||
@@ -159,7 +507,10 @@ generated struct rather than the model you expected.
|
||||
already moved past the failure, the sync also rewinds the window to the
|
||||
oldest retryable row's `ReceivedAt` — otherwise the email could never be
|
||||
re-fetched. Once the cap is reached the row is terminal, so an email Claude
|
||||
can never parse stops costing API calls.
|
||||
can never parse stops costing API calls. A failure is any error from the
|
||||
classify call — Python down, a 502, a 503 because `CLAUDE_API_KEY` is unset
|
||||
— so an outage of the Python service uses up attempts just as an Anthropic
|
||||
outage does. The one exception is a cancelled sync, which records nothing.
|
||||
- **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*
|
||||
@@ -180,10 +531,12 @@ generated struct rather than the model you expected.
|
||||
| `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 |
|
||||
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the four Claude routes (default `python:8000`) |
|
||||
| `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`) |
|
||||
| `JOB_LEADS_ENABLED` / `JOB_LEADS_INTERVAL` | lead pipeline timer (default off, `6h`) |
|
||||
| `ADZUNA_APP_ID` / `ADZUNA_APP_KEY` / `REED_API_KEY` | keyword-search lead sources; optional |
|
||||
| `MSGRAPH_CLIENT_ID` / `_SECRET` / `_TENANT_ID` / `_REDIRECT_URI` | Microsoft Graph backend |
|
||||
| `IMAP_HOST` / `_PORT` / `_EMAIL` / `_PASSWORD` | IMAP backend |
|
||||
|
||||
@@ -191,3 +544,7 @@ 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).
|
||||
|
||||
`CLAUDE_API_KEY` is not in the table: the backend does not read it. It is in
|
||||
the registry with `services: ["python"]`, because the Python service is the
|
||||
only container that uses it.
|
||||
|
||||
@@ -4,7 +4,6 @@ go 1.26
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.95
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
@@ -49,10 +48,6 @@ require (
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||
github.com/sosodev/duration v1.4.0 // indirect
|
||||
github.com/tidwall/gjson v1.18.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tidwall/sjson v1.2.5 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
|
||||
@@ -37,8 +37,6 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0 h1:oUTzFaUpAevfuELAP1sjL6CQJ9HHAfT7CoSYSac11PY=
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
|
||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||
@@ -60,8 +58,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
|
||||
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -205,16 +201,6 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||
@@ -522,8 +508,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
|
||||
@@ -16,9 +16,23 @@ resolver:
|
||||
filename_template: "{name}.resolvers.go"
|
||||
|
||||
models:
|
||||
# Two bindings, tried in order. IntID comes first, so it is what gqlgen
|
||||
# picks where it has a free choice — resolver arguments stay `id int`.
|
||||
# UintID is there so a model's `ID uint` field binds to `id: ID!` directly,
|
||||
# with no hand-written resolver converting it. Both write an id as a quoted
|
||||
# decimal string ("12") and read a string or a number, so which one a field
|
||||
# uses is invisible on the wire.
|
||||
ID:
|
||||
model:
|
||||
- github.com/99designs/gqlgen/graphql.IntID
|
||||
- github.com/99designs/gqlgen/graphql.UintID
|
||||
# Bound to MarshalJobStatus / UnmarshalJobStatus in services, so the Go
|
||||
# type stays `string` (models.JobApplication.Status binds as it is) and the
|
||||
# marshaller, not a generated enum type, decides what is accepted and what
|
||||
# is emitted. See services/job_status.go for why.
|
||||
JobStatus:
|
||||
model:
|
||||
- adam-french.co.uk/backend/services.JobStatus
|
||||
User:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.User
|
||||
@@ -75,6 +89,18 @@ models:
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
JobSource:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobSource
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
JobLead:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobLead
|
||||
JobSearchProfile:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobSearchProfile
|
||||
Place:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Place
|
||||
|
||||
@@ -7,24 +7,16 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
|
||||
// Admin-only, but there is no check to see here: the field is marked
|
||||
// @admin in the schema and the directive (directives.go) has already
|
||||
// refused anyone else by the time this runs.
|
||||
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&activity).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -41,8 +33,3 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
||||
}
|
||||
return ptrs(activities), nil
|
||||
}
|
||||
|
||||
// Activity returns ActivityResolver implementation.
|
||||
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
|
||||
|
||||
type activityResolver struct{ *Resolver }
|
||||
|
||||
@@ -121,6 +121,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
|
||||
// Me is the resolver for the me field.
|
||||
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
// Checked here rather than with @signedIn because the message differs:
|
||||
// this query has always answered "unauthorized", and the directive's is
|
||||
// "authentication required".
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
|
||||
@@ -7,22 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *bookmarkResolver) ID(ctx context.Context, obj *models.Bookmark) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateBookmark is the resolver for the createBookmark field.
|
||||
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -32,9 +23,6 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
|
||||
|
||||
// DeleteBookmark is the resolver for the deleteBookmark field.
|
||||
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
|
||||
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.
|
||||
@@ -56,8 +44,3 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
||||
}
|
||||
return ptrs(bookmarks), nil
|
||||
}
|
||||
|
||||
// Bookmark returns BookmarkResolver implementation.
|
||||
func (r *Resolver) Bookmark() BookmarkResolver { return &bookmarkResolver{r} }
|
||||
|
||||
type bookmarkResolver struct{ *Resolver }
|
||||
|
||||
@@ -27,7 +27,8 @@ const (
|
||||
|
||||
// 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.
|
||||
// not an error here, because many queries are public. Turning "anonymous"
|
||||
// into a refusal is the job of the schema directives, per field.
|
||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||
if !ok {
|
||||
@@ -38,6 +39,10 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
|
||||
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
|
||||
// float64 because claims are decoded by encoding/json, hence the conversion.
|
||||
//
|
||||
// ok is also the test behind the @signedIn directive. A resolver calls this
|
||||
// itself when it needs the id for more than a gate: to record a post's
|
||||
// author, or to compare the caller with a row's owner.
|
||||
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -50,11 +55,12 @@ 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.
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. It is
|
||||
// what the @admin directive tests (directives.go), which is how nearly every
|
||||
// mutation is authorised; resolvers call it directly only for the softer
|
||||
// cases a directive cannot express, such as the messages query filtering
|
||||
// rather than refusing. 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 {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
)
|
||||
|
||||
// The schema's two authorisation directives. A field marked @admin or
|
||||
// @signedIn in graph/schema/*.graphql has the matching function here run
|
||||
// before its resolver; if it returns an error the resolver is never called
|
||||
// and the error is what the client receives for that field.
|
||||
//
|
||||
// This replaces a check that used to be copied into the top of every guarded
|
||||
// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx /
|
||||
// UserIDFromCtx test against the claims AuthContextMiddleware verified — but
|
||||
// it is now declared next to the field, where a missing one can be seen and
|
||||
// tested for (directives_test.go), instead of being a line someone has to
|
||||
// remember to paste.
|
||||
//
|
||||
// The two error strings are part of the contract with the front end, which
|
||||
// shows them as they are; the tracker page, for one, explains "admin access
|
||||
// required" as a lapsed session. Do not reword them.
|
||||
//
|
||||
// This file is hand-written and never touched by gqlgen.
|
||||
|
||||
const (
|
||||
errAdminRequired = "admin access required"
|
||||
errSignedInRequired = "authentication required"
|
||||
)
|
||||
|
||||
// Directives is the set gqlgen needs in graph.Config. It is a function so
|
||||
// that main and the tests wire exactly the same implementations.
|
||||
//
|
||||
// Leaving a directive nil in the Config does not open the fields that use it:
|
||||
// the generated code answers "directive admin is not implemented" for each.
|
||||
func Directives() DirectiveRoot {
|
||||
return DirectiveRoot{
|
||||
Admin: requireAdmin,
|
||||
SignedIn: requireSignedIn,
|
||||
}
|
||||
}
|
||||
|
||||
// requireAdmin implements @admin: the request must carry an access token
|
||||
// whose admin claim is true. Admin comes from the token, not the database, so
|
||||
// demoting a user only bites once their access token is replaced.
|
||||
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf(errAdminRequired)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
// requireSignedIn implements @signedIn: any verified access token will do,
|
||||
// admin or not. An admin is signed in, so this never needs pairing with
|
||||
// @admin.
|
||||
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf(errSignedInRequired)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/99designs/gqlgen/graphql/handler"
|
||||
"github.com/99designs/gqlgen/graphql/handler/transport"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/vektah/gqlparser/v2/ast"
|
||||
|
||||
"adam-french.co.uk/backend/handlers"
|
||||
)
|
||||
|
||||
// Authorisation is declared in the schema (@admin / @signedIn) and enforced
|
||||
// by directives.go. These tests cover both halves: that the two functions
|
||||
// decide correctly, and that the schema marks the fields it should — the
|
||||
// second being the one that matters day to day, since the way this goes
|
||||
// wrong is a new field added without a directive.
|
||||
//
|
||||
// Nothing here needs a database: a refused field never reaches its resolver,
|
||||
// and the tests only ever drive fields that are refused or that return before
|
||||
// touching the Store.
|
||||
|
||||
// withClaims builds the context AuthContextMiddleware would for a verified
|
||||
// token. Claims are decoded from JSON in production, hence float64 for the id.
|
||||
func withClaims(id float64, admin bool) context.Context {
|
||||
claims := jwt.MapClaims{"id": id, "admin": admin}
|
||||
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||
}
|
||||
|
||||
func TestDirectives(t *testing.T) {
|
||||
anonymous := context.Background()
|
||||
user := withClaims(2, false)
|
||||
admin := withClaims(1, true)
|
||||
// A token that verified but carries no id: not something GenerateJWT
|
||||
// mints, but it must not count as signed in.
|
||||
noID := func() context.Context {
|
||||
claims := jwt.MapClaims{"admin": false}
|
||||
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||
}()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
directive func(context.Context, any, graphql.Resolver) (any, error)
|
||||
ctx context.Context
|
||||
wantErr string // "" means the resolver must run
|
||||
}{
|
||||
{"@admin refuses an anonymous request", requireAdmin, anonymous, "admin access required"},
|
||||
{"@admin refuses a signed-in non-admin", requireAdmin, user, "admin access required"},
|
||||
{"@admin admits an admin", requireAdmin, admin, ""},
|
||||
{"@signedIn refuses an anonymous request", requireSignedIn, anonymous, "authentication required"},
|
||||
{"@signedIn refuses a token with no id", requireSignedIn, noID, "authentication required"},
|
||||
{"@signedIn admits a non-admin", requireSignedIn, user, ""},
|
||||
{"@signedIn admits an admin", requireSignedIn, admin, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
called := false
|
||||
next := func(ctx context.Context) (any, error) {
|
||||
called = true
|
||||
return "resolved", nil
|
||||
}
|
||||
res, err := c.directive(c.ctx, nil, next)
|
||||
|
||||
if c.wantErr == "" {
|
||||
if err != nil || !called || res != "resolved" {
|
||||
t.Fatalf("res = %v, err = %v, resolver called = %v; want the resolver's result", res, err, called)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The exact strings are what the front end displays.
|
||||
if err == nil || err.Error() != c.wantErr {
|
||||
t.Fatalf("err = %v, want %q", err, c.wantErr)
|
||||
}
|
||||
if called {
|
||||
t.Fatal("the resolver ran for a refused request")
|
||||
}
|
||||
if res != nil {
|
||||
t.Fatalf("res = %v, want nil alongside the error", res)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Directives() must supply every directive the schema declares; a nil one
|
||||
// makes gqlgen fail each field that uses it.
|
||||
func TestDirectivesAreAllImplemented(t *testing.T) {
|
||||
d := Directives()
|
||||
if d.Admin == nil || d.SignedIn == nil {
|
||||
t.Fatal("Directives() left a directive unimplemented")
|
||||
}
|
||||
}
|
||||
|
||||
// guardOf reports which authorisation directive a field carries: "admin",
|
||||
// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds
|
||||
// nothing to @admin) and fails the test rather than being quietly accepted.
|
||||
func guardOf(t *testing.T, field *ast.FieldDefinition) string {
|
||||
t.Helper()
|
||||
admin := field.Directives.ForName("admin") != nil
|
||||
signedIn := field.Directives.ForName("signedIn") != nil
|
||||
switch {
|
||||
case admin && signedIn:
|
||||
t.Errorf("%s carries both @admin and @signedIn", field.Name)
|
||||
return "admin"
|
||||
case admin:
|
||||
return "admin"
|
||||
case signedIn:
|
||||
return "signedIn"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func schemaUnderTest() *ast.Schema {
|
||||
return NewExecutableSchema(Config{}).Schema()
|
||||
}
|
||||
|
||||
// publicMutations is the complete list of mutations that anyone may call.
|
||||
// A mutation is public only by being named here, so adding one to the schema
|
||||
// without a directive fails TestEveryMutationIsGuarded until it is either
|
||||
// guarded or deliberately listed.
|
||||
//
|
||||
// All three are how a session is obtained or given up, so they cannot require
|
||||
// one: login checks a password, refreshToken checks the refresh cookie, and
|
||||
// logout is a no-op for a visitor who is not signed in.
|
||||
var publicMutations = []string{"login", "logout", "refreshToken"}
|
||||
|
||||
func TestEveryMutationIsGuarded(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
var seen []string
|
||||
for _, field := range schema.Mutation.Fields {
|
||||
if strings.HasPrefix(field.Name, "__") {
|
||||
continue
|
||||
}
|
||||
seen = append(seen, field.Name)
|
||||
guard := guardOf(t, field)
|
||||
public := slices.Contains(publicMutations, field.Name)
|
||||
switch {
|
||||
case guard == "" && !public:
|
||||
t.Errorf("mutation %s has neither @admin nor @signedIn, so anyone can call it; "+
|
||||
"add a directive in the schema, or add it to publicMutations if that is intended", field.Name)
|
||||
case guard != "" && public:
|
||||
t.Errorf("mutation %s is listed as public but carries @%s", field.Name, guard)
|
||||
}
|
||||
}
|
||||
// A renamed or removed mutation must not leave a stale exemption behind.
|
||||
for _, name := range publicMutations {
|
||||
if !slices.Contains(seen, name) {
|
||||
t.Errorf("publicMutations lists %s, which is not in the schema", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The mutations that need only a session rather than an admin. Pinned so that
|
||||
// loosening a mutation from @admin to @signedIn — which the test above would
|
||||
// accept — has to be done here too.
|
||||
func TestSignedInMutationsArePinned(t *testing.T) {
|
||||
want := []string{"createPlace", "deletePlace", "updatePlace"}
|
||||
var got []string
|
||||
for _, field := range schemaUnderTest().Mutation.Fields {
|
||||
if guardOf(t, field) == "signedIn" {
|
||||
got = append(got, field.Name)
|
||||
}
|
||||
}
|
||||
sort.Strings(got)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("@signedIn mutations = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Queries are public by default — the home page is built from them — so the
|
||||
// rule cannot be "every field is guarded". Instead the guarded set is pinned
|
||||
// exactly: removing a directive from one of these, or adding a query that
|
||||
// exposes private data without one, has to be a visible change to this map.
|
||||
//
|
||||
// Three queries are sensitive to who is asking without being in it, because
|
||||
// they answer rather than refuse: `me` returns "unauthorized" itself,
|
||||
// `messages` filters out private rows for non-admins, and
|
||||
// `spotifyNeedsReauth` is false for non-admins.
|
||||
func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
want := map[string]string{
|
||||
"users": "admin",
|
||||
"user": "admin",
|
||||
"jobApplications": "admin",
|
||||
"jobApplication": "admin",
|
||||
"jobAppReferences": "admin",
|
||||
"jobSources": "admin",
|
||||
"jobLeads": "admin",
|
||||
"jobLead": "admin",
|
||||
"jobSearchProfile": "admin",
|
||||
"jobLeadSyncStatus": "admin",
|
||||
"places": "signedIn",
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, field := range schemaUnderTest().Query.Fields {
|
||||
if strings.HasPrefix(field.Name, "__") {
|
||||
continue
|
||||
}
|
||||
if guard := guardOf(t, field); guard != "" {
|
||||
got[field.Name] = guard
|
||||
}
|
||||
}
|
||||
for name, guard := range want {
|
||||
if got[name] != guard {
|
||||
t.Errorf("query %s: guard = %q, want @%s", name, got[name], guard)
|
||||
}
|
||||
}
|
||||
for name, guard := range got {
|
||||
if _, ok := want[name]; !ok {
|
||||
t.Errorf("query %s carries @%s but is not in the pinned list; add it there if the guard is intended", name, guard)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The directives are FIELD_DEFINITION only and are meant for the two root
|
||||
// types. One on an object's field would be enforced, but nothing above would
|
||||
// notice it being removed, so keep them where the tests look.
|
||||
func TestDirectivesOnlyOnRootFields(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
for name, def := range schema.Types {
|
||||
if def == schema.Query || def == schema.Mutation || strings.HasPrefix(name, "__") {
|
||||
continue
|
||||
}
|
||||
for _, field := range def.Fields {
|
||||
if guardOf(t, field) != "" {
|
||||
t.Errorf("%s.%s carries an authorisation directive outside Query/Mutation", name, field.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// execute runs one operation through the real executable schema, wired the
|
||||
// way main wires it, and returns the response's error messages. The Store is
|
||||
// empty: every operation below is refused, or returns, before its resolver
|
||||
// would touch the database.
|
||||
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
|
||||
t.Helper()
|
||||
srv := handler.New(NewExecutableSchema(Config{
|
||||
Resolvers: &Resolver{Store: &handlers.Store{}},
|
||||
Directives: Directives(),
|
||||
}))
|
||||
srv.AddTransport(transport.POST{})
|
||||
|
||||
body, err := json.Marshal(map[string]any{"query": query, "variables": variables})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/graphql", bytes.NewReader(body)).WithContext(ctx)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rec, req)
|
||||
|
||||
var resp struct {
|
||||
Errors []struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decoding response %s: %v", rec.Body, err)
|
||||
}
|
||||
var messages []string
|
||||
for _, e := range resp.Errors {
|
||||
messages = append(messages, e.Message)
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
// End to end: the message a client receives for a refused field is the bare
|
||||
// string the resolvers used to return, with nothing wrapped around it.
|
||||
func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"anonymous admin query", context.Background(), `{ users { id } }`, "admin access required"},
|
||||
{"non-admin admin query", withClaims(2, false), `{ jobApplications { id } }`, "admin access required"},
|
||||
{"anonymous admin mutation", context.Background(), `mutation { deleteJobApplication(id: 1) }`, "admin access required"},
|
||||
{"non-admin admin mutation", withClaims(2, false), `mutation { deleteUser(id: 1) { id } }`, "admin access required"},
|
||||
{"anonymous signed-in query", context.Background(), `{ places { id } }`, "authentication required"},
|
||||
{"anonymous signed-in mutation", context.Background(), `mutation { deletePlace(id: 1) { id } }`, "authentication required"},
|
||||
// Not a directive, and a different message on purpose.
|
||||
{"me keeps its own message", context.Background(), `{ me { id } }`, "unauthorized"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := execute(t, c.ctx, c.query, nil)
|
||||
if !slices.Equal(got, []string{c.want}) {
|
||||
t.Fatalf("errors = %q, want exactly %q", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The JobStatus enum over the wire, from the side the tracker page uses it:
|
||||
// status sent as a JSON string variable. A value in the vocabulary reaches the
|
||||
// resolver (shown by the resolver's own validation error, which comes before
|
||||
// any database access); one outside it is refused before the resolver runs.
|
||||
func TestJobStatusInputOverTheWire(t *testing.T) {
|
||||
const mutation = `mutation ($input: CreateJobApplicationInput!) { createJobApplication(input: $input) { id status } }`
|
||||
admin := withClaims(1, true)
|
||||
input := func(status any) map[string]any {
|
||||
// A blank title makes the resolver return early, so no test here
|
||||
// needs a database.
|
||||
return map[string]any{"input": map[string]any{"jobTitle": " ", "company": "Acme", "status": status}}
|
||||
}
|
||||
|
||||
for _, status := range []string{"saved", "applied", "screening", "assessment", "interviewing", "offer", "rejected", "withdrawn"} {
|
||||
got := execute(t, admin, mutation, input(status))
|
||||
if !slices.Equal(got, []string{"jobTitle and company are required"}) {
|
||||
t.Errorf("status %q: errors = %q, want it accepted and the resolver reached", status, got)
|
||||
}
|
||||
}
|
||||
|
||||
for _, status := range []any{"hired", "Applied", "", " applied", 3} {
|
||||
got := execute(t, admin, mutation, input(status))
|
||||
if len(got) != 1 || got[0] == "jobTitle and company are required" {
|
||||
t.Errorf("status %#v: errors = %q, want it refused before the resolver", status, got)
|
||||
}
|
||||
}
|
||||
|
||||
// The guard still comes first: an anonymous caller learns nothing about
|
||||
// the vocabulary from a valid input.
|
||||
if got := execute(t, context.Background(), mutation, input("applied")); !slices.Equal(got, []string{"admin access required"}) {
|
||||
t.Errorf("anonymous: errors = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// IDs: the wire form must be what it was when every type had a hand-written
|
||||
// resolver returning int. Both marshallers write a quoted decimal string and
|
||||
// both read a string or a number.
|
||||
func TestUintIDWireFormatMatchesIntID(t *testing.T) {
|
||||
for _, id := range []uint{0, 1, 12, 4294967295} {
|
||||
var asUint, asInt bytes.Buffer
|
||||
graphql.MarshalUintID(id).MarshalGQL(&asUint)
|
||||
graphql.MarshalIntID(int(id)).MarshalGQL(&asInt)
|
||||
if asUint.String() != asInt.String() {
|
||||
t.Errorf("id %d: UintID writes %s, IntID wrote %s", id, &asUint, &asInt)
|
||||
}
|
||||
}
|
||||
if got := func() string {
|
||||
var b bytes.Buffer
|
||||
graphql.MarshalUintID(12).MarshalGQL(&b)
|
||||
return b.String()
|
||||
}(); got != `"12"` {
|
||||
t.Errorf("MarshalUintID(12) = %s, want \"12\"", got)
|
||||
}
|
||||
}
|
||||
+30
-9
@@ -9,8 +9,13 @@
|
||||
// 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.
|
||||
// types. A model's `ID uint` binds to `id: ID!` directly, because
|
||||
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
|
||||
// needed for it. A field resolver is only written where the Go type has
|
||||
// no binding (Message.authorId and Rowing's time/distance are unsigned in
|
||||
// Go and Int in the schema).
|
||||
// - The JobStatus enum is bound to a custom marshaller in
|
||||
// services/job_status.go rather than a generated type; see that file.
|
||||
// - 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
|
||||
@@ -18,13 +23,29 @@
|
||||
//
|
||||
// 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.
|
||||
// annotates the context and lets everything through. What guards a field is a
|
||||
// directive on it in the schema:
|
||||
//
|
||||
// createUser(input: CreateUserInput!): User! @admin
|
||||
// places: [Place!]! @signedIn
|
||||
//
|
||||
// @admin requires an admin's access token, @signedIn any valid one. Both are
|
||||
// implemented once, in directives.go, and run before the resolver, so a
|
||||
// guarded resolver contains no check of its own. A field with NEITHER
|
||||
// directive is fully public.
|
||||
//
|
||||
// The rule of thumb in this schema is that queries are public and mutations
|
||||
// are @admin, with these exceptions: login, logout and refreshToken are
|
||||
// public; the places mutations and query are @signedIn; and the users, job
|
||||
// application and job reference queries are @admin (they are private data).
|
||||
// directives_test.go holds that list and fails when the schema departs from
|
||||
// it — in particular when a mutation is added with no directive.
|
||||
//
|
||||
// A directive is only a gate. Anything finer stays in the resolver and uses
|
||||
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
|
||||
// author, `me` answers for the caller (with its own "unauthorized" error),
|
||||
// the messages query hides private messages from non-admins rather than
|
||||
// refusing, and spotifyNeedsReauth is simply false for non-admins.
|
||||
//
|
||||
// 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
|
||||
|
||||
@@ -7,23 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *favoriteResolver) ID(ctx context.Context, obj *models.Favorite) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateFavorite is the resolver for the createFavorite field.
|
||||
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&favorite).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -40,8 +30,3 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
||||
}
|
||||
return ptrs(favorites), nil
|
||||
}
|
||||
|
||||
// Favorite returns FavoriteResolver implementation.
|
||||
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
|
||||
|
||||
type favoriteResolver struct{ *Resolver }
|
||||
|
||||
+3700
-549
File diff suppressed because it is too large
Load Diff
@@ -7,22 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobAppReferenceResolver) ID(ctx context.Context, obj *models.JobAppReference) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobAppReference is the resolver for the createJobAppReference field.
|
||||
func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input model.CreateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
ref := models.JobAppReference{
|
||||
Category: input.Category,
|
||||
Label: input.Label,
|
||||
@@ -39,9 +30,6 @@ func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input mode
|
||||
|
||||
// UpdateJobAppReference is the resolver for the updateJobAppReference field.
|
||||
func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, input model.UpdateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var ref models.JobAppReference
|
||||
if err := r.Store.DB.First(&ref, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -66,10 +54,13 @@ func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, in
|
||||
|
||||
// DeleteJobAppReference is the resolver for the deleteJobAppReference field.
|
||||
func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
// Loaded first so a missing id is an error rather than a `true` that
|
||||
// deleted nothing; see DeleteJobApplication.
|
||||
var ref models.JobAppReference
|
||||
if err := r.Store.DB.First(&ref, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := r.Store.DB.Delete(&models.JobAppReference{}, id).Error; err != nil {
|
||||
if err := r.Store.DB.Delete(&ref).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
@@ -77,9 +68,6 @@ func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (b
|
||||
|
||||
// JobAppReferences is the resolver for the jobAppReferences field.
|
||||
func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
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.
|
||||
@@ -88,8 +76,3 @@ func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppR
|
||||
}
|
||||
return refs, nil
|
||||
}
|
||||
|
||||
// JobAppReference returns JobAppReferenceResolver implementation.
|
||||
func (r *Resolver) JobAppReference() JobAppReferenceResolver { return &jobAppReferenceResolver{r} }
|
||||
|
||||
type jobAppReferenceResolver struct{ *Resolver }
|
||||
|
||||
@@ -12,19 +12,10 @@ import (
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobApplicationResolver) ID(ctx context.Context, obj *models.JobApplication) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobApplication is the resolver for the createJobApplication field.
|
||||
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// String! is non-null but not non-empty, and the columns are only
|
||||
// `not null`, so "" stores happily and then never matches the email
|
||||
// pipeline's LOWER(company) lookup — an orphan row no sync can advance.
|
||||
@@ -33,14 +24,18 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
|
||||
if jobTitle == "" || company == "" {
|
||||
return nil, fmt.Errorf("jobTitle and company are required")
|
||||
}
|
||||
// input.Status is already one of the JobStatus values: the enum's
|
||||
// unmarshaller (services.UnmarshalJobStatus) refused anything else before
|
||||
// this resolver was reached, so it is stored as it came.
|
||||
app := models.JobApplication{
|
||||
JobTitle: jobTitle,
|
||||
Company: company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: services.NormalizeStatus(input.Status),
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
JobTitle: jobTitle,
|
||||
Company: company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: input.Status,
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
Description: input.Description,
|
||||
}
|
||||
if err := r.Store.DB.Create(&app).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -50,9 +45,6 @@ func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model
|
||||
|
||||
// UpdateJobApplication is the resolver for the updateJobApplication field.
|
||||
func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, input model.UpdateJobApplicationInput) (*models.JobApplication, error) {
|
||||
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.
|
||||
// An explicit "" on a nullable column does clear it — that is how the UI
|
||||
@@ -81,7 +73,7 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
app.URL = input.URL
|
||||
}
|
||||
if input.Status != nil {
|
||||
app.Status = services.NormalizeStatus(*input.Status)
|
||||
app.Status = *input.Status
|
||||
}
|
||||
if input.Notes != nil {
|
||||
app.Notes = input.Notes
|
||||
@@ -89,6 +81,9 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
if input.AppliedAt != nil {
|
||||
app.AppliedAt = input.AppliedAt
|
||||
}
|
||||
if input.Description != nil {
|
||||
app.Description = input.Description
|
||||
}
|
||||
if err := r.Store.DB.Save(&app).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -97,12 +92,19 @@ func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, inp
|
||||
|
||||
// DeleteJobApplication is the resolver for the deleteJobApplication field.
|
||||
func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
// Loaded first so a missing id is an error, as it is for the deletes that
|
||||
// return the row (deletePost, deletePlace, deleteBookmark). Deleting by
|
||||
// id alone reports success whether or not anything matched, which told
|
||||
// the tracker a row was gone when it had never existed. The return type
|
||||
// stays Boolean! for the front end's sake, so the only value is true.
|
||||
//
|
||||
// Soft delete: the row is kept, which is what lets the email pipeline see
|
||||
// that an application was deleted and not re-create it.
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
// 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 {
|
||||
if err := r.Store.DB.Delete(&app).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
@@ -110,10 +112,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")
|
||||
}
|
||||
// Admin-only even though it is a query (@admin in the schema): job
|
||||
// applications are private.
|
||||
//
|
||||
// A row whose stored status is outside the JobStatus enum does not fail
|
||||
// this list: services.MarshalJobStatus passes it through.
|
||||
//
|
||||
// Find can populate a slice of pointers directly, avoiding the
|
||||
// copy-to-pointers loop the other list resolvers need.
|
||||
var apps []*models.JobApplication
|
||||
@@ -128,17 +132,9 @@ func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobAppli
|
||||
|
||||
// JobApplication is the resolver for the jobApplication field.
|
||||
func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// JobApplication returns JobApplicationResolver implementation.
|
||||
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
|
||||
|
||||
type jobApplicationResolver struct{ *Resolver }
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// CreateJobSource is the resolver for the createJobSource field.
|
||||
func (r *mutationResolver) CreateJobSource(ctx context.Context, input model.CreateJobSourceInput) (*models.JobSource, error) {
|
||||
src := models.JobSource{Kind: input.Kind, Label: input.Label, Enabled: true}
|
||||
if input.Token != nil {
|
||||
src.Token = *input.Token
|
||||
}
|
||||
if input.Query != nil {
|
||||
src.Query = *input.Query
|
||||
}
|
||||
if input.Location != nil {
|
||||
src.Location = *input.Location
|
||||
}
|
||||
if input.Enabled != nil {
|
||||
src.Enabled = *input.Enabled
|
||||
}
|
||||
if err := services.ValidateJobSource(&src); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Store.DB.Create(&src).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &src, nil
|
||||
}
|
||||
|
||||
// UpdateJobSource is the resolver for the updateJobSource field.
|
||||
func (r *mutationResolver) UpdateJobSource(ctx context.Context, id int, input model.UpdateJobSourceInput) (*models.JobSource, error) {
|
||||
// Partial update, as in UpdateJobApplication: a nil field is untouched.
|
||||
// The merged row is validated as a whole, because whether a token or a
|
||||
// query is required depends on the kind, which may itself be changing.
|
||||
var src models.JobSource
|
||||
if err := r.Store.DB.First(&src, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Kind != nil {
|
||||
src.Kind = *input.Kind
|
||||
}
|
||||
if input.Label != nil {
|
||||
src.Label = *input.Label
|
||||
}
|
||||
if input.Token != nil {
|
||||
src.Token = *input.Token
|
||||
}
|
||||
if input.Query != nil {
|
||||
src.Query = *input.Query
|
||||
}
|
||||
if input.Location != nil {
|
||||
src.Location = *input.Location
|
||||
}
|
||||
if input.Enabled != nil {
|
||||
src.Enabled = *input.Enabled
|
||||
}
|
||||
if err := services.ValidateJobSource(&src); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Named columns rather than Save: the fetcher writes last_fetched_at,
|
||||
// last_count and last_error on this row during a run, and saving the
|
||||
// whole struct loaded above would put stale values back over them.
|
||||
if err := r.Store.DB.Model(&src).
|
||||
Select("Kind", "Label", "Token", "Query", "Location", "Enabled").
|
||||
Updates(&src).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &src, nil
|
||||
}
|
||||
|
||||
// DeleteJobSource is the resolver for the deleteJobSource field.
|
||||
func (r *mutationResolver) DeleteJobSource(ctx context.Context, id int) (bool, error) {
|
||||
// Loaded first so a missing id is an error; see DeleteJobApplication.
|
||||
// The source's leads are deliberately left alone: they are still real
|
||||
// postings, and deleting them would let a re-added source file every one
|
||||
// of them again, dismissed ones included.
|
||||
var src models.JobSource
|
||||
if err := r.Store.DB.First(&src, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := r.Store.DB.Delete(&src).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// DismissJobLead is the resolver for the dismissJobLead field.
|
||||
func (r *mutationResolver) DismissJobLead(ctx context.Context, id int) (*models.JobLead, error) {
|
||||
return r.setLeadState(id, services.LeadNew, services.LeadDismissed)
|
||||
}
|
||||
|
||||
// RestoreJobLead is the resolver for the restoreJobLead field.
|
||||
func (r *mutationResolver) RestoreJobLead(ctx context.Context, id int) (*models.JobLead, error) {
|
||||
return r.setLeadState(id, services.LeadDismissed, services.LeadNew)
|
||||
}
|
||||
|
||||
// PromoteJobLead is the resolver for the promoteJobLead field.
|
||||
func (r *mutationResolver) PromoteJobLead(ctx context.Context, id int) (*models.JobLead, error) {
|
||||
return services.PromoteJobLead(r.Store.DB, uint(id), time.Now())
|
||||
}
|
||||
|
||||
// UpdateJobSearchProfile is the resolver for the updateJobSearchProfile field.
|
||||
func (r *mutationResolver) UpdateJobSearchProfile(ctx context.Context, input model.UpdateJobSearchProfileInput) (*models.JobSearchProfile, error) {
|
||||
profile, err := services.LoadJobSearchProfile(r.Store.DB)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Profile != nil {
|
||||
profile.Profile = *input.Profile
|
||||
}
|
||||
if input.IncludeKeywords != nil {
|
||||
profile.IncludeKeywords = strings.TrimSpace(*input.IncludeKeywords)
|
||||
}
|
||||
if input.ExcludeKeywords != nil {
|
||||
profile.ExcludeKeywords = strings.TrimSpace(*input.ExcludeKeywords)
|
||||
}
|
||||
if input.Locations != nil {
|
||||
profile.Locations = strings.TrimSpace(*input.Locations)
|
||||
}
|
||||
if input.MinScore != nil {
|
||||
profile.MinScore = *input.MinScore
|
||||
}
|
||||
if err := services.SaveJobSearchProfile(r.Store.DB, profile); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
// RunJobLeadSync is the resolver for the runJobLeadSync field.
|
||||
func (r *mutationResolver) RunJobLeadSync(ctx context.Context) (bool, error) {
|
||||
if r.Store.JobLeads == nil {
|
||||
return false, fmt.Errorf("job leads are not configured")
|
||||
}
|
||||
return r.Store.JobLeads.RunInBackground(services.LeadJobSync), nil
|
||||
}
|
||||
|
||||
// ScoreJobLeads is the resolver for the scoreJobLeads field.
|
||||
func (r *mutationResolver) ScoreJobLeads(ctx context.Context) (bool, error) {
|
||||
if r.Store.JobLeads == nil {
|
||||
return false, fmt.Errorf("job leads are not configured")
|
||||
}
|
||||
return r.Store.JobLeads.RunInBackground(services.LeadJobScore), nil
|
||||
}
|
||||
|
||||
// RescoreJobLeads is the resolver for the rescoreJobLeads field.
|
||||
func (r *mutationResolver) RescoreJobLeads(ctx context.Context) (bool, error) {
|
||||
if r.Store.JobLeads == nil {
|
||||
return false, fmt.Errorf("job leads are not configured")
|
||||
}
|
||||
return r.Store.JobLeads.RunInBackground(services.LeadJobRescore), nil
|
||||
}
|
||||
|
||||
// JobSources is the resolver for the jobSources field.
|
||||
func (r *queryResolver) JobSources(ctx context.Context) ([]*models.JobSource, error) {
|
||||
var sources []*models.JobSource
|
||||
if err := r.Store.DB.Order("label ASC, id ASC").Find(&sources).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sources, nil
|
||||
}
|
||||
|
||||
// JobLeads is the resolver for the jobLeads field.
|
||||
func (r *queryResolver) JobLeads(ctx context.Context, state *string, includeUnmatched *bool) ([]*models.JobLead, error) {
|
||||
// Omit, not Select: every column but the description, which is tens of
|
||||
// kilobytes a row and is fetched one lead at a time through jobLead. A
|
||||
// client that asks for description here gets "".
|
||||
query := r.Store.DB.Omit("description")
|
||||
if state != nil {
|
||||
query = query.Where("state = ?", *state)
|
||||
}
|
||||
if includeUnmatched == nil || !*includeUnmatched {
|
||||
// A promoted or dismissed lead is shown whatever the filter now says
|
||||
// about it; `matched` only decides what the inbox offers.
|
||||
query = query.Where("(matched = ? OR state <> ?)", true, services.LeadNew)
|
||||
}
|
||||
var leads []*models.JobLead
|
||||
// Best first, unscored after scored, newest first within a score. The
|
||||
// limit is a backstop for includeUnmatched on a database holding several
|
||||
// whole boards.
|
||||
if err := query.Order("score DESC NULLS LAST, created_at DESC, id DESC").Limit(2000).Find(&leads).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return leads, nil
|
||||
}
|
||||
|
||||
// JobLead is the resolver for the jobLead field.
|
||||
func (r *queryResolver) JobLead(ctx context.Context, id int) (*models.JobLead, error) {
|
||||
var lead models.JobLead
|
||||
if err := r.Store.DB.First(&lead, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &lead, nil
|
||||
}
|
||||
|
||||
// JobSearchProfile is the resolver for the jobSearchProfile field.
|
||||
func (r *queryResolver) JobSearchProfile(ctx context.Context) (*models.JobSearchProfile, error) {
|
||||
return services.LoadJobSearchProfile(r.Store.DB)
|
||||
}
|
||||
|
||||
// JobLeadSyncStatus is the resolver for the jobLeadSyncStatus field.
|
||||
func (r *queryResolver) JobLeadSyncStatus(ctx context.Context) (*model.JobLeadSyncStatus, error) {
|
||||
if r.Store.JobLeads == nil {
|
||||
return &model.JobLeadSyncStatus{LastError: "job leads are not configured"}, nil
|
||||
}
|
||||
status := r.Store.JobLeads.Status()
|
||||
return &model.JobLeadSyncStatus{Running: status.Running, LastRunAt: status.LastRunAt, LastError: status.LastError}, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// setLeadState moves a lead from one state to another and returns it. It
|
||||
// lives here, not in job_lead.resolvers.go, because gqlgen moves anything in
|
||||
// a resolvers file that is not a resolver to the bottom on regeneration.
|
||||
//
|
||||
// The move is refused unless the lead is in `from`, which is what stops a
|
||||
// promoted lead being dismissed or restored: its application exists, and
|
||||
// flipping the lead would only make the inbox disagree with the tracker.
|
||||
func (r *mutationResolver) setLeadState(id int, from, to string) (*models.JobLead, error) {
|
||||
var lead models.JobLead
|
||||
if err := r.Store.DB.First(&lead, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if lead.State == to {
|
||||
return &lead, nil
|
||||
}
|
||||
if lead.State != from {
|
||||
return nil, fmt.Errorf("a %s lead cannot be made %s", lead.State, to)
|
||||
}
|
||||
if err := r.Store.DB.Model(&lead).Update("state", to).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &lead, nil
|
||||
}
|
||||
@@ -11,11 +11,6 @@ import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -13,9 +13,10 @@ import (
|
||||
// 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.
|
||||
// is what lets public queries work and leaves every authorisation decision
|
||||
// to the field being resolved — the @admin / @signedIn directives on it (see
|
||||
// directives.go), or the resolver itself for anything finer. Both cookie and
|
||||
// verify errors are swallowed for exactly that reason.
|
||||
//
|
||||
// It takes the database because validating a token means loading the user to
|
||||
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
|
||||
|
||||
@@ -38,13 +38,23 @@ type CreateJobAppReferenceInput struct {
|
||||
}
|
||||
|
||||
type CreateJobApplicationInput struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
type CreateJobSourceInput struct {
|
||||
Kind string `json:"kind"`
|
||||
Label string `json:"label"`
|
||||
Token *string `json:"token,omitempty"`
|
||||
Query *string `json:"query,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
}
|
||||
|
||||
type CreatePlaceInput struct {
|
||||
@@ -77,6 +87,12 @@ type GiteaFeedItem struct {
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type JobLeadSyncStatus struct {
|
||||
Running bool `json:"running"`
|
||||
LastRunAt *time.Time `json:"lastRunAt,omitempty"`
|
||||
LastError string `json:"lastError"`
|
||||
}
|
||||
|
||||
type LoginInput struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
@@ -138,13 +154,31 @@ type UpdateJobAppReferenceInput struct {
|
||||
}
|
||||
|
||||
type UpdateJobApplicationInput struct {
|
||||
JobTitle *string `json:"jobTitle,omitempty"`
|
||||
Company *string `json:"company,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
JobTitle *string `json:"jobTitle,omitempty"`
|
||||
Company *string `json:"company,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateJobSearchProfileInput struct {
|
||||
Profile *string `json:"profile,omitempty"`
|
||||
IncludeKeywords *string `json:"includeKeywords,omitempty"`
|
||||
ExcludeKeywords *string `json:"excludeKeywords,omitempty"`
|
||||
Locations *string `json:"locations,omitempty"`
|
||||
MinScore *int `json:"minScore,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateJobSourceInput struct {
|
||||
Kind *string `json:"kind,omitempty"`
|
||||
Label *string `json:"label,omitempty"`
|
||||
Token *string `json:"token,omitempty"`
|
||||
Query *string `json:"query,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
}
|
||||
|
||||
type UpdatePlaceInput struct {
|
||||
|
||||
@@ -7,7 +7,6 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
@@ -16,11 +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")
|
||||
}
|
||||
// collaboratively edited list on the site, so the schema marks these
|
||||
// fields @signedIn rather than @admin. There is no per-user ownership, so
|
||||
// any signed-in user can edit or delete any place.
|
||||
place := models.Place{
|
||||
Title: input.Title,
|
||||
Location: input.Location,
|
||||
@@ -43,9 +40,6 @@ func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePl
|
||||
|
||||
// UpdatePlace is the resolver for the updatePlace field.
|
||||
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
|
||||
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
|
||||
@@ -84,9 +78,6 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
|
||||
|
||||
// DeletePlace is the resolver for the deletePlace field.
|
||||
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
var place models.Place
|
||||
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -97,24 +88,11 @@ func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Pla
|
||||
return &place, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *placeResolver) ID(ctx context.Context, obj *models.Place) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Places is the resolver for the places field.
|
||||
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
var places []models.Place
|
||||
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(places), nil
|
||||
}
|
||||
|
||||
// Place returns PlaceResolver implementation.
|
||||
func (r *Resolver) Place() PlaceResolver { return &placeResolver{r} }
|
||||
|
||||
type placeResolver struct{ *Resolver }
|
||||
|
||||
@@ -15,10 +15,9 @@ import (
|
||||
|
||||
// CreatePost is the resolver for the createPost field.
|
||||
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// @admin has already established that there is a session; the id is read
|
||||
// here because the post needs an author, not as a second gate. The !ok
|
||||
// branch is only reachable with a token that has admin but no usable id.
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -34,10 +33,6 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
|
||||
|
||||
// UpdatePost is the resolver for the updatePost field.
|
||||
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -48,8 +43,9 @@ 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.
|
||||
// Admin alone (the @admin on the field) is not enough: a post may only be
|
||||
// edited by its author, so one admin cannot rewrite another's posts. This
|
||||
// is the kind of rule a directive cannot express, so it stays here.
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
@@ -67,10 +63,6 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
|
||||
// DeletePost is the resolver for the deletePost field.
|
||||
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -95,11 +87,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -120,8 +107,3 @@ func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error)
|
||||
}
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// Post returns PostResolver implementation.
|
||||
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
|
||||
|
||||
type postResolver struct{ *Resolver }
|
||||
|
||||
@@ -12,10 +12,12 @@ import "adam-french.co.uk/backend/handlers"
|
||||
// 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.
|
||||
// The generated code embeds *Resolver in per-type resolver structs, which is
|
||||
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
|
||||
// resolvers files. A type only gets one when a field of it needs a resolver:
|
||||
// queryResolver and mutationResolver always, messageResolver and
|
||||
// rowingResolver for their unsigned-to-Int fields. Most object types bind
|
||||
// every field straight to the model and have none.
|
||||
type Resolver struct {
|
||||
Store *handlers.Store
|
||||
}
|
||||
|
||||
@@ -20,11 +20,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
return ptrs(rows), nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -18,5 +18,5 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createActivity(input: CreateActivityInput!): Activity!
|
||||
createActivity(input: CreateActivityInput!): Activity! @admin
|
||||
}
|
||||
|
||||
@@ -7,10 +7,14 @@ type AuthPayload {
|
||||
user: User!
|
||||
}
|
||||
|
||||
# `me` carries no directive although it needs a session: it answers
|
||||
# "unauthorized", not @signedIn's "authentication required", and the front end
|
||||
# relies on that query failing quietly for an anonymous visitor.
|
||||
extend type Query {
|
||||
me: User
|
||||
}
|
||||
|
||||
# Deliberately public: these are how a session is obtained and given up.
|
||||
extend type Mutation {
|
||||
login(input: LoginInput!): AuthPayload!
|
||||
logout: Boolean!
|
||||
|
||||
@@ -18,6 +18,6 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark!
|
||||
deleteBookmark(id: ID!): Bookmark!
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark! @admin
|
||||
deleteBookmark(id: ID!): Bookmark! @admin
|
||||
}
|
||||
|
||||
@@ -18,5 +18,5 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite!
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite! @admin
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# Reusable snippets for filling in application forms. Private, like the
|
||||
# applications themselves, so the query is @admin as well as the mutations.
|
||||
|
||||
type JobAppReference {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
@@ -23,11 +26,13 @@ input UpdateJobAppReferenceInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobAppReferences: [JobAppReference!]!
|
||||
jobAppReferences: [JobAppReference!]! @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference!
|
||||
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference!
|
||||
deleteJobAppReference(id: ID!): Boolean!
|
||||
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference! @admin
|
||||
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference! @admin
|
||||
# Errors on an id that does not exist, like the other deletes; the Boolean
|
||||
# is only ever true.
|
||||
deleteJobAppReference(id: ID!): Boolean! @admin
|
||||
}
|
||||
|
||||
@@ -1,10 +1,36 @@
|
||||
# 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.
|
||||
# Job application tracker. Rows come from these mutations, automatically from
|
||||
# the email sync pipeline (backend/services/email_sync.go), from the browser
|
||||
# capture userscript (backend/handlers/handle_job_capture.go), or from
|
||||
# promoting a lead (job_lead.graphql). These are private data, so the queries
|
||||
# here are @admin 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.
|
||||
# description is the captured posting text. It can run to tens of kilobytes,
|
||||
# so the tracker's list query leaves it out and asks for it per row.
|
||||
|
||||
# The lifecycle of an application, in the order the email pipeline and the
|
||||
# capture endpoint are allowed to advance it. The values are lowercase on
|
||||
# purpose: they are exactly the strings stored in the status column and ranked
|
||||
# in services.statusOrder (backend/services/email_sync.go), and a test there
|
||||
# fails if this list and that map ever differ. Adding a status means adding
|
||||
# it in both places, and to the tracker page and the capture userscript.
|
||||
#
|
||||
# It is bound to a custom marshaller (services/job_status.go, via gqlgen.yml)
|
||||
# rather than a generated Go type: input is strict, so a mutation carrying a
|
||||
# status outside this list is refused, while output passes a legacy stored
|
||||
# value through so one old row cannot fail the whole jobApplications query.
|
||||
#
|
||||
# On the wire it is still a JSON string ("applied"), as it was when the field
|
||||
# was a String, both in variables and in responses.
|
||||
enum JobStatus {
|
||||
saved
|
||||
applied
|
||||
screening
|
||||
assessment
|
||||
interviewing
|
||||
offer
|
||||
rejected
|
||||
withdrawn
|
||||
}
|
||||
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
@@ -14,9 +40,10 @@ type JobApplication {
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
status: JobStatus!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
input CreateJobApplicationInput {
|
||||
@@ -24,9 +51,10 @@ input CreateJobApplicationInput {
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
status: JobStatus!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
input UpdateJobApplicationInput {
|
||||
@@ -34,18 +62,21 @@ input UpdateJobApplicationInput {
|
||||
company: String
|
||||
location: String
|
||||
url: String
|
||||
status: String
|
||||
status: JobStatus
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobApplications: [JobApplication!]!
|
||||
jobApplication(id: ID!): JobApplication
|
||||
jobApplications: [JobApplication!]! @admin
|
||||
jobApplication(id: ID!): JobApplication @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobApplication(input: CreateJobApplicationInput!): JobApplication!
|
||||
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication!
|
||||
deleteJobApplication(id: ID!): Boolean!
|
||||
createJobApplication(input: CreateJobApplicationInput!): JobApplication! @admin
|
||||
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication! @admin
|
||||
# Errors on an id that does not exist, like the other deletes; the Boolean
|
||||
# is only ever true.
|
||||
deleteJobApplication(id: ID!): Boolean! @admin
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
# Job leads: postings found automatically, as opposed to applications being
|
||||
# tracked (job_application.graphql). The fetcher in
|
||||
# backend/services/job_leads.go polls each JobSource, files what it finds as
|
||||
# JobLead rows and has Claude score them against the JobSearchProfile. A lead
|
||||
# reaches the tracker only when it is promoted from the leads page.
|
||||
#
|
||||
# All of it is private, so every field here is @admin, queries included.
|
||||
|
||||
# One place to poll. `kind` is one of greenhouse, lever, ashby (a company's
|
||||
# board: `token` is its slug and `label` the company name) or adzuna, reed (a
|
||||
# keyword search: `query` and `location`, with `label` only a display name).
|
||||
# It is a String rather than an enum because the resolver validates it and
|
||||
# the list is the fetcher's to extend (services/job_sources.go).
|
||||
#
|
||||
# The last* fields are written by the fetcher, never by a mutation.
|
||||
type JobSource {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
kind: String!
|
||||
label: String!
|
||||
token: String!
|
||||
query: String!
|
||||
location: String!
|
||||
enabled: Boolean!
|
||||
lastFetchedAt: Time
|
||||
lastCount: Int!
|
||||
lastError: String!
|
||||
}
|
||||
|
||||
input CreateJobSourceInput {
|
||||
kind: String!
|
||||
label: String!
|
||||
token: String
|
||||
query: String
|
||||
location: String
|
||||
enabled: Boolean
|
||||
}
|
||||
|
||||
input UpdateJobSourceInput {
|
||||
kind: String
|
||||
label: String
|
||||
token: String
|
||||
query: String
|
||||
location: String
|
||||
enabled: Boolean
|
||||
}
|
||||
|
||||
# description is the posting's full text, tens of kilobytes on some boards,
|
||||
# so the list query on the leads page leaves it out and asks per row — the
|
||||
# same arrangement as JobApplication.description.
|
||||
#
|
||||
# state is new, dismissed or promoted. score (0-100) and scoreReasons are
|
||||
# null until Claude has scored the lead, which only happens to matched ones.
|
||||
type JobLead {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
sourceKind: String!
|
||||
jobTitle: String!
|
||||
company: String!
|
||||
location: String!
|
||||
url: String!
|
||||
description: String!
|
||||
postedAt: Time
|
||||
lastSeenAt: Time!
|
||||
matched: Boolean!
|
||||
state: String!
|
||||
score: Int
|
||||
scoreReasons: String
|
||||
scoredAt: Time
|
||||
jobAppId: ID
|
||||
}
|
||||
|
||||
# The single row a lead is judged against. profile is free text sent to
|
||||
# Claude with each posting; the three keyword lists hold one entry per line
|
||||
# and drive the pre-filter; minScore is the inbox's display threshold.
|
||||
type JobSearchProfile {
|
||||
updatedAt: Time!
|
||||
profile: String!
|
||||
includeKeywords: String!
|
||||
excludeKeywords: String!
|
||||
locations: String!
|
||||
minScore: Int!
|
||||
}
|
||||
|
||||
input UpdateJobSearchProfileInput {
|
||||
profile: String
|
||||
includeKeywords: String
|
||||
excludeKeywords: String
|
||||
locations: String
|
||||
minScore: Int
|
||||
}
|
||||
|
||||
# lastRunAt and lastError describe the most recent run in this backend
|
||||
# process; both reset when it restarts.
|
||||
type JobLeadSyncStatus {
|
||||
running: Boolean!
|
||||
lastRunAt: Time
|
||||
lastError: String!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobSources: [JobSource!]! @admin
|
||||
# state filters to one of new, dismissed, promoted; omitted returns all.
|
||||
# Leads that failed the pre-filter are left out unless includeUnmatched.
|
||||
jobLeads(state: String, includeUnmatched: Boolean): [JobLead!]! @admin
|
||||
jobLead(id: ID!): JobLead @admin
|
||||
jobSearchProfile: JobSearchProfile! @admin
|
||||
jobLeadSyncStatus: JobLeadSyncStatus! @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobSource(input: CreateJobSourceInput!): JobSource! @admin
|
||||
updateJobSource(id: ID!, input: UpdateJobSourceInput!): JobSource! @admin
|
||||
# Errors on an id that does not exist, like the other deletes; the Boolean
|
||||
# is only ever true. The source's leads are kept.
|
||||
deleteJobSource(id: ID!): Boolean! @admin
|
||||
|
||||
dismissJobLead(id: ID!): JobLead! @admin
|
||||
# Puts a dismissed lead back in the inbox. A promoted lead cannot be
|
||||
# restored: its application exists, and is managed on the tracker.
|
||||
restoreJobLead(id: ID!): JobLead! @admin
|
||||
# Adds the lead to the tracker as a saved application — or, if the posting
|
||||
# is already tracked, links to that row instead of making a second — and
|
||||
# returns the lead, now promoted, with jobAppId set.
|
||||
promoteJobLead(id: ID!): JobLead! @admin
|
||||
|
||||
updateJobSearchProfile(input: UpdateJobSearchProfileInput!): JobSearchProfile! @admin
|
||||
|
||||
# Starts a fetch-and-score run in the background and returns at once: true
|
||||
# if it started, false if one was already running. Poll jobLeadSyncStatus
|
||||
# to see it finish.
|
||||
runJobLeadSync: Boolean! @admin
|
||||
|
||||
# Scores every matched lead that has no score yet, without polling any
|
||||
# source. Background and polled like runJobLeadSync, and refused (false)
|
||||
# while either is running.
|
||||
scoreJobLeads: Boolean! @admin
|
||||
|
||||
# Scores every matched inbox lead again, scored or not, for after the
|
||||
# profile or the model has changed. A lead keeps its old score until its
|
||||
# new one arrives. Background and polled like the two above, and refused
|
||||
# (false) while any of the three is running.
|
||||
rescoreJobLeads: Boolean! @admin
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
#
|
||||
# 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.
|
||||
# rather than causing an error — which is why the query has no @admin: the
|
||||
# resolver makes that decision per row.
|
||||
|
||||
type Message {
|
||||
id: ID!
|
||||
|
||||
@@ -1,5 +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.
|
||||
# Places to go. Unlike most mutations these require only a signed-in user
|
||||
# (@signedIn), not an admin, and there is no per-user ownership: the list is
|
||||
# shared. The query is guarded too — the list is not public.
|
||||
|
||||
type Place {
|
||||
id: ID!
|
||||
@@ -38,11 +39,11 @@ input UpdatePlaceInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
places: [Place!]!
|
||||
places: [Place!]! @signedIn
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createPlace(input: CreatePlaceInput!): Place!
|
||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place!
|
||||
deletePlace(id: ID!): Place!
|
||||
createPlace(input: CreatePlaceInput!): Place! @signedIn
|
||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place! @signedIn
|
||||
deletePlace(id: ID!): Place! @signedIn
|
||||
}
|
||||
|
||||
@@ -22,8 +22,10 @@ extend type Query {
|
||||
post(id: ID!): Post
|
||||
}
|
||||
|
||||
# @admin is only the first half of the rule for updatePost and deletePost:
|
||||
# the resolver also requires the caller to be the post's author.
|
||||
extend type Mutation {
|
||||
createPost(input: CreatePostInput!): Post!
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post!
|
||||
deletePost(id: ID!): Post!
|
||||
createPost(input: CreatePostInput!): Post! @admin
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post! @admin
|
||||
deletePost(id: ID!): Post! @admin
|
||||
}
|
||||
|
||||
@@ -16,5 +16,22 @@
|
||||
|
||||
scalar Time
|
||||
|
||||
# Authorisation. There is no middleware in front of /graphql, so a field is
|
||||
# PUBLIC unless it carries one of these. Each is implemented once, in
|
||||
# graph/directives.go, and runs before the field's resolver:
|
||||
#
|
||||
# @admin the request must carry an admin's access token
|
||||
# (error: "admin access required")
|
||||
# @signedIn any valid access token will do
|
||||
# (error: "authentication required")
|
||||
#
|
||||
# Every mutation needs one of them unless it is deliberately public (login,
|
||||
# logout, refreshToken); graph/directives_test.go fails otherwise, and pins
|
||||
# which queries are guarded. Rules that are not a plain gate stay in the
|
||||
# resolver: a post is only editable by its author, `me` answers for whoever is
|
||||
# signed in, and `messages` filters private rows rather than refusing.
|
||||
directive @admin on FIELD_DEFINITION
|
||||
directive @signedIn on FIELD_DEFINITION
|
||||
|
||||
type Query
|
||||
type Mutation
|
||||
|
||||
@@ -36,6 +36,7 @@ extend type Query {
|
||||
spotifyRecent: [SpotifyRecentItem!]
|
||||
# True only for an admin session while the backend lacks a Spotify client
|
||||
# (OAuth never completed or the token was revoked), used by the Listening
|
||||
# widget to offer a reconnect link. Everyone else gets false.
|
||||
# widget to offer a reconnect link. Everyone else gets false — a soft
|
||||
# check in the resolver, not @admin, so the home page query never errors.
|
||||
spotifyNeedsReauth: Boolean!
|
||||
}
|
||||
|
||||
@@ -12,12 +12,12 @@ input CreateUserInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
users: [User!]!
|
||||
user(id: ID!): User
|
||||
users: [User!]! @admin
|
||||
user(id: ID!): User @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createUser(input: CreateUserInput!): User!
|
||||
deleteUser(id: ID!): User!
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User!
|
||||
createUser(input: CreateUserInput!): User! @admin
|
||||
deleteUser(id: ID!): User! @admin
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
|
||||
}
|
||||
|
||||
@@ -61,6 +61,8 @@ func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// A soft check, deliberately not @admin: the directive would turn this
|
||||
// into an error on the public home page query.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -16,12 +16,9 @@ import (
|
||||
|
||||
// CreateUser is the resolver for the createUser field.
|
||||
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
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.
|
||||
// Only an existing admin can create accounts (@admin in the schema) —
|
||||
// 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
|
||||
@@ -37,10 +34,6 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
|
||||
|
||||
// DeleteUser is the resolver for the deleteUser field.
|
||||
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
@@ -55,10 +48,6 @@ func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User
|
||||
|
||||
// SetUserAdmin is the resolver for the setUserAdmin field.
|
||||
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
callerID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -85,9 +74,6 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
||||
|
||||
// Users is the resolver for the users field.
|
||||
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var users []models.User
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -97,22 +83,9 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
|
||||
// User is the resolver for the user field.
|
||||
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// User returns UserResolver implementation.
|
||||
func (r *Resolver) User() UserResolver { return &userResolver{r} }
|
||||
|
||||
type userResolver struct{ *Resolver }
|
||||
|
||||
@@ -8,95 +8,10 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// This file backs the admin diagnostics panel: a configuration report and a
|
||||
// log tail. Both are admin-only REST endpoints rather than GraphQL because
|
||||
// they read the process environment and the filesystem — things outside the
|
||||
// data model the GraphQL schema describes.
|
||||
|
||||
// ConfigVar describes one piece of configuration the backend can report on.
|
||||
// Required marks vars whose absence visibly breaks a feature; Optional vars
|
||||
// have a working default.
|
||||
type ConfigVar struct {
|
||||
Name string `json:"name"`
|
||||
Purpose string `json:"purpose"`
|
||||
Required bool `json:"required"`
|
||||
}
|
||||
|
||||
// configVars is the checklist the panel renders. Sensitive values are never
|
||||
// returned — only whether each var is present — so the endpoint cannot leak
|
||||
// credentials even to an admin client.
|
||||
var configVars = []ConfigVar{
|
||||
{"POSTGRES_HOST", "Database connectivity", true},
|
||||
{"POSTGRES_USER", "Database connectivity", true},
|
||||
{"POSTGRES_PASSWORD", "Database connectivity", true},
|
||||
{"POSTGRES_DB", "Database connectivity", true},
|
||||
{"DOMAIN", "Site origin, JWT cookie domain", true},
|
||||
{"AUTH_SECRET", "JWT signing", true},
|
||||
{"SPOTIFY_CLIENT_ID", "Spotify listening widget", true},
|
||||
{"SPOTIFY_CLIENT_SECRET", "Spotify listening widget", true},
|
||||
{"SPOTIFY_REDIRECT_URI", "Spotify listening widget", true},
|
||||
{"STEAM_API_KEY", "Steam status widget", false},
|
||||
{"STEAM_ID", "Steam status widget", false},
|
||||
{"CLAUDE_API_KEY", "Email summarisation", false},
|
||||
{"EMAIL_BACKEND", "Email sync (graph/imap)", false},
|
||||
{"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false},
|
||||
{"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false},
|
||||
{"MSGRAPH_REDIRECT_URI", "Email sync (Microsoft Graph)", false},
|
||||
{"MSGRAPH_TENANT_ID", "Email sync (Microsoft Graph)", false},
|
||||
{"IMAP_HOST", "Email sync (IMAP fallback)", false},
|
||||
{"IMAP_EMAIL", "Email sync (IMAP fallback)", false},
|
||||
{"IMAP_PASSWORD", "Email sync (IMAP fallback)", false},
|
||||
{"GITEA_HOST", "Gitea activity feed", false},
|
||||
{"GITEA_PORT", "Gitea activity feed", false},
|
||||
{"JWT_COOKIE_SECURE", "Cookie security in dev", false},
|
||||
{"ICECAST_URL", "Radio queue widget", false},
|
||||
}
|
||||
|
||||
// ConfigCheck backs GET /admin/config. It reports one entry per known var:
|
||||
// set or empty, plus the value only for vars flagged non-sensitive (none of
|
||||
// the credentials are). A var not in the list at all is not reported — the
|
||||
// point is a checklist, not a full env dump.
|
||||
func (store *Store) ConfigCheck(ctx *gin.Context) {
|
||||
type entry struct {
|
||||
ConfigVar
|
||||
Set bool `json:"set"`
|
||||
Value string `json:"value,omitempty"`
|
||||
Secret bool `json:"secret"`
|
||||
}
|
||||
|
||||
// Vars whose *value* may come back (bad values like "consumers" are fine;
|
||||
// they contain no credential).
|
||||
visible := map[string]bool{
|
||||
"EMAIL_BACKEND": true,
|
||||
"MSGRAPH_TENANT_ID": true,
|
||||
"ICECAST_URL": true,
|
||||
"STEAM_ID": true,
|
||||
}
|
||||
|
||||
// Explicitly-credentialled vars get the secret badge so the panel can
|
||||
// label them "present" instead of showing a masked string.
|
||||
secrets := map[string]bool{
|
||||
"POSTGRES_PASSWORD": true,
|
||||
"AUTH_SECRET": true,
|
||||
"SPOTIFY_CLIENT_SECRET": true,
|
||||
"MSGRAPH_CLIENT_SECRET": true,
|
||||
"CLAUDE_API_KEY": true,
|
||||
"STEAM_API_KEY": true,
|
||||
"IMAP_PASSWORD": true,
|
||||
}
|
||||
|
||||
result := make([]entry, 0, len(configVars))
|
||||
for _, v := range configVars {
|
||||
val := os.Getenv(v.Name)
|
||||
e := entry{ConfigVar: v, Set: strings.TrimSpace(val) != "", Secret: secrets[v.Name]}
|
||||
if e.Set && visible[v.Name] {
|
||||
e.Value = val
|
||||
}
|
||||
result = append(result, e)
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"vars": result})
|
||||
}
|
||||
// This file backs the admin diagnostics panel's log tail. It is an admin-only
|
||||
// REST endpoint rather than GraphQL because it reads the filesystem — outside
|
||||
// the data model the GraphQL schema describes. The configuration report that
|
||||
// used to live here is now the Environment tab (handle_env.go).
|
||||
|
||||
// logTailBytes and logTailLines bound how much of the log file one request
|
||||
// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// This file backs the admin panel's Environment tab: a report on every
|
||||
// variable in .env, and a way to change the ones that are safe to change.
|
||||
//
|
||||
// The handlers never read or write .env. State is this process's own
|
||||
// environment, and a change is a request left for the host to apply (see
|
||||
// services.EnvManager). REST rather than GraphQL for the same reason as the
|
||||
// rest of the admin endpoints: this is process and host state, not the data
|
||||
// model the schema describes.
|
||||
|
||||
// envSecretHintMinLen is the shortest secret that gets its last four
|
||||
// characters shown. Below it, four characters is too much of the value.
|
||||
const envSecretHintMinLen = 12
|
||||
|
||||
type envVarView struct {
|
||||
services.EnvVar
|
||||
Secret bool `json:"secret"`
|
||||
Set bool `json:"set"`
|
||||
// Value is sent only for non-secret variables; Hint (the last four
|
||||
// characters) is all a secret ever reveals.
|
||||
Value string `json:"value,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
}
|
||||
|
||||
type envGroupView struct {
|
||||
Name string `json:"name"`
|
||||
Vars []envVarView `json:"vars"`
|
||||
}
|
||||
|
||||
// GetEnv backs GET /admin/env: every registry variable grouped for display,
|
||||
// plus the state of the latest change.
|
||||
//
|
||||
// Values are what this process was started with, not what .env holds now —
|
||||
// the two differ between a save and the recreate that follows it, which is
|
||||
// what the status's pending list is for.
|
||||
func (store *Store) GetEnv(ctx *gin.Context) {
|
||||
var groups []envGroupView
|
||||
index := map[string]int{}
|
||||
for _, v := range store.Env.Vars() {
|
||||
value := os.Getenv(v.Name)
|
||||
view := envVarView{EnvVar: v, Secret: v.Secret(), Set: strings.TrimSpace(value) != ""}
|
||||
switch {
|
||||
case !view.Set:
|
||||
case !view.Secret:
|
||||
view.Value = value
|
||||
case len(value) >= envSecretHintMinLen:
|
||||
view.Hint = value[len(value)-4:]
|
||||
}
|
||||
|
||||
i, seen := index[v.Group]
|
||||
if !seen {
|
||||
i = len(groups)
|
||||
index[v.Group] = i
|
||||
groups = append(groups, envGroupView{Name: v.Group})
|
||||
}
|
||||
groups[i].Vars = append(groups[i].Vars, view)
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"groups": groups, "status": store.Env.Status()})
|
||||
}
|
||||
|
||||
type updateEnvRequest struct {
|
||||
// Set maps a variable to its new value; "" clears it.
|
||||
Set map[string]string `json:"set"`
|
||||
// Generate names "generated" variables to mint a random value for.
|
||||
Generate []string `json:"generate"`
|
||||
}
|
||||
|
||||
// UpdateEnv backs PUT /admin/env. It queues the change for the host and
|
||||
// returns straight away; the panel follows progress on GET /admin/env/status,
|
||||
// through the backend's own restart.
|
||||
//
|
||||
// The response is the only time a generated value is sent anywhere.
|
||||
func (store *Store) UpdateEnv(ctx *gin.Context) {
|
||||
var body updateEnvRequest
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
generated, recreates, err := store.Env.Submit(body.Set, body.Generate)
|
||||
if errors.Is(err, services.ErrEnvApplying) {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
// Validation messages name the variable, never the value.
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(body.Set)+len(body.Generate))
|
||||
for name := range body.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
names = append(names, body.Generate...)
|
||||
log.Printf("[Env] change queued for %s", strings.Join(names, ", "))
|
||||
|
||||
ctx.Header("Cache-Control", "no-store")
|
||||
ctx.JSON(http.StatusAccepted, gin.H{
|
||||
"generated": generated,
|
||||
"services": recreates,
|
||||
"status": store.Env.Status(),
|
||||
})
|
||||
}
|
||||
|
||||
// GetEnvStatus backs GET /admin/env/status.
|
||||
func (store *Store) GetEnvStatus(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
||||
}
|
||||
|
||||
// CancelEnv backs DELETE /admin/env/pending: withdraw a request nothing on
|
||||
// the host has picked up, so new secrets do not sit in the shared directory
|
||||
// waiting for a watcher that is not there.
|
||||
func (store *Store) CancelEnv(ctx *gin.Context) {
|
||||
if err := store.Env.Cancel(); err != nil {
|
||||
log.Println("Cancelling env request failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to cancel the request"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func envRouter(t *testing.T) (*gin.Engine, string) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dir := t.TempDir()
|
||||
env, err := services.NewEnvManager(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
store := &Store{Env: env}
|
||||
r := gin.New()
|
||||
r.GET("/admin/env", store.GetEnv)
|
||||
r.PUT("/admin/env", store.UpdateEnv)
|
||||
r.GET("/admin/env/status", store.GetEnvStatus)
|
||||
r.DELETE("/admin/env/pending", store.CancelEnv)
|
||||
return r, dir
|
||||
}
|
||||
|
||||
func envDo(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// The property the whole tab rests on: a secret's value never leaves the
|
||||
// server, while a non-secret's does so it can be edited in place.
|
||||
func TestGetEnvNeverReturnsSecrets(t *testing.T) {
|
||||
r, _ := envRouter(t)
|
||||
t.Setenv("CLAUDE_API_KEY", "sk-ant-very-secret-value-9f3a")
|
||||
t.Setenv("POSTGRES_PASSWORD", "hunter2")
|
||||
t.Setenv("STEAM_ID", "76561198000000000")
|
||||
t.Setenv("TFL_APP_KEY", "")
|
||||
|
||||
rec := envDo(r, http.MethodGet, "/admin/env", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, secret := range []string{"sk-ant-very-secret-value-9f3a", "hunter2"} {
|
||||
if strings.Contains(body, secret) {
|
||||
t.Fatalf("response contains the secret %q", secret)
|
||||
}
|
||||
}
|
||||
|
||||
var parsed struct {
|
||||
Groups []struct {
|
||||
Vars []envVarView `json:"vars"`
|
||||
} `json:"groups"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatalf("parsing response: %v", err)
|
||||
}
|
||||
byName := map[string]envVarView{}
|
||||
for _, g := range parsed.Groups {
|
||||
for _, v := range g.Vars {
|
||||
byName[v.Name] = v
|
||||
}
|
||||
}
|
||||
|
||||
if v := byName["CLAUDE_API_KEY"]; !v.Set || !v.Secret || v.Value != "" || v.Hint != "9f3a" {
|
||||
t.Errorf("CLAUDE_API_KEY = %+v, want set, secret, no value, hint 9f3a", v)
|
||||
}
|
||||
// Too short for four characters to be a safe hint.
|
||||
if v := byName["POSTGRES_PASSWORD"]; !v.Set || v.Hint != "" || v.Editable {
|
||||
t.Errorf("POSTGRES_PASSWORD = %+v, want set, no hint, locked", v)
|
||||
}
|
||||
if v := byName["STEAM_ID"]; v.Value != "76561198000000000" || v.Secret {
|
||||
t.Errorf("STEAM_ID = %+v, want its value shown", v)
|
||||
}
|
||||
if v := byName["TFL_APP_KEY"]; v.Set {
|
||||
t.Errorf("TFL_APP_KEY = %+v, want unset", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateEnv(t *testing.T) {
|
||||
r, dir := envRouter(t)
|
||||
requestPath := filepath.Join(dir, "request.json")
|
||||
|
||||
t.Run("a locked variable is refused and nothing is queued", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"POSTGRES_PASSWORD":"x"}}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
if _, err := os.Stat(requestPath); err == nil {
|
||||
t.Fatal("a refused change left a request behind")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a malformed body is refused", func(t *testing.T) {
|
||||
if rec := envDo(r, http.MethodPut, "/admin/env", `{"set":`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a valid change is queued and a generated value returned once", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"STEAM_ID":"42"},"generate":["BACKEND_SECRET"]}`)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202: %s", rec.Code, rec.Body)
|
||||
}
|
||||
var parsed struct {
|
||||
Generated map[string]string `json:"generated"`
|
||||
Status services.EnvApplyStatus `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatalf("parsing response: %v", err)
|
||||
}
|
||||
secret := parsed.Generated["BACKEND_SECRET"]
|
||||
if len(secret) != 64 {
|
||||
t.Fatalf("generated BACKEND_SECRET = %q, want 64 hex characters", secret)
|
||||
}
|
||||
if parsed.Status.State != "pending" {
|
||||
t.Fatalf("status = %+v, want pending", parsed.Status)
|
||||
}
|
||||
|
||||
// Reading the state back must not repeat it.
|
||||
for _, path := range []string{"/admin/env", "/admin/env/status"} {
|
||||
if strings.Contains(envDo(r, http.MethodGet, path, "").Body.String(), secret) {
|
||||
t.Fatalf("GET %s repeats the generated secret", path)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a pending change can be withdrawn", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodDelete, "/admin/env/pending", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
if _, err := os.Stat(requestPath); err == nil {
|
||||
t.Fatal("the request file survived the cancel")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Job capture: the three endpoints behind vue/public/job-capture.user.js,
|
||||
// which adds the posting open in the browser to the job tracker.
|
||||
//
|
||||
// These are REST, and token-authenticated, because the caller is a userscript
|
||||
// running on someone else's origin (linkedin.com, an ATS). The auth cookies
|
||||
// are SameSite=Lax and never accompany such a request, so the GraphQL
|
||||
// mutations, which rely on them, are out of reach from there.
|
||||
//
|
||||
// The token is deliberately narrow: it opens these routes and nothing else,
|
||||
// so a token leaked from the browser can add rows to the tracker and spend
|
||||
// Claude calls, but cannot read the tracker, edit other data or log in.
|
||||
//
|
||||
// As with rowing, the Claude call lives in the Python service
|
||||
// (python/app/jobs.py) and everything touching the database stays here.
|
||||
|
||||
const (
|
||||
// jobExtractPath is internal in the same way as rowingReadPath: nginx
|
||||
// refuses /py/internal/ and the route refuses anything nginx forwarded.
|
||||
jobExtractPath = "/internal/jobs/extract"
|
||||
|
||||
// maxCaptureBody bounds a capture request. A long posting is tens of
|
||||
// kilobytes of text; the userscript trims the page to maxPageRunes before
|
||||
// sending, so anything near this limit is not a job page.
|
||||
maxCaptureBody = 512 << 10
|
||||
|
||||
// maxPageRunes caps both the text sent to Claude and the description
|
||||
// stored. It mirrors MAX_TEXT_CHARS in python/app/jobs.py, which rejects
|
||||
// anything longer, so the cut has to happen on this side.
|
||||
maxPageRunes = 40_000
|
||||
)
|
||||
|
||||
// CaptureTokenMiddleware guards the capture routes with the token generated
|
||||
// in the admin panel (services.CaptureToken), presented as
|
||||
// "Authorization: Bearer <token>".
|
||||
//
|
||||
// Until a token has been generated the routes are off (503) rather than
|
||||
// open; "no token" must never be satisfied by a request that sends none.
|
||||
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
|
||||
if store.CaptureToken == nil {
|
||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
|
||||
return
|
||||
}
|
||||
if set, _ := store.CaptureToken.Status(); !set {
|
||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "no capture token has been generated"})
|
||||
return
|
||||
}
|
||||
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
|
||||
if !ok || !store.CaptureToken.Verify(presented) {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// The three handlers below manage that token from the admin panel. They sit
|
||||
// in the cookie-authenticated admin group, not behind the token: the token
|
||||
// must not be able to replace itself.
|
||||
|
||||
func captureTokenStatus(token *services.CaptureToken) gin.H {
|
||||
set, createdAt := token.Status()
|
||||
if !set {
|
||||
return gin.H{"set": false}
|
||||
}
|
||||
return gin.H{"set": true, "createdAt": createdAt}
|
||||
}
|
||||
|
||||
// GetCaptureToken backs GET /admin/capture-token: whether a token exists and
|
||||
// when it was made. The token itself is not recoverable — only its hash is
|
||||
// stored.
|
||||
func (store *Store) GetCaptureToken(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
|
||||
}
|
||||
|
||||
// GenerateCaptureToken backs POST /admin/capture-token. It replaces any
|
||||
// existing token, so the userscript must be reconfigured with the new one,
|
||||
// and its response is the only time the token is ever sent anywhere.
|
||||
func (store *Store) GenerateCaptureToken(ctx *gin.Context) {
|
||||
token, createdAt, err := store.CaptureToken.Generate()
|
||||
if err != nil {
|
||||
log.Println("Generating capture token failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store the token"})
|
||||
return
|
||||
}
|
||||
// The response carries a credential; keep it out of any cache.
|
||||
ctx.Header("Cache-Control", "no-store")
|
||||
ctx.JSON(http.StatusOK, gin.H{"token": token, "createdAt": createdAt})
|
||||
}
|
||||
|
||||
// RevokeCaptureToken backs DELETE /admin/capture-token, switching the capture
|
||||
// routes off until a new token is generated.
|
||||
func (store *Store) RevokeCaptureToken(ctx *gin.Context) {
|
||||
if err := store.CaptureToken.Revoke(); err != nil {
|
||||
log.Println("Revoking capture token failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to revoke the token"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
|
||||
}
|
||||
|
||||
// capturedJob is the slice of an application the userscript needs back: enough
|
||||
// to show "already tracked as …" and no more. The token is not meant to be
|
||||
// able to read the tracker, so notes and the description stay out of it.
|
||||
type capturedJob struct {
|
||||
ID uint `json:"id"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func capturedJobOf(app *models.JobApplication) *capturedJob {
|
||||
return &capturedJob{ID: app.ID, JobTitle: app.JobTitle, Company: app.Company, Status: app.Status}
|
||||
}
|
||||
|
||||
// JobCaptureStatus backs GET /jobs/capture/status?url=. It is what lets the
|
||||
// userscript show a posting's tracked status instead of an "add" button.
|
||||
func (store *Store) JobCaptureStatus(ctx *gin.Context) {
|
||||
raw := ctx.Query("url")
|
||||
canonical, ok := services.CanonicalJobURL(raw)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
|
||||
return
|
||||
}
|
||||
app, err := services.FindApplicationByURL(store.DB, canonical, raw)
|
||||
if err != nil {
|
||||
log.Println("Job capture status lookup failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
if app == nil {
|
||||
ctx.JSON(http.StatusOK, gin.H{"found": false})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"found": true, "application": capturedJobOf(app)})
|
||||
}
|
||||
|
||||
// ExtractedJobPosting is the JSON contract for what Claude reads off a job
|
||||
// page: the body of the Python service's reply (JobPosting in
|
||||
// python/app/jobs.py). Empty strings and nulls mean "not found on the page".
|
||||
type ExtractedJobPosting struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// extractJobPosting sends a page's text to the Python service and returns the
|
||||
// fields Claude picked out. Like readRowingDisplay it is a thin wrapper over
|
||||
// services.CallPython, which decides which replies are relayed (a
|
||||
// *services.PythonError) and which are only logged.
|
||||
func (store *Store) extractJobPosting(ctx context.Context, pageURL, title, text string) (ExtractedJobPosting, error) {
|
||||
return services.CallPython[ExtractedJobPosting](ctx, store.PythonURL, jobExtractPath, struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}{pageURL, title, text})
|
||||
}
|
||||
|
||||
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
|
||||
// is still valid UTF-8 for Postgres and for JSON.
|
||||
func truncateRunes(s string, max int) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= max {
|
||||
return s
|
||||
}
|
||||
return string(runes[:max])
|
||||
}
|
||||
|
||||
// bindCapture decodes a size-limited JSON body, answering 400 itself when it
|
||||
// cannot.
|
||||
func bindCapture(ctx *gin.Context, into any) bool {
|
||||
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxCaptureBody)
|
||||
if err := ctx.ShouldBindJSON(into); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// JobCaptureExtract backs POST /jobs/capture/extract: page text in, the
|
||||
// popup's pre-filled fields out. Nothing is stored; saving is a separate
|
||||
// request made once the fields have been checked by eye.
|
||||
func (store *Store) JobCaptureExtract(ctx *gin.Context) {
|
||||
var input struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if !bindCapture(ctx, &input) {
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(input.Text)
|
||||
if text == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "text is required"})
|
||||
return
|
||||
}
|
||||
|
||||
posting, err := store.extractJobPosting(ctx.Request.Context(),
|
||||
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
|
||||
if err != nil {
|
||||
log.Println("Job extract failed:", err)
|
||||
var readErr *services.PythonError
|
||||
if errors.As(err, &readErr) {
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.Detail})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": "failed to read the page"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, posting)
|
||||
}
|
||||
|
||||
// JobCapture backs POST /jobs/capture, an upsert: a posting already in the
|
||||
// tracker is updated in place rather than added again. The matching and
|
||||
// merging rules are services.UpsertJobApplication's; this handler owns the
|
||||
// request body and the status codes.
|
||||
func (store *Store) JobCapture(ctx *gin.Context) {
|
||||
var input services.JobCaptureInput
|
||||
if !bindCapture(ctx, &input) {
|
||||
return
|
||||
}
|
||||
input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
|
||||
|
||||
app, action, err := services.UpsertJobApplication(store.DB, input, time.Now())
|
||||
var invalid *services.JobInputError
|
||||
switch {
|
||||
case errors.As(err, &invalid):
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": invalid.Error()})
|
||||
case err != nil:
|
||||
log.Println("Job capture failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
|
||||
case action == "created":
|
||||
ctx.JSON(http.StatusCreated, gin.H{"action": action, "application": capturedJobOf(app)})
|
||||
default:
|
||||
ctx.JSON(http.StatusOK, gin.H{"action": action, "application": capturedJobOf(app)})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// The capture handlers themselves need a database, and the only driver in
|
||||
// go.mod is postgres, so what is covered here is everything around the
|
||||
// queries: the token gate, the URL key that decides whether a posting is
|
||||
// already tracked, the merge rule for a repeat capture, and the call to the
|
||||
// Python service.
|
||||
|
||||
func TestCaptureTokenMiddleware(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
serve := func(store *Store, header string) int {
|
||||
r := gin.New()
|
||||
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
|
||||
req := httptest.NewRequest(http.MethodGet, "/x", nil)
|
||||
if header != "" {
|
||||
req.Header.Set("Authorization", header)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec.Code
|
||||
}
|
||||
newToken := func() *services.CaptureToken {
|
||||
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
return tok
|
||||
}
|
||||
|
||||
// The case the middleware exists to get right: with no token generated,
|
||||
// a request presenting nothing (or an empty bearer) must not get in.
|
||||
t.Run("no token generated switches the routes off", func(t *testing.T) {
|
||||
store := &Store{CaptureToken: newToken()}
|
||||
for _, header := range []string{"", "Bearer ", "Bearer anything"} {
|
||||
if got := serve(store, header); got != http.StatusServiceUnavailable {
|
||||
t.Fatalf("header %q: status = %d, want 503", header, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("a store built without the token service is off too", func(t *testing.T) {
|
||||
if got := serve(&Store{}, "Bearer x"); got != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", got)
|
||||
}
|
||||
})
|
||||
|
||||
store := &Store{CaptureToken: newToken()}
|
||||
token, _, err := store.CaptureToken.Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
header string
|
||||
want int
|
||||
}{
|
||||
{"the generated token is let through", "Bearer " + token, http.StatusOK},
|
||||
{"a wrong token is refused", "Bearer nope", http.StatusUnauthorized},
|
||||
{"no header is refused", "", http.StatusUnauthorized},
|
||||
{"the bare token without the scheme is refused", token, http.StatusUnauthorized},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := serve(store, c.header); got != c.want {
|
||||
t.Fatalf("status = %d, want %d", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The admin endpoints, driven without the admin middleware (covered
|
||||
// elsewhere): generate shows the token once, status never does, and a second
|
||||
// generate or a revoke stops the first token working.
|
||||
func TestCaptureTokenAdminEndpoints(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
store := &Store{CaptureToken: tok}
|
||||
r := gin.New()
|
||||
r.GET("/t", store.GetCaptureToken)
|
||||
r.POST("/t", store.GenerateCaptureToken)
|
||||
r.DELETE("/t", store.RevokeCaptureToken)
|
||||
|
||||
call := func(method string) (map[string]any, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest(method, "/t", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: status = %d, body = %s", method, rec.Code, rec.Body)
|
||||
}
|
||||
var out map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
return out, rec
|
||||
}
|
||||
|
||||
if out, _ := call(http.MethodGet); out["set"] != false {
|
||||
t.Fatalf("fresh status = %v", out)
|
||||
}
|
||||
|
||||
out, rec := call(http.MethodPost)
|
||||
first, _ := out["token"].(string)
|
||||
if !tok.Verify(first) {
|
||||
t.Fatalf("generated token %q does not verify", first)
|
||||
}
|
||||
if rec.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("the response carrying the token must not be cacheable")
|
||||
}
|
||||
|
||||
out, _ = call(http.MethodGet)
|
||||
if out["set"] != true || out["createdAt"] == nil {
|
||||
t.Fatalf("status after generate = %v", out)
|
||||
}
|
||||
if _, leaked := out["token"]; leaked {
|
||||
t.Fatal("status must never return the token")
|
||||
}
|
||||
|
||||
call(http.MethodPost)
|
||||
if tok.Verify(first) {
|
||||
t.Fatal("regenerating must invalidate the previous token")
|
||||
}
|
||||
|
||||
if out, _ := call(http.MethodDelete); out["set"] != false {
|
||||
t.Fatalf("status after revoke = %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateRunes(t *testing.T) {
|
||||
if got := truncateRunes("££££", 2); got != "££" {
|
||||
t.Fatalf("got %q; the cut must fall on a rune boundary", got)
|
||||
}
|
||||
if got := truncateRunes("short", 10); got != "short" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func jobExtractor(t *testing.T, handler http.HandlerFunc) *Store {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &Store{PythonURL: srv.URL}
|
||||
}
|
||||
|
||||
func TestExtractJobPostingRequestAndReply(t *testing.T) {
|
||||
var got map[string]string
|
||||
var path string
|
||||
var forwarded bool
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
// As with the rowing reader, either header makes the Python route
|
||||
// answer 404.
|
||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": null}`))
|
||||
})
|
||||
|
||||
posting, err := store.extractJobPosting(context.Background(), "https://x.com/1", "Engineer | Acme", "page text")
|
||||
if err != nil {
|
||||
t.Fatalf("extractJobPosting: %v", err)
|
||||
}
|
||||
if posting.JobTitle != "Engineer" || posting.Company != "Acme" || posting.Location == nil || *posting.Location != "London" || posting.Notes != nil {
|
||||
t.Fatalf("got %+v", posting)
|
||||
}
|
||||
if path != jobExtractPath {
|
||||
t.Fatalf("path = %q, want %q", path, jobExtractPath)
|
||||
}
|
||||
if forwarded {
|
||||
t.Fatal("request carried a proxy header the Python route rejects")
|
||||
}
|
||||
if got["url"] != "https://x.com/1" || got["title"] != "Engineer | Acme" || got["text"] != "page text" {
|
||||
t.Fatalf("request body = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractJobPostingErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a services.PythonError with this message
|
||||
}{
|
||||
{"extractor failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse the posting"}`, "failed to parse the posting"},
|
||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"malformed success body", http.StatusOK, `not json`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
_, err := store.extractJobPosting(context.Background(), "https://x.com/1", "t", "text")
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var readErr *services.PythonError
|
||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if readErr != nil && readErr.Detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The extract handler runs without a database, so it can be driven whole: the
|
||||
// page text must be cut to the limit the Python side enforces before it is
|
||||
// forwarded, or a long page would come back as an opaque 422.
|
||||
func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
var forwardedLen int
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]string
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
forwardedLen = len([]rune(body["text"]))
|
||||
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": null, "notes": null}`))
|
||||
})
|
||||
r := gin.New()
|
||||
r.POST("/extract", store.JobCaptureExtract)
|
||||
|
||||
post := func(body string) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/extract", strings.NewReader(body)))
|
||||
return rec
|
||||
}
|
||||
|
||||
long, _ := json.Marshal(map[string]string{"url": "https://x.com/1", "title": "t", "text": strings.Repeat("é", maxPageRunes+500)})
|
||||
rec := post(string(long))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
if forwardedLen != maxPageRunes {
|
||||
t.Fatalf("forwarded %d runes, want %d", forwardedLen, maxPageRunes)
|
||||
}
|
||||
var out ExtractedJobPosting
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.Company != "Acme" {
|
||||
t.Fatalf("body = %s (%v)", rec.Body, err)
|
||||
}
|
||||
|
||||
if rec := post(`{"url": "https://x.com/1", "text": " "}`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("blank text: status = %d", rec.Code)
|
||||
}
|
||||
if rec := post(`not json`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("bad body: status = %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
@@ -13,7 +11,6 @@ import (
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -22,15 +19,40 @@ import (
|
||||
// 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.
|
||||
//
|
||||
// The Claude call itself lives in the Python service (python/app/rowing.py),
|
||||
// reached directly over the Docker network. Everything that needs the session
|
||||
// or the database — the admin gate, EXIF, the duplicate check, the sanity
|
||||
// bounds, the insert — stays here.
|
||||
|
||||
// ExtractedRowingData is the JSON contract for what Claude reads off the
|
||||
// display; the keys must match the prompt in CreateRowing.
|
||||
// display: the body of the Python service's reply, whose keys are the ones
|
||||
// its prompt asks the model for (RowingReading in python/app/rowing.py).
|
||||
type ExtractedRowingData struct {
|
||||
TimeMinutes uint64 `json:"timeMinutes"`
|
||||
TimeSeconds uint64 `json:"timeSeconds"`
|
||||
Distance uint64 `json:"distance"`
|
||||
}
|
||||
|
||||
// rowingReadPath is the Python route. It is internal: nginx refuses
|
||||
// /py/internal/ and the route itself refuses anything nginx forwarded, so the
|
||||
// only way in is the direct container-to-container call services.CallPython
|
||||
// makes.
|
||||
const rowingReadPath = "/internal/rowing/read"
|
||||
|
||||
// readRowingDisplay sends the image to the Python service and returns what
|
||||
// Claude read off it. No plausibility checking happens on either side of this
|
||||
// call; that is CreateRowing's job. A failure the reader described in its own
|
||||
// words comes back as a *services.PythonError (see services.CallPython).
|
||||
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
|
||||
// Data is a []byte so that it is sent as standard base64, the encoding
|
||||
// the Anthropic API expects.
|
||||
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
|
||||
MediaType string `json:"media_type"`
|
||||
Data []byte `json:"data"`
|
||||
}{mediaType, image})
|
||||
}
|
||||
|
||||
// GetRowing backs the public GET /rowing with every logged session, newest
|
||||
// first.
|
||||
func (store *Store) GetRowing(ctx *gin.Context) {
|
||||
@@ -47,9 +69,10 @@ func (store *Store) GetRowing(ctx *gin.Context) {
|
||||
|
||||
// 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.
|
||||
// distance (via the Python service), sanity-checks the result and stores a
|
||||
// session.
|
||||
//
|
||||
// Note it is admin-gated and calls a paid API once per request, so the
|
||||
// Note it is admin-gated and costs a paid API call 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")
|
||||
@@ -81,16 +104,17 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
// exif.Decode consumed part of the stream, so rewind before reading the
|
||||
// bytes to send to Claude.
|
||||
// bytes to send on for reading.
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
|
||||
return
|
||||
}
|
||||
|
||||
// Cap the upload before buffering it (and then base64-encoding it, 1.33x
|
||||
// bigger): the route is admin-only but an unbounded read would still let
|
||||
// a giant file exhaust the Pi's memory and produce a huge paid API call.
|
||||
// 10MB is well above any photo this endpoint is meant to take.
|
||||
// bigger, on its way to the Python service): the route is admin-only but
|
||||
// an unbounded read would still let a giant file exhaust the Pi's memory
|
||||
// and produce a huge paid API call. 10MB is well above any photo this
|
||||
// endpoint is meant to take; the Python side's own limit is sized from it.
|
||||
if file.Size > 10<<20 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"})
|
||||
return
|
||||
@@ -110,13 +134,14 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
}
|
||||
// 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.
|
||||
// keep the API call well-formed rather than to police the file. The
|
||||
// Python service enforces the same list; checking here first gives the
|
||||
// admin a clear 400 instead of that side's validation error.
|
||||
mediaType := file.Header.Get("Content-Type")
|
||||
if !allowedMediaTypes[mediaType] {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
|
||||
return
|
||||
}
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
|
||||
// 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
|
||||
@@ -137,55 +162,18 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Build the message with an image + text prompt
|
||||
message, err := store.ClaudeClient.Messages.New(context.Background(), anthropic.MessageNewParams{
|
||||
Model: anthropic.ModelClaudeHaiku4_5,
|
||||
MaxTokens: 256,
|
||||
Messages: []anthropic.MessageParam{
|
||||
{
|
||||
Role: "user",
|
||||
Content: []anthropic.ContentBlockParamUnion{
|
||||
// Image block
|
||||
anthropic.NewImageBlock(anthropic.Base64ImageSourceParam{
|
||||
Type: "base64",
|
||||
MediaType: anthropic.Base64ImageSourceMediaType(mediaType),
|
||||
Data: encoded,
|
||||
}),
|
||||
// Text prompt requesting exactly 2 variables
|
||||
anthropic.NewTextBlock(
|
||||
`Look at this rowing machine display. Extract the total elapsed time and total distance.
|
||||
|
||||
Return ONLY a JSON object with these exact keys and numeric values:
|
||||
- "timeMinutes": total minutes (e.g. 2:30 = 2)
|
||||
- "timeSeconds": total seconds (e.g. 2:30 = 30)
|
||||
- "distance": distance in meters as a number (e.g. 5000)
|
||||
|
||||
No text, no markdown, no explanation. Just the JSON object.`),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to process image"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(message.Content) == 0 {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "empty response from image processor"})
|
||||
return
|
||||
}
|
||||
|
||||
// Strip a markdown code fence if the model wrapped its JSON in one
|
||||
// despite the prompt; shared with the email pipeline, which asks for bare
|
||||
// JSON in the same way and gets fenced output just as often.
|
||||
extractedData := ExtractedRowingData{}
|
||||
raw := services.StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
err = json.Unmarshal([]byte(raw), &extractedData)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse image data"})
|
||||
// The reader's own messages ("failed to parse image data", ...) are
|
||||
// passed on; anything else is a plumbing failure the admin can do
|
||||
// nothing with.
|
||||
msg := "failed to process image"
|
||||
var readErr *services.PythonError
|
||||
if errors.As(err, &readErr) {
|
||||
msg = readErr.Detail
|
||||
}
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// readRowingDisplay is the Go half of the contract with the Python service's
|
||||
// /internal/rowing/read. CreateRowing itself needs a database and a real
|
||||
// multipart photo with EXIF, so what is covered is the call: the request the
|
||||
// Python side receives, and how each kind of reply comes back.
|
||||
|
||||
func rowingReader(t *testing.T, handler http.HandlerFunc) *Store {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &Store{PythonURL: srv.URL}
|
||||
}
|
||||
|
||||
func TestReadRowingDisplayRequestAndReply(t *testing.T) {
|
||||
var got struct {
|
||||
MediaType string `json:"media_type"`
|
||||
Data string `json:"data"`
|
||||
}
|
||||
var path string
|
||||
var forwarded bool
|
||||
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
// The Python route treats either header as "came through nginx" and
|
||||
// answers 404, so this call must never carry them.
|
||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}`))
|
||||
})
|
||||
|
||||
data, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("hello"))
|
||||
if err != nil {
|
||||
t.Fatalf("readRowingDisplay: %v", err)
|
||||
}
|
||||
if data != (ExtractedRowingData{TimeMinutes: 20, TimeSeconds: 5, Distance: 5000}) {
|
||||
t.Fatalf("got %+v", data)
|
||||
}
|
||||
if path != rowingReadPath {
|
||||
t.Fatalf("path = %q, want %q", path, rowingReadPath)
|
||||
}
|
||||
if forwarded {
|
||||
t.Fatal("request carried a proxy header the Python route rejects")
|
||||
}
|
||||
// "hello" in standard base64, the encoding the Anthropic API expects.
|
||||
if got.MediaType != "image/jpeg" || got.Data != "aGVsbG8=" {
|
||||
t.Fatalf("request body = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadRowingDisplayErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a services.PythonError with this message
|
||||
}{
|
||||
{"reader failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
|
||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"non-JSON 502 is not relayed", http.StatusBadGateway, `<html>bad gateway</html>`, ""},
|
||||
{"malformed success body", http.StatusOK, `not json`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
|
||||
_, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("x"))
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var readErr *services.PythonError
|
||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if readErr != nil && readErr.Detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/zmb3/spotify/v2"
|
||||
spotifyauth "github.com/zmb3/spotify/v2/auth"
|
||||
"gorm.io/gorm"
|
||||
@@ -30,11 +29,30 @@ type Store struct {
|
||||
DB *gorm.DB
|
||||
SpotifyAuth *spotifyauth.Authenticator
|
||||
SpotifyClient *spotify.Client
|
||||
ClaudeClient *anthropic.Client
|
||||
Auth *services.Auth
|
||||
Notes *services.Notes
|
||||
LoginLimiter *services.RateLimiter
|
||||
EmailSync *services.EmailSyncService
|
||||
// JobLeads is the lead fetcher (services/job_leads.go). The GraphQL
|
||||
// resolvers use it to start a run and report on one.
|
||||
JobLeads *services.JobLeadService
|
||||
|
||||
// Base URL of the Python service on the Docker network, no trailing
|
||||
// slash. Used for the calls that bypass nginx, all through
|
||||
// services.CallPython: reading a rowing display photo (handle_rowing.go)
|
||||
// and a job posting (handle_job_capture.go). The email pipeline and the
|
||||
// lead pipeline make the other two such calls and hold their own copies
|
||||
// of this value.
|
||||
PythonURL string
|
||||
|
||||
// Bearer token for the browser capture routes (handle_job_capture.go),
|
||||
// generated from the admin panel. Nil, or holding no token, means those
|
||||
// routes are switched off, not open.
|
||||
CaptureToken *services.CaptureToken
|
||||
|
||||
// Registry of .env variables and the request/status hand-off with the
|
||||
// host that applies changes to them (handle_env.go).
|
||||
Env *services.EnvManager
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
|
||||
+89
-14
@@ -27,8 +27,9 @@ import (
|
||||
// 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.
|
||||
// — plus the GraphQL endpoint, which is authorised by the @admin / @signedIn
|
||||
// directives in its schema instead of by 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).
|
||||
@@ -89,10 +90,10 @@ func main() {
|
||||
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
|
||||
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
|
||||
|
||||
// CLAUDE
|
||||
claudeAPIKey := os.Getenv("CLAUDE_API_KEY")
|
||||
claudeConfig := services.ClaudeConfig{APIKey: claudeAPIKey}
|
||||
claudeClient := services.InitClaude(&claudeConfig)
|
||||
// No Claude client here: every Claude call — the rowing photo reader, the
|
||||
// job posting reader and the email classifier — is made by the Python
|
||||
// service, which is the only container that reads CLAUDE_API_KEY. The
|
||||
// backend reaches those routes at pythonURL, below.
|
||||
|
||||
authSecret := os.Getenv("BACKEND_SECRET")
|
||||
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
||||
@@ -114,6 +115,20 @@ func main() {
|
||||
steamAPIKey := os.Getenv("STEAM_API_KEY")
|
||||
steamID := os.Getenv("STEAM_ID")
|
||||
|
||||
// PYTHON SERVICE
|
||||
// Called directly over the Docker network, not through nginx, for its
|
||||
// four /internal/ Claude routes (services/python_call.go). The defaults
|
||||
// mirror docker-compose.yml, where both variables are optional.
|
||||
pythonHost := os.Getenv("PYTHON_HOST")
|
||||
if pythonHost == "" {
|
||||
pythonHost = "python"
|
||||
}
|
||||
pythonPort := os.Getenv("PYTHON_PORT")
|
||||
if pythonPort == "" {
|
||||
pythonPort = "8000"
|
||||
}
|
||||
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
|
||||
|
||||
// EMAIL SYNC
|
||||
// An unparseable EMAIL_SYNC_INTERVAL is silently ignored and the 30
|
||||
// minute default stands — a typo here fails quietly.
|
||||
@@ -138,13 +153,48 @@ func main() {
|
||||
SyncInterval: emailSyncInterval,
|
||||
Enabled: os.Getenv("EMAIL_SYNC_ENABLED") == "true",
|
||||
}
|
||||
emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient)
|
||||
emailSync := services.InitEmailSync(&emailSyncConfig, db, pythonURL)
|
||||
|
||||
// JOB LEADS
|
||||
// Like EMAIL_SYNC_INTERVAL, an unparseable JOB_LEADS_INTERVAL is ignored
|
||||
// and the default stands. Six hours: boards change a few times a day at
|
||||
// most, and every run can spend Claude calls.
|
||||
jobLeadsInterval := 6 * time.Hour
|
||||
if interval := os.Getenv("JOB_LEADS_INTERVAL"); interval != "" {
|
||||
if parsed, err := time.ParseDuration(interval); err == nil && parsed > 0 {
|
||||
jobLeadsInterval = parsed
|
||||
}
|
||||
}
|
||||
jobLeads := services.InitJobLeads(&services.JobLeadConfig{
|
||||
Enabled: os.Getenv("JOB_LEADS_ENABLED") == "true",
|
||||
Interval: jobLeadsInterval,
|
||||
AdzunaAppID: os.Getenv("ADZUNA_APP_ID"),
|
||||
AdzunaAppKey: os.Getenv("ADZUNA_APP_KEY"),
|
||||
ReedAPIKey: os.Getenv("REED_API_KEY"),
|
||||
}, db, pythonURL)
|
||||
|
||||
// 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}
|
||||
// JOB CAPTURE
|
||||
// The userscript's bearer token is generated in the admin panel and kept
|
||||
// (hashed) beside the OAuth tokens. A damaged file is logged, not fatal:
|
||||
// capture stays off until a new token is generated.
|
||||
captureToken, err := services.InitCaptureToken(services.CAPTURE_TOKEN_JSON_PATH)
|
||||
if err != nil {
|
||||
log.Println("Job capture token not loaded:", err)
|
||||
}
|
||||
|
||||
// ENVIRONMENT
|
||||
// The registry is embedded, so the only way this fails is a malformed
|
||||
// env_registry.json — a build mistake worth stopping for.
|
||||
envManager, err := services.NewEnvManager(services.ENV_APPLY_DIR)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, JobLeads: jobLeads, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, CaptureToken: captureToken, Env: envManager}
|
||||
|
||||
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||
// the Gin context, so the order in the admin group matters.
|
||||
@@ -153,6 +203,13 @@ func main() {
|
||||
protected := r.Group("/", store.AuthMiddlewear)
|
||||
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
||||
|
||||
// JOB CAPTURE: called by the browser userscript from other origins, so
|
||||
// these authenticate with a bearer token instead of the session cookies.
|
||||
capture := r.Group("/jobs/capture", store.CaptureTokenMiddleware)
|
||||
capture.GET("/status", store.JobCaptureStatus)
|
||||
capture.POST("/extract", store.JobCaptureExtract)
|
||||
capture.POST("", store.JobCapture)
|
||||
|
||||
// ROWING
|
||||
r.GET("/rowing", store.GetRowing)
|
||||
admin.POST("/rowing", store.CreateRowing)
|
||||
@@ -194,19 +251,36 @@ func main() {
|
||||
// NOTES
|
||||
admin.GET("/notes/*path", store.GetNoteFile)
|
||||
|
||||
// ADMIN DIAGNOSTICS: env-var checklist and log tail for the admin panel.
|
||||
admin.GET("/admin/config", store.ConfigCheck)
|
||||
// ADMIN DIAGNOSTICS: log tail for the admin panel.
|
||||
admin.GET("/admin/logs", store.Logs)
|
||||
// ENVIRONMENT: report on .env and queue changes for the host to apply.
|
||||
admin.GET("/admin/env", store.GetEnv)
|
||||
admin.PUT("/admin/env", store.UpdateEnv)
|
||||
admin.GET("/admin/env/status", store.GetEnvStatus)
|
||||
admin.DELETE("/admin/env/pending", store.CancelEnv)
|
||||
// The job capture token is managed with the session cookie, never with
|
||||
// the token itself.
|
||||
admin.GET("/admin/capture-token", store.GetCaptureToken)
|
||||
admin.POST("/admin/capture-token", store.GenerateCaptureToken)
|
||||
admin.DELETE("/admin/capture-token", store.RevokeCaptureToken)
|
||||
|
||||
// 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.
|
||||
// Note the whole API is one POST route with no middleware guard.
|
||||
// Authorisation is declared in the schema instead: a field marked @admin
|
||||
// or @signedIn is refused by the matching function in graph.Directives()
|
||||
// before its resolver runs. A field with neither is PUBLIC, so a new
|
||||
// mutation needs one — graph/directives_test.go fails until it has one or
|
||||
// is added to the list of deliberately public fields there.
|
||||
//
|
||||
// Directives must stay wired here: gqlgen fails closed on a nil directive
|
||||
// (the field errors with "directive admin is not implemented"), so
|
||||
// dropping this line breaks every guarded field rather than opening it.
|
||||
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
||||
Resolvers: &graph.Resolver{Store: &store},
|
||||
Resolvers: &graph.Resolver{Store: &store},
|
||||
Directives: graph.Directives(),
|
||||
}))
|
||||
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
|
||||
gqlSrv.AddTransport(transport.Options{})
|
||||
@@ -246,6 +320,7 @@ func main() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go store.EmailSync.StartScheduler(ctx)
|
||||
go store.JobLeads.StartScheduler(ctx)
|
||||
|
||||
port := os.Getenv("BACKEND_PORT")
|
||||
// Blocks until the server stops. Any return is a failure — a port clash,
|
||||
|
||||
+122
-15
@@ -20,8 +20,9 @@ import (
|
||||
// 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).
|
||||
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
|
||||
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
|
||||
// On the wire an id is a quoted decimal string, "12".
|
||||
|
||||
// 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.
|
||||
@@ -207,23 +208,129 @@ type Place struct {
|
||||
}
|
||||
|
||||
// JobApplication is a tracked job application. Rows are created by hand
|
||||
// through GraphQL or automatically by the email pipeline.
|
||||
// through GraphQL, automatically by the email pipeline, from the browser by
|
||||
// the capture userscript (handlers/handle_job_capture.go), or by promoting a
|
||||
// JobLead (services.PromoteJobLead).
|
||||
//
|
||||
// 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.
|
||||
// Status is a plain string column, but its vocabulary is fixed: the values
|
||||
// ranked in services.statusOrder ("saved", "applied", "screening",
|
||||
// "assessment", "interviewing", "offer", "rejected", "withdrawn"), which the
|
||||
// GraphQL schema repeats as `enum JobStatus`. Every writer keeps to it —
|
||||
// GraphQL refuses anything else, the email pipeline and the capture endpoint
|
||||
// coerce with services.NormalizeStatus — but the column predates that, so a
|
||||
// reader must not assume an old row conforms (services.MarshalJobStatus does
|
||||
// not). The pipeline matches an existing application on (Company, JobTitle)
|
||||
// compared case-insensitively.
|
||||
//
|
||||
// Description is the posting's text as captured from the page, kept because
|
||||
// postings are usually taken down long before the interview. It is large, so
|
||||
// list queries should not select it.
|
||||
type JobApplication struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
JobTitle string `gorm:"not null" json:"jobTitle"`
|
||||
Company string `gorm:"not null" json:"company"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
Status string `gorm:"not null" json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
AppliedAt *time.Time `json:"appliedAt"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
}
|
||||
|
||||
// JobSource is one place the lead fetcher (services/job_leads.go) polls for
|
||||
// postings. Kind decides which of the other fields mean anything:
|
||||
//
|
||||
// - "greenhouse", "lever", "ashby": one company's public job board. Token is
|
||||
// the board's slug (the "acme" in boards.greenhouse.io/acme) and Label is
|
||||
// the company name every lead from it is filed under.
|
||||
// - "adzuna", "reed": a keyword search. Query and Location are the search
|
||||
// terms and Label is only a display name; the company comes from each
|
||||
// result.
|
||||
//
|
||||
// The Last* fields are written by the fetcher after every poll and are what
|
||||
// the leads page shows beside the source. LastError is "" after a clean poll.
|
||||
type JobSource struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
JobTitle string `gorm:"not null" json:"jobTitle"`
|
||||
Company string `gorm:"not null" json:"company"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
Status string `gorm:"not null" json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
AppliedAt *time.Time `json:"appliedAt"`
|
||||
Kind string `gorm:"not null" json:"kind"`
|
||||
Label string `gorm:"not null" json:"label"`
|
||||
Token string `json:"token"`
|
||||
Query string `json:"query"`
|
||||
Location string `json:"location"`
|
||||
// No `default:true` tag: GORM applies a default to a zero value on
|
||||
// insert, which would make it impossible to create a source disabled.
|
||||
Enabled bool `gorm:"not null" json:"enabled"`
|
||||
LastFetchedAt *time.Time `json:"lastFetchedAt"`
|
||||
LastCount int `gorm:"not null;default:0" json:"lastCount"`
|
||||
LastError string `json:"lastError"`
|
||||
}
|
||||
|
||||
// JobLead is a posting the fetcher found, waiting in the leads inbox to be
|
||||
// tracked or dismissed. It is deliberately not a JobApplication: a single
|
||||
// company board is hundreds of postings, almost all irrelevant, and the
|
||||
// tracker, its status vocabulary and the email matcher are about jobs
|
||||
// actually applied to.
|
||||
//
|
||||
// Like ProcessedEmail it has no DeletedAt and is NOT soft deleted. The
|
||||
// (SourceKind, ExternalID) unique index is the dedup that stops every poll
|
||||
// re-adding the same posting, and it only works if a dismissed lead is still
|
||||
// a row: dismissal is State "dismissed", never a delete.
|
||||
//
|
||||
// ExternalID is the source's own id for the posting. For the board kinds it
|
||||
// is "<token>/<id>", because ids are only unique within one board.
|
||||
//
|
||||
// State is "new", "dismissed" or "promoted" (see the LeadState constants in
|
||||
// services/job_leads.go). JobAppID is set on a promoted lead and is a plain
|
||||
// nullable column, not a GORM association.
|
||||
//
|
||||
// Matched says whether the lead passed the keyword pre-filter the last time
|
||||
// the fetcher ran; only matched leads are shown by default and only they are
|
||||
// scored. Score (0-100) and ScoreReasons are Claude's, and nil until scored.
|
||||
// ScoredAt is when that score was given, which is how a rescore tells the
|
||||
// leads it has redone from the ones it has yet to reach; it is nil on a lead
|
||||
// scored before the column existed. ScoreAttempts counts failed tries, so a
|
||||
// posting Claude can never score stops costing a call per run.
|
||||
type JobLead struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
SourceID uint `gorm:"index" json:"sourceId"`
|
||||
SourceKind string `gorm:"not null;uniqueIndex:idx_job_lead_external" json:"sourceKind"`
|
||||
ExternalID string `gorm:"not null;uniqueIndex:idx_job_lead_external" json:"externalId"`
|
||||
JobTitle string `gorm:"not null" json:"jobTitle"`
|
||||
Company string `gorm:"not null" json:"company"`
|
||||
Location string `json:"location"`
|
||||
URL string `json:"url"`
|
||||
Description string `gorm:"type:text" json:"description"`
|
||||
PostedAt *time.Time `json:"postedAt"`
|
||||
LastSeenAt time.Time `json:"lastSeenAt"`
|
||||
Matched bool `gorm:"not null;default:false;index" json:"matched"`
|
||||
State string `gorm:"not null;default:new;index" json:"state"`
|
||||
Score *int `json:"score"`
|
||||
ScoreReasons *string `json:"scoreReasons"`
|
||||
ScoredAt *time.Time `json:"scoredAt"`
|
||||
ScoreAttempts int `gorm:"not null;default:0" json:"scoreAttempts"`
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
}
|
||||
|
||||
// JobSearchProfile is what a lead is judged against. There is exactly one
|
||||
// row, with ID 1, created on first read (services.LoadJobSearchProfile).
|
||||
//
|
||||
// Profile is free text about experience and what kind of job is wanted; it is
|
||||
// sent to Claude with each posting. The three keyword lists hold one entry
|
||||
// per line and drive the cheap pre-filter that runs before any Claude call.
|
||||
// MinScore is only a display threshold for the inbox.
|
||||
type JobSearchProfile struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Profile string `gorm:"type:text" json:"profile"`
|
||||
IncludeKeywords string `gorm:"type:text" json:"includeKeywords"`
|
||||
ExcludeKeywords string `gorm:"type:text" json:"excludeKeywords"`
|
||||
Locations string `gorm:"type:text" json:"locations"`
|
||||
MinScore int `gorm:"not null;default:60" json:"minScore"`
|
||||
}
|
||||
|
||||
@@ -18,7 +18,9 @@ import (
|
||||
|
||||
func testAuth() *Auth {
|
||||
return InitAuth(&AuthConfig{
|
||||
Secret: []byte("test-secret"),
|
||||
// InitAuth panics on anything under 32 bytes, so the fixture has to be
|
||||
// a realistic length even though nothing here depends on its value.
|
||||
Secret: []byte("test-secret-0123456789abcdef0123456789"),
|
||||
Domain: "example.test",
|
||||
AccessTokenLifetime: time.Hour,
|
||||
RefreshTokenLifetime: 24 * time.Hour,
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CAPTURE_TOKEN_JSON_PATH sits beside the Spotify and Graph tokens, in the
|
||||
// directory docker-compose bind-mounts so that it survives a rebuild.
|
||||
const CAPTURE_TOKEN_JSON_PATH = "/backend/token/job_capture_token.json"
|
||||
|
||||
// CaptureToken holds the bearer token the job capture userscript presents
|
||||
// (handlers/handle_job_capture.go). The token is minted from the admin panel
|
||||
// rather than set in .env, so it can be replaced without a redeploy when the
|
||||
// browser profile holding it is lost.
|
||||
//
|
||||
// Only a SHA-256 of the token is kept, in memory and on disk: the token is
|
||||
// shown once, when generated, and cannot be read back afterwards. A plain
|
||||
// hash is enough because the token is 32 random bytes, not a password — there
|
||||
// is nothing to brute-force.
|
||||
//
|
||||
// There is at most one token. Generating replaces it, which is also how a
|
||||
// leaked one is rotated.
|
||||
type CaptureToken struct {
|
||||
path string
|
||||
|
||||
mu sync.RWMutex
|
||||
hash []byte
|
||||
createdAt time.Time
|
||||
}
|
||||
|
||||
type captureTokenFile struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// InitCaptureToken loads the token file if there is one. A missing file is
|
||||
// the normal first-run state and means "no token": the capture routes stay
|
||||
// off until one is generated. A file that cannot be read or parsed is
|
||||
// reported, and likewise leaves the routes off rather than open.
|
||||
func InitCaptureToken(path string) (*CaptureToken, error) {
|
||||
t := &CaptureToken{path: path}
|
||||
|
||||
raw, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return t, nil
|
||||
}
|
||||
if err != nil {
|
||||
return t, fmt.Errorf("reading capture token: %w", err)
|
||||
}
|
||||
var stored captureTokenFile
|
||||
if err := json.Unmarshal(raw, &stored); err != nil {
|
||||
return t, fmt.Errorf("parsing capture token: %w", err)
|
||||
}
|
||||
hash, err := hex.DecodeString(stored.SHA256)
|
||||
if err != nil || len(hash) != sha256.Size {
|
||||
return t, fmt.Errorf("capture token file holds no valid hash")
|
||||
}
|
||||
t.hash, t.createdAt = hash, stored.CreatedAt
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// Generate mints a new token, replacing any existing one, and returns it.
|
||||
// This is the only moment the token itself exists on the server.
|
||||
//
|
||||
// The file is written before the in-memory hash is swapped, so a failed write
|
||||
// leaves the old token working instead of handing out one that would stop
|
||||
// working at the next restart.
|
||||
func (t *CaptureToken) Generate() (string, time.Time, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token := hex.EncodeToString(raw)
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
now := time.Now().UTC()
|
||||
|
||||
data, err := json.MarshalIndent(captureTokenFile{SHA256: hex.EncodeToString(sum[:]), CreatedAt: now}, "", " ")
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(t.path), 0755); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("creating token directory: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(t.path, data, 0600); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("writing capture token: %w", err)
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
t.hash, t.createdAt = sum[:], now
|
||||
t.mu.Unlock()
|
||||
return token, now, nil
|
||||
}
|
||||
|
||||
// Revoke deletes the token, switching the capture routes off.
|
||||
func (t *CaptureToken) Revoke() error {
|
||||
if err := os.Remove(t.path); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("removing capture token: %w", err)
|
||||
}
|
||||
t.mu.Lock()
|
||||
t.hash, t.createdAt = nil, time.Time{}
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Status reports whether a token exists and when it was generated.
|
||||
func (t *CaptureToken) Status() (set bool, createdAt time.Time) {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
return t.hash != nil, t.createdAt
|
||||
}
|
||||
|
||||
// Verify reports whether presented is the current token. With no token it is
|
||||
// false for every input, the empty string included.
|
||||
func (t *CaptureToken) Verify(presented string) bool {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
if t.hash == nil {
|
||||
return false
|
||||
}
|
||||
sum := sha256.Sum256([]byte(presented))
|
||||
return subtle.ConstantTimeCompare(sum[:], t.hash) == 1
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newCaptureToken(t *testing.T) (*CaptureToken, string) {
|
||||
t.Helper()
|
||||
// A nested path: the token directory may not exist on a fresh checkout.
|
||||
path := filepath.Join(t.TempDir(), "token", "job_capture_token.json")
|
||||
tok, err := InitCaptureToken(path)
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
return tok, path
|
||||
}
|
||||
|
||||
func TestCaptureTokenStartsUnsetAndRejectsEverything(t *testing.T) {
|
||||
tok, _ := newCaptureToken(t)
|
||||
if set, _ := tok.Status(); set {
|
||||
t.Fatal("a fresh store reports a token")
|
||||
}
|
||||
// The empty string is the credential of a request with no token at all.
|
||||
for _, presented := range []string{"", "anything"} {
|
||||
if tok.Verify(presented) {
|
||||
t.Fatalf("Verify(%q) passed with no token generated", presented)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureTokenGenerateVerifyAndRotate(t *testing.T) {
|
||||
tok, path := newCaptureToken(t)
|
||||
|
||||
first, createdAt, err := tok.Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
if len(first) != 64 {
|
||||
t.Fatalf("token is %d chars, want 64 hex chars (32 bytes)", len(first))
|
||||
}
|
||||
if set, at := tok.Status(); !set || !at.Equal(createdAt) {
|
||||
t.Fatalf("Status = %v, %v", set, at)
|
||||
}
|
||||
if !tok.Verify(first) || tok.Verify(first+"x") || tok.Verify("") {
|
||||
t.Fatal("Verify does not accept exactly the generated token")
|
||||
}
|
||||
|
||||
// The file must be useless to someone who reads it, and private anyway.
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("reading token file: %v", err)
|
||||
}
|
||||
if strings.Contains(string(raw), first) {
|
||||
t.Fatal("the token itself was written to disk")
|
||||
}
|
||||
if info, _ := os.Stat(path); info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("token file mode = %v, want 0600", info.Mode().Perm())
|
||||
}
|
||||
|
||||
second, _, err := tok.Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
if tok.Verify(first) || !tok.Verify(second) {
|
||||
t.Fatal("generating again must replace the old token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureTokenSurvivesRestart(t *testing.T) {
|
||||
tok, path := newCaptureToken(t)
|
||||
token, createdAt, _ := tok.Generate()
|
||||
|
||||
reloaded, err := InitCaptureToken(path)
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
if !reloaded.Verify(token) {
|
||||
t.Fatal("token no longer verifies after a reload")
|
||||
}
|
||||
if _, at := reloaded.Status(); !at.Equal(createdAt) {
|
||||
t.Fatalf("createdAt = %v, want %v", at, createdAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureTokenRevoke(t *testing.T) {
|
||||
tok, path := newCaptureToken(t)
|
||||
token, _, _ := tok.Generate()
|
||||
|
||||
if err := tok.Revoke(); err != nil {
|
||||
t.Fatalf("Revoke: %v", err)
|
||||
}
|
||||
if tok.Verify(token) {
|
||||
t.Fatal("token still verifies after Revoke")
|
||||
}
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatal("token file still exists, so the token would return on restart")
|
||||
}
|
||||
if err := tok.Revoke(); err != nil {
|
||||
t.Fatalf("revoking with nothing to revoke: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A damaged file must leave the routes off, never open and never fatal.
|
||||
func TestCaptureTokenCorruptFile(t *testing.T) {
|
||||
for name, content := range map[string]string{
|
||||
"not json": "{",
|
||||
"not a hash": `{"sha256": "zz"}`,
|
||||
"short hash": `{"sha256": "abcd"}`,
|
||||
"empty object": `{}`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "t.json")
|
||||
os.WriteFile(path, []byte(content), 0o600)
|
||||
tok, err := InitCaptureToken(path)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if tok == nil || tok.Verify("") {
|
||||
t.Fatal("a corrupt file must yield a usable store that rejects everything")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"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
|
||||
}
|
||||
@@ -54,6 +54,9 @@ func migrateDatabase(db *gorm.DB) error {
|
||||
&models.Bookmark{},
|
||||
&models.Place{},
|
||||
&models.ProcessedEmail{},
|
||||
&models.JobSource{},
|
||||
&models.JobLead{},
|
||||
&models.JobSearchProfile{},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// The classify step of the email pipeline: the request the Python service's
|
||||
// /internal/email/classify receives, and what processEmail does with each
|
||||
// kind of reply. A stub server stands in for Python.
|
||||
//
|
||||
// processEmail is driven only as far as it can go without a database. That
|
||||
// covers every failure (they all return before the first query) and the two
|
||||
// "nothing to do" answers; an email that is about a job goes on to look the
|
||||
// application up, which needs Postgres and is not exercised here.
|
||||
|
||||
func classifierStub(t *testing.T, handler http.HandlerFunc) *EmailSyncService {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &EmailSyncService{PythonURL: srv.URL}
|
||||
}
|
||||
|
||||
func testEmail() graphMessage {
|
||||
email := graphMessage{
|
||||
ID: "msg-1",
|
||||
Subject: "Your application to Acme",
|
||||
ReceivedDateTime: "2026-03-15T10:30:00Z",
|
||||
Body: graphBody{ContentType: "html", Content: "<p>Thanks for applying</p>"},
|
||||
}
|
||||
email.From.EmailAddress = graphEmailAddress{Name: "Acme Hiring", Address: "[email protected]"}
|
||||
return email
|
||||
}
|
||||
|
||||
func TestClassifyEmailRequest(t *testing.T) {
|
||||
var path string
|
||||
var body map[string]any
|
||||
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"isJobEmail": true, "action": "create", "company": "Acme", "jobTitle": "Engineer",
|
||||
"status": "applied", "location": "London", "url": null, "appliedAt": "2026-03-15", "notes": null}`))
|
||||
})
|
||||
|
||||
analysis, err := s.classifyEmail(context.Background(), testEmail())
|
||||
if err != nil {
|
||||
t.Fatalf("classifyEmail: %v", err)
|
||||
}
|
||||
if path != "/internal/email/classify" {
|
||||
t.Fatalf("path = %q", path)
|
||||
}
|
||||
// The whole contract: one key, holding the headers, a blank line and the
|
||||
// cleaned body. The Python side hands this string to Claude unchanged.
|
||||
want := "Subject: Your application to Acme\nFrom: Acme Hiring <[email protected]>\nDate: 2026-03-15T10:30:00Z\n\nThanks for applying"
|
||||
if len(body) != 1 || body["message"] != want {
|
||||
t.Fatalf("request body = %v\nwant message %q", body, want)
|
||||
}
|
||||
|
||||
if !analysis.IsJobEmail || analysis.Action != "create" || analysis.Company != "Acme" ||
|
||||
analysis.JobTitle != "Engineer" || analysis.Status != "applied" {
|
||||
t.Fatalf("analysis = %+v", analysis)
|
||||
}
|
||||
if analysis.Location == nil || *analysis.Location != "London" || analysis.URL != nil ||
|
||||
analysis.AppliedAt == nil || *analysis.AppliedAt != "2026-03-15" || analysis.Notes != nil {
|
||||
t.Fatalf("nullable fields = %+v", analysis)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessEmailWithoutAJob(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
reply string
|
||||
}{
|
||||
// What Python sends for a non-job email: every other field defaulted.
|
||||
{"not a job email", `{"isJobEmail": false, "action": "", "company": "", "jobTitle": "", "status": "",
|
||||
"location": null, "url": null, "appliedAt": null, "notes": null}`},
|
||||
// (company, job title) is the only key an application has, so an
|
||||
// answer missing either cannot be matched or created.
|
||||
{"a job email with no company", `{"isJobEmail": true, "action": "create", "company": "", "jobTitle": "Engineer", "status": "applied"}`},
|
||||
{"a job email with no title", `{"isJobEmail": true, "action": "create", "company": "Acme", "jobTitle": "", "status": "applied"}`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(c.reply))
|
||||
})
|
||||
action, jobAppID, err := s.processEmail(context.Background(), testEmail())
|
||||
if err != nil || action != "skipped" || jobAppID != nil {
|
||||
t.Fatalf("processEmail = (%q, %v, %v), want (skipped, nil, nil)", action, jobAppID, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Every way the classifier can fail must come back from processEmail as an
|
||||
// error with no action: that is what makes SyncEmails record the email as
|
||||
// Action "error" with one more attempt used, to be retried next sync.
|
||||
func TestProcessEmailClassifierFailures(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantRelayed string // the 502 detail, when there is one
|
||||
}{
|
||||
{"Claude failed", http.StatusBadGateway, `{"detail": "failed to classify the email"}`, "failed to classify the email"},
|
||||
{"Claude's reply was unparseable", http.StatusBadGateway, `{"detail": "failed to parse the email classification"}`, "failed to parse the email classification"},
|
||||
{"no API key", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"request rejected", http.StatusUnprocessableEntity, `{"detail": [{"msg": "too long"}]}`, ""},
|
||||
{"malformed 200 body", http.StatusOK, `not json`, ""},
|
||||
{"200 body of the wrong shape", http.StatusOK, `{"isJobEmail": "yes"}`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
action, jobAppID, err := s.processEmail(context.Background(), testEmail())
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if action != "" || jobAppID != nil {
|
||||
t.Fatalf("processEmail = (%q, %v) alongside an error", action, jobAppID)
|
||||
}
|
||||
// Not a cancellation: SyncEmails skips those without recording
|
||||
// anything, which would leave a real failure retried for ever.
|
||||
if errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("err = %v reads as a cancelled sync", err)
|
||||
}
|
||||
var pyErr *PythonError
|
||||
if errors.As(err, &pyErr) != (c.wantRelayed != "") {
|
||||
t.Fatalf("err = %v, want PythonError: %v", err, c.wantRelayed != "")
|
||||
}
|
||||
if pyErr != nil && pyErr.Detail != c.wantRelayed {
|
||||
t.Fatalf("detail = %q, want %q", pyErr.Detail, c.wantRelayed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The other half of the rule above: a sync abandoned mid-call (the admin
|
||||
// closed the tab) must be recognisable, so the email's attempts do not advance.
|
||||
func TestProcessEmailCancelled(t *testing.T) {
|
||||
s := classifierStub(t, func(http.ResponseWriter, *http.Request) {})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, _, err := s.processEmail(ctx, testEmail()); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("err = %v, want it to wrap context.Canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifierMessageIsCapped(t *testing.T) {
|
||||
// An ordinary email is nowhere near the cap and is not touched.
|
||||
if got := classifierMessage(testEmail()); !strings.HasSuffix(got, "\n\nThanks for applying") {
|
||||
t.Fatalf("message = %q", got)
|
||||
}
|
||||
|
||||
// cleanEmailBody bounds the body, so only the headers can push a message
|
||||
// over. Multi-byte runes: the cap counts characters, as the Python side
|
||||
// does, and the cut must not split one.
|
||||
long := testEmail()
|
||||
long.Subject = strings.Repeat("é", maxClassifyRunes+50)
|
||||
got := classifierMessage(long)
|
||||
if n := utf8.RuneCountInString(got); n != maxClassifyRunes {
|
||||
t.Fatalf("message is %d runes, want %d", n, maxClassifyRunes)
|
||||
}
|
||||
if !utf8.ValidString(got) {
|
||||
t.Fatal("the cut split a rune")
|
||||
}
|
||||
|
||||
// More bytes than the cap but fewer runes: within the limit, so intact.
|
||||
wide := testEmail()
|
||||
wide.Subject = strings.Repeat("é", maxClassifyRunes/2+10)
|
||||
if got := classifierMessage(wide); !strings.HasSuffix(got, "\n\nThanks for applying") {
|
||||
t.Fatal("a message under the rune cap was cut")
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,12 @@ package services
|
||||
|
||||
import "testing"
|
||||
|
||||
// These tests cover the status progression rule only — statusAdvances, the
|
||||
// These tests cover the status progression rule only — StatusAdvances, the
|
||||
// predicate extracted out of updateJobApplication. The rest of
|
||||
// updateJobApplication (note appending, the DB.Save, the returned counters)
|
||||
// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is
|
||||
// deliberately not exercised here. Nothing in this file touches Claude or the
|
||||
// Graph API either; email classification is a network call by construction.
|
||||
// deliberately not exercised here. Nothing in this file touches the classifier
|
||||
// or the Graph API either; see email_classify_test.go for the former.
|
||||
|
||||
func TestStatusAdvances(t *testing.T) {
|
||||
cases := []struct {
|
||||
@@ -34,6 +34,10 @@ func TestStatusAdvances(t *testing.T) {
|
||||
// ranks above rejected, so this single pair is allowed.
|
||||
{"rejected may still become withdrawn because withdrawn ranks higher", "rejected", "withdrawn", true},
|
||||
|
||||
// saved is a browser capture that has not been applied to yet.
|
||||
{"a saved posting advances once the application is confirmed", "saved", "applied", true},
|
||||
{"an applied row cannot fall back to saved", "applied", "saved", false},
|
||||
|
||||
{"an unknown new status is never applied", "applied", "hired", false},
|
||||
{"an empty new status is never applied", "applied", "", false},
|
||||
{"an unknown new status cannot escape a terminal state either", "rejected", "ghosted", false},
|
||||
@@ -43,8 +47,8 @@ func TestStatusAdvances(t *testing.T) {
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := statusAdvances(c.current, c.next); got != c.want {
|
||||
t.Errorf("statusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
|
||||
if got := StatusAdvances(c.current, c.next); got != c.want {
|
||||
t.Errorf("StatusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -66,7 +70,7 @@ func TestTerminalStatusesRankHighest(t *testing.T) {
|
||||
|
||||
// NormalizeStatus is the guard that keeps Claude's occasional casing drift
|
||||
// ("Interview", "on hold") out of the status column: an unrecognised value
|
||||
// stored verbatim makes statusAdvances treat the row's current status as
|
||||
// stored verbatim makes StatusAdvances treat the row's current status as
|
||||
// unknown, which switches the forward-only rule off for that row entirely.
|
||||
func TestNormalizeStatus(t *testing.T) {
|
||||
cases := []struct {
|
||||
@@ -75,6 +79,7 @@ func TestNormalizeStatus(t *testing.T) {
|
||||
want string
|
||||
}{
|
||||
{"a tracked status passes through", "interviewing", "interviewing"},
|
||||
{"saved is tracked, so a capture keeps it", "saved", "saved"},
|
||||
{"casing drift is lowered, not rejected", "Interviewing", "interviewing"},
|
||||
{"surrounding whitespace is trimmed", " offer ", "offer"},
|
||||
{"an untracked status falls back to the pipeline default", "on hold", "applied"},
|
||||
|
||||
+121
-95
@@ -17,7 +17,6 @@ import (
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -27,6 +26,13 @@ import (
|
||||
// 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.
|
||||
//
|
||||
// The Claude call itself is not made here: like the site's other two, it
|
||||
// lives in the Python service (python/app/email_classify.py, which owns the
|
||||
// prompt and the parsing of the model's reply) and is reached through
|
||||
// CallPython. Everything that needs the mailbox or the database — fetching,
|
||||
// the pre-filter, dedup and retry accounting, matching an email to an
|
||||
// application, the forward-only status rule — stays in this file.
|
||||
|
||||
// MSGRAPH_TOKEN_JSON_PATH lives in a Docker volume so the OAuth refresh token
|
||||
// survives restarts, exactly like the Spotify token.
|
||||
@@ -54,9 +60,12 @@ type EmailSyncService struct {
|
||||
// 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
|
||||
HTTPClient *http.Client
|
||||
DB *gorm.DB
|
||||
// PythonURL is the Python service's base URL on the Docker network, no
|
||||
// trailing slash: the same value as handlers.Store.PythonURL. The
|
||||
// classifier is called there (see classifyEmail).
|
||||
PythonURL string
|
||||
// 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.
|
||||
@@ -103,11 +112,15 @@ type graphBody struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Claude response type
|
||||
// Classifier 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.
|
||||
// EmailAnalysis is the JSON contract with the Python service's
|
||||
// /internal/email/classify: the body of its 200 reply. The keys here must stay
|
||||
// in step with EmailAnalysis and the prompt in python/app/email_classify.py,
|
||||
// which asks Claude for exactly these. Pointer fields are the ones that may
|
||||
// come back null; the plain strings come back "" when the model had nothing
|
||||
// (or when the email is not a job email, in which case only IsJobEmail means
|
||||
// anything).
|
||||
type EmailAnalysis struct {
|
||||
IsJobEmail bool `json:"isJobEmail"`
|
||||
Action string `json:"action"`
|
||||
@@ -122,7 +135,7 @@ type EmailAnalysis struct {
|
||||
|
||||
// Email filtering config
|
||||
|
||||
// Cheap pre-filter, applied before any Claude call so that the bulk of a
|
||||
// Cheap pre-filter, applied before any classifier 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).
|
||||
@@ -151,14 +164,26 @@ var senderDomains = []string{
|
||||
// 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.
|
||||
//
|
||||
// "saved" is the one status no email can produce: it marks a posting captured
|
||||
// from the browser but not applied to yet (handlers/handle_job_capture.go).
|
||||
// It ranks lowest so that the "thanks for applying" email advances the row.
|
||||
//
|
||||
// This map is the vocabulary. It is written down in four other places, which
|
||||
// must list the same statuses: `enum JobStatus` in
|
||||
// graph/schema/job_application.graphql (enforced —
|
||||
// TestJobStatusEnumMatchesStatusOrder fails on any difference), the
|
||||
// classifier prompt in python/app/email_classify.py (all but "saved"), the
|
||||
// tracker page and the capture userscript.
|
||||
var statusOrder = map[string]int{
|
||||
"applied": 0,
|
||||
"screening": 1,
|
||||
"assessment": 2,
|
||||
"interviewing": 3,
|
||||
"offer": 4,
|
||||
"rejected": 5,
|
||||
"withdrawn": 6,
|
||||
"saved": 0,
|
||||
"applied": 1,
|
||||
"screening": 2,
|
||||
"assessment": 3,
|
||||
"interviewing": 4,
|
||||
"offer": 5,
|
||||
"rejected": 6,
|
||||
"withdrawn": 7,
|
||||
}
|
||||
|
||||
// Token persistence
|
||||
@@ -258,11 +283,15 @@ func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
// 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 {
|
||||
//
|
||||
// pythonURL is where the classifier lives. It is not validated or probed: an
|
||||
// unreachable Python service shows up as each email failing and being
|
||||
// retried, the same way a bad API key used to.
|
||||
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, pythonURL string) *EmailSyncService {
|
||||
svc := &EmailSyncService{
|
||||
Config: config,
|
||||
DB: db,
|
||||
ClaudeClient: claudeClient,
|
||||
Config: config,
|
||||
DB: db,
|
||||
PythonURL: pythonURL,
|
||||
}
|
||||
|
||||
switch config.Backend {
|
||||
@@ -613,48 +642,66 @@ func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// processEmail sends a single email to Claude and creates/updates a JobApplication.
|
||||
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
|
||||
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
|
||||
cleaned := cleanEmailBody(email.Body.Content, email.Body.ContentType)
|
||||
// emailClassifyPath is the Python route, internal in the same way as the
|
||||
// rowing and job-posting readers' (see python_call.go).
|
||||
const emailClassifyPath = "/internal/email/classify"
|
||||
|
||||
userMsg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
|
||||
// maxClassifyRunes mirrors MAX_MESSAGE_CHARS in python/app/email_classify.py,
|
||||
// which answers 422 to anything longer. cleanEmailBody already caps the body
|
||||
// far below this, so the limit only bites on a pathological subject or sender
|
||||
// — but a 422 would be recorded as a failed attempt and retried to the cap,
|
||||
// so the cut is made here rather than left to chance.
|
||||
const maxClassifyRunes = 200_000
|
||||
|
||||
// classifierMessage formats one email as the classifier's user turn: Subject,
|
||||
// From and Date lines, a blank line, then the cleaned body. The Python side
|
||||
// passes the string to Claude unchanged, so this layout is part of what the
|
||||
// prompt there was written against.
|
||||
//
|
||||
// The result is cut to maxClassifyRunes on a rune boundary. The body comes
|
||||
// last, so it is what gives way first.
|
||||
func classifierMessage(email graphMessage) string {
|
||||
msg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
|
||||
email.Subject,
|
||||
email.From.EmailAddress.Name,
|
||||
email.From.EmailAddress.Address,
|
||||
email.ReceivedDateTime,
|
||||
cleaned,
|
||||
cleanEmailBody(email.Body.Content, email.Body.ContentType),
|
||||
)
|
||||
// Counting runes means converting; skip it for the ordinary case, where
|
||||
// even the byte length (never less than the rune count) is under the cap.
|
||||
if len(msg) <= maxClassifyRunes {
|
||||
return msg
|
||||
}
|
||||
runes := []rune(msg)
|
||||
if len(runes) <= maxClassifyRunes {
|
||||
return msg
|
||||
}
|
||||
return string(runes[:maxClassifyRunes])
|
||||
}
|
||||
|
||||
message, err := s.ClaudeClient.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: anthropic.ModelClaudeHaiku4_5,
|
||||
MaxTokens: 512,
|
||||
System: []anthropic.TextBlockParam{
|
||||
{Text: emailClassificationPrompt},
|
||||
},
|
||||
Messages: []anthropic.MessageParam{
|
||||
{
|
||||
Role: "user",
|
||||
Content: []anthropic.ContentBlockParamUnion{anthropic.NewTextBlock(userMsg)},
|
||||
},
|
||||
},
|
||||
})
|
||||
// classifyEmail asks the Python service what an email is. Every failure —
|
||||
// the service unreachable, Claude failing (502), no API key (503), a reply
|
||||
// that will not decode — comes back as an error, which SyncEmails records as
|
||||
// a retryable failure of this email.
|
||||
func (s *EmailSyncService) classifyEmail(ctx context.Context, email graphMessage) (EmailAnalysis, error) {
|
||||
analysis, err := CallPython[EmailAnalysis](ctx, s.PythonURL, emailClassifyPath, struct {
|
||||
Message string `json:"message"`
|
||||
}{classifierMessage(email)})
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("Claude API error: %w", err)
|
||||
// %w keeps context.Canceled visible to SyncEmails, which must not
|
||||
// count an abandoned sync against the email.
|
||||
return EmailAnalysis{}, fmt.Errorf("classifying email: %w", err)
|
||||
}
|
||||
return analysis, nil
|
||||
}
|
||||
|
||||
if len(message.Content) == 0 {
|
||||
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.
|
||||
raw := StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
var analysis EmailAnalysis
|
||||
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
|
||||
return "", nil, fmt.Errorf("parsing Claude response: %w (raw: %s)", err, raw)
|
||||
// processEmail has a single email classified and creates/updates a JobApplication.
|
||||
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
|
||||
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
|
||||
analysis, err := s.classifyEmail(ctx, email)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
if !analysis.IsJobEmail {
|
||||
@@ -703,6 +750,11 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
// statusOrder. An unrecognised status stored verbatim would disable the
|
||||
// forward-only guard for that row (updateJobApplication allows any recognised
|
||||
// status over an unknown one), so the safe fallback is the pipeline's default.
|
||||
//
|
||||
// It is for values that arrive outside GraphQL: the classifier's answer and
|
||||
// the capture endpoint's body. The GraphQL mutations do not use it — their
|
||||
// status is a JobStatus, which UnmarshalJobStatus refuses outright when it is
|
||||
// not in the vocabulary rather than quietly storing "applied".
|
||||
func NormalizeStatus(s string) string {
|
||||
lowered := strings.ToLower(strings.TrimSpace(s))
|
||||
if _, ok := statusOrder[lowered]; ok {
|
||||
@@ -744,27 +796,36 @@ func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string
|
||||
return "created", &app.ID, nil
|
||||
}
|
||||
|
||||
// statusAdvances reports whether next is a forward move from current through
|
||||
// StatusAdvances reports whether next is a forward move from current 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. An unknown next status is never applied;
|
||||
// an unknown current status is treated as "anywhere before the start", so any
|
||||
// recognised status can take over from it.
|
||||
func statusAdvances(current, next string) bool {
|
||||
//
|
||||
// Exported because the browser capture endpoint applies the same rule.
|
||||
func StatusAdvances(current, next string) bool {
|
||||
nextOrder, nextExists := statusOrder[next]
|
||||
currentOrder, currentExists := statusOrder[current]
|
||||
return nextExists && (!currentExists || nextOrder > currentOrder)
|
||||
}
|
||||
|
||||
// updateJobApplication advances an existing application's status, but only
|
||||
// ever forwards (see statusAdvances).
|
||||
// ever forwards (see StatusAdvances).
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
if !statusAdvances(existing.Status, analysis.Status) {
|
||||
if !StatusAdvances(existing.Status, analysis.Status) {
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
existing.Status = analysis.Status
|
||||
|
||||
// A row captured as "saved" has no applied date; the email that moves it
|
||||
// to "applied" is the best evidence of when that happened.
|
||||
if existing.AppliedAt == nil && existing.Status == "applied" {
|
||||
now := time.Now()
|
||||
existing.AppliedAt = &now
|
||||
}
|
||||
|
||||
// Append to notes if Claude provided any
|
||||
if analysis.Notes != nil && *analysis.Notes != "" {
|
||||
if existing.Notes != nil && *existing.Notes != "" {
|
||||
@@ -784,7 +845,7 @@ func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication,
|
||||
}
|
||||
|
||||
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
|
||||
// Claude, cutting token cost and noise.
|
||||
// the classifier, 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
|
||||
@@ -845,7 +906,9 @@ func cleanEmailBody(content string, contentType string) string {
|
||||
text = strings.Join(cleaned, "\n")
|
||||
|
||||
// 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.
|
||||
// and leave an invalid UTF-8 tail. That is harmless: the text travels to
|
||||
// the classifier as JSON, and encoding/json replaces the broken tail with
|
||||
// U+FFFD rather than emitting invalid UTF-8.
|
||||
if len(text) > 4000 {
|
||||
text = text[:4000]
|
||||
}
|
||||
@@ -862,43 +925,6 @@ 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:
|
||||
- "isJobEmail": boolean - true if this email is about a job application
|
||||
- "action": "create" | "update" | "none" - whether this represents a new application confirmation or an update to an existing one
|
||||
- "company": string - the company name
|
||||
- "jobTitle": string - the job title/position
|
||||
- "status": string - one of: "applied", "screening", "interviewing", "assessment", "offer", "rejected", "withdrawn"
|
||||
- "location": string or null - job location if mentioned
|
||||
- "url": string or null - any application portal URL
|
||||
- "appliedAt": string or null - ISO 8601 date if an application date is mentioned (YYYY-MM-DD format)
|
||||
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
|
||||
|
||||
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
|
||||
|
||||
// StripMarkdownFence removes a surrounding markdown code fence from a model's
|
||||
// response, so text that should have been bare JSON can be unmarshalled
|
||||
// whether or not the model wrapped it.
|
||||
//
|
||||
// The two TrimPrefix calls are ordered so that "```json" is removed first and
|
||||
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
|
||||
// returned unchanged apart from surrounding whitespace.
|
||||
//
|
||||
// Shared with handlers.CreateRowing, which prompts for bare JSON in the same
|
||||
// way and gets the same fenced output.
|
||||
func StripMarkdownFence(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
|
||||
// maxEmailAttempts caps how many times a failing email is reprocessed. Each
|
||||
// attempt costs a Claude call, so the cap is what stops one permanently
|
||||
// unparseable email billing on every sync forever. Three gives a transient
|
||||
|
||||
@@ -8,12 +8,13 @@ import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// These tests cover only the pure helpers of the email sync: body cleaning,
|
||||
// truncation, fence stripping, timestamp parsing, the retry predicate and the
|
||||
// filter. Everything else in email_sync.go — token acquisition, the Graph
|
||||
// paging loop, processEmail and the create/update paths — needs either a live
|
||||
// *gorm.DB, a Microsoft Graph endpoint or a Claude call, none of which exist
|
||||
// in a test run, so they are deliberately not exercised here.
|
||||
// These tests cover the pure helpers of the email sync: body cleaning,
|
||||
// truncation, timestamp parsing, the retry predicate and the filter. The
|
||||
// classify step, which is an HTTP call to the Python service, is covered in
|
||||
// email_classify_test.go. What is left uncovered — token acquisition, the
|
||||
// Graph paging loop, and the create/update paths processEmail ends in — needs
|
||||
// either a live *gorm.DB or a Microsoft Graph endpoint, neither of which
|
||||
// exists in a test run.
|
||||
//
|
||||
// matchesFilter is a method but reads no field of the receiver (it matches
|
||||
// against the package-level subjectKeywords/senderDomains), which is why a
|
||||
@@ -135,29 +136,6 @@ func TestTruncate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripMarkdownFence(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{"json-tagged fence", "```json\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"bare fence", "```\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"unfenced input is returned as-is", `{"a":1}`, `{"a":1}`},
|
||||
{"surrounding whitespace is trimmed", "\n\n {\"a\":1} \n", `{"a":1}`},
|
||||
{"leading whitespace before the fence", " ```json\n{\"a\":1}\n``` ", `{"a":1}`},
|
||||
{"opening fence only", "```json\n{\"a\":1}", `{"a":1}`},
|
||||
{"empty input", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := StripMarkdownFence(c.raw); got != c.want {
|
||||
t.Fatalf("StripMarkdownFence(%q) = %q, want %q", c.raw, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseReceivedAt(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
_ "embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ENV_APPLY_DIR is the directory shared with the host (./env-apply/run in the
|
||||
// checkout, bind-mounted by docker-compose). It is the whole interface
|
||||
// between this process and the host script that edits .env.
|
||||
const ENV_APPLY_DIR = "/backend/env-apply"
|
||||
|
||||
// The registry is JSON rather than a Go literal because the host script
|
||||
// (env-apply/apply.py) reads the same file from the checkout: one list
|
||||
// decides both what the panel offers and what the host will accept.
|
||||
//
|
||||
//go:embed env_registry.json
|
||||
var envRegistryJSON []byte
|
||||
|
||||
// EnvVar is one registry entry.
|
||||
//
|
||||
// Kind decides how a value is validated and how the panel renders it:
|
||||
// "secret" and "generated" are never sent to the browser; "generated" can
|
||||
// also be minted here. Services lists the compose services that read the
|
||||
// variable, which is what the host recreates after a change.
|
||||
type EnvVar struct {
|
||||
Name string `json:"name"`
|
||||
Group string `json:"group"`
|
||||
Purpose string `json:"purpose"`
|
||||
Kind string `json:"kind"`
|
||||
Editable bool `json:"editable"`
|
||||
LockedReason string `json:"lockedReason,omitempty"`
|
||||
Services []string `json:"services,omitempty"`
|
||||
DocsURL string `json:"docsUrl,omitempty"`
|
||||
Options []string `json:"options,omitempty"`
|
||||
Warning string `json:"warning,omitempty"`
|
||||
}
|
||||
|
||||
// Secret reports whether the variable's value must stay on the server.
|
||||
func (v EnvVar) Secret() bool {
|
||||
return v.Kind == "secret" || v.Kind == "generated"
|
||||
}
|
||||
|
||||
// EnvManager turns an edit made in the admin panel into a request for the
|
||||
// host to apply.
|
||||
//
|
||||
// The backend deliberately cannot write .env or restart containers itself:
|
||||
// it is the internet-facing process, and either ability would make a
|
||||
// compromised admin session a compromised host. Instead it validates the
|
||||
// change and leaves request.json in the shared directory; the host's watcher
|
||||
// (env-apply/apply.py, run by a systemd path unit) merges it into .env,
|
||||
// recreates the affected containers and reports back through status.json.
|
||||
type EnvManager struct {
|
||||
dir string
|
||||
vars []EnvVar
|
||||
byName map[string]EnvVar
|
||||
|
||||
// Serialises Submit and Cancel so two requests cannot interleave their
|
||||
// read-merge-write of request.json. The host is a separate process and is
|
||||
// handled by renames instead (see Submit).
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// envApplyRequest is request.json. Clearing a variable is setting it to "".
|
||||
type envApplyRequest struct {
|
||||
ID string `json:"id"`
|
||||
RequestedAt time.Time `json:"requestedAt"`
|
||||
Set map[string]string `json:"set"`
|
||||
}
|
||||
|
||||
// EnvApplyStatus is what the panel polls. State is one of idle, pending
|
||||
// (request written, host has not picked it up), applying, applied, failed.
|
||||
type EnvApplyStatus struct {
|
||||
State string `json:"state"`
|
||||
ID string `json:"id,omitempty"`
|
||||
// When the state was entered.
|
||||
At *time.Time `json:"at,omitempty"`
|
||||
// Names in a pending request. Values are never reported.
|
||||
Pending []string `json:"pending,omitempty"`
|
||||
Services []string `json:"services,omitempty"`
|
||||
Changed []string `json:"changed,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
// False once a request has waited long enough that nothing on the host
|
||||
// can be watching for it (a dev machine, or the units not installed).
|
||||
Watcher bool `json:"watcher"`
|
||||
}
|
||||
|
||||
const (
|
||||
envRequestFile = "request.json"
|
||||
envStatusFile = "status.json"
|
||||
|
||||
// The path unit fires within a second, so a request still unclaimed
|
||||
// after this long means there is no watcher.
|
||||
envWatcherGrace = 15 * time.Second
|
||||
// An "applying" status older than this is a host script that died
|
||||
// mid-run; stop letting it block new requests.
|
||||
envApplyingStale = 5 * time.Minute
|
||||
|
||||
envValueMaxLen = 4096
|
||||
)
|
||||
|
||||
// ErrEnvApplying is returned by Submit while the host is mid-apply.
|
||||
var ErrEnvApplying = errors.New("a change is being applied; try again in a moment")
|
||||
|
||||
// NewEnvManager parses the embedded registry. dir need not exist yet: without
|
||||
// the bind mount, reads report "idle" and Submit fails with a clear error.
|
||||
func NewEnvManager(dir string) (*EnvManager, error) {
|
||||
var vars []EnvVar
|
||||
if err := json.Unmarshal(envRegistryJSON, &vars); err != nil {
|
||||
return nil, fmt.Errorf("parsing env registry: %w", err)
|
||||
}
|
||||
byName := make(map[string]EnvVar, len(vars))
|
||||
for _, v := range vars {
|
||||
if _, dup := byName[v.Name]; dup {
|
||||
return nil, fmt.Errorf("env registry lists %s twice", v.Name)
|
||||
}
|
||||
byName[v.Name] = v
|
||||
}
|
||||
return &EnvManager{dir: dir, vars: vars, byName: byName}, nil
|
||||
}
|
||||
|
||||
// Vars returns the registry in file order, which is the order the panel
|
||||
// shows.
|
||||
func (m *EnvManager) Vars() []EnvVar {
|
||||
return m.vars
|
||||
}
|
||||
|
||||
// Validate checks one proposed value. The empty string clears the variable
|
||||
// and is always acceptable for an editable one.
|
||||
//
|
||||
// The control-character rule is the security-relevant one: .env is line
|
||||
// oriented, so a newline in a value would let an edit to an allowed variable
|
||||
// write a second, arbitrary one.
|
||||
func (m *EnvManager) Validate(name, value string) error {
|
||||
v, ok := m.byName[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("%s is not a known variable", name)
|
||||
}
|
||||
if !v.Editable {
|
||||
return fmt.Errorf("%s cannot be changed from the panel", name)
|
||||
}
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
if len(value) > envValueMaxLen {
|
||||
return fmt.Errorf("%s is too long", name)
|
||||
}
|
||||
for _, r := range value {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return fmt.Errorf("%s contains a control character", name)
|
||||
}
|
||||
}
|
||||
// The host writes values single-quoted, and a dotenv single-quoted
|
||||
// string has no escape for the quote itself.
|
||||
if strings.ContainsRune(value, '\'') {
|
||||
return fmt.Errorf("%s cannot contain a single quote", name)
|
||||
}
|
||||
|
||||
switch v.Kind {
|
||||
case "url":
|
||||
u, err := url.Parse(value)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return fmt.Errorf("%s must be an http(s) URL", name)
|
||||
}
|
||||
case "bool":
|
||||
if value != "true" && value != "false" {
|
||||
return fmt.Errorf("%s must be true or false", name)
|
||||
}
|
||||
case "duration":
|
||||
if d, err := time.ParseDuration(value); err != nil || d <= 0 {
|
||||
return fmt.Errorf("%s must be a duration such as 30m", name)
|
||||
}
|
||||
case "number":
|
||||
if n, err := strconv.Atoi(value); err != nil || n <= 0 {
|
||||
return fmt.Errorf("%s must be a positive whole number", name)
|
||||
}
|
||||
case "enum":
|
||||
if !slices.Contains(v.Options, value) {
|
||||
return fmt.Errorf("%s must be one of: %s", name, strings.Join(v.Options, ", "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ServicesFor is the set of compose services a change to names recreates.
|
||||
// The backend is always among them: the panel reports state from this
|
||||
// process's own environment, which only a recreate refreshes.
|
||||
func (m *EnvManager) ServicesFor(names []string) []string {
|
||||
services := []string{"backend"}
|
||||
for _, name := range names {
|
||||
for _, s := range m.byName[name].Services {
|
||||
if !slices.Contains(services, s) {
|
||||
services = append(services, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(services)
|
||||
return services
|
||||
}
|
||||
|
||||
// Submit validates a batch of edits and hands it to the host. set holds
|
||||
// explicit values ("" clears); generate names variables to mint a random
|
||||
// value for. The generated values are returned and exist nowhere else on
|
||||
// this side — the caller shows them once.
|
||||
//
|
||||
// Nothing is written unless the whole batch is valid.
|
||||
//
|
||||
// A request the host has not yet claimed is merged into rather than
|
||||
// refused, so edits are not stuck behind an absent watcher. The host claims
|
||||
// a request by renaming it, so the worst a race can do is hand it values it
|
||||
// has already applied.
|
||||
func (m *EnvManager) Submit(set map[string]string, generate []string) (map[string]string, []string, error) {
|
||||
changes := make(map[string]string, len(set)+len(generate))
|
||||
for name, value := range set {
|
||||
value = strings.TrimSpace(value)
|
||||
if err := m.Validate(name, value); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
changes[name] = value
|
||||
}
|
||||
generated := make(map[string]string, len(generate))
|
||||
for _, name := range generate {
|
||||
if v, ok := m.byName[name]; !ok || !v.Editable || v.Kind != "generated" {
|
||||
return nil, nil, fmt.Errorf("%s cannot be generated", name)
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
generated[name] = hex.EncodeToString(raw)
|
||||
changes[name] = generated[name]
|
||||
}
|
||||
if len(changes) == 0 {
|
||||
return nil, nil, errors.New("no changes given")
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if status := m.readStatus(); status != nil && status.State == "applying" &&
|
||||
status.At != nil && time.Since(*status.At) < envApplyingStale {
|
||||
return nil, nil, ErrEnvApplying
|
||||
}
|
||||
|
||||
request := envApplyRequest{Set: changes}
|
||||
if pending := m.readRequest(); pending != nil {
|
||||
for name, value := range pending.Set {
|
||||
if _, replaced := changes[name]; !replaced {
|
||||
request.Set[name] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
id := make([]byte, 8)
|
||||
if _, err := rand.Read(id); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
request.ID = hex.EncodeToString(id)
|
||||
request.RequestedAt = time.Now().UTC()
|
||||
|
||||
if err := m.writeRequest(&request); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(request.Set))
|
||||
for name := range request.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
return generated, m.ServicesFor(names), nil
|
||||
}
|
||||
|
||||
// writeRequest writes request.json so the host only ever sees a complete
|
||||
// file it can read: temp name, owner and mode set, then rename.
|
||||
//
|
||||
// This process runs as root in the container while the host script runs as
|
||||
// the checkout's owner, so the file is handed to whoever owns the shared
|
||||
// directory. 0600 because it holds the new secrets in the clear until the
|
||||
// host consumes it.
|
||||
func (m *EnvManager) writeRequest(request *envApplyRequest) error {
|
||||
info, err := os.Stat(m.dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the env-apply directory is not mounted: %w", err)
|
||||
}
|
||||
data, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := filepath.Join(m.dir, envRequestFile+".tmp")
|
||||
if err := os.WriteFile(tmp, data, 0600); err != nil {
|
||||
return fmt.Errorf("writing env request: %w", err)
|
||||
}
|
||||
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
if err := os.Chown(tmp, int(stat.Uid), int(stat.Gid)); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("handing env request to the host user: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.Rename(tmp, filepath.Join(m.dir, envRequestFile)); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("writing env request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cancel withdraws a request the host has not claimed. Once claimed it is
|
||||
// too late, and this is a no-op.
|
||||
func (m *EnvManager) Cancel() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := os.Remove(filepath.Join(m.dir, envRequestFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("removing env request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EnvManager) readRequest() *envApplyRequest {
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var request envApplyRequest
|
||||
if json.Unmarshal(raw, &request) != nil {
|
||||
return nil
|
||||
}
|
||||
return &request
|
||||
}
|
||||
|
||||
func (m *EnvManager) readStatus() *EnvApplyStatus {
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envStatusFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var status EnvApplyStatus
|
||||
if json.Unmarshal(raw, &status) != nil {
|
||||
return nil
|
||||
}
|
||||
return &status
|
||||
}
|
||||
|
||||
// Status reports where the latest change has got to. An unclaimed request
|
||||
// takes precedence over status.json, which then describes an older change.
|
||||
func (m *EnvManager) Status() EnvApplyStatus {
|
||||
if request := m.readRequest(); request != nil {
|
||||
names := make([]string, 0, len(request.Set))
|
||||
for name := range request.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
slices.Sort(names)
|
||||
at := request.RequestedAt
|
||||
return EnvApplyStatus{
|
||||
State: "pending",
|
||||
ID: request.ID,
|
||||
At: &at,
|
||||
Pending: names,
|
||||
Services: m.ServicesFor(names),
|
||||
Watcher: time.Since(at) < envWatcherGrace,
|
||||
}
|
||||
}
|
||||
if status := m.readStatus(); status != nil {
|
||||
status.Watcher = true
|
||||
return *status
|
||||
}
|
||||
return EnvApplyStatus{State: "idle", Watcher: true}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newEnvManager(t *testing.T) *EnvManager {
|
||||
t.Helper()
|
||||
m, err := NewEnvManager(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func readRequestFile(t *testing.T, m *EnvManager) envApplyRequest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
t.Fatalf("reading request: %v", err)
|
||||
}
|
||||
var request envApplyRequest
|
||||
if err := json.Unmarshal(raw, &request); err != nil {
|
||||
t.Fatalf("parsing request: %v", err)
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
// The registry and .env.example describe the same variables; a name added to
|
||||
// one and not the other is either invisible in the panel or undocumented.
|
||||
func TestEnvRegistryMatchesEnvExample(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../.env.example")
|
||||
if err != nil {
|
||||
t.Fatalf("reading .env.example: %v", err)
|
||||
}
|
||||
var example []string
|
||||
for _, match := range regexp.MustCompile(`(?m)^([A-Z][A-Z0-9_]*)=`).FindAllStringSubmatch(string(raw), -1) {
|
||||
example = append(example, match[1])
|
||||
}
|
||||
|
||||
var registry []string
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
registry = append(registry, v.Name)
|
||||
}
|
||||
|
||||
for _, name := range example {
|
||||
if !slices.Contains(registry, name) {
|
||||
t.Errorf("%s is in .env.example but not in env_registry.json", name)
|
||||
}
|
||||
}
|
||||
for _, name := range registry {
|
||||
if !slices.Contains(example, name) {
|
||||
t.Errorf("%s is in env_registry.json but not in .env.example", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// composePythonEnv returns the variable names in the `environment:` list of
|
||||
// the `python` service in docker-compose.yml.
|
||||
//
|
||||
// It reads the file as text rather than through a YAML library — there is
|
||||
// none among this module's direct dependencies, and the shape needed is
|
||||
// narrow: a two-space-indented `python:` key under `services:`, a
|
||||
// four-space-indented `environment:` under it, and `- NAME=value` items. If
|
||||
// the compose file is ever restructured so that this finds nothing, the test
|
||||
// below fails loudly rather than passing on an empty list.
|
||||
func composePythonEnv(t *testing.T) []string {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile("../../docker-compose.yml")
|
||||
if err != nil {
|
||||
t.Fatalf("reading docker-compose.yml: %v", err)
|
||||
}
|
||||
|
||||
item := regexp.MustCompile(`^ - ["']?([A-Z][A-Z0-9_]*)(=|["']?\s*$)`)
|
||||
var names []string
|
||||
inPython, inEnvironment := false, false
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
continue
|
||||
}
|
||||
indent := len(line) - len(strings.TrimLeft(line, " "))
|
||||
switch {
|
||||
case indent <= 2:
|
||||
// A new service (or a top-level key) ends the block.
|
||||
inPython, inEnvironment = line == " python:", false
|
||||
case inPython && indent == 4:
|
||||
inEnvironment = trimmed == "environment:"
|
||||
case inPython && inEnvironment:
|
||||
match := item.FindStringSubmatch(line)
|
||||
if match == nil {
|
||||
t.Fatalf("python.environment has an entry this test cannot read: %q", line)
|
||||
}
|
||||
names = append(names, match[1])
|
||||
}
|
||||
}
|
||||
if len(names) == 0 {
|
||||
t.Fatal("found no python.environment list in docker-compose.yml; has the file's layout changed?")
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// The python service is the one container given an explicit `environment:`
|
||||
// list instead of the whole .env, so that it never holds the database
|
||||
// password or the JWT secret. The cost is a third place a new Python variable
|
||||
// has to be added — the registry, .env.example and that list — and forgetting
|
||||
// the third is silent: the variable is simply empty inside the container.
|
||||
//
|
||||
// So the registry's claim "python reads this" and the compose list must
|
||||
// agree, in both directions:
|
||||
//
|
||||
// - a variable the registry says python reads must be passed to it;
|
||||
// - an editable variable that is passed to it must say so in the registry,
|
||||
// or changing it in the admin panel would not recreate the container.
|
||||
//
|
||||
// Locked variables are exempt from the second rule. They are never applied
|
||||
// through the panel, so the registry gives none of them a services list
|
||||
// (PYTHON_PORT is passed to python and is one of these). Names in the compose
|
||||
// list that are not registry variables at all, such as the literal ROOT_PATH,
|
||||
// are not this test's business.
|
||||
func TestEnvRegistryMatchesComposePythonEnvironment(t *testing.T) {
|
||||
compose := composePythonEnv(t)
|
||||
|
||||
registry := map[string]EnvVar{}
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
registry[v.Name] = v
|
||||
if slices.Contains(v.Services, "python") && !slices.Contains(compose, v.Name) {
|
||||
t.Errorf("%s lists the python service in env_registry.json but is not in "+
|
||||
"python.environment in docker-compose.yml, so the container never receives it", v.Name)
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range compose {
|
||||
v, known := registry[name]
|
||||
if !known || !v.Editable {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(v.Services, "python") {
|
||||
t.Errorf("%s is passed to the python service in docker-compose.yml but env_registry.json "+
|
||||
"does not list python among its services, so editing it would not recreate the container", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvRegistryEntriesAreWellFormed(t *testing.T) {
|
||||
kinds := []string{"secret", "generated", "text", "url", "bool", "duration", "number", "enum"}
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
if !slices.Contains(kinds, v.Kind) {
|
||||
t.Errorf("%s has unknown kind %q", v.Name, v.Kind)
|
||||
}
|
||||
if v.Group == "" || v.Purpose == "" {
|
||||
t.Errorf("%s is missing its group or purpose", v.Name)
|
||||
}
|
||||
if v.Editable && len(v.Services) == 0 {
|
||||
t.Errorf("%s is editable but names no service to recreate", v.Name)
|
||||
}
|
||||
if !v.Editable && v.LockedReason == "" {
|
||||
t.Errorf("%s is locked without a reason", v.Name)
|
||||
}
|
||||
if v.Kind == "enum" && len(v.Options) == 0 {
|
||||
t.Errorf("%s is an enum with no options", v.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvValidate(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
cases := []struct {
|
||||
name, value string
|
||||
ok bool
|
||||
}{
|
||||
{"CLAUDE_API_KEY", "sk-ant-abc123", true},
|
||||
{"CLAUDE_API_KEY", "", true},
|
||||
// The injection case: a newline would start a second variable.
|
||||
{"CLAUDE_API_KEY", "x\nPOSTGRES_PASSWORD=owned", false},
|
||||
{"CLAUDE_API_KEY", "x\rY", false},
|
||||
{"CLAUDE_API_KEY", "it's", false},
|
||||
{"CLAUDE_API_KEY", strings.Repeat("a", envValueMaxLen+1), false},
|
||||
{"POSTGRES_PASSWORD", "anything", false},
|
||||
{"NOT_A_VARIABLE", "anything", false},
|
||||
{"EMAIL_BACKEND", "graph", true},
|
||||
{"EMAIL_BACKEND", "pop3", false},
|
||||
{"EMAIL_SYNC_INTERVAL", "45m", true},
|
||||
{"EMAIL_SYNC_INTERVAL", "soon", false},
|
||||
{"EMAIL_SYNC_INTERVAL", "-5m", false},
|
||||
{"EMAIL_SYNC_ENABLED", "true", true},
|
||||
{"EMAIL_SYNC_ENABLED", "yes", false},
|
||||
{"IMAP_PORT", "993", true},
|
||||
{"IMAP_PORT", "imaps", false},
|
||||
{"SPOTIFY_REDIRECT_URI", "https://example.com/api/spotify/callback", true},
|
||||
{"SPOTIFY_REDIRECT_URI", "example.com/callback", false},
|
||||
{"SPOTIFY_REDIRECT_URI", "javascript:alert(1)", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
err := m.Validate(c.name, c.value)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("Validate(%s, %q) error = %v, want ok = %v", c.name, c.value, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitWritesRequest(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
generated, services, err := m.Submit(
|
||||
map[string]string{"TFL_APP_KEY": " tfl-key ", "STEAM_ID": ""},
|
||||
[]string{"ICECAST_RELAY_PASSWORD"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
if len(generated["ICECAST_RELAY_PASSWORD"]) != 64 {
|
||||
t.Fatalf("generated value = %q, want 64 hex characters", generated["ICECAST_RELAY_PASSWORD"])
|
||||
}
|
||||
if want := []string{"backend", "icecast2", "python"}; !slices.Equal(services, want) {
|
||||
t.Fatalf("services = %v, want %v", services, want)
|
||||
}
|
||||
|
||||
request := readRequestFile(t, m)
|
||||
want := map[string]string{
|
||||
"TFL_APP_KEY": "tfl-key", // surrounding whitespace from a paste is dropped
|
||||
"STEAM_ID": "",
|
||||
"ICECAST_RELAY_PASSWORD": generated["ICECAST_RELAY_PASSWORD"],
|
||||
}
|
||||
if len(request.Set) != len(want) {
|
||||
t.Fatalf("request.Set = %v, want %v", request.Set, want)
|
||||
}
|
||||
for name, value := range want {
|
||||
if request.Set[name] != value {
|
||||
t.Errorf("request.Set[%s] = %q, want %q", name, request.Set[name], value)
|
||||
}
|
||||
}
|
||||
|
||||
info, err := os.Stat(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0600 {
|
||||
t.Errorf("request mode = %v, want 0600: it holds secrets in the clear", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitRejectsWholeBatch(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
cases := []struct {
|
||||
name string
|
||||
set map[string]string
|
||||
generate []string
|
||||
}{
|
||||
{"one bad value", map[string]string{"STEAM_ID": "1", "EMAIL_BACKEND": "pop3"}, nil},
|
||||
{"a locked variable", map[string]string{"STEAM_ID": "1", "DOMAIN": "evil.example"}, nil},
|
||||
{"generating a pasted secret", nil, []string{"CLAUDE_API_KEY"}},
|
||||
{"generating a locked secret", nil, []string{"POSTGRES_PASSWORD"}},
|
||||
{"nothing at all", nil, nil},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if _, _, err := m.Submit(c.set, c.generate); err == nil {
|
||||
t.Fatal("Submit succeeded, want an error")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(m.dir, envRequestFile)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("a rejected batch left a request file behind")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitMergesUnclaimedRequest(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1", "TFL_APP_KEY": "old"}, nil); err != nil {
|
||||
t.Fatalf("first Submit: %v", err)
|
||||
}
|
||||
if _, _, err := m.Submit(map[string]string{"TFL_APP_KEY": "new"}, nil); err != nil {
|
||||
t.Fatalf("second Submit: %v", err)
|
||||
}
|
||||
request := readRequestFile(t, m)
|
||||
if request.Set["STEAM_ID"] != "1" || request.Set["TFL_APP_KEY"] != "new" {
|
||||
t.Fatalf("merged request = %v, want the earlier STEAM_ID kept and TFL_APP_KEY replaced", request.Set)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitWithoutMount(t *testing.T) {
|
||||
m, err := NewEnvManager(filepath.Join(t.TempDir(), "absent"))
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err == nil {
|
||||
t.Fatal("Submit succeeded with no shared directory")
|
||||
}
|
||||
if got := m.Status().State; got != "idle" {
|
||||
t.Fatalf("Status().State = %q, want idle", got)
|
||||
}
|
||||
}
|
||||
|
||||
func writeStatusFile(t *testing.T, m *EnvManager, state string, at time.Time) {
|
||||
t.Helper()
|
||||
data, _ := json.Marshal(EnvApplyStatus{State: state, ID: "abc", At: &at})
|
||||
if err := os.WriteFile(filepath.Join(m.dir, envStatusFile), data, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvStatus(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
if got := m.Status(); got.State != "idle" || !got.Watcher {
|
||||
t.Fatalf("fresh status = %+v, want idle with watcher assumed", got)
|
||||
}
|
||||
|
||||
writeStatusFile(t, m, "applied", time.Now())
|
||||
if got := m.Status(); got.State != "applied" || got.ID != "abc" {
|
||||
t.Fatalf("status = %+v, want the host's applied report", got)
|
||||
}
|
||||
|
||||
// An unclaimed request outranks the report of an older change.
|
||||
if _, _, err := m.Submit(map[string]string{"CLAUDE_API_KEY": "sk-secret"}, nil); err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
got := m.Status()
|
||||
if got.State != "pending" || !slices.Equal(got.Pending, []string{"CLAUDE_API_KEY"}) || !got.Watcher {
|
||||
t.Fatalf("status = %+v, want pending CLAUDE_API_KEY", got)
|
||||
}
|
||||
if encoded, _ := json.Marshal(got); strings.Contains(string(encoded), "sk-secret") {
|
||||
t.Fatal("the status leaks a pending value")
|
||||
}
|
||||
|
||||
// Backdate the request past the grace period: nothing is watching.
|
||||
request := readRequestFile(t, m)
|
||||
request.RequestedAt = time.Now().Add(-2 * envWatcherGrace)
|
||||
if err := m.writeRequest(&request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Status().Watcher {
|
||||
t.Fatal("a long-unclaimed request still reports a watcher")
|
||||
}
|
||||
|
||||
if err := m.Cancel(); err != nil {
|
||||
t.Fatalf("Cancel: %v", err)
|
||||
}
|
||||
if got := m.Status().State; got != "applied" {
|
||||
t.Fatalf("after Cancel state = %q, want the earlier applied report", got)
|
||||
}
|
||||
if err := m.Cancel(); err != nil {
|
||||
t.Fatalf("Cancel with nothing pending: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitRefusedWhileApplying(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
writeStatusFile(t, m, "applying", time.Now())
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); !errors.Is(err, ErrEnvApplying) {
|
||||
t.Fatalf("Submit error = %v, want ErrEnvApplying", err)
|
||||
}
|
||||
|
||||
// A host script that died mid-run must not block the panel for ever.
|
||||
writeStatusFile(t, m, "applying", time.Now().Add(-2*envApplyingStale))
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err != nil {
|
||||
t.Fatalf("Submit after a stale applying status: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
[
|
||||
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Claude calls, all made by the Python service: email classifier, rowing photo reader, job posting reader, job lead scorer", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
|
||||
{"name": "CLAUDE_MODEL", "group": "API keys", "purpose": "Model for every Claude call: lead scoring, email classifier, posting reader, rowing photo reader. Blank uses claude-sonnet-5-5. Rough cost per million tokens in/out: Haiku $1/$5, Sonnet $2/$10, Opus $4/$20", "kind": "enum", "options": ["claude-haiku-4-5", "claude-sonnet-5-5", "claude-opus-5-5"], "editable": true, "services": ["python"]},
|
||||
{"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"},
|
||||
{"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"},
|
||||
|
||||
{"name": "SPOTIFY_CLIENT_ID", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
|
||||
{"name": "SPOTIFY_CLIENT_SECRET", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
|
||||
{"name": "SPOTIFY_REDIRECT_URI", "group": "Spotify", "purpose": "Must match the URI registered in the Spotify dashboard exactly", "kind": "url", "editable": true, "services": ["backend"]},
|
||||
{"name": "SPOTIFY_AUTH_STATE", "group": "Spotify", "purpose": "Former fixed OAuth state", "kind": "secret", "editable": false, "lockedReason": "No longer read: the OAuth state is a per-request nonce."},
|
||||
|
||||
{"name": "EMAIL_BACKEND", "group": "Email ingest", "purpose": "Mail source for the email pipeline", "kind": "enum", "options": ["graph", "imap"], "editable": true, "services": ["backend"]},
|
||||
{"name": "EMAIL_SYNC_ENABLED", "group": "Email ingest", "purpose": "Run the periodic email sync", "kind": "bool", "editable": true, "services": ["backend"]},
|
||||
{"name": "EMAIL_SYNC_INTERVAL", "group": "Email ingest", "purpose": "Time between syncs, as a Go duration such as 30m (default 30m)", "kind": "duration", "editable": true, "services": ["backend"]},
|
||||
{"name": "MSGRAPH_CLIENT_ID", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
|
||||
{"name": "MSGRAPH_CLIENT_SECRET", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
|
||||
{"name": "MSGRAPH_TENANT_ID", "group": "Email ingest", "purpose": "\"consumers\" for a personal outlook.com account", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "MSGRAPH_REDIRECT_URI", "group": "Email ingest", "purpose": "OAuth callback, behind the site's HTTPS origin", "kind": "url", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_HOST", "group": "Email ingest", "purpose": "IMAP fallback server", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_PORT", "group": "Email ingest", "purpose": "IMAP fallback port (993)", "kind": "number", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_EMAIL", "group": "Email ingest", "purpose": "IMAP fallback account", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_PASSWORD", "group": "Email ingest", "purpose": "App-specific password, not the account password", "kind": "secret", "editable": true, "services": ["backend"]},
|
||||
|
||||
{"name": "JOB_LEADS_ENABLED", "group": "Job leads", "purpose": "Run the periodic job-lead fetch; \"Check now\" on /cv/leads works either way", "kind": "bool", "editable": true, "services": ["backend"]},
|
||||
{"name": "JOB_LEADS_INTERVAL", "group": "Job leads", "purpose": "Time between fetches, as a Go duration such as 6h (default 6h)", "kind": "duration", "editable": true, "services": ["backend"]},
|
||||
{"name": "ADZUNA_APP_ID", "group": "Job leads", "purpose": "Adzuna job search, for adzuna lead sources", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://developer.adzuna.com/admin/access_details"},
|
||||
{"name": "ADZUNA_APP_KEY", "group": "Job leads", "purpose": "Adzuna job search, for adzuna lead sources", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://developer.adzuna.com/admin/access_details"},
|
||||
{"name": "REED_API_KEY", "group": "Job leads", "purpose": "Reed job search, for reed lead sources", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://www.reed.co.uk/developers/jobseeker"},
|
||||
|
||||
{"name": "ICECAST_SOURCE_PASSWORD", "group": "Radio", "purpose": "Liquidsoap to Icecast, and live broadcasters to the harbor port", "kind": "generated", "editable": true, "services": ["icecast2"], "warning": "Live broadcasting clients must be given the new password."},
|
||||
{"name": "ICECAST_RELAY_PASSWORD", "group": "Radio", "purpose": "Icecast relay clients", "kind": "generated", "editable": true, "services": ["icecast2"]},
|
||||
{"name": "ICECAST_ADMIN_USER", "group": "Radio", "purpose": "Icecast web admin login", "kind": "text", "editable": true, "services": ["icecast2"]},
|
||||
{"name": "ICECAST_ADMIN_PASSWORD", "group": "Radio", "purpose": "Icecast web admin login", "kind": "generated", "editable": true, "services": ["icecast2"]},
|
||||
|
||||
{"name": "BACKEND_SECRET", "group": "Backend", "purpose": "Signs the JWTs in the auth cookies", "kind": "generated", "editable": true, "services": ["backend"], "warning": "Rotating this logs everyone out, including you."},
|
||||
{"name": "SILVERBULLET_GIT_INTERVAL", "group": "Backend", "purpose": "Seconds between notes commit/push cycles (default 300)", "kind": "number", "editable": true, "services": ["silverbullet-git"]},
|
||||
|
||||
{"name": "DOMAIN", "group": "Infrastructure", "purpose": "Apex domain: TLS certificate, cookie domain, nginx server name", "kind": "text", "editable": false, "lockedReason": "Changing the domain needs a new certificate and a full restart."},
|
||||
{"name": "EMAIL", "group": "Infrastructure", "purpose": "Let's Encrypt account address", "kind": "text", "editable": false, "lockedReason": "Only read by certbot when it registers the account."},
|
||||
{"name": "OBSIDIAN_DIR", "group": "Infrastructure", "purpose": "Host path of the notes vault", "kind": "text", "editable": false, "lockedReason": "A bind-mount path: a wrong value stops the stack from starting."},
|
||||
{"name": "SEED_DB", "group": "Infrastructure", "purpose": "Development-only test data switch", "kind": "bool", "editable": false, "lockedReason": "Would inject test data into the live site."},
|
||||
{"name": "BACKEND_HOST", "group": "Infrastructure", "purpose": "Backend container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "BACKEND_PORT", "group": "Infrastructure", "purpose": "Backend listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "BACKEND_ENDPOINT", "group": "Infrastructure", "purpose": "URL prefix nginx mounts the API at", "kind": "text", "editable": false, "lockedReason": "The Vue app assumes /api."},
|
||||
{"name": "PYTHON_HOST", "group": "Infrastructure", "purpose": "Python container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "PYTHON_PORT", "group": "Infrastructure", "purpose": "Python listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "ICECAST_HOST", "group": "Infrastructure", "purpose": "Icecast container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "ICECAST_PORT", "group": "Infrastructure", "purpose": "Icecast listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "ICECAST_MOUNT", "group": "Infrastructure", "purpose": "Listener-facing stream mount", "kind": "text", "editable": false, "lockedReason": "The player and nginx both assume this mount."},
|
||||
{"name": "LIQUIDSOAP_HARBOR_MOUNT", "group": "Infrastructure", "purpose": "Live broadcast mount", "kind": "text", "editable": false, "lockedReason": "Broadcasting clients are configured against it."},
|
||||
{"name": "LIQUIDSOAP_HARBOR_PORT", "group": "Infrastructure", "purpose": "Live broadcast port, published to the host", "kind": "text", "editable": false, "lockedReason": "A published port: changing it needs the router and clients updated."},
|
||||
{"name": "SILVERBULLET_HOST", "group": "Infrastructure", "purpose": "Notes editor container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "SILVERBULLET_PORT", "group": "Infrastructure", "purpose": "Notes editor port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "SILVERBULLET_PUBLIC_HOST", "group": "Infrastructure", "purpose": "Public notes container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "SILVERBULLET_PUBLIC_PORT", "group": "Infrastructure", "purpose": "Public notes port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
|
||||
{"name": "POSTGRES_HOST", "group": "Database", "purpose": "Database container name", "kind": "text", "editable": false, "lockedReason": "Renames the database container."},
|
||||
{"name": "POSTGRES_PORT", "group": "Database", "purpose": "Database port", "kind": "text", "editable": false, "lockedReason": "Every client of the database assumes it."},
|
||||
{"name": "POSTGRES_USER", "group": "Database", "purpose": "Database role", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
|
||||
{"name": "POSTGRES_PASSWORD", "group": "Database", "purpose": "Database password", "kind": "secret", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
|
||||
{"name": "POSTGRES_DB", "group": "Database", "purpose": "Backend database name", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised."},
|
||||
{"name": "POSTGRES_GITEA_DB", "group": "Database", "purpose": "Gitea database name", "kind": "text", "editable": false, "lockedReason": "Created by hand on a fresh volume."},
|
||||
|
||||
{"name": "GITEA_HOST", "group": "Gitea", "purpose": "Gitea container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "GITEA_PORT", "group": "Gitea", "purpose": "Gitea HTTP port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "GITEA_INTERNAL_TOKEN", "group": "Gitea", "purpose": "Gitea internal API token", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_LFS_JWT_SECRET", "group": "Gitea", "purpose": "Gitea LFS token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_OAUTH2_JWT_SECRET", "group": "Gitea", "purpose": "Gitea OAuth2 token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_RUNNER_HOST", "group": "Gitea", "purpose": "Gitea URL the Actions runner registers against", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
|
||||
{"name": "GITEA_RUNNER_NAME", "group": "Gitea", "purpose": "Actions runner name", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
|
||||
{"name": "GITEA_RUNNER_REGISTRATION_TOKEN", "group": "Gitea", "purpose": "Single-use runner registration token", "kind": "secret", "editable": false, "lockedReason": "Single-use, and ignored once the runner is registered."}
|
||||
]
|
||||
@@ -0,0 +1,827 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// Job leads: the pipeline that finds postings, as opposed to tracking
|
||||
// applications. On a timer it polls every enabled models.JobSource
|
||||
// (job_sources.go), files what it has not seen before as a models.JobLead,
|
||||
// marks which leads pass a keyword pre-filter, and asks Claude — through the
|
||||
// Python service, like every Claude call — to score those against the
|
||||
// models.JobSearchProfile.
|
||||
//
|
||||
// Leads are a separate table from the tracker on purpose (see models.JobLead).
|
||||
// The one way a lead reaches the tracker is promotion, a deliberate click on
|
||||
// the leads page (graph/job_lead.resolvers.go), which goes through
|
||||
// UpsertJobApplication so it cannot duplicate a posting already captured.
|
||||
|
||||
// Lead states, stored in JobLead.State.
|
||||
const (
|
||||
LeadNew = "new"
|
||||
LeadDismissed = "dismissed"
|
||||
LeadPromoted = "promoted"
|
||||
)
|
||||
|
||||
const (
|
||||
// jobScorePath is internal in the same way as the other /internal/
|
||||
// routes: nginx refuses /py/internal/ and the route refuses anything
|
||||
// nginx forwarded.
|
||||
jobScorePath = "/internal/jobs/score"
|
||||
|
||||
// maxScoresPerRun bounds the Claude calls one Run can make, and so both
|
||||
// its cost and its length. A first poll of a few boards can match
|
||||
// hundreds of leads; the rest are picked up by later runs, newest first,
|
||||
// or all at once by ScoreAll. It is also ScoreAll's batch size.
|
||||
maxScoresPerRun = 40
|
||||
|
||||
// maxScoreAttempts caps how many times a lead Claude failed to score is
|
||||
// retried, for the same reason as maxEmailAttempts.
|
||||
maxScoreAttempts = 3
|
||||
|
||||
// maxRunDuration bounds a whole run. Generous: forty scores at a worst
|
||||
// case of two minutes each would exceed it, but a healthy call is a few
|
||||
// seconds, and a run that is cut short loses nothing — unscored leads are
|
||||
// simply still unscored next time.
|
||||
maxRunDuration = 20 * time.Minute
|
||||
|
||||
// maxScoreAllDuration bounds ScoreAll, which has no cap on the count. An
|
||||
// hour is several hundred leads at a few seconds each; whatever is left
|
||||
// when it runs out is picked up by pressing the button again.
|
||||
maxScoreAllDuration = time.Hour
|
||||
|
||||
// leadBatch sizes the IN lists and inserts, well inside Postgres's limit
|
||||
// of 65535 bound parameters per statement.
|
||||
leadBatch = 500
|
||||
)
|
||||
|
||||
// ErrLeadSyncRunning is returned by Run when another run holds the lock.
|
||||
var ErrLeadSyncRunning = errors.New("lead sync already in progress")
|
||||
|
||||
// JobLeadConfig configures the pipeline. The API keys are optional: a search
|
||||
// source whose key is missing reports that as its own error and the rest of
|
||||
// the run carries on.
|
||||
type JobLeadConfig struct {
|
||||
Enabled bool
|
||||
Interval time.Duration
|
||||
AdzunaAppID string
|
||||
AdzunaAppKey string
|
||||
ReedAPIKey string
|
||||
}
|
||||
|
||||
// JobLeadService owns the lead pipeline.
|
||||
type JobLeadService struct {
|
||||
Config *JobLeadConfig
|
||||
DB *gorm.DB
|
||||
// PythonURL is the Python service's base URL on the Docker network, the
|
||||
// same value as handlers.Store.PythonURL.
|
||||
PythonURL string
|
||||
// HTTPClient fetches the sources. Its timeout is per request, and has to
|
||||
// allow for a multi-megabyte board arriving over the Pi's connection.
|
||||
HTTPClient *http.Client
|
||||
|
||||
// mu is used with TryLock, as in EmailSyncService: a run requested while
|
||||
// another is going is refused, not queued.
|
||||
mu sync.Mutex
|
||||
|
||||
// statusMu guards the three fields below, which the leads page polls
|
||||
// while a run it started is in flight.
|
||||
statusMu sync.Mutex
|
||||
running bool
|
||||
lastRunAt *time.Time
|
||||
lastError string
|
||||
}
|
||||
|
||||
// LeadSyncStatus is what the leads page shows beside its "Check now" button.
|
||||
type LeadSyncStatus struct {
|
||||
Running bool
|
||||
// LastRunAt is when the most recent run finished; nil until one has, in
|
||||
// this process — it is not persisted, so a restart clears it.
|
||||
LastRunAt *time.Time
|
||||
// LastError is "" after a run in which nothing failed outright. One
|
||||
// source failing is not here; it is on that JobSource.
|
||||
LastError string
|
||||
}
|
||||
|
||||
// InitJobLeads builds the service. It makes no network or database calls.
|
||||
func InitJobLeads(config *JobLeadConfig, db *gorm.DB, pythonURL string) *JobLeadService {
|
||||
return &JobLeadService{
|
||||
Config: config,
|
||||
DB: db,
|
||||
PythonURL: pythonURL,
|
||||
HTTPClient: &http.Client{Timeout: 60 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// Status reports whether a run is in flight and how the last one ended.
|
||||
func (s *JobLeadService) Status() LeadSyncStatus {
|
||||
s.statusMu.Lock()
|
||||
defer s.statusMu.Unlock()
|
||||
return LeadSyncStatus{Running: s.running, LastRunAt: s.lastRunAt, LastError: s.lastError}
|
||||
}
|
||||
|
||||
// StartScheduler runs the pipeline on every tick until ctx is cancelled. It
|
||||
// is meant to be run in its own goroutine and returns straight away when
|
||||
// JOB_LEADS_ENABLED is not "true".
|
||||
//
|
||||
// Unlike the email scheduler it does not run at start-up: every deploy
|
||||
// restarts the backend, and a deploy should not spend forty Claude calls. The
|
||||
// first run is one interval in, or whenever "Check now" is pressed — which
|
||||
// works whether or not the scheduler is enabled.
|
||||
func (s *JobLeadService) StartScheduler(ctx context.Context) {
|
||||
if !s.Config.Enabled {
|
||||
log.Println("[JobLeads] Scheduler disabled; runs only on request")
|
||||
return
|
||||
}
|
||||
log.Printf("[JobLeads] Starting scheduler, interval: %s", s.Config.Interval)
|
||||
|
||||
ticker := time.NewTicker(s.Config.Interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("[JobLeads] Scheduler stopped")
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := s.Run(ctx); err != nil {
|
||||
log.Printf("[JobLeads] Run error: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LeadJob names one of the pipeline's three jobs, for RunInBackground.
|
||||
type LeadJob int
|
||||
|
||||
const (
|
||||
// LeadJobSync is Run: poll the sources, then score up to a cap.
|
||||
LeadJobSync LeadJob = iota
|
||||
// LeadJobScore is ScoreAll: score every unscored lead, polling nothing.
|
||||
LeadJobScore
|
||||
// LeadJobRescore is RescoreAll: score every inbox lead again.
|
||||
LeadJobRescore
|
||||
)
|
||||
|
||||
// RunInBackground starts a job and returns at once, reporting false when one
|
||||
// was already going. It backs the page's buttons — "Check now", "Score
|
||||
// unscored" and "Rescore all". Any of them can take minutes, far longer than
|
||||
// a request should be held open, so the page polls Status instead of waiting.
|
||||
func (s *JobLeadService) RunInBackground(job LeadJob) bool {
|
||||
if s.Status().Running {
|
||||
return false
|
||||
}
|
||||
run := s.Run
|
||||
switch job {
|
||||
case LeadJobScore:
|
||||
run = s.ScoreAll
|
||||
case LeadJobRescore:
|
||||
run = s.RescoreAll
|
||||
}
|
||||
go func() {
|
||||
// Not the request's context: the request is over long before this is.
|
||||
if err := run(context.Background()); err != nil && !errors.Is(err, ErrLeadSyncRunning) {
|
||||
log.Printf("[JobLeads] Manual run error: %v", err)
|
||||
}
|
||||
}()
|
||||
return true
|
||||
}
|
||||
|
||||
// Run is one pass of the pipeline: fetch, store, pre-filter, score.
|
||||
func (s *JobLeadService) Run(ctx context.Context) error {
|
||||
return s.exclusive(ctx, maxRunDuration, s.fetchAndScore)
|
||||
}
|
||||
|
||||
// ScoreAll scores every matched lead that has no score yet, without polling
|
||||
// any source. It exists because Run caps its scoring at maxScoresPerRun: after
|
||||
// a first poll of several boards, or after the profile was filled in late,
|
||||
// there is a backlog, and clearing it should not mean re-fetching every board
|
||||
// (and spending search-API quota) forty leads at a time.
|
||||
//
|
||||
// The pre-filter is re-applied first, so keywords edited since the last run
|
||||
// decide what gets scored. There is no cap on the count — the person pressed a
|
||||
// button that says "all" — only maxScoreAllDuration on the time.
|
||||
func (s *JobLeadService) ScoreAll(ctx context.Context) error {
|
||||
return s.scoreAll(ctx, false)
|
||||
}
|
||||
|
||||
// RescoreAll scores every matched lead in the inbox again, including the
|
||||
// ones that already have a score. It is for when what a score means has
|
||||
// changed: the profile was rewritten, or CLAUDE_MODEL was switched.
|
||||
//
|
||||
// Old scores are not wiped first. Each lead keeps the score it has until its
|
||||
// new one arrives, so the inbox stays sorted and readable while the job runs,
|
||||
// and a job that dies halfway (no API key, a restart) leaves every lead with
|
||||
// a score, some new and some old, rather than half of them blank. What is
|
||||
// left to do is told apart by ScoredAt: anything scored before this job
|
||||
// started is still due. Pressing the button again after a failure therefore
|
||||
// starts over rather than resuming, which costs calls but is never wrong.
|
||||
//
|
||||
// Leads that had used up their attempts get them back: a posting the old
|
||||
// model could not score may be fine on the new one.
|
||||
func (s *JobLeadService) RescoreAll(ctx context.Context) error {
|
||||
return s.scoreAll(ctx, true)
|
||||
}
|
||||
|
||||
func (s *JobLeadService) scoreAll(ctx context.Context, rescore bool) error {
|
||||
return s.exclusive(ctx, maxScoreAllDuration, func(ctx context.Context) error {
|
||||
profile, err := LoadJobSearchProfile(s.DB)
|
||||
if err != nil {
|
||||
return fmt.Errorf("loading the search profile: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(profile.Profile) == "" {
|
||||
return errors.New("the search profile is empty, so there is nothing to score against")
|
||||
}
|
||||
if err := s.refilter(newLeadFilter(profile)); err != nil {
|
||||
return fmt.Errorf("re-applying the filter: %w", err)
|
||||
}
|
||||
|
||||
var due *time.Time
|
||||
if rescore {
|
||||
started := time.Now()
|
||||
due = &started
|
||||
if err := s.DB.Model(&models.JobLead{}).
|
||||
Where("state = ? AND matched = ? AND score_attempts > 0", LeadNew, true).
|
||||
UpdateColumn("score_attempts", 0).Error; err != nil {
|
||||
return fmt.Errorf("resetting score attempts: %w", err)
|
||||
}
|
||||
log.Println("[JobLeads] Rescoring every inbox lead")
|
||||
} else {
|
||||
log.Println("[JobLeads] Scoring all unscored leads")
|
||||
}
|
||||
total := 0
|
||||
var failed []uint
|
||||
for {
|
||||
// Each pass takes the next batch. A lead that fails is skipped
|
||||
// for the rest of this job, so one press spends one attempt on
|
||||
// it, not all three — a passing Claude hiccup should not write a
|
||||
// lead off for good. That is also why the loop terminates: every
|
||||
// lead a pass looks at is either scored or added to `failed`.
|
||||
scored, tried, nowFailed, err := s.scoreLeads(ctx, profile, failed, due)
|
||||
total += scored
|
||||
failed = append(failed, nowFailed...)
|
||||
if err != nil || tried == 0 {
|
||||
log.Printf("[JobLeads] Scoring finished: %d scored", total)
|
||||
return err
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// exclusive runs work as the one pipeline job in flight, maintaining the
|
||||
// status the page polls. A second job requested meanwhile is refused.
|
||||
func (s *JobLeadService) exclusive(ctx context.Context, limit time.Duration, work func(context.Context) error) (err error) {
|
||||
if !s.mu.TryLock() {
|
||||
return ErrLeadSyncRunning
|
||||
}
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.statusMu.Lock()
|
||||
s.running = true
|
||||
s.statusMu.Unlock()
|
||||
|
||||
// Runs before the unlock above. It also absorbs a panic, turning it into
|
||||
// this job's error, so one malformed posting cannot take the backend down
|
||||
// or leave `running` stuck true.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("[JobLeads] PANIC recovered: %v", r)
|
||||
err = fmt.Errorf("internal error during the run")
|
||||
}
|
||||
now := time.Now()
|
||||
s.statusMu.Lock()
|
||||
s.running = false
|
||||
s.lastRunAt = &now
|
||||
s.lastError = ""
|
||||
if err != nil {
|
||||
s.lastError = err.Error()
|
||||
}
|
||||
s.statusMu.Unlock()
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, limit)
|
||||
defer cancel()
|
||||
return work(ctx)
|
||||
}
|
||||
|
||||
// fetchAndScore is the body of Run.
|
||||
func (s *JobLeadService) fetchAndScore(ctx context.Context) error {
|
||||
profile, err := LoadJobSearchProfile(s.DB)
|
||||
if err != nil {
|
||||
return fmt.Errorf("loading the search profile: %w", err)
|
||||
}
|
||||
filter := newLeadFilter(profile)
|
||||
|
||||
var sources []models.JobSource
|
||||
if err := s.DB.Where("enabled = ?", true).Order("id ASC").Find(&sources).Error; err != nil {
|
||||
return fmt.Errorf("loading sources: %w", err)
|
||||
}
|
||||
tracked, err := s.trackedURLs()
|
||||
if err != nil {
|
||||
return fmt.Errorf("loading tracked applications: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[JobLeads] Starting run over %d sources", len(sources))
|
||||
added := 0
|
||||
for _, src := range sources {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
jobs, fetchErr := s.fetchSource(ctx, src)
|
||||
var n int
|
||||
if fetchErr == nil {
|
||||
n, fetchErr = s.storeLeads(ctx, src, jobs, filter, tracked)
|
||||
added += n
|
||||
}
|
||||
s.recordPoll(src, len(jobs), fetchErr)
|
||||
}
|
||||
|
||||
if err := s.refilter(filter); err != nil {
|
||||
return fmt.Errorf("re-applying the filter: %w", err)
|
||||
}
|
||||
scored, _, _, err := s.scoreLeads(ctx, profile, nil, nil)
|
||||
log.Printf("[JobLeads] Run finished: %d new leads, %d scored", added, scored)
|
||||
return err
|
||||
}
|
||||
|
||||
// recordPoll writes a poll's outcome onto its source for the page to show.
|
||||
// Updates rather than Save, so a source edited on the page mid-run is not
|
||||
// overwritten with the copy this run loaded.
|
||||
func (s *JobLeadService) recordPoll(src models.JobSource, count int, fetchErr error) {
|
||||
now := time.Now()
|
||||
updates := map[string]any{"last_fetched_at": &now, "last_error": ""}
|
||||
if fetchErr != nil {
|
||||
log.Printf("[JobLeads] %s %q failed: %v", src.Kind, src.Label, fetchErr)
|
||||
updates["last_error"] = truncate(fetchErr.Error(), 300)
|
||||
} else {
|
||||
updates["last_count"] = count
|
||||
}
|
||||
if err := s.DB.Model(&models.JobSource{}).Where("id = ?", src.ID).Updates(updates).Error; err != nil {
|
||||
log.Printf("[JobLeads] Recording the poll of source %d failed: %v", src.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// trackedURLs maps the canonical URL of every live application that has one
|
||||
// to its id, so a fetched posting that is already in the tracker can be told
|
||||
// apart from a fresh lead.
|
||||
func (s *JobLeadService) trackedURLs() (map[string]uint, error) {
|
||||
var apps []models.JobApplication
|
||||
if err := s.DB.Select("id", "url").Where("url IS NOT NULL AND url <> ''").Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tracked := make(map[string]uint, len(apps))
|
||||
for _, app := range apps {
|
||||
if canonical, ok := CanonicalJobURL(*app.URL); ok {
|
||||
tracked[canonical] = app.ID
|
||||
}
|
||||
}
|
||||
return tracked, nil
|
||||
}
|
||||
|
||||
// storeLeads files the postings a source returned and reports how many were
|
||||
// new. A posting seen before only has its LastSeenAt moved: its state, score
|
||||
// and text are left exactly as they are, which is what keeps a dismissed
|
||||
// lead dismissed.
|
||||
func (s *JobLeadService) storeLeads(ctx context.Context, src models.JobSource, jobs []fetchedJob, filter leadFilter, tracked map[string]uint) (int, error) {
|
||||
now := time.Now()
|
||||
added := 0
|
||||
for start := 0; start < len(jobs); start += leadBatch {
|
||||
batch := jobs[start:min(start+leadBatch, len(jobs))]
|
||||
ids := make([]string, len(batch))
|
||||
for i, job := range batch {
|
||||
ids[i] = job.ExternalID
|
||||
}
|
||||
|
||||
var known []string
|
||||
if err := s.DB.Model(&models.JobLead{}).
|
||||
Where("source_kind = ? AND external_id IN ?", src.Kind, ids).
|
||||
Pluck("external_id", &known).Error; err != nil {
|
||||
return added, fmt.Errorf("looking up existing leads: %w", err)
|
||||
}
|
||||
if len(known) > 0 {
|
||||
if err := s.DB.Model(&models.JobLead{}).
|
||||
Where("source_kind = ? AND external_id IN ?", src.Kind, known).
|
||||
UpdateColumn("last_seen_at", now).Error; err != nil {
|
||||
return added, fmt.Errorf("updating existing leads: %w", err)
|
||||
}
|
||||
}
|
||||
seen := make(map[string]bool, len(known))
|
||||
for _, id := range known {
|
||||
seen[id] = true
|
||||
}
|
||||
|
||||
var fresh []models.JobLead
|
||||
for _, job := range batch {
|
||||
// `seen` also catches a posting listed twice in one response.
|
||||
if seen[job.ExternalID] {
|
||||
continue
|
||||
}
|
||||
seen[job.ExternalID] = true
|
||||
lead, ok := newLead(src, job, filter, tracked, now)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// The full text costs a request per job, so it is fetched only
|
||||
// for a lead that will be shown and scored. A failure leaves the
|
||||
// snippet in place rather than losing the lead.
|
||||
if job.detailID != "" && lead.Matched && lead.State == LeadNew {
|
||||
if full, err := s.fetchReedDescription(ctx, job.detailID); err == nil && full != "" {
|
||||
lead.Description = truncateRunes(full, maxLeadRunes)
|
||||
}
|
||||
}
|
||||
fresh = append(fresh, lead)
|
||||
}
|
||||
if len(fresh) == 0 {
|
||||
continue
|
||||
}
|
||||
// DoNothing covers the one way a row can appear between the lookup
|
||||
// above and this insert: a second search source of the same kind
|
||||
// returning the same advert. Runs themselves never overlap.
|
||||
result := s.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&fresh)
|
||||
if result.Error != nil {
|
||||
return added, fmt.Errorf("saving new leads: %w", result.Error)
|
||||
}
|
||||
added += int(result.RowsAffected)
|
||||
}
|
||||
return added, nil
|
||||
}
|
||||
|
||||
// newLead turns a fetched posting into the row to insert. ok is false for a
|
||||
// posting with no id, title or company, which could be neither deduplicated
|
||||
// nor promoted.
|
||||
//
|
||||
// A posting whose URL is already in the tracker is filed as promoted and
|
||||
// linked to that application: it still has to be a row, or the next poll
|
||||
// would consider it again, but it must not be offered in the inbox.
|
||||
func newLead(src models.JobSource, job fetchedJob, filter leadFilter, tracked map[string]uint, now time.Time) (models.JobLead, bool) {
|
||||
title := strings.TrimSpace(job.Title)
|
||||
company := strings.TrimSpace(job.Company)
|
||||
if job.ExternalID == "" || title == "" || company == "" {
|
||||
return models.JobLead{}, false
|
||||
}
|
||||
lead := models.JobLead{
|
||||
SourceID: src.ID,
|
||||
SourceKind: src.Kind,
|
||||
ExternalID: job.ExternalID,
|
||||
JobTitle: title,
|
||||
Company: company,
|
||||
Location: strings.TrimSpace(job.Location),
|
||||
URL: strings.TrimSpace(job.URL),
|
||||
Description: truncateRunes(job.Description, maxLeadRunes),
|
||||
PostedAt: job.PostedAt,
|
||||
LastSeenAt: now,
|
||||
State: LeadNew,
|
||||
}
|
||||
lead.Matched = filter.matches(lead.JobTitle, lead.Location)
|
||||
if canonical, ok := CanonicalJobURL(lead.URL); ok {
|
||||
lead.URL = canonical
|
||||
if appID, found := tracked[canonical]; found {
|
||||
lead.State = LeadPromoted
|
||||
lead.JobAppID = &appID
|
||||
}
|
||||
}
|
||||
return lead, true
|
||||
}
|
||||
|
||||
// refilter brings Matched up to date for every lead still in the inbox, so
|
||||
// that editing the keywords on the page takes effect on the next run instead
|
||||
// of only for postings found afterwards.
|
||||
func (s *JobLeadService) refilter(filter leadFilter) error {
|
||||
var leads []models.JobLead
|
||||
if err := s.DB.Select("id", "job_title", "location", "matched").
|
||||
Where("state = ?", LeadNew).Find(&leads).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var toMatch, toUnmatch []uint
|
||||
for _, lead := range leads {
|
||||
switch matched := filter.matches(lead.JobTitle, lead.Location); {
|
||||
case matched && !lead.Matched:
|
||||
toMatch = append(toMatch, lead.ID)
|
||||
case !matched && lead.Matched:
|
||||
toUnmatch = append(toUnmatch, lead.ID)
|
||||
}
|
||||
}
|
||||
for value, ids := range map[bool][]uint{true: toMatch, false: toUnmatch} {
|
||||
for start := 0; start < len(ids); start += leadBatch {
|
||||
if err := s.DB.Model(&models.JobLead{}).
|
||||
Where("id IN ?", ids[start:min(start+leadBatch, len(ids))]).
|
||||
UpdateColumn("matched", value).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PromoteJobLead adds a lead to the tracker as a saved application and marks
|
||||
// it promoted. It goes through UpsertJobApplication, so a posting that was
|
||||
// captured from the browser in the meantime is linked to, not duplicated —
|
||||
// the lead's text and score fill any fields that row was missing.
|
||||
//
|
||||
// Promoting twice is harmless: the second call finds the lead already
|
||||
// promoted and returns it.
|
||||
func PromoteJobLead(db *gorm.DB, id uint, now time.Time) (*models.JobLead, error) {
|
||||
var lead models.JobLead
|
||||
if err := db.First(&lead, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if lead.State == LeadPromoted && lead.JobAppID != nil {
|
||||
return &lead, nil
|
||||
}
|
||||
|
||||
app, _, err := UpsertJobApplication(db, JobCaptureInput{
|
||||
JobTitle: lead.JobTitle,
|
||||
Company: lead.Company,
|
||||
Location: lead.Location,
|
||||
URL: lead.URL,
|
||||
Status: "saved",
|
||||
Notes: leadNotes(&lead),
|
||||
Description: lead.Description,
|
||||
}, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lead.State = LeadPromoted
|
||||
lead.JobAppID = &app.ID
|
||||
if err := db.Model(&lead).Updates(map[string]any{"state": lead.State, "job_app_id": lead.JobAppID}).Error; err != nil {
|
||||
return nil, fmt.Errorf("marking the lead promoted: %w", err)
|
||||
}
|
||||
return &lead, nil
|
||||
}
|
||||
|
||||
// leadNotes is the line a promoted lead leaves in the application's notes, so
|
||||
// why it looked worth applying to is still there once the lead is forgotten.
|
||||
func leadNotes(lead *models.JobLead) string {
|
||||
if lead.Score == nil {
|
||||
return ""
|
||||
}
|
||||
note := fmt.Sprintf("Lead score %d/100", *lead.Score)
|
||||
if lead.ScoreReasons != nil && strings.TrimSpace(*lead.ScoreReasons) != "" {
|
||||
note += ": " + strings.TrimSpace(*lead.ScoreReasons)
|
||||
}
|
||||
return note
|
||||
}
|
||||
|
||||
// ValidateJobSource tidies a source's fields and reports the first thing
|
||||
// wrong with it, in words for the page. Which fields are required depends on
|
||||
// the kind; the ones a kind does not use are cleared so a source switched
|
||||
// from one kind to another does not carry the old kind's settings around.
|
||||
func ValidateJobSource(src *models.JobSource) error {
|
||||
src.Kind = strings.ToLower(strings.TrimSpace(src.Kind))
|
||||
src.Label = strings.TrimSpace(src.Label)
|
||||
src.Token = strings.TrimSpace(src.Token)
|
||||
src.Query = strings.TrimSpace(src.Query)
|
||||
src.Location = strings.TrimSpace(src.Location)
|
||||
|
||||
switch {
|
||||
case IsBoardSource(src.Kind):
|
||||
// The token goes into a URL path. Board slugs are letters, digits
|
||||
// and a little punctuation; anything else is a pasted URL or a typo.
|
||||
if src.Token == "" || strings.ContainsAny(src.Token, "/?#& ") {
|
||||
return fmt.Errorf("token must be the board's slug, e.g. the \"acme\" in boards.greenhouse.io/acme")
|
||||
}
|
||||
if src.Label == "" {
|
||||
return fmt.Errorf("label is required: it is the company name its leads are filed under")
|
||||
}
|
||||
src.Query, src.Location = "", ""
|
||||
case IsSearchSource(src.Kind):
|
||||
if src.Query == "" {
|
||||
return fmt.Errorf("query is required for a search source")
|
||||
}
|
||||
if src.Label == "" {
|
||||
src.Label = src.Query
|
||||
}
|
||||
src.Token = ""
|
||||
default:
|
||||
return fmt.Errorf("kind must be one of greenhouse, lever, ashby, adzuna, reed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Pre-filter
|
||||
|
||||
// leadFilter is the keyword test a lead must pass before it is shown or
|
||||
// costs a Claude call. It is intentionally crude and cheap: its job is to
|
||||
// throw out the obviously irrelevant ninety percent of a company board
|
||||
// (sales, legal, other countries), not to judge fit — that is the score.
|
||||
type leadFilter struct {
|
||||
include []string
|
||||
exclude []string
|
||||
locations []string
|
||||
}
|
||||
|
||||
func newLeadFilter(profile *models.JobSearchProfile) leadFilter {
|
||||
return leadFilter{
|
||||
include: splitKeywords(profile.IncludeKeywords),
|
||||
exclude: splitKeywords(profile.ExcludeKeywords),
|
||||
locations: splitKeywords(profile.Locations),
|
||||
}
|
||||
}
|
||||
|
||||
// splitKeywords reads a keyword list as the page stores it: one entry per
|
||||
// line, commas also accepted, case and surrounding space ignored.
|
||||
func splitKeywords(list string) []string {
|
||||
var out []string
|
||||
for _, entry := range strings.FieldsFunc(list, func(r rune) bool { return r == '\n' || r == ',' }) {
|
||||
if entry = strings.ToLower(strings.TrimSpace(entry)); entry != "" {
|
||||
out = append(out, entry)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// matches reports whether a posting passes. An empty list is no constraint,
|
||||
// so with nothing configured every lead matches.
|
||||
//
|
||||
// - the title must contain one of the include keywords, and none of the
|
||||
// exclude keywords, as whole words (see containsWord);
|
||||
// - the location must contain one of the wanted locations as a plain
|
||||
// substring ("london" finds "Cardiff, London or Remote (UK)"). A posting
|
||||
// that states no location passes: unknown is not the same as wrong.
|
||||
func (f leadFilter) matches(title, location string) bool {
|
||||
title = strings.ToLower(title)
|
||||
if len(f.include) > 0 && !containsAnyWord(title, f.include) {
|
||||
return false
|
||||
}
|
||||
if containsAnyWord(title, f.exclude) {
|
||||
return false
|
||||
}
|
||||
location = strings.ToLower(strings.TrimSpace(location))
|
||||
if len(f.locations) == 0 || location == "" {
|
||||
return true
|
||||
}
|
||||
for _, wanted := range f.locations {
|
||||
if strings.Contains(location, wanted) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func containsAnyWord(text string, words []string) bool {
|
||||
for _, word := range words {
|
||||
if containsWord(text, word) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// containsWord reports whether word occurs in text on word boundaries, with
|
||||
// an optional plural "s". Boundaries are what let "intern" be excluded
|
||||
// without also excluding "Internal Tools Engineer", and the plural is what
|
||||
// lets "engineer" find "Engineers". Both arguments are already lowercase.
|
||||
func containsWord(text, word string) bool {
|
||||
isWordRune := func(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) }
|
||||
for from := 0; ; {
|
||||
i := strings.Index(text[from:], word)
|
||||
if i < 0 {
|
||||
return false
|
||||
}
|
||||
start := from + i
|
||||
end := start + len(word)
|
||||
before := []rune(text[:start])
|
||||
after := []rune(strings.TrimPrefix(text[end:], "s"))
|
||||
if (len(before) == 0 || !isWordRune(before[len(before)-1])) &&
|
||||
(len(after) == 0 || !isWordRune(after[0])) {
|
||||
return true
|
||||
}
|
||||
from = start + 1
|
||||
}
|
||||
}
|
||||
|
||||
// Scoring
|
||||
|
||||
// LeadScore is the JSON contract for Claude's verdict on one lead: the body
|
||||
// of the Python service's reply (LeadScore in python/app/job_score.py).
|
||||
type LeadScore struct {
|
||||
Score int `json:"score"`
|
||||
Reasons string `json:"reasons"`
|
||||
}
|
||||
|
||||
// scoreRequest is the body of POST /internal/jobs/score; the field names are
|
||||
// JobScoreRequest's in python/app/main.py.
|
||||
type scoreRequest struct {
|
||||
Profile string `json:"profile"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location string `json:"location"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// scoreLeads asks Claude to score the matched leads that have no score yet,
|
||||
// newest first, up to maxScoresPerRun, leaving out the ids in skip. It reports
|
||||
// how many it scored, how many it tried, and which ones Claude failed on;
|
||||
// tried is zero once nothing is left to score, which is what ScoreAll loops
|
||||
// on.
|
||||
//
|
||||
// rescoreBefore, when set, widens "has no score yet" to "has no score from
|
||||
// this job": a lead whose score is older than that time is due again. Its old
|
||||
// score stays in place until the new one is saved, and through a failure.
|
||||
//
|
||||
// With no profile text there is nothing to score against, so it does nothing
|
||||
// — leads still arrive and can be read, they just carry no score.
|
||||
func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSearchProfile, skip []uint, rescoreBefore *time.Time) (scored, tried int, failed []uint, err error) {
|
||||
if strings.TrimSpace(profile.Profile) == "" {
|
||||
return 0, 0, nil, nil
|
||||
}
|
||||
query := s.DB.Where("state = ? AND matched = ? AND score_attempts < ?", LeadNew, true, maxScoreAttempts)
|
||||
if rescoreBefore == nil {
|
||||
query = query.Where("score IS NULL")
|
||||
} else {
|
||||
query = query.Where("(score IS NULL OR scored_at IS NULL OR scored_at < ?)", *rescoreBefore)
|
||||
}
|
||||
if len(skip) > 0 {
|
||||
query = query.Where("id NOT IN ?", skip)
|
||||
}
|
||||
var leads []models.JobLead
|
||||
if err := query.Order("created_at DESC, id DESC").Limit(maxScoresPerRun).Find(&leads).Error; err != nil {
|
||||
return 0, 0, nil, fmt.Errorf("loading leads to score: %w", err)
|
||||
}
|
||||
|
||||
for i := range leads {
|
||||
lead := &leads[i]
|
||||
result, err := s.scoreLead(ctx, profile.Profile, lead)
|
||||
tried++
|
||||
|
||||
var readErr *PythonError
|
||||
switch {
|
||||
case err == nil:
|
||||
reasons := strings.TrimSpace(result.Reasons)
|
||||
score := min(max(result.Score, 0), 100)
|
||||
if dbErr := s.DB.Model(lead).Updates(map[string]any{"score": score, "score_reasons": reasons, "scored_at": time.Now()}).Error; dbErr != nil {
|
||||
return scored, tried, failed, fmt.Errorf("saving a score: %w", dbErr)
|
||||
}
|
||||
scored++
|
||||
case errors.As(err, &readErr):
|
||||
// Claude answered badly for this posting. Count the attempt and
|
||||
// move on; maxScoreAttempts stops it being retried forever.
|
||||
log.Printf("[JobLeads] Scoring lead %d failed: %v", lead.ID, err)
|
||||
if dbErr := s.DB.Model(lead).UpdateColumn("score_attempts", gorm.Expr("score_attempts + 1")).Error; dbErr != nil {
|
||||
return scored, tried, failed, fmt.Errorf("recording a failed score: %w", dbErr)
|
||||
}
|
||||
failed = append(failed, lead.ID)
|
||||
case ctx.Err() != nil:
|
||||
// Out of time (or shut down) mid-call. Nothing is wrong with
|
||||
// scoring, so say what happened rather than "unavailable".
|
||||
return scored, tried, failed, errors.New("ran out of time before every lead was scored; run it again to continue")
|
||||
default:
|
||||
// Anything else is not about this lead: no API key, or the Python
|
||||
// service down. The next lead would fail the same way, so stop,
|
||||
// and spend no attempt on it.
|
||||
// The detail names internal addresses and goes to the log; the
|
||||
// returned error is shown on the leads page.
|
||||
log.Printf("[JobLeads] Scoring stopped at lead %d: %v", lead.ID, err)
|
||||
return scored, tried, failed, errors.New("scoring is unavailable: the Python service did not answer, or has no Claude key (see the backend log)")
|
||||
}
|
||||
}
|
||||
return scored, tried, failed, nil
|
||||
}
|
||||
|
||||
func (s *JobLeadService) scoreLead(ctx context.Context, profile string, lead *models.JobLead) (LeadScore, error) {
|
||||
return CallPython[LeadScore](ctx, s.PythonURL, jobScorePath, scoreRequest{
|
||||
Profile: truncateRunes(profile, maxProfileRunes),
|
||||
JobTitle: lead.JobTitle,
|
||||
Company: lead.Company,
|
||||
Location: lead.Location,
|
||||
Description: lead.Description,
|
||||
})
|
||||
}
|
||||
|
||||
// Search profile
|
||||
|
||||
// maxProfileRunes caps the profile text, both as stored and as sent. It
|
||||
// mirrors MAX_PROFILE_CHARS in python/app/job_score.py.
|
||||
const maxProfileRunes = 12_000
|
||||
|
||||
// jobSearchProfileID is the one row's id; see models.JobSearchProfile.
|
||||
const jobSearchProfileID = 1
|
||||
|
||||
// LoadJobSearchProfile returns the single profile row, creating it empty the
|
||||
// first time it is asked for.
|
||||
func LoadJobSearchProfile(db *gorm.DB) (*models.JobSearchProfile, error) {
|
||||
profile := models.JobSearchProfile{ID: jobSearchProfileID}
|
||||
if err := db.FirstOrCreate(&profile, models.JobSearchProfile{ID: jobSearchProfileID}).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &profile, nil
|
||||
}
|
||||
|
||||
// SaveJobSearchProfile stores an edited profile, bounding the free text.
|
||||
func SaveJobSearchProfile(db *gorm.DB, profile *models.JobSearchProfile) error {
|
||||
profile.ID = jobSearchProfileID
|
||||
profile.Profile = truncateRunes(strings.TrimSpace(profile.Profile), maxProfileRunes)
|
||||
profile.MinScore = min(max(profile.MinScore, 0), 100)
|
||||
return db.Save(profile).Error
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// The parts of the lead pipeline that need no database: the pre-filter, how a
|
||||
// fetched posting becomes a row, source validation, the note a promoted lead
|
||||
// leaves, and the scoring call. Storing, re-filtering and the scoring loop's
|
||||
// bookkeeping all run queries and are exercised in the dev stack instead.
|
||||
|
||||
func TestLeadFilter(t *testing.T) {
|
||||
filter := newLeadFilter(&models.JobSearchProfile{
|
||||
IncludeKeywords: "Engineer\ndeveloper, SRE",
|
||||
ExcludeKeywords: "intern\nsenior staff\nsales",
|
||||
Locations: "London\nremote",
|
||||
})
|
||||
cases := []struct {
|
||||
title, location string
|
||||
want bool
|
||||
}{
|
||||
{"Backend Engineer", "London, UK", true},
|
||||
{"Software Engineers (Platform)", "Remote - EMEA", true},
|
||||
{"SRE", "Cardiff, London or Remote (UK)", true},
|
||||
{"Engineering Manager", "London", false}, // "engineer" is not a whole word here
|
||||
{"Account Executive", "London", false},
|
||||
{"Engineer Intern", "London", false},
|
||||
{"Internal Tools Engineer", "London", true}, // "intern" must not catch "Internal"
|
||||
{"Senior Staff Engineer", "London", false},
|
||||
{"Sales Engineer", "London", false},
|
||||
{"Backend Engineer", "New York, NY", false},
|
||||
{"Backend Engineer", "", true}, // unknown location passes
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := filter.matches(c.title, c.location); got != c.want {
|
||||
t.Errorf("matches(%q, %q) = %v, want %v", c.title, c.location, got, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing configured: everything passes.
|
||||
if !newLeadFilter(&models.JobSearchProfile{}).matches("Chief Vibes Officer", "Mars") {
|
||||
t.Error("an empty filter should match everything")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainsWord(t *testing.T) {
|
||||
cases := []struct {
|
||||
text, word string
|
||||
want bool
|
||||
}{
|
||||
{"go developer", "go", true},
|
||||
{"golang developer", "go", false},
|
||||
{"c++ engineer", "c++", true},
|
||||
{"developers wanted", "developer", true},
|
||||
{"developerss", "developer", false},
|
||||
{"site reliability engineer (sre)", "sre", true},
|
||||
{"ingénieur logiciel", "nieur", false},
|
||||
{"", "go", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := containsWord(c.text, c.word); got != c.want {
|
||||
t.Errorf("containsWord(%q, %q) = %v, want %v", c.text, c.word, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewLead(t *testing.T) {
|
||||
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
|
||||
src := models.JobSource{ID: 7, Kind: SourceGreenhouse, Label: "Acme", Token: "acme"}
|
||||
filter := newLeadFilter(&models.JobSearchProfile{IncludeKeywords: "engineer"})
|
||||
tracked := map[string]uint{"https://boards.greenhouse.io/acme/jobs/2": 42}
|
||||
|
||||
t.Run("a fresh posting is a new, matched lead", func(t *testing.T) {
|
||||
lead, ok := newLead(src, fetchedJob{
|
||||
ExternalID: "acme/1", Title: " Backend Engineer ", Company: "Acme", Location: "London",
|
||||
URL: "https://boards.greenhouse.io/acme/jobs/1/?gh_src=abc", Description: "Text",
|
||||
}, filter, tracked, now)
|
||||
if !ok {
|
||||
t.Fatal("not ok")
|
||||
}
|
||||
if lead.State != LeadNew || !lead.Matched || lead.JobAppID != nil || lead.SourceID != 7 ||
|
||||
lead.SourceKind != SourceGreenhouse || lead.JobTitle != "Backend Engineer" || !lead.LastSeenAt.Equal(now) {
|
||||
t.Errorf("lead = %+v", lead)
|
||||
}
|
||||
// Stored canonical, so it is the same key the tracker would hold.
|
||||
if lead.URL != "https://boards.greenhouse.io/acme/jobs/1" {
|
||||
t.Errorf("url = %q", lead.URL)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a posting already in the tracker is filed as promoted", func(t *testing.T) {
|
||||
lead, ok := newLead(src, fetchedJob{
|
||||
ExternalID: "acme/2", Title: "Backend Engineer", Company: "Acme",
|
||||
URL: "https://boards.greenhouse.io/acme/jobs/2?utm_source=x",
|
||||
}, filter, tracked, now)
|
||||
if !ok || lead.State != LeadPromoted || lead.JobAppID == nil || *lead.JobAppID != 42 {
|
||||
t.Errorf("lead = %+v, ok = %v", lead, ok)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a posting that fails the filter is kept, unmatched", func(t *testing.T) {
|
||||
lead, ok := newLead(src, fetchedJob{ExternalID: "acme/3", Title: "Account Executive", Company: "Acme"}, filter, tracked, now)
|
||||
if !ok || lead.Matched || lead.State != LeadNew {
|
||||
t.Errorf("lead = %+v, ok = %v", lead, ok)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a posting with no id, title or company is dropped", func(t *testing.T) {
|
||||
for _, job := range []fetchedJob{
|
||||
{Title: "Engineer", Company: "Acme"},
|
||||
{ExternalID: "acme/4", Company: "Acme"},
|
||||
{ExternalID: "acme/5", Title: "Engineer", Company: " "},
|
||||
} {
|
||||
if _, ok := newLead(src, job, filter, tracked, now); ok {
|
||||
t.Errorf("%+v should be dropped", job)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a long description is cut on a rune boundary", func(t *testing.T) {
|
||||
lead, _ := newLead(src, fetchedJob{
|
||||
ExternalID: "acme/6", Title: "Engineer", Company: "Acme", Description: strings.Repeat("é", maxLeadRunes+10),
|
||||
}, filter, tracked, now)
|
||||
if got := len([]rune(lead.Description)); got != maxLeadRunes {
|
||||
t.Errorf("description is %d runes", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestValidateJobSource(t *testing.T) {
|
||||
ok := []struct {
|
||||
in models.JobSource
|
||||
want models.JobSource
|
||||
}{
|
||||
// Fields the kind does not use are cleared.
|
||||
{models.JobSource{Kind: " Greenhouse ", Label: " Acme ", Token: " acme ", Query: "stale"},
|
||||
models.JobSource{Kind: "greenhouse", Label: "Acme", Token: "acme"}},
|
||||
// A search's label defaults to its query.
|
||||
{models.JobSource{Kind: "reed", Query: "golang", Location: "London", Token: "stale"},
|
||||
models.JobSource{Kind: "reed", Label: "golang", Query: "golang", Location: "London"}},
|
||||
}
|
||||
for _, c := range ok {
|
||||
src := c.in
|
||||
if err := ValidateJobSource(&src); err != nil || src != c.want {
|
||||
t.Errorf("ValidateJobSource(%+v) = %+v, %v; want %+v", c.in, src, err, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
bad := []models.JobSource{
|
||||
{Kind: "monster", Label: "x", Query: "go"},
|
||||
{Kind: "lever", Label: "Acme"},
|
||||
{Kind: "lever", Label: "Acme", Token: "https://jobs.lever.co/acme"},
|
||||
{Kind: "ashby", Token: "acme"},
|
||||
{Kind: "adzuna", Label: "x"},
|
||||
}
|
||||
for _, src := range bad {
|
||||
if err := ValidateJobSource(&src); err == nil {
|
||||
t.Errorf("ValidateJobSource(%+v) should fail", src)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeadNotes(t *testing.T) {
|
||||
score := 82
|
||||
reasons := " Strong Go match; hybrid London. "
|
||||
if got := leadNotes(&models.JobLead{}); got != "" {
|
||||
t.Errorf("unscored lead notes = %q", got)
|
||||
}
|
||||
if got := leadNotes(&models.JobLead{Score: &score}); got != "Lead score 82/100" {
|
||||
t.Errorf("notes = %q", got)
|
||||
}
|
||||
if got := leadNotes(&models.JobLead{Score: &score, ScoreReasons: &reasons}); got != "Lead score 82/100: Strong Go match; hybrid London." {
|
||||
t.Errorf("notes = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScoreLeadRequestAndErrors(t *testing.T) {
|
||||
var path string
|
||||
var body map[string]any
|
||||
reply := func(w http.ResponseWriter) { w.Write([]byte(`{"score": 82, "reasons": "Strong match"}`)) }
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
reply(w)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
s := &JobLeadService{PythonURL: srv.URL}
|
||||
lead := &models.JobLead{JobTitle: "Engineer", Company: "Acme", Location: "London", Description: "Text"}
|
||||
|
||||
got, err := s.scoreLead(context.Background(), "Five years of Go", lead)
|
||||
if err != nil || got.Score != 82 || got.Reasons != "Strong match" {
|
||||
t.Fatalf("scoreLead = %+v, %v", got, err)
|
||||
}
|
||||
if path != "/internal/jobs/score" {
|
||||
t.Errorf("path = %q", path)
|
||||
}
|
||||
want := map[string]any{"profile": "Five years of Go", "jobTitle": "Engineer", "company": "Acme", "location": "London", "description": "Text"}
|
||||
for key, value := range want {
|
||||
if body[key] != value {
|
||||
t.Errorf("body[%q] = %v, want %v", key, body[key], value)
|
||||
}
|
||||
}
|
||||
if len(body) != len(want) {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
|
||||
// The two kinds of failure scoreLeads tells apart: Claude answering badly
|
||||
// for this posting (a PythonError, counted against the lead) and scoring
|
||||
// being unavailable altogether (anything else, which stops the run).
|
||||
var readErr *PythonError
|
||||
reply = func(w http.ResponseWriter) {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
w.Write([]byte(`{"detail": "failed to parse the score"}`))
|
||||
}
|
||||
if _, err := s.scoreLead(context.Background(), "p", lead); !errors.As(err, &readErr) {
|
||||
t.Errorf("a 502 should be a PythonError, got %v", err)
|
||||
}
|
||||
reply = func(w http.ResponseWriter) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
w.Write([]byte(`{"detail": "CLAUDE_API_KEY is not set"}`))
|
||||
}
|
||||
if _, err := s.scoreLead(context.Background(), "p", lead); err == nil || errors.As(err, &readErr) {
|
||||
t.Errorf("a 503 should be a plain error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeadSyncStatusStartsIdle(t *testing.T) {
|
||||
s := InitJobLeads(&JobLeadConfig{}, nil, "http://python:8000")
|
||||
if status := s.Status(); status.Running || status.LastRunAt != nil || status.LastError != "" {
|
||||
t.Errorf("status = %+v", status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// The job sources the lead fetcher (job_leads.go) polls: one function per
|
||||
// models.JobSource.Kind, each turning that source's JSON into the common
|
||||
// fetchedJob. Nothing here touches the database.
|
||||
//
|
||||
// The three board kinds are public, keyless endpoints that return a whole
|
||||
// company board, description included, in one response. Their shapes were
|
||||
// checked against live boards. The two search kinds need API keys and their
|
||||
// shapes are taken from the providers' documentation — if one of them starts
|
||||
// reporting zero results or a decode error, its struct here is the first
|
||||
// thing to compare against a real response.
|
||||
|
||||
// Source kinds. The strings are stored in JobSource.Kind and JobLead.SourceKind
|
||||
// and repeated in the leads page's kind picker (vue/src/views/CV/JobSources.vue).
|
||||
const (
|
||||
SourceGreenhouse = "greenhouse"
|
||||
SourceLever = "lever"
|
||||
SourceAshby = "ashby"
|
||||
SourceAdzuna = "adzuna"
|
||||
SourceReed = "reed"
|
||||
)
|
||||
|
||||
// IsBoardSource reports whether kind is one company's board, identified by a
|
||||
// token, rather than a keyword search.
|
||||
func IsBoardSource(kind string) bool {
|
||||
return kind == SourceGreenhouse || kind == SourceLever || kind == SourceAshby
|
||||
}
|
||||
|
||||
// IsSearchSource reports whether kind is a keyword search.
|
||||
func IsSearchSource(kind string) bool {
|
||||
return kind == SourceAdzuna || kind == SourceReed
|
||||
}
|
||||
|
||||
// Base URLs, variables so the tests can point each at a stub server.
|
||||
var (
|
||||
greenhouseBase = "https://boards-api.greenhouse.io"
|
||||
leverBase = "https://api.lever.co"
|
||||
ashbyBase = "https://api.ashbyhq.com"
|
||||
adzunaBase = "https://api.adzuna.com"
|
||||
reedBase = "https://www.reed.co.uk"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxSourceBody bounds one response. A large board with every description
|
||||
// inline runs to several megabytes (Palantir's Lever board is about six);
|
||||
// this is far above that and only there so a misbehaving endpoint cannot
|
||||
// fill the Pi's memory.
|
||||
maxSourceBody = 64 << 20
|
||||
|
||||
// searchPages × searchPageSize is how deep a keyword search is read on
|
||||
// each poll. Results are newest first and polls are hours apart, so the
|
||||
// first hundred is where anything new will be.
|
||||
searchPages = 2
|
||||
searchPageSize = 50
|
||||
|
||||
// adzunaMaxDaysOld keeps a search to recent adverts; older ones were seen
|
||||
// by an earlier poll or are not worth surfacing now.
|
||||
adzunaMaxDaysOld = 14
|
||||
|
||||
// maxLeadRunes caps a stored description. It mirrors MAX_DESCRIPTION_CHARS
|
||||
// in python/app/job_score.py, which rejects anything longer.
|
||||
maxLeadRunes = 40_000
|
||||
)
|
||||
|
||||
// fetchedJob is one posting as a source reported it, before it becomes a
|
||||
// models.JobLead.
|
||||
type fetchedJob struct {
|
||||
// ExternalID is unique within the source kind; see models.JobLead.
|
||||
ExternalID string
|
||||
Title string
|
||||
Company string
|
||||
Location string
|
||||
URL string
|
||||
Description string
|
||||
PostedAt *time.Time
|
||||
// detailID is set when Description is only a snippet and the full text is
|
||||
// one more request away (Reed). The fetcher makes that request only for
|
||||
// a new lead that passed the pre-filter.
|
||||
detailID string
|
||||
}
|
||||
|
||||
// fetchSource returns everything src currently lists.
|
||||
func (s *JobLeadService) fetchSource(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
|
||||
switch src.Kind {
|
||||
case SourceGreenhouse:
|
||||
return s.fetchGreenhouse(ctx, src)
|
||||
case SourceLever:
|
||||
return s.fetchLever(ctx, src)
|
||||
case SourceAshby:
|
||||
return s.fetchAshby(ctx, src)
|
||||
case SourceAdzuna:
|
||||
return s.fetchAdzuna(ctx, src)
|
||||
case SourceReed:
|
||||
return s.fetchReed(ctx, src)
|
||||
}
|
||||
return nil, fmt.Errorf("unknown source kind %q", src.Kind)
|
||||
}
|
||||
|
||||
// getJSON GETs target and decodes a 200 reply into out. basicUser, when set,
|
||||
// is sent as the username of HTTP basic auth with an empty password, which is
|
||||
// how Reed takes its API key.
|
||||
//
|
||||
// The error never includes the URL: Adzuna's carries the API key in its query
|
||||
// string, and this error is stored in JobSource.LastError and shown on the
|
||||
// page.
|
||||
func (s *JobLeadService) getJSON(ctx context.Context, target, basicUser string, out any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("building request")
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if basicUser != "" {
|
||||
req.SetBasicAuth(basicUser, "")
|
||||
}
|
||||
resp, err := s.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
// A *url.Error's message quotes the full URL; keep only its cause.
|
||||
if urlErr, ok := err.(*url.Error); ok {
|
||||
err = urlErr.Err
|
||||
}
|
||||
return fmt.Errorf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
switch {
|
||||
case resp.StatusCode == http.StatusNotFound:
|
||||
return fmt.Errorf("not found (404): check the board token")
|
||||
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
|
||||
return fmt.Errorf("refused (%d): check the API key", resp.StatusCode)
|
||||
case resp.StatusCode != http.StatusOK:
|
||||
return fmt.Errorf("source returned %d", resp.StatusCode)
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, maxSourceBody)).Decode(out); err != nil {
|
||||
return fmt.Errorf("unexpected response: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Greenhouse
|
||||
|
||||
type greenhouseBoard struct {
|
||||
Jobs []struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
AbsoluteURL string `json:"absolute_url"`
|
||||
// Content is HTML that has itself been entity-escaped ("<p>").
|
||||
Content string `json:"content"`
|
||||
FirstPublished string `json:"first_published"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
Location struct {
|
||||
Name string `json:"name"`
|
||||
} `json:"location"`
|
||||
} `json:"jobs"`
|
||||
}
|
||||
|
||||
func (s *JobLeadService) fetchGreenhouse(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
|
||||
var board greenhouseBoard
|
||||
target := fmt.Sprintf("%s/v1/boards/%s/jobs?content=true", greenhouseBase, url.PathEscape(src.Token))
|
||||
if err := s.getJSON(ctx, target, "", &board); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
jobs := make([]fetchedJob, 0, len(board.Jobs))
|
||||
for _, j := range board.Jobs {
|
||||
posted := j.FirstPublished
|
||||
if posted == "" {
|
||||
posted = j.UpdatedAt
|
||||
}
|
||||
jobs = append(jobs, fetchedJob{
|
||||
ExternalID: boardExternalID(src.Token, strconv.FormatInt(j.ID, 10)),
|
||||
Title: j.Title,
|
||||
Company: src.Label,
|
||||
Location: j.Location.Name,
|
||||
URL: j.AbsoluteURL,
|
||||
// Unescape once to get the HTML back; htmlToText handles the rest.
|
||||
Description: htmlToText(html.UnescapeString(j.Content)),
|
||||
PostedAt: parseTime(time.RFC3339, posted),
|
||||
})
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
// Lever
|
||||
|
||||
type leverPosting struct {
|
||||
ID string `json:"id"`
|
||||
Text string `json:"text"`
|
||||
HostedURL string `json:"hostedUrl"`
|
||||
CreatedAt int64 `json:"createdAt"` // Unix milliseconds
|
||||
Categories struct {
|
||||
Location string `json:"location"`
|
||||
} `json:"categories"`
|
||||
WorkplaceType string `json:"workplaceType"`
|
||||
DescriptionPlain string `json:"descriptionPlain"`
|
||||
AdditionalPlain string `json:"additionalPlain"`
|
||||
// Lists are the posting's headed bullet sections ("What you'll do"),
|
||||
// which descriptionPlain does not include.
|
||||
Lists []struct {
|
||||
Text string `json:"text"`
|
||||
Content string `json:"content"` // HTML <li> items
|
||||
} `json:"lists"`
|
||||
}
|
||||
|
||||
func (s *JobLeadService) fetchLever(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
|
||||
var postings []leverPosting
|
||||
target := fmt.Sprintf("%s/v0/postings/%s?mode=json", leverBase, url.PathEscape(src.Token))
|
||||
if err := s.getJSON(ctx, target, "", &postings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
jobs := make([]fetchedJob, 0, len(postings))
|
||||
for _, p := range postings {
|
||||
parts := []string{strings.TrimSpace(p.DescriptionPlain)}
|
||||
for _, list := range p.Lists {
|
||||
parts = append(parts, strings.TrimSpace(list.Text)+"\n"+htmlToText(list.Content))
|
||||
}
|
||||
parts = append(parts, strings.TrimSpace(p.AdditionalPlain))
|
||||
|
||||
var posted *time.Time
|
||||
if p.CreatedAt > 0 {
|
||||
t := time.UnixMilli(p.CreatedAt).UTC()
|
||||
posted = &t
|
||||
}
|
||||
jobs = append(jobs, fetchedJob{
|
||||
ExternalID: boardExternalID(src.Token, p.ID),
|
||||
Title: p.Text,
|
||||
Company: src.Label,
|
||||
Location: withWorkplace(p.Categories.Location, p.WorkplaceType),
|
||||
URL: p.HostedURL,
|
||||
Description: joinNonEmpty(parts, "\n\n"),
|
||||
PostedAt: posted,
|
||||
})
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
// Ashby
|
||||
|
||||
type ashbyBoard struct {
|
||||
Jobs []struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Location string `json:"location"`
|
||||
WorkplaceType string `json:"workplaceType"`
|
||||
PublishedAt string `json:"publishedAt"`
|
||||
IsListed bool `json:"isListed"`
|
||||
JobURL string `json:"jobUrl"`
|
||||
DescriptionPlain string `json:"descriptionPlain"`
|
||||
} `json:"jobs"`
|
||||
}
|
||||
|
||||
func (s *JobLeadService) fetchAshby(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
|
||||
var board ashbyBoard
|
||||
target := fmt.Sprintf("%s/posting-api/job-board/%s", ashbyBase, url.PathEscape(src.Token))
|
||||
if err := s.getJSON(ctx, target, "", &board); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
jobs := make([]fetchedJob, 0, len(board.Jobs))
|
||||
for _, j := range board.Jobs {
|
||||
// Unlisted postings are reachable by direct link only; the company
|
||||
// has chosen not to advertise them.
|
||||
if !j.IsListed {
|
||||
continue
|
||||
}
|
||||
jobs = append(jobs, fetchedJob{
|
||||
ExternalID: boardExternalID(src.Token, j.ID),
|
||||
Title: strings.TrimSpace(j.Title),
|
||||
Company: src.Label,
|
||||
Location: withWorkplace(j.Location, j.WorkplaceType),
|
||||
URL: j.JobURL,
|
||||
Description: strings.TrimSpace(j.DescriptionPlain),
|
||||
PostedAt: parseTime(time.RFC3339, j.PublishedAt),
|
||||
})
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
// Adzuna
|
||||
|
||||
type adzunaResults struct {
|
||||
Results []struct {
|
||||
// A string in the API, though it is all digits.
|
||||
ID json.Number `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"` // a snippet, about 500 characters
|
||||
RedirectURL string `json:"redirect_url"`
|
||||
Created string `json:"created"`
|
||||
Company struct {
|
||||
DisplayName string `json:"display_name"`
|
||||
} `json:"company"`
|
||||
Location struct {
|
||||
DisplayName string `json:"display_name"`
|
||||
} `json:"location"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
// fetchAdzuna runs one UK keyword search. Adzuna only ever returns a snippet
|
||||
// of the description and has no endpoint for the rest, so these leads are
|
||||
// scored on less text than the others.
|
||||
func (s *JobLeadService) fetchAdzuna(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
|
||||
if s.Config.AdzunaAppID == "" || s.Config.AdzunaAppKey == "" {
|
||||
return nil, fmt.Errorf("ADZUNA_APP_ID and ADZUNA_APP_KEY are not set")
|
||||
}
|
||||
var jobs []fetchedJob
|
||||
for page := 1; page <= searchPages; page++ {
|
||||
query := url.Values{
|
||||
"app_id": {s.Config.AdzunaAppID},
|
||||
"app_key": {s.Config.AdzunaAppKey},
|
||||
"what": {src.Query},
|
||||
"results_per_page": {strconv.Itoa(searchPageSize)},
|
||||
"max_days_old": {strconv.Itoa(adzunaMaxDaysOld)},
|
||||
"sort_by": {"date"},
|
||||
}
|
||||
if src.Location != "" {
|
||||
query.Set("where", src.Location)
|
||||
}
|
||||
var results adzunaResults
|
||||
target := fmt.Sprintf("%s/v1/api/jobs/gb/search/%d?%s", adzunaBase, page, query.Encode())
|
||||
if err := s.getJSON(ctx, target, "", &results); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range results.Results {
|
||||
jobs = append(jobs, fetchedJob{
|
||||
ExternalID: r.ID.String(),
|
||||
// Adzuna wraps the matched search terms in <strong>.
|
||||
Title: htmlToText(r.Title),
|
||||
Company: r.Company.DisplayName,
|
||||
Location: r.Location.DisplayName,
|
||||
URL: r.RedirectURL,
|
||||
Description: htmlToText(r.Description),
|
||||
PostedAt: parseTime(time.RFC3339, r.Created),
|
||||
})
|
||||
}
|
||||
if len(results.Results) < searchPageSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
// Reed
|
||||
|
||||
type reedResults struct {
|
||||
Results []struct {
|
||||
JobID int64 `json:"jobId"`
|
||||
EmployerName string `json:"employerName"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
LocationName string `json:"locationName"`
|
||||
Date string `json:"date"` // dd/mm/yyyy
|
||||
JobDescription string `json:"jobDescription"`
|
||||
JobURL string `json:"jobUrl"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
type reedDetail struct {
|
||||
JobDescription string `json:"jobDescription"` // HTML
|
||||
}
|
||||
|
||||
// fetchReed runs one keyword search. The search returns a snippet of each
|
||||
// description; the full text is fetchReedDescription, one request per job.
|
||||
func (s *JobLeadService) fetchReed(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
|
||||
if s.Config.ReedAPIKey == "" {
|
||||
return nil, fmt.Errorf("REED_API_KEY is not set")
|
||||
}
|
||||
var jobs []fetchedJob
|
||||
for page := 0; page < searchPages; page++ {
|
||||
query := url.Values{
|
||||
"keywords": {src.Query},
|
||||
"resultsToTake": {strconv.Itoa(searchPageSize)},
|
||||
"resultsToSkip": {strconv.Itoa(page * searchPageSize)},
|
||||
}
|
||||
if src.Location != "" {
|
||||
query.Set("locationName", src.Location)
|
||||
}
|
||||
var results reedResults
|
||||
target := fmt.Sprintf("%s/api/1.0/search?%s", reedBase, query.Encode())
|
||||
if err := s.getJSON(ctx, target, s.Config.ReedAPIKey, &results); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range results.Results {
|
||||
id := strconv.FormatInt(r.JobID, 10)
|
||||
jobs = append(jobs, fetchedJob{
|
||||
ExternalID: id,
|
||||
Title: r.JobTitle,
|
||||
Company: r.EmployerName,
|
||||
Location: r.LocationName,
|
||||
URL: r.JobURL,
|
||||
Description: htmlToText(r.JobDescription),
|
||||
PostedAt: parseTime("02/01/2006", r.Date),
|
||||
detailID: id,
|
||||
})
|
||||
}
|
||||
if len(results.Results) < searchPageSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
// fetchReedDescription returns the full text of one Reed advert.
|
||||
func (s *JobLeadService) fetchReedDescription(ctx context.Context, jobID string) (string, error) {
|
||||
var detail reedDetail
|
||||
target := fmt.Sprintf("%s/api/1.0/jobs/%s", reedBase, url.PathEscape(jobID))
|
||||
if err := s.getJSON(ctx, target, s.Config.ReedAPIKey, &detail); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return htmlToText(detail.JobDescription), nil
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
// boardExternalID namespaces a board's own job id with the board, because
|
||||
// ids are only unique within one company's board.
|
||||
func boardExternalID(token, id string) string {
|
||||
return strings.ToLower(strings.TrimSpace(token)) + "/" + id
|
||||
}
|
||||
|
||||
// withWorkplace appends a posting's remote/hybrid/on-site label to its
|
||||
// location, where the source reports one separately. The pre-filter matches
|
||||
// on the result, so "remote" in the wanted locations finds these.
|
||||
func withWorkplace(location, workplace string) string {
|
||||
location = strings.TrimSpace(location)
|
||||
workplace = strings.ToLower(strings.TrimSpace(workplace))
|
||||
if workplace == "" || workplace == "unspecified" || strings.Contains(strings.ToLower(location), workplace) {
|
||||
return location
|
||||
}
|
||||
if location == "" {
|
||||
return workplace
|
||||
}
|
||||
return location + " (" + workplace + ")"
|
||||
}
|
||||
|
||||
func joinNonEmpty(parts []string, sep string) string {
|
||||
kept := parts[:0:0]
|
||||
for _, p := range parts {
|
||||
if strings.TrimSpace(p) != "" {
|
||||
kept = append(kept, p)
|
||||
}
|
||||
}
|
||||
return strings.Join(kept, sep)
|
||||
}
|
||||
|
||||
// parseTime returns nil for a value that does not parse: a missing posting
|
||||
// date is not worth failing a fetch over.
|
||||
func parseTime(layout, value string) *time.Time {
|
||||
t, err := time.Parse(layout, strings.TrimSpace(value))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &t
|
||||
}
|
||||
|
||||
var (
|
||||
// Tags that end a line in rendered HTML. Replaced with a newline before
|
||||
// the rest are stripped, so paragraphs and bullets survive as lines.
|
||||
htmlBlockTag = regexp.MustCompile(`(?i)</?(p|div|br|li|ul|ol|h[1-6]|tr|section)\b[^>]*>`)
|
||||
htmlAnyTag = regexp.MustCompile(`<[^>]*>`)
|
||||
htmlSpaces = regexp.MustCompile(`[ \t\x{00a0}]+`)
|
||||
htmlBlankRuns = regexp.MustCompile(`\n[ \t]*(\n[ \t]*)+`)
|
||||
)
|
||||
|
||||
// htmlToText reduces a posting's HTML to readable plain text. Like
|
||||
// cleanEmailBody it is a regex strip, not a parser, which is enough for text
|
||||
// that is read by a person and by a language model and never rendered as
|
||||
// HTML. Unlike cleanEmailBody it keeps the whole text and its line structure.
|
||||
func htmlToText(content string) string {
|
||||
text := htmlBlockTag.ReplaceAllString(content, "\n")
|
||||
text = htmlAnyTag.ReplaceAllString(text, "")
|
||||
text = html.UnescapeString(text)
|
||||
text = htmlSpaces.ReplaceAllString(text, " ")
|
||||
text = htmlBlankRuns.ReplaceAllString(text, "\n\n")
|
||||
lines := strings.Split(text, "\n")
|
||||
for i, line := range lines {
|
||||
lines[i] = strings.TrimSpace(line)
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(lines, "\n"))
|
||||
}
|
||||
|
||||
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
|
||||
// is still valid UTF-8 for Postgres and for JSON.
|
||||
func truncateRunes(s string, max int) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= max {
|
||||
return s
|
||||
}
|
||||
return string(runes[:max])
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// The source fetchers, each against a stub server replying with a cut-down
|
||||
// copy of a real response (the board kinds) or of the documented shape (the
|
||||
// search kinds, which need API keys). What is under test is the request each
|
||||
// one makes and how its JSON becomes a fetchedJob.
|
||||
|
||||
// sourceStub points every source's base URL at one stub server for the test.
|
||||
func sourceStub(t *testing.T, config JobLeadConfig, handler http.HandlerFunc) *JobLeadService {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
for _, base := range []*string{&greenhouseBase, &leverBase, &ashbyBase, &adzunaBase, &reedBase} {
|
||||
old := *base
|
||||
*base = srv.URL
|
||||
t.Cleanup(func() { *base = old })
|
||||
}
|
||||
return &JobLeadService{Config: &config, HTTPClient: srv.Client()}
|
||||
}
|
||||
|
||||
func TestFetchGreenhouse(t *testing.T) {
|
||||
var path string
|
||||
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.RequestURI()
|
||||
w.Write([]byte(`{"jobs": [{
|
||||
"absolute_url": "https://job-boards.greenhouse.io/monzo/jobs/8143930",
|
||||
"location": {"name": "Cardiff, London or Remote (UK)"},
|
||||
"id": 8143930,
|
||||
"updated_at": "2026-09-25T05:17:09-04:00",
|
||||
"title": "Backend Engineer",
|
||||
"first_published": "2026-08-24T09:04:42-04:00",
|
||||
"content": "<div class="intro"><p><strong>About us</strong></p><ul><li>Go &amp; Kotlin</li><li>On-call</li></ul></div>"
|
||||
}], "meta": {"total": 1}}`))
|
||||
})
|
||||
|
||||
jobs, err := s.fetchGreenhouse(context.Background(), models.JobSource{Kind: SourceGreenhouse, Label: "Monzo", Token: "Monzo"})
|
||||
if err != nil {
|
||||
t.Fatalf("fetchGreenhouse: %v", err)
|
||||
}
|
||||
if path != "/v1/boards/Monzo/jobs?content=true" {
|
||||
t.Errorf("request = %q", path)
|
||||
}
|
||||
if len(jobs) != 1 {
|
||||
t.Fatalf("got %d jobs", len(jobs))
|
||||
}
|
||||
j := jobs[0]
|
||||
// The id is namespaced by the board, lowercased so "Monzo" and "monzo"
|
||||
// are one board.
|
||||
if j.ExternalID != "monzo/8143930" || j.Title != "Backend Engineer" || j.Company != "Monzo" ||
|
||||
j.Location != "Cardiff, London or Remote (UK)" || j.URL != "https://job-boards.greenhouse.io/monzo/jobs/8143930" {
|
||||
t.Errorf("job = %+v", j)
|
||||
}
|
||||
// Doubly escaped HTML comes out as plain lines.
|
||||
if j.Description != "About us\n\nGo & Kotlin\n\nOn-call" {
|
||||
t.Errorf("description = %q", j.Description)
|
||||
}
|
||||
if j.PostedAt == nil || j.PostedAt.UTC().Format("2006-01-02") != "2026-08-24" {
|
||||
t.Errorf("postedAt = %v", j.PostedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchLever(t *testing.T) {
|
||||
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.RequestURI() != "/v0/postings/acme?mode=json" {
|
||||
t.Errorf("request = %q", r.URL.RequestURI())
|
||||
}
|
||||
w.Write([]byte(`[{
|
||||
"additionalPlain": "We are an equal opportunity employer.",
|
||||
"categories": {"commitment": "Full-time", "location": "London, UK", "team": "Platform"},
|
||||
"createdAt": 1786469891368,
|
||||
"descriptionPlain": "A World-Changing Company\n",
|
||||
"id": "6ed76ce8-4156",
|
||||
"lists": [{"text": "What you'll do", "content": "<li>Build things</li><li>Run them</li>"}],
|
||||
"text": "Platform Engineer",
|
||||
"workplaceType": "hybrid",
|
||||
"hostedUrl": "https://jobs.lever.co/acme/6ed76ce8-4156"
|
||||
}]`))
|
||||
})
|
||||
|
||||
jobs, err := s.fetchLever(context.Background(), models.JobSource{Kind: SourceLever, Label: "Acme", Token: "acme"})
|
||||
if err != nil || len(jobs) != 1 {
|
||||
t.Fatalf("fetchLever: %v, %d jobs", err, len(jobs))
|
||||
}
|
||||
j := jobs[0]
|
||||
if j.ExternalID != "acme/6ed76ce8-4156" || j.Title != "Platform Engineer" || j.Location != "London, UK (hybrid)" {
|
||||
t.Errorf("job = %+v", j)
|
||||
}
|
||||
want := "A World-Changing Company\n\nWhat you'll do\nBuild things\n\nRun them\n\nWe are an equal opportunity employer."
|
||||
if j.Description != want {
|
||||
t.Errorf("description = %q\nwant %q", j.Description, want)
|
||||
}
|
||||
if j.PostedAt == nil || j.PostedAt.Year() != 2026 {
|
||||
t.Errorf("postedAt = %v", j.PostedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchAshbySkipsUnlisted(t *testing.T) {
|
||||
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/posting-api/job-board/ramp" {
|
||||
t.Errorf("path = %q", r.URL.Path)
|
||||
}
|
||||
w.Write([]byte(`{"apiVersion": "1", "jobs": [
|
||||
{"id": "34413f8d", "title": " Security Engineer, Cloud", "location": "London", "workplaceType": "Remote",
|
||||
"publishedAt": "2026-04-07T17:12:35.753+00:00", "isListed": true,
|
||||
"jobUrl": "https://jobs.ashbyhq.com/ramp/34413f8d", "descriptionPlain": "ABOUT RAMP\n\nRamp is building."},
|
||||
{"id": "hidden", "title": "Secret", "isListed": false, "jobUrl": "https://jobs.ashbyhq.com/ramp/hidden"}
|
||||
]}`))
|
||||
})
|
||||
|
||||
jobs, err := s.fetchAshby(context.Background(), models.JobSource{Kind: SourceAshby, Label: "Ramp", Token: "ramp"})
|
||||
if err != nil || len(jobs) != 1 {
|
||||
t.Fatalf("fetchAshby: %v, %d jobs", err, len(jobs))
|
||||
}
|
||||
j := jobs[0]
|
||||
if j.ExternalID != "ramp/34413f8d" || j.Title != "Security Engineer, Cloud" || j.Location != "London (remote)" ||
|
||||
j.Description != "ABOUT RAMP\n\nRamp is building." || j.PostedAt == nil {
|
||||
t.Errorf("job = %+v", j)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchAdzuna(t *testing.T) {
|
||||
var requests []string
|
||||
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "key1"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
requests = append(requests, r.URL.Path)
|
||||
q := r.URL.Query()
|
||||
if q.Get("app_id") != "id1" || q.Get("app_key") != "key1" || q.Get("what") != "golang" || q.Get("where") != "London" {
|
||||
t.Errorf("query = %v", q)
|
||||
}
|
||||
w.Write([]byte(`{"results": [{
|
||||
"id": "5012345678", "title": "<strong>Golang</strong> Developer",
|
||||
"description": "We need a <strong>Golang</strong> developer…",
|
||||
"redirect_url": "https://www.adzuna.co.uk/jobs/land/ad/5012345678?se=abc",
|
||||
"created": "2026-10-01T09:00:00Z",
|
||||
"company": {"display_name": "Acme Ltd"}, "location": {"display_name": "London, UK"}
|
||||
}]}`))
|
||||
})
|
||||
|
||||
jobs, err := s.fetchAdzuna(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "golang", Location: "London"})
|
||||
if err != nil || len(jobs) != 1 {
|
||||
t.Fatalf("fetchAdzuna: %v, %d jobs", err, len(jobs))
|
||||
}
|
||||
// A short page is the last page: no second request.
|
||||
if len(requests) != 1 || requests[0] != "/v1/api/jobs/gb/search/1" {
|
||||
t.Errorf("requests = %v", requests)
|
||||
}
|
||||
j := jobs[0]
|
||||
if j.ExternalID != "5012345678" || j.Title != "Golang Developer" || j.Company != "Acme Ltd" ||
|
||||
j.Description != "We need a Golang developer…" || j.detailID != "" {
|
||||
t.Errorf("job = %+v", j)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchReed(t *testing.T) {
|
||||
s := sourceStub(t, JobLeadConfig{ReedAPIKey: "reedkey"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
// The key is the basic-auth username, with an empty password.
|
||||
if user, pass, ok := r.BasicAuth(); !ok || user != "reedkey" || pass != "" {
|
||||
t.Errorf("basic auth = %q %q %v", user, pass, ok)
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/1.0/search":
|
||||
if q := r.URL.Query(); q.Get("keywords") != "golang" || q.Get("locationName") != "London" {
|
||||
t.Errorf("query = %v", q)
|
||||
}
|
||||
w.Write([]byte(`{"results": [{"jobId": 51234567, "employerName": "Acme", "jobTitle": "Go Engineer",
|
||||
"locationName": "London", "date": "03/10/2026", "jobDescription": "Snippet…",
|
||||
"jobUrl": "https://www.reed.co.uk/jobs/go-engineer/51234567"}], "totalResults": 1}`))
|
||||
case "/api/1.0/jobs/51234567":
|
||||
w.Write([]byte(`{"jobId": 51234567, "jobDescription": "<p>The full advert.</p><p>Second paragraph.</p>"}`))
|
||||
default:
|
||||
t.Errorf("unexpected path %q", r.URL.Path)
|
||||
}
|
||||
})
|
||||
|
||||
jobs, err := s.fetchReed(context.Background(), models.JobSource{Kind: SourceReed, Query: "golang", Location: "London"})
|
||||
if err != nil || len(jobs) != 1 {
|
||||
t.Fatalf("fetchReed: %v, %d jobs", err, len(jobs))
|
||||
}
|
||||
j := jobs[0]
|
||||
if j.ExternalID != "51234567" || j.Company != "Acme" || j.Description != "Snippet…" || j.detailID != "51234567" {
|
||||
t.Errorf("job = %+v", j)
|
||||
}
|
||||
if j.PostedAt == nil || j.PostedAt.Format("2006-01-02") != "2026-10-03" {
|
||||
t.Errorf("postedAt = %v", j.PostedAt)
|
||||
}
|
||||
|
||||
full, err := s.fetchReedDescription(context.Background(), j.detailID)
|
||||
if err != nil || full != "The full advert.\n\nSecond paragraph." {
|
||||
t.Errorf("fetchReedDescription = %q, %v", full, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchSourcesNeedTheirKeys(t *testing.T) {
|
||||
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("no request should be made without a key, got %s", r.URL.Path)
|
||||
})
|
||||
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"}); err == nil || !strings.Contains(err.Error(), "ADZUNA_APP_ID") {
|
||||
t.Errorf("adzuna err = %v", err)
|
||||
}
|
||||
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceReed, Query: "go"}); err == nil || !strings.Contains(err.Error(), "REED_API_KEY") {
|
||||
t.Errorf("reed err = %v", err)
|
||||
}
|
||||
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: "monster"}); err == nil {
|
||||
t.Error("an unknown kind should be an error")
|
||||
}
|
||||
}
|
||||
|
||||
// The error ends up in JobSource.LastError, on the page. It must say what to
|
||||
// fix and must never quote the request URL, which for Adzuna holds the key.
|
||||
func TestSourceErrorsAreSafeToShow(t *testing.T) {
|
||||
cases := []struct {
|
||||
status int
|
||||
want string
|
||||
}{
|
||||
{http.StatusNotFound, "check the board token"},
|
||||
{http.StatusUnauthorized, "check the API key"},
|
||||
{http.StatusInternalServerError, "source returned 500"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "sekrit"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
})
|
||||
_, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"})
|
||||
if err == nil || !strings.Contains(err.Error(), c.want) || strings.Contains(err.Error(), "sekrit") {
|
||||
t.Errorf("status %d: err = %v", c.status, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A connection failure is the case where net/http would quote the URL.
|
||||
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "sekrit"}, func(http.ResponseWriter, *http.Request) {})
|
||||
adzunaBase = "http://127.0.0.1:1"
|
||||
_, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"})
|
||||
if err == nil || strings.Contains(err.Error(), "sekrit") {
|
||||
t.Errorf("connection failure: err = %v", err)
|
||||
}
|
||||
|
||||
s = sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("<html>")) })
|
||||
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceLever, Token: "acme"}); err == nil || !strings.Contains(err.Error(), "unexpected response") {
|
||||
t.Errorf("non-JSON reply: err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTMLToText(t *testing.T) {
|
||||
cases := []struct{ in, want string }{
|
||||
{"<p>One</p><p>Two</p>", "One\n\nTwo"},
|
||||
{"<ul><li>a</li><li>b & c</li></ul>", "a\n\nb & c"},
|
||||
{"plain text here", "plain text here"},
|
||||
{"<span>inline</span> <b>tags</b> stay on a line", "inline tags stay on a line"},
|
||||
{"line<br>break<br/>twice", "line\nbreak\ntwice"},
|
||||
{"", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := htmlToText(c.in); got != c.want {
|
||||
t.Errorf("htmlToText(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithWorkplace(t *testing.T) {
|
||||
cases := []struct{ location, workplace, want string }{
|
||||
{"London", "Hybrid", "London (hybrid)"},
|
||||
{"Remote - UK", "remote", "Remote - UK"},
|
||||
{"", "Remote", "remote"},
|
||||
{"London", "", "London"},
|
||||
{"London", "unspecified", "London"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := withWorkplace(c.location, c.workplace); got != c.want {
|
||||
t.Errorf("withWorkplace(%q, %q) = %q, want %q", c.location, c.workplace, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
)
|
||||
|
||||
// The job-status vocabulary, as GraphQL sees it.
|
||||
//
|
||||
// The schema declares `enum JobStatus` (graph/schema/job_application.graphql)
|
||||
// and gqlgen.yml binds it to the two functions below instead of letting
|
||||
// gqlgen generate a Go enum type. That keeps models.JobApplication.Status a
|
||||
// plain string column — no migration, and the email pipeline and the capture
|
||||
// endpoint go on writing strings — while the GraphQL boundary still refuses a
|
||||
// status nobody ranked.
|
||||
//
|
||||
// statusOrder (email_sync.go) is the vocabulary; the enum in the schema has to
|
||||
// list the same values, and TestJobStatusEnumMatchesStatusOrder fails when
|
||||
// they differ. The functions live in this package, rather than in graph,
|
||||
// because this is where statusOrder is and graph already imports services.
|
||||
|
||||
// KnownStatus reports whether s is exactly one of the tracked statuses. No
|
||||
// trimming or case folding: see NormalizeStatus for the forgiving version the
|
||||
// email pipeline and the capture endpoint use on values that did not come
|
||||
// through GraphQL.
|
||||
func KnownStatus(s string) bool {
|
||||
_, ok := statusOrder[s]
|
||||
return ok
|
||||
}
|
||||
|
||||
// MarshalJobStatus writes a stored status to a GraphQL response.
|
||||
//
|
||||
// It is deliberately lenient, where the input side is strict. The column is
|
||||
// older than the enum, so a row can hold a status outside the vocabulary: the
|
||||
// tracker's early Title Case values ("Rejected"), or something written by
|
||||
// hand. A generated enum type would fail to serialise such a row, and because
|
||||
// JobApplication.status is non-null that one error would null out the whole
|
||||
// jobApplications list — one stale row hiding every application. So:
|
||||
//
|
||||
// - a value that is in the vocabulary once trimmed and lowered is emitted
|
||||
// in that canonical form, which also means an edit form sends back
|
||||
// something the input side accepts;
|
||||
// - anything else is emitted exactly as stored. That is not a legal
|
||||
// JobStatus, strictly, but the response is JSON and the tracker page
|
||||
// shows an unlisted status as-is so that it can be corrected, which is
|
||||
// more use than an error or a made-up substitute.
|
||||
//
|
||||
// The value is written with gqlgen's own String marshaller, so it is the same
|
||||
// quoted JSON string the field produced when it was declared String.
|
||||
func MarshalJobStatus(s string) graphql.Marshaler {
|
||||
if canonical := strings.ToLower(strings.TrimSpace(s)); KnownStatus(canonical) {
|
||||
s = canonical
|
||||
}
|
||||
return graphql.MarshalString(s)
|
||||
}
|
||||
|
||||
// UnmarshalJobStatus reads a status from a mutation's input, and is where
|
||||
// drift is refused: only the exact lowercase values are accepted, so nothing
|
||||
// outside the vocabulary can be written through GraphQL.
|
||||
//
|
||||
// The value arrives as a string whether the client sent a JSON string
|
||||
// variable ("applied", which is what the tracker page does) or wrote the enum
|
||||
// literal in the query document (applied).
|
||||
func UnmarshalJobStatus(v any) (string, error) {
|
||||
s, ok := v.(string)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("status must be a string")
|
||||
}
|
||||
if !KnownStatus(s) {
|
||||
return "", fmt.Errorf("%q is not a valid JobStatus", s)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/vektah/gqlparser/v2"
|
||||
"github.com/vektah/gqlparser/v2/ast"
|
||||
)
|
||||
|
||||
// jobStatusEnumValues reads `enum JobStatus` out of the schema file itself.
|
||||
// The test lives here, not in graph, because statusOrder is unexported and
|
||||
// graph imports this package; parsing the file directly avoids both an
|
||||
// export that exists only for a test and an import cycle.
|
||||
func jobStatusEnumValues(t *testing.T) []string {
|
||||
t.Helper()
|
||||
const path = "../graph/schema/job_application.graphql"
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("reading the schema: %v", err)
|
||||
}
|
||||
// The file extends Query and Mutation and uses Time and the two
|
||||
// authorisation directives, all declared in schema.graphql; give it just
|
||||
// enough of those to parse on its own.
|
||||
const prelude = "scalar Time\ndirective @admin on FIELD_DEFINITION\ndirective @signedIn on FIELD_DEFINITION\ntype Query\ntype Mutation\n"
|
||||
schema, gqlErr := gqlparser.LoadSchema(
|
||||
&ast.Source{Name: "prelude", Input: prelude},
|
||||
&ast.Source{Name: path, Input: string(raw)},
|
||||
)
|
||||
if gqlErr != nil {
|
||||
t.Fatalf("parsing the schema: %v", gqlErr)
|
||||
}
|
||||
def := schema.Types["JobStatus"]
|
||||
if def == nil || def.Kind != ast.Enum {
|
||||
t.Fatal("the schema has no `enum JobStatus`")
|
||||
}
|
||||
var values []string
|
||||
for _, v := range def.EnumValues {
|
||||
values = append(values, v.Name)
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
// One vocabulary, two places it has to be written down: the enum the GraphQL
|
||||
// API validates against and the map the email pipeline ranks with. A status
|
||||
// in the enum but not the map could be saved from the tracker and then never
|
||||
// advanced; one in the map but not the enum could be stored by the pipeline
|
||||
// and then not edited.
|
||||
func TestJobStatusEnumMatchesStatusOrder(t *testing.T) {
|
||||
enum := jobStatusEnumValues(t)
|
||||
var ranked []string
|
||||
for status := range statusOrder {
|
||||
ranked = append(ranked, status)
|
||||
}
|
||||
sort.Strings(ranked)
|
||||
|
||||
sorted := slices.Clone(enum)
|
||||
sort.Strings(sorted)
|
||||
if !slices.Equal(sorted, ranked) {
|
||||
t.Fatalf("enum JobStatus = %v\nstatusOrder = %v\nthe two must list the same statuses", sorted, ranked)
|
||||
}
|
||||
|
||||
// The schema lists them in lifecycle order, which is the order the
|
||||
// tracker shows; keep it agreeing with the ranks.
|
||||
for i, status := range enum {
|
||||
if statusOrder[status] != i {
|
||||
t.Errorf("enum lists %q at position %d but statusOrder ranks it %d", status, i, statusOrder[status])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The exact strings, spelled out once: these are what is stored in the
|
||||
// database and sent by the front end and the userscript, so a rename is a
|
||||
// data migration, not an edit.
|
||||
func TestJobStatusVocabulary(t *testing.T) {
|
||||
want := []string{"saved", "applied", "screening", "assessment", "interviewing", "offer", "rejected", "withdrawn"}
|
||||
if got := jobStatusEnumValues(t); !slices.Equal(got, want) {
|
||||
t.Fatalf("enum JobStatus = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalJobStatus(t *testing.T) {
|
||||
for status := range statusOrder {
|
||||
if got, err := UnmarshalJobStatus(status); err != nil || got != status {
|
||||
t.Errorf("UnmarshalJobStatus(%q) = %q, %v", status, got, err)
|
||||
}
|
||||
}
|
||||
// Strict on the way in: none of the forgiveness NormalizeStatus shows the
|
||||
// email pipeline. In particular nothing is coerced to "applied".
|
||||
for _, bad := range []any{"hired", "Applied", " applied", "", "on hold", 3, nil, true} {
|
||||
if got, err := UnmarshalJobStatus(bad); err == nil {
|
||||
t.Errorf("UnmarshalJobStatus(%#v) = %q, want an error", bad, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalJobStatus(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
stored string
|
||||
want string
|
||||
}{
|
||||
{"a tracked status is a quoted string, as when the field was a String", "interviewing", `"interviewing"`},
|
||||
{"the tracker's old Title Case rows read back canonical", "Rejected", `"rejected"`},
|
||||
{"stray whitespace is dropped for a tracked status", " offer ", `"offer"`},
|
||||
// The reason this is a custom marshaller: a generated enum type would
|
||||
// error here, and status is non-null, so one such row would null the
|
||||
// whole jobApplications list.
|
||||
{"an untracked status is passed through, not refused", "Interview", `"Interview"`},
|
||||
{"an untracked status is not rewritten to the default", "on hold", `"on hold"`},
|
||||
{"an empty status stays empty", "", `""`},
|
||||
{"quotes in a stray value are escaped", `a"b`, `"a\"b"`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
var b bytes.Buffer
|
||||
MarshalJobStatus(c.stored).MarshalGQL(&b)
|
||||
if b.String() != c.want {
|
||||
t.Fatalf("MarshalJobStatus(%q) wrote %s, want %s", c.stored, &b, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Adding a posting to the job tracker without making a second row for one
|
||||
// that is already there. Three callers share this: the browser capture
|
||||
// endpoint (handlers/handle_job_capture.go), promoting a discovered lead
|
||||
// (graph/job_lead.resolvers.go), and the lead fetcher (job_leads.go), which
|
||||
// uses the URL matching to keep a posting already tracked out of the inbox.
|
||||
// It lives in services because the fetcher does, and services cannot import
|
||||
// handlers.
|
||||
|
||||
// trackingParams are query parameters that say how the visitor arrived, not
|
||||
// which posting this is. Anything not listed is kept: ATS boards identify the
|
||||
// job in the query string often enough (gh_jid, jk, jobId) that dropping
|
||||
// unknown parameters would merge different postings.
|
||||
var trackingParams = map[string]bool{
|
||||
"trk": true, "trackingid": true, "refid": true, "ebp": true,
|
||||
"gh_src": true, "lever-source": true, "lever-origin": true,
|
||||
"source": true, "src": true, "ref": true,
|
||||
"fbclid": true, "gclid": true, "mc_cid": true, "mc_eid": true,
|
||||
}
|
||||
|
||||
// linkedInJobPath matches both forms of a LinkedIn posting path: the bare
|
||||
// /jobs/view/123 and the public slug form /jobs/view/some-title-at-co-123.
|
||||
var linkedInJobPath = regexp.MustCompile(`^/jobs/view/(?:.*-)?(\d+)/?$`)
|
||||
|
||||
// CanonicalJobURL reduces a posting URL to a form that is the same however
|
||||
// the page was reached, so it can serve as the key that decides whether a
|
||||
// posting is already tracked. ok is false for anything that is not an
|
||||
// absolute http(s) URL.
|
||||
//
|
||||
// LinkedIn gets its own rule because the same posting appears under several
|
||||
// paths (search results, collections, the recommended feed), all carrying the
|
||||
// id in ?currentJobId= rather than in the path.
|
||||
func CanonicalJobURL(raw string) (canonical string, ok bool) {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return "", false
|
||||
}
|
||||
host := strings.ToLower(u.Host)
|
||||
query := u.Query()
|
||||
|
||||
if host == "linkedin.com" || strings.HasSuffix(host, ".linkedin.com") {
|
||||
id := query.Get("currentJobId")
|
||||
if m := linkedInJobPath.FindStringSubmatch(u.Path); m != nil {
|
||||
id = m[1]
|
||||
}
|
||||
if id != "" && strings.Trim(id, "0123456789") == "" {
|
||||
return "https://www.linkedin.com/jobs/view/" + id + "/", true
|
||||
}
|
||||
}
|
||||
|
||||
for key := range query {
|
||||
lowered := strings.ToLower(key)
|
||||
if trackingParams[lowered] || strings.HasPrefix(lowered, "utm_") {
|
||||
query.Del(key)
|
||||
}
|
||||
}
|
||||
|
||||
out := url.URL{
|
||||
Scheme: u.Scheme,
|
||||
Host: host,
|
||||
// A trailing slash is not a different posting.
|
||||
Path: strings.TrimRight(u.Path, "/"),
|
||||
// Encode sorts by key, so parameter order does not matter either.
|
||||
RawQuery: query.Encode(),
|
||||
}
|
||||
return out.String(), true
|
||||
}
|
||||
|
||||
// FindApplicationByURL returns the newest live application stored under this posting's
|
||||
// URL, or nil. The raw form is tried as well as the canonical one because rows
|
||||
// typed into the tracker by hand hold whatever was pasted.
|
||||
func FindApplicationByURL(db *gorm.DB, canonical, raw string) (*models.JobApplication, error) {
|
||||
return firstApplication(db.Where("url IN ?", []string{canonical, strings.TrimSpace(raw)}))
|
||||
}
|
||||
|
||||
// firstApplication returns the newest row the query matches, or nil for none.
|
||||
// Limit(1).Find rather than First: a miss is the ordinary answer here (every
|
||||
// badge lookup on an untracked posting), and First reports one as
|
||||
// ErrRecordNotFound, which GORM writes to the log as an error each time.
|
||||
func firstApplication(query *gorm.DB) (*models.JobApplication, error) {
|
||||
var apps []models.JobApplication
|
||||
if err := query.Order("created_at DESC, id DESC").Limit(1).Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(apps) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return &apps[0], nil
|
||||
}
|
||||
|
||||
// JobCaptureInput is a posting to add to the tracker. Its JSON form is the
|
||||
// body of POST /jobs/capture: the popup's fields.
|
||||
type JobCaptureInput struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location string `json:"location"`
|
||||
URL string `json:"url"`
|
||||
Status string `json:"status"`
|
||||
Notes string `json:"notes"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func nonEmpty(p *string) bool { return p != nil && strings.TrimSpace(*p) != "" }
|
||||
|
||||
// MergeCapture folds a repeat capture into the application it matched and
|
||||
// reports whether anything changed.
|
||||
//
|
||||
// It only ever adds: the status moves forwards or not at all (the same rule
|
||||
// the email pipeline follows, so re-capturing a posting marked "saved" cannot
|
||||
// pull an interviewing application back), and a field already holding a value
|
||||
// is left alone, because the row may have been corrected by hand since. Title
|
||||
// and company are never touched — they are the key the email pipeline matches
|
||||
// on.
|
||||
func MergeCapture(app *models.JobApplication, in JobCaptureInput, now time.Time) bool {
|
||||
changed := false
|
||||
|
||||
if status := NormalizeStatus(in.Status); StatusAdvances(app.Status, status) {
|
||||
app.Status = status
|
||||
changed = true
|
||||
}
|
||||
// Saved-then-applied is the common path here, and the moment of the
|
||||
// second capture is the application date.
|
||||
if app.AppliedAt == nil && app.Status == "applied" {
|
||||
app.AppliedAt = &now
|
||||
changed = true
|
||||
}
|
||||
|
||||
fill := func(field **string, value string) {
|
||||
if value != "" && !nonEmpty(*field) {
|
||||
*field = &value
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
fill(&app.Location, in.Location)
|
||||
fill(&app.URL, in.URL)
|
||||
fill(&app.Description, in.Description)
|
||||
|
||||
// Notes accumulate, as they do when the pipeline updates a row, but a
|
||||
// repeat capture of the same page must not append the same line twice.
|
||||
if in.Notes != "" {
|
||||
switch {
|
||||
case !nonEmpty(app.Notes):
|
||||
app.Notes = &in.Notes
|
||||
changed = true
|
||||
case !strings.Contains(*app.Notes, in.Notes):
|
||||
combined := *app.Notes + "\n" + in.Notes
|
||||
app.Notes = &combined
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// JobInputError is a problem with the input itself (a missing title, a URL
|
||||
// that is not one), worded for the person who sent it. Anything else
|
||||
// UpsertJobApplication returns is a database failure and belongs in the log.
|
||||
type JobInputError struct{ msg string }
|
||||
|
||||
func (e *JobInputError) Error() string { return e.msg }
|
||||
|
||||
// UpsertJobApplication adds a posting to the tracker, or folds it into the
|
||||
// application it matches, and reports which: "created", "updated" or
|
||||
// "unchanged".
|
||||
//
|
||||
// The upsert matters beyond tidiness: the email pipeline identifies an
|
||||
// application by (company, job title), so two rows for one posting means the
|
||||
// confirmation email advances only one of them.
|
||||
//
|
||||
// Match order is the posting URL, then (company, job title) compared the way
|
||||
// the pipeline compares them. Only live rows match — unlike the pipeline's
|
||||
// lookup, which also sees deleted rows so that an email cannot resurrect one.
|
||||
// Capturing or promoting is a deliberate act, so doing it for a posting whose
|
||||
// row was deleted makes a new row.
|
||||
//
|
||||
// The caller bounds Description's length; everything else is trimmed here.
|
||||
func UpsertJobApplication(db *gorm.DB, input JobCaptureInput, now time.Time) (*models.JobApplication, string, error) {
|
||||
input.JobTitle = strings.TrimSpace(input.JobTitle)
|
||||
input.Company = strings.TrimSpace(input.Company)
|
||||
input.Location = strings.TrimSpace(input.Location)
|
||||
input.Notes = strings.TrimSpace(input.Notes)
|
||||
input.Description = strings.TrimSpace(input.Description)
|
||||
if input.JobTitle == "" || input.Company == "" {
|
||||
return nil, "", &JobInputError{"jobTitle and company are required"}
|
||||
}
|
||||
|
||||
rawURL := input.URL
|
||||
if strings.TrimSpace(rawURL) != "" {
|
||||
canonical, ok := CanonicalJobURL(rawURL)
|
||||
if !ok {
|
||||
return nil, "", &JobInputError{"url must be an absolute http(s) URL"}
|
||||
}
|
||||
input.URL = canonical
|
||||
} else {
|
||||
input.URL = ""
|
||||
}
|
||||
|
||||
var existing *models.JobApplication
|
||||
var err error
|
||||
if input.URL != "" {
|
||||
existing, err = FindApplicationByURL(db, input.URL, rawURL)
|
||||
}
|
||||
if err == nil && existing == nil {
|
||||
existing, err = firstApplication(db.Where(
|
||||
"LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", input.Company, input.JobTitle))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("looking up the application: %w", err)
|
||||
}
|
||||
|
||||
if existing != nil {
|
||||
if !MergeCapture(existing, input, now) {
|
||||
return existing, "unchanged", nil
|
||||
}
|
||||
if err := db.Save(existing).Error; err != nil {
|
||||
return nil, "", fmt.Errorf("updating the application: %w", err)
|
||||
}
|
||||
return existing, "updated", nil
|
||||
}
|
||||
|
||||
// A new row is the merge of the input into an empty application, which
|
||||
// keeps the two paths agreeing on what an empty field and "applied" mean.
|
||||
// The empty status counts as unknown, so any status takes over from it.
|
||||
app := models.JobApplication{JobTitle: input.JobTitle, Company: input.Company}
|
||||
MergeCapture(&app, input, now)
|
||||
if err := db.Create(&app).Error; err != nil {
|
||||
return nil, "", fmt.Errorf("creating the application: %w", err)
|
||||
}
|
||||
return &app, "created", nil
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
func TestCanonicalJobURL(t *testing.T) {
|
||||
const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/"
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want string // "" means rejected
|
||||
}{
|
||||
// One LinkedIn posting, reached four ways, must be one key.
|
||||
{"linkedin direct", "https://www.linkedin.com/jobs/view/4012345678/?trk=public_jobs", linkedIn},
|
||||
{"linkedin slug form", "https://uk.linkedin.com/jobs/view/backend-engineer-at-acme-4012345678?refId=abc", linkedIn},
|
||||
{"linkedin search pane", "https://www.linkedin.com/jobs/search/?currentJobId=4012345678&keywords=go", linkedIn},
|
||||
{"linkedin collections pane", "https://www.linkedin.com/jobs/collections/recommended/?currentJobId=4012345678", linkedIn},
|
||||
{"linkedin page with no job id is left as a normal URL", "https://www.linkedin.com/jobs/search/?keywords=go", "https://www.linkedin.com/jobs/search?keywords=go"},
|
||||
{"a non-numeric linkedin id is not trusted", "https://www.linkedin.com/jobs/search/?currentJobId=4/../x", "https://www.linkedin.com/jobs/search?currentJobId=4%2F..%2Fx"},
|
||||
{"a lookalike host does not get the linkedin rule", "https://notlinkedin.com/jobs/view/42", "https://notlinkedin.com/jobs/view/42"},
|
||||
|
||||
{"tracking parameters and the fragment are dropped", "https://jobs.lever.co/acme/abc-123?lever-source=LinkedIn&utm_medium=x#apply", "https://jobs.lever.co/acme/abc-123"},
|
||||
// gh_jid IS the posting on an embedded Greenhouse board.
|
||||
{"a parameter that identifies the job is kept", "https://acme.com/careers?gh_jid=77&gh_src=abc", "https://acme.com/careers?gh_jid=77"},
|
||||
{"parameter order does not matter", "https://x.com/job?b=2&a=1", "https://x.com/job?a=1&b=2"},
|
||||
{"host case and a trailing slash do not matter", "https://Boards.Greenhouse.io/acme/jobs/55/", "https://boards.greenhouse.io/acme/jobs/55"},
|
||||
|
||||
{"a relative path is rejected", "/jobs/view/1", ""},
|
||||
{"a non-http scheme is rejected", "javascript:alert(1)", ""},
|
||||
{"empty is rejected", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got, ok := CanonicalJobURL(c.in)
|
||||
if ok != (c.want != "") || got != c.want {
|
||||
t.Fatalf("CanonicalJobURL(%q) = %q, %v; want %q", c.in, got, ok, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func strPtr(s string) *string { return &s }
|
||||
|
||||
func TestMergeCapture(t *testing.T) {
|
||||
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
|
||||
earlier := now.Add(-48 * time.Hour)
|
||||
|
||||
t.Run("a new row takes every field and an applied date", func(t *testing.T) {
|
||||
app := models.JobApplication{JobTitle: "Engineer", Company: "Acme"}
|
||||
in := JobCaptureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Notes: "Hybrid", Description: "Full text"}
|
||||
if !MergeCapture(&app, in, now) {
|
||||
t.Fatal("expected a change")
|
||||
}
|
||||
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
|
||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
||||
}
|
||||
if *app.Location != "London" || *app.URL != "https://x.com/1" || *app.Notes != "Hybrid" || *app.Description != "Full text" {
|
||||
t.Fatalf("fields not filled: %+v", app)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a saved posting has no applied date", func(t *testing.T) {
|
||||
app := models.JobApplication{}
|
||||
MergeCapture(&app, JobCaptureInput{Status: "saved"}, now)
|
||||
if app.Status != "saved" || app.AppliedAt != nil {
|
||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("saved then applied advances and dates the application", func(t *testing.T) {
|
||||
app := models.JobApplication{Status: "saved"}
|
||||
if !MergeCapture(&app, JobCaptureInput{Status: "applied"}, now) {
|
||||
t.Fatal("expected a change")
|
||||
}
|
||||
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
|
||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a repeat capture cannot move an application backwards", func(t *testing.T) {
|
||||
app := models.JobApplication{Status: "interviewing", AppliedAt: &earlier}
|
||||
if MergeCapture(&app, JobCaptureInput{Status: "saved"}, now) {
|
||||
t.Fatal("expected no change")
|
||||
}
|
||||
if app.Status != "interviewing" || !app.AppliedAt.Equal(earlier) {
|
||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fields already set are kept, empty ones are filled", func(t *testing.T) {
|
||||
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Location: strPtr("Remote"), URL: strPtr("")}
|
||||
in := JobCaptureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Description: "Full text"}
|
||||
if !MergeCapture(&app, in, now) {
|
||||
t.Fatal("expected a change")
|
||||
}
|
||||
if *app.Location != "Remote" {
|
||||
t.Fatalf("location overwritten: %q", *app.Location)
|
||||
}
|
||||
if *app.URL != "https://x.com/1" || *app.Description != "Full text" {
|
||||
t.Fatalf("empty fields not filled: url=%q", *app.URL)
|
||||
}
|
||||
if !app.AppliedAt.Equal(earlier) {
|
||||
t.Fatal("an existing applied date must not be replaced")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("notes append once", func(t *testing.T) {
|
||||
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Notes: strPtr("Recruiter: Sam")}
|
||||
in := JobCaptureInput{Status: "applied", Notes: "Hybrid, £70k"}
|
||||
if !MergeCapture(&app, in, now) || *app.Notes != "Recruiter: Sam\nHybrid, £70k" {
|
||||
t.Fatalf("notes = %q", *app.Notes)
|
||||
}
|
||||
if MergeCapture(&app, in, now) {
|
||||
t.Fatalf("the same note was appended twice: %q", *app.Notes)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Every Claude call the site makes lives in the Python service, behind an
|
||||
// /internal/ route. This file is the one way the Go backend reaches those
|
||||
// routes: the rowing photo reader and the job posting reader (handlers), the
|
||||
// email classifier (email_sync.go) and the job lead scorer (job_leads.go). It sits in services rather than
|
||||
// handlers because both packages need it and handlers already imports
|
||||
// services, not the other way round.
|
||||
//
|
||||
// The routes are internal in a specific sense: nginx answers 404 for
|
||||
// /py/internal/, and each route itself refuses a request carrying a proxy
|
||||
// header, so the only way in is this direct container-to-container call. That
|
||||
// is why the request below sets nothing but Content-Type.
|
||||
|
||||
// pythonClient bounds the wait on the Python service. Two minutes sits above
|
||||
// that side's own worst case (a 30s Claude timeout, retried twice with
|
||||
// backoff), so a slow Claude surfaces as Python's error rather than as a
|
||||
// timeout here. One client for every route, so they share a connection pool.
|
||||
var pythonClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// PythonError is a failure the Python service reported in words that are safe
|
||||
// and useful to show a person: the string `detail` of a 502, which is always
|
||||
// one of that route's own fixed messages ("failed to parse image data", ...).
|
||||
//
|
||||
// Everything else — a refused connection, a 422, a 503 for a missing API key,
|
||||
// a reply that will not decode — comes back as an ordinary error instead. The
|
||||
// distinction is the point: a caller relays a PythonError and only logs the
|
||||
// rest, because the rest describe plumbing the user can do nothing about and
|
||||
// may quote internals.
|
||||
type PythonError struct{ Detail string }
|
||||
|
||||
func (e *PythonError) Error() string { return e.Detail }
|
||||
|
||||
// CallPython POSTs body as JSON to baseURL+path and decodes a 200 reply into
|
||||
// T. baseURL is the service's address on the Docker network with no trailing
|
||||
// slash (handlers.Store.PythonURL); path is the route, starting with a slash.
|
||||
//
|
||||
// Any non-200 is an error. See PythonError for which ones are relayable. A
|
||||
// cancelled ctx is wrapped, not replaced, so errors.Is(err, context.Canceled)
|
||||
// still holds — the email pipeline relies on that to tell an abandoned sync
|
||||
// from a failed email.
|
||||
func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T, error) {
|
||||
var out T
|
||||
|
||||
// Note for callers sending bytes: encoding/json writes a []byte as
|
||||
// standard base64, which is the form the Anthropic API wants and so what
|
||||
// the Python side passes straight through.
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("encoding request for %s: %w", path, err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+path, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := pythonClient.Do(req)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("calling %s: %w", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the
|
||||
// route's own fixed messages; a 422's detail is a list, which fails
|
||||
// to decode into the string and falls through to the generic error,
|
||||
// and a 503's detail names an environment variable, which is for the
|
||||
// log rather than the page. The body is capped because it is only
|
||||
// ever quoted in a log line.
|
||||
var failure struct {
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
|
||||
return out, &PythonError{Detail: failure.Detail}
|
||||
}
|
||||
return out, fmt.Errorf("%s returned %d: %s", path, resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
// A fresh zero value, so a half-decoded T never escapes with an error.
|
||||
var zero T
|
||||
return zero, fmt.Errorf("decoding %s response: %w", path, err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// CallPython is the one path from this backend to the Python service's
|
||||
// internal routes, so its contract is tested here once rather than per
|
||||
// caller: what the request looks like, and which replies come back as a
|
||||
// relayable *PythonError, which as a plain error.
|
||||
|
||||
type pythonReply struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
Note *string `json:"note"`
|
||||
}
|
||||
|
||||
func pythonStub(t *testing.T, handler http.HandlerFunc) string {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv.URL
|
||||
}
|
||||
|
||||
func TestCallPythonRequestAndReply(t *testing.T) {
|
||||
var (
|
||||
method, path, contentType string
|
||||
forwarded bool
|
||||
got map[string]any
|
||||
)
|
||||
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type")
|
||||
// The Python routes treat either header as "came through nginx" and
|
||||
// answer 404, so the helper must never send them.
|
||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"name": "x", "count": 3, "note": null}`))
|
||||
})
|
||||
|
||||
reply, err := CallPython[pythonReply](context.Background(), url, "/internal/thing", struct {
|
||||
Text string `json:"text"`
|
||||
Data []byte `json:"data"`
|
||||
}{"hello", []byte("hello")})
|
||||
if err != nil {
|
||||
t.Fatalf("CallPython: %v", err)
|
||||
}
|
||||
if reply.Name != "x" || reply.Count != 3 || reply.Note != nil {
|
||||
t.Fatalf("reply = %+v", reply)
|
||||
}
|
||||
if method != http.MethodPost || path != "/internal/thing" || contentType != "application/json" {
|
||||
t.Fatalf("request was %s %s (%s)", method, path, contentType)
|
||||
}
|
||||
if forwarded {
|
||||
t.Fatal("request carried a proxy header the Python routes reject")
|
||||
}
|
||||
// A []byte travels as standard base64, which is what the rowing reader
|
||||
// relies on for the image.
|
||||
if got["text"] != "hello" || got["data"] != "aGVsbG8=" {
|
||||
t.Fatalf("request body = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a *PythonError with this message
|
||||
}{
|
||||
{"a 502's string detail is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
|
||||
{"a 502 with an empty detail is not", http.StatusBadGateway, `{"detail": ""}`, ""},
|
||||
{"a 502 that is not JSON is not", http.StatusBadGateway, `<html>bad gateway</html>`, ""},
|
||||
// A 422's detail is a list of validation errors, not a message.
|
||||
{"a validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
// Its detail is a string, but it names an environment variable: for
|
||||
// the log, not for the page.
|
||||
{"a missing API key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"a 404 is not relayed", http.StatusNotFound, `{"detail": "Not Found"}`, ""},
|
||||
{"a malformed success body is an error", http.StatusOK, `not json`, ""},
|
||||
{"a success body of the wrong shape is an error", http.StatusOK, `{"count": "three"}`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
|
||||
reply, err := CallPython[pythonReply](context.Background(), url, "/internal/thing", struct{}{})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if reply != (pythonReply{}) {
|
||||
t.Fatalf("reply = %+v alongside an error, want the zero value", reply)
|
||||
}
|
||||
var pyErr *PythonError
|
||||
if relayed := errors.As(err, &pyErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if pyErr != nil && (pyErr.Detail != c.wantDetail || pyErr.Error() != c.wantDetail) {
|
||||
t.Fatalf("detail = %q, want %q", pyErr.Detail, c.wantDetail)
|
||||
}
|
||||
// A plumbing error names the route, so the log line says which
|
||||
// of the three calls it was.
|
||||
if pyErr == nil && !strings.Contains(err.Error(), "/internal/thing") {
|
||||
t.Fatalf("err = %v, want it to name the route", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonUnreachable(t *testing.T) {
|
||||
url := pythonStub(t, func(http.ResponseWriter, *http.Request) {})
|
||||
// Port 1 on localhost: nothing listens there.
|
||||
_, err := CallPython[pythonReply](context.Background(), "http://127.0.0.1:1", "/internal/thing", struct{}{})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var pyErr *PythonError
|
||||
if errors.As(err, &pyErr) {
|
||||
t.Fatalf("a transport failure was reported as relayable: %v", err)
|
||||
}
|
||||
|
||||
// A cancelled call must still read as context.Canceled: the email
|
||||
// pipeline uses that to avoid counting an abandoned sync as a failure.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := CallPython[pythonReply](ctx, url, "/internal/thing", struct{}{}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("err = %v, want it to wrap context.Canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonUnencodableBody(t *testing.T) {
|
||||
// Channels cannot be marshalled; the point is that this fails before any
|
||||
// request is made, so the URL is never dialled.
|
||||
if _, err := CallPython[pythonReply](context.Background(), "http://127.0.0.1:1", "/internal/thing", make(chan int)); err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
}
|
||||
@@ -70,5 +70,36 @@ func SeedDatabase(db *gorm.DB) {
|
||||
}
|
||||
db.Create(&rowingEntries)
|
||||
|
||||
// Job leads, so /cv/leads has something to show without a poll: the dev
|
||||
// stack usually has no Claude key, and the scheduler is off by default.
|
||||
// The sources are real public boards, so "Check now" works against them.
|
||||
db.Create(&models.JobSearchProfile{
|
||||
ID: jobSearchProfileID,
|
||||
Profile: "Five years of backend work in Go and Python. Looking for a mid-level or senior backend or platform role, in London or remote in the UK.",
|
||||
IncludeKeywords: "engineer\ndeveloper",
|
||||
ExcludeKeywords: "intern\nmanager",
|
||||
Locations: "london\nremote",
|
||||
MinScore: 60,
|
||||
})
|
||||
sources := []models.JobSource{
|
||||
{Kind: SourceGreenhouse, Label: "Monzo", Token: "monzo", Enabled: true},
|
||||
{Kind: SourceAshby, Label: "Ramp", Token: "ramp", Enabled: false},
|
||||
}
|
||||
db.Create(&sources)
|
||||
high, mid, low := 86, 64, 35
|
||||
highWhy := "Your Go and platform experience matches the core requirements; no payments background."
|
||||
midWhy := "Backend fit is good, but the role wants Kotlin, which your profile does not mention."
|
||||
lowWhy := "The role is a staff-level position leading several teams, above the level you are after."
|
||||
posted := now.AddDate(0, 0, -3)
|
||||
leads := []models.JobLead{
|
||||
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-1", JobTitle: "Backend Engineer, Platform", Company: "Monzo", Location: "London or Remote (UK)", URL: "https://example.com/jobs/1", Description: "We are looking for a backend engineer to join our platform team.\n\nYou will build and run Go services.", PostedAt: &posted, LastSeenAt: now, Matched: true, State: LeadNew, Score: &high, ScoreReasons: &highWhy},
|
||||
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-2", JobTitle: "Senior Backend Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/2", Description: "Kotlin services at scale.", LastSeenAt: now, Matched: true, State: LeadNew, Score: &mid, ScoreReasons: &midWhy},
|
||||
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-3", JobTitle: "Staff Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/3", LastSeenAt: now, Matched: true, State: LeadNew, Score: &low, ScoreReasons: &lowWhy},
|
||||
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-4", JobTitle: "Software Engineer, Data", Company: "Monzo", Location: "Remote (UK)", URL: "https://example.com/jobs/4", LastSeenAt: now, Matched: true, State: LeadNew},
|
||||
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-5", JobTitle: "Account Executive", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/5", LastSeenAt: now, Matched: false, State: LeadNew},
|
||||
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-6", JobTitle: "Android Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/6", LastSeenAt: now, Matched: true, State: LeadDismissed, Score: &low},
|
||||
}
|
||||
db.Create(&leads)
|
||||
|
||||
log.Println("Database seeded successfully")
|
||||
}
|
||||
|
||||
@@ -16,8 +16,6 @@ import (
|
||||
// - FetchLatestFeed: it is an HTTP call to the Gitea container. Its only
|
||||
// logic beyond the request is the empty-feed nil,nil case, and testing it
|
||||
// would mean either a network or an injected client that does not exist.
|
||||
// - claude.go: InitClaude is a single SDK constructor with no validation and
|
||||
// no prompt building; there is nothing to assert that is not the SDK's.
|
||||
// - The 1-minute Gitea cache TTL: it lives in handlers.Store, not here.
|
||||
// - RateLimiter's window expiry uses the real clock (Allow calls time.Now
|
||||
// directly and there is no injectable clock), so the expiry case below
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
# - 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.
|
||||
#
|
||||
@@ -68,10 +67,6 @@ services:
|
||||
ports:
|
||||
- 80:80
|
||||
- 443:443
|
||||
hasura:
|
||||
environment:
|
||||
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.
|
||||
|
||||
+19
-54
@@ -21,7 +21,7 @@
|
||||
# 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,
|
||||
# POSTGRES_GITEA_DB, BACKEND_HOST,
|
||||
# ICECAST_HOST, GITEA_HOST, OBSIDIAN_DIR, and the GITEA_*
|
||||
# secrets. PYTHON_HOST/PYTHON_PORT/TFL_APP_KEY/LIQUIDSOAP_HARBOR_PORT have
|
||||
# inline defaults.
|
||||
@@ -36,7 +36,7 @@
|
||||
# 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, silverbullet and python have no `ports:` — they are
|
||||
# why the backend, db, silverbullet and python have no `ports:` — they are
|
||||
# deliberately not exposed and are reached through nginx.
|
||||
# =============================================================================
|
||||
|
||||
@@ -111,7 +111,6 @@ services:
|
||||
- backend
|
||||
- icecast2
|
||||
- gitea
|
||||
- hasura
|
||||
- silverbullet
|
||||
- silverbullet-public
|
||||
- python
|
||||
@@ -177,6 +176,10 @@ services:
|
||||
# rebuild, forcing a manual re-authorisation of Spotify after each
|
||||
# deploy. Gitignored (it is a credential).
|
||||
- ./backend/token/:/backend/token
|
||||
# Hand-off directory for the admin panel's Environment tab: the backend
|
||||
# queues a change here and env-apply/apply.py on the host applies it.
|
||||
# The backend gets this instead of .env itself or the Docker socket.
|
||||
- ./env-apply/run:/backend/env-apply
|
||||
# The Obsidian vault on the host, read by the backend for the notes API.
|
||||
# Same directory is mounted read-write into silverbullet (the editor) and
|
||||
# read-only into silverbullet-public (the /notes/ site).
|
||||
@@ -187,9 +190,11 @@ services:
|
||||
# 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.
|
||||
# Reported to docker only: nothing acts on `unhealthy` since the autoheal
|
||||
# watchdog was retired (.deprecated/autoheal), so this just shows up in
|
||||
# `docker ps`. `restart: always` covers a crashed process, not a hung one.
|
||||
# start_period gives the Go process 10s to bind before failures start
|
||||
# counting.
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:8080/"]
|
||||
interval: 30s
|
||||
@@ -197,31 +202,6 @@ 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. Because of that the image is pinned BY DIGEST,
|
||||
# not by a floating tag: `:latest` meant any future push to Docker Hub would
|
||||
# silently gain root on the Pi at the next `docker compose pull`/`up`. The
|
||||
# digest below is a multi-arch index (it includes linux/arm64, which is what
|
||||
# the Pi pulls) and was the content of `willfarrell/autoheal:latest` at the
|
||||
# time of pinning. To bump it: pull the new tag, `docker image inspect
|
||||
# willfarrell/autoheal:<tag> --format '{{index .RepoDigests 0}}'`, and paste
|
||||
# the digest here — never go back to a bare tag.
|
||||
# Deliberately NOT on app-network: it talks only to the socket.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal@sha256:4ce976e9033b41426d44633295d6a08f9bc5929b27866352d91b31d4f6b26447
|
||||
container_name: autoheal
|
||||
restart: always
|
||||
environment:
|
||||
- AUTOHEAL_CONTAINER_LABEL=all
|
||||
- AUTOHEAL_INTERVAL=30
|
||||
- AUTOHEAL_START_PERIOD=60
|
||||
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;
|
||||
@@ -259,26 +239,6 @@ services:
|
||||
retries: 10
|
||||
start_period: 90s
|
||||
|
||||
# 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}"
|
||||
restart: always
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
|
||||
HASURA_GRAPHQL_ADMIN_SECRET: "${HASURA_GRAPHQL_ADMIN_SECRET}"
|
||||
HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
|
||||
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.
|
||||
@@ -389,7 +349,7 @@ services:
|
||||
SB_REVISIONS: disabled
|
||||
# Newline separated (commas are silently ignored). Gitignore semantics,
|
||||
# so these match at any depth. Must match the folder list in the
|
||||
# /notes/ deny regex in BOTH nginx templates, or a new entry here is
|
||||
# /notes/ deny regex in nginx/nginx_routes.conf.template, or a new entry here is
|
||||
# hidden from the list but still publicly fetchable.
|
||||
SB_SPACE_IGNORE: |
|
||||
private/
|
||||
@@ -438,8 +398,11 @@ services:
|
||||
# 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.
|
||||
# than `env_file: ./.env` — it only gets the variables it needs and never
|
||||
# sees the database password, Spotify secrets, or the other API keys.
|
||||
# CLAUDE_API_KEY is the one secret on the list: the rowing photo reader and
|
||||
# the job posting reader (POST /internal/rowing/read and /internal/jobs/extract,
|
||||
# called by the backend, blocked at nginx) make their Claude calls here.
|
||||
python:
|
||||
build:
|
||||
context: ./python
|
||||
@@ -452,6 +415,8 @@ services:
|
||||
- PYTHON_PORT=${PYTHON_PORT:-8000}
|
||||
- ROOT_PATH=/py
|
||||
- TFL_APP_KEY=${TFL_APP_KEY:-}
|
||||
- CLAUDE_API_KEY=${CLAUDE_API_KEY:-}
|
||||
- CLAUDE_MODEL=${CLAUDE_MODEL:-}
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,os; urllib.request.urlopen(f\"http://localhost:{os.environ.get('PYTHON_PORT','8000')}/health\")"]
|
||||
interval: 30s
|
||||
|
||||
Executable
+266
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env python3
|
||||
# =============================================================================
|
||||
# apply.py — the host half of the admin panel's Environment tab.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# Takes the change the backend queued in env-apply/run/request.json, merges
|
||||
# it into ./.env, recreates the containers that read the changed variables,
|
||||
# and reports the outcome in env-apply/run/status.json for the panel to show.
|
||||
#
|
||||
# WHY IT RUNS ON THE HOST
|
||||
# The backend is the internet-facing process. It is given neither write
|
||||
# access to .env nor the Docker socket, so the most a hijacked admin session
|
||||
# can do is ask for a change to a variable this script agrees is editable.
|
||||
# The list of those is backend/services/env_registry.json, read here from
|
||||
# the checkout — the same file the backend embeds.
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# On the Pi, started by the systemd path unit that install.sh sets up, the
|
||||
# moment request.json appears. By hand anywhere else:
|
||||
# python3 env-apply/apply.py
|
||||
# On a dev machine pass the compose files the stack was started with:
|
||||
# python3 env-apply/apply.py \
|
||||
# --compose-cmd "docker compose -f docker-compose.yml -f docker-compose.dev.yml"
|
||||
#
|
||||
# SAFETY
|
||||
# - The request is claimed by rename before anything else, so it is consumed
|
||||
# exactly once and its secrets leave the shared directory even on failure.
|
||||
# - .env is replaced atomically (temp file + rename) and the previous
|
||||
# version kept as .env.bak. If compose then rejects the file, the backup
|
||||
# is put back before anything is recreated.
|
||||
# - Only the services that read a changed variable are recreated (plus the
|
||||
# backend, whose own environment is what the panel reports). A plain
|
||||
# `docker compose up -d` would restart Postgres and nginx for any edit,
|
||||
# because they load the whole file too; the next deploy catches them up.
|
||||
# - An flock on run/lock keeps this from overlapping itself or the deploy
|
||||
# workflow, which takes the same lock.
|
||||
#
|
||||
# Standard library only: it has to run on a bare Raspberry Pi OS.
|
||||
# =============================================================================
|
||||
import argparse
|
||||
import datetime
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Values made only of these are written bare; anything else is single-quoted,
|
||||
# which dotenv reads literally (no $ interpolation, no # comments).
|
||||
BARE_VALUE = re.compile(r"^[A-Za-z0-9_./:@+,=-]*$")
|
||||
|
||||
# How much compose output a failed run reports back to the panel.
|
||||
OUTPUT_TAIL_LINES = 40
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def format_line(name, value):
|
||||
if BARE_VALUE.match(value):
|
||||
return f"{name}={value}"
|
||||
return f"{name}='{value}'"
|
||||
|
||||
|
||||
def merge(text, changes):
|
||||
"""Return .env text with each changed variable's line replaced in place.
|
||||
|
||||
Comments, blank lines and ordering are kept. A variable with no line yet
|
||||
is appended.
|
||||
"""
|
||||
remaining = dict(changes)
|
||||
out = []
|
||||
for line in text.splitlines():
|
||||
match = re.match(r"^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=", line)
|
||||
if match and match.group(2) in changes:
|
||||
name = match.group(2)
|
||||
out.append((match.group(1) or "") + format_line(name, changes[name]))
|
||||
remaining.pop(name, None)
|
||||
else:
|
||||
out.append(line)
|
||||
if remaining:
|
||||
if out and out[-1].strip():
|
||||
out.append("")
|
||||
out.append("# Added from the admin panel")
|
||||
for name in sorted(remaining):
|
||||
out.append(format_line(name, remaining[name]))
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def write_atomically(path, text):
|
||||
"""Replace path, keeping its mode and owner."""
|
||||
stat = os.stat(path)
|
||||
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".env.tmp.")
|
||||
try:
|
||||
with os.fdopen(fd, "w") as handle:
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.chmod(tmp, stat.st_mode & 0o7777)
|
||||
try:
|
||||
os.chown(tmp, stat.st_uid, stat.st_gid)
|
||||
except PermissionError:
|
||||
pass # not root and not the owner; the rename below still works
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
raise
|
||||
|
||||
|
||||
def load_registry(path):
|
||||
with open(path) as handle:
|
||||
return {entry["name"]: entry for entry in json.load(handle)}
|
||||
|
||||
|
||||
def check(changes, registry):
|
||||
"""Refuse anything the backend should never have asked for."""
|
||||
if not isinstance(changes, dict) or not changes:
|
||||
raise ValueError("the request changes nothing")
|
||||
for name, value in changes.items():
|
||||
entry = registry.get(name)
|
||||
if entry is None or not entry.get("editable"):
|
||||
raise ValueError(f"{name} is not editable")
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{name} is not a string")
|
||||
if "'" in value or any(ord(c) < 0x20 or ord(c) == 0x7F for c in value):
|
||||
raise ValueError(f"{name} holds a character .env cannot carry")
|
||||
|
||||
|
||||
def services_for(names, registry):
|
||||
services = {"backend"}
|
||||
for name in names:
|
||||
services.update(registry[name].get("services", []))
|
||||
return sorted(services)
|
||||
|
||||
|
||||
def run(cmd, cwd):
|
||||
result = subprocess.run(
|
||||
cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
|
||||
)
|
||||
return result.returncode, result.stdout
|
||||
|
||||
|
||||
def tail(text):
|
||||
return "\n".join(text.strip().splitlines()[-OUTPUT_TAIL_LINES:])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--env-file", default=os.path.join(ROOT, ".env"))
|
||||
parser.add_argument("--run-dir", default=os.path.join(ROOT, "env-apply", "run"))
|
||||
parser.add_argument(
|
||||
"--registry",
|
||||
default=os.path.join(ROOT, "backend", "services", "env_registry.json"),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--compose-cmd",
|
||||
default="docker compose",
|
||||
help="compose invocation, e.g. to add -f files for a dev stack",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="report what would change and leave everything untouched",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
compose = shlex.split(args.compose_cmd)
|
||||
compose_dir = os.path.dirname(os.path.abspath(args.env_file))
|
||||
request_path = os.path.join(args.run_dir, "request.json")
|
||||
claimed_path = os.path.join(args.run_dir, "request.claimed")
|
||||
status_path = os.path.join(args.run_dir, "status.json")
|
||||
backup_path = args.env_file + ".bak"
|
||||
|
||||
def report(state, request_id, **extra):
|
||||
body = {"state": state, "id": request_id, "at": now(), **extra}
|
||||
tmp = status_path + ".tmp"
|
||||
with open(tmp, "w") as handle:
|
||||
json.dump(body, handle)
|
||||
os.chmod(tmp, 0o644)
|
||||
os.replace(tmp, status_path)
|
||||
|
||||
if args.dry_run:
|
||||
if not os.path.exists(request_path):
|
||||
print("No request pending.")
|
||||
return 0
|
||||
with open(request_path) as handle:
|
||||
request = json.load(handle)
|
||||
registry = load_registry(args.registry)
|
||||
check(request.get("set"), registry)
|
||||
names = sorted(request["set"])
|
||||
print("Would set:", ", ".join(names))
|
||||
print("Would recreate:", ", ".join(services_for(names, registry)))
|
||||
return 0
|
||||
|
||||
with open(os.path.join(args.run_dir, "lock"), "w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
|
||||
# Claim first: after this rename the request cannot be applied twice,
|
||||
# and a crash below leaves no secrets where the backend can read them.
|
||||
try:
|
||||
os.replace(request_path, claimed_path)
|
||||
except FileNotFoundError:
|
||||
print("No request pending.")
|
||||
return 0
|
||||
try:
|
||||
with open(claimed_path) as handle:
|
||||
request = json.load(handle)
|
||||
finally:
|
||||
os.unlink(claimed_path)
|
||||
|
||||
request_id = str(request.get("id", ""))
|
||||
try:
|
||||
registry = load_registry(args.registry)
|
||||
changes = request.get("set")
|
||||
check(changes, registry)
|
||||
names = sorted(changes)
|
||||
services = services_for(names, registry)
|
||||
report("applying", request_id, changed=names, services=services)
|
||||
|
||||
with open(args.env_file) as handle:
|
||||
before = handle.read()
|
||||
shutil.copy2(args.env_file, backup_path)
|
||||
os.chmod(backup_path, 0o600)
|
||||
write_atomically(args.env_file, merge(before, changes))
|
||||
|
||||
# Catch a file compose cannot parse before any container is
|
||||
# stopped for it.
|
||||
code, output = run(compose + ["config", "-q"], compose_dir)
|
||||
if code != 0:
|
||||
write_atomically(args.env_file, before)
|
||||
raise RuntimeError(
|
||||
"compose rejected the new .env; it was restored.\n" + tail(output)
|
||||
)
|
||||
|
||||
code, output = run(
|
||||
compose + ["up", "-d", "--no-deps", "--force-recreate"] + services,
|
||||
compose_dir,
|
||||
)
|
||||
if code != 0:
|
||||
# .env keeps the new values: they are valid, and the usual
|
||||
# cause here is a container that would not start, which the
|
||||
# old values would not fix.
|
||||
raise RuntimeError(
|
||||
".env was updated but recreating the containers failed.\n"
|
||||
+ tail(output)
|
||||
)
|
||||
except Exception as error: # noqa: BLE001 - everything is reported
|
||||
report("failed", request_id, output=str(error))
|
||||
print(f"Failed: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
report("applied", request_id, changed=names, services=services)
|
||||
print(f"Applied {', '.join(names)}; recreated {', '.join(services)}.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# install.sh — one-time setup, on the Pi, of the watcher behind the admin
|
||||
# panel's Environment tab.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# Installs two systemd units:
|
||||
# web-server-env-apply.path watches env-apply/run/request.json
|
||||
# web-server-env-apply.service runs apply.py when that file appears
|
||||
# The units are generated here rather than committed because they need this
|
||||
# checkout's absolute path and the user that owns it.
|
||||
#
|
||||
# HOW TO RUN
|
||||
# From the deploy checkout, as the user that runs docker compose there:
|
||||
# ./env-apply/install.sh
|
||||
# It calls sudo for the three steps that need root. Re-running is safe and
|
||||
# is how to pick up a change to the units below.
|
||||
#
|
||||
# WHY A PATH UNIT
|
||||
# PathExists fires as soon as the backend writes the request, and also at
|
||||
# boot if a request was queued while the Pi was down. apply.py renames the
|
||||
# request away before doing anything else, so the unit cannot retrigger on
|
||||
# the same file.
|
||||
#
|
||||
# The service runs as the checkout's owner, not root: it needs exactly what
|
||||
# the deploy workflow has (write .env, run docker compose) and no more.
|
||||
# DOCKER_API_VERSION and COMPOSE_BAKE mirror .gitea/workflows/deploy.yaml.
|
||||
# =============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
RUN_USER="$(id -un)"
|
||||
RUN_DIR="${ROOT}/env-apply/run"
|
||||
|
||||
if [ "$RUN_USER" = "root" ]; then
|
||||
echo "Run this as the user that owns the checkout, not root." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! command -v python3 >/dev/null; then
|
||||
echo "python3 is required." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The backend bind-mounts this directory. If Docker creates it first it is
|
||||
# root-owned and apply.py cannot write its status there.
|
||||
mkdir -p "$RUN_DIR"
|
||||
if [ "$(stat -c %U "$RUN_DIR")" != "$RUN_USER" ]; then
|
||||
sudo chown "$RUN_USER" "$RUN_DIR"
|
||||
fi
|
||||
|
||||
sudo tee /etc/systemd/system/web-server-env-apply.path >/dev/null <<EOF
|
||||
[Unit]
|
||||
Description=Watch for .env changes queued from the admin panel
|
||||
|
||||
[Path]
|
||||
PathExists=${RUN_DIR}/request.json
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
sudo tee /etc/systemd/system/web-server-env-apply.service >/dev/null <<EOF
|
||||
[Unit]
|
||||
Description=Apply a .env change queued from the admin panel
|
||||
After=docker.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=${RUN_USER}
|
||||
WorkingDirectory=${ROOT}
|
||||
Environment=DOCKER_API_VERSION=1.41
|
||||
Environment=COMPOSE_BAKE=false
|
||||
ExecStart=/usr/bin/env python3 ${ROOT}/env-apply/apply.py
|
||||
EOF
|
||||
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now web-server-env-apply.path
|
||||
|
||||
echo "Installed. Watching ${RUN_DIR}/request.json as ${RUN_USER}."
|
||||
echo "Logs: journalctl -u web-server-env-apply.service"
|
||||
+10
-3
@@ -1,5 +1,6 @@
|
||||
# =============================================================================
|
||||
# nginx image — the public edge. Stock nginx plus two tools and three templates.
|
||||
# nginx image — the public edge. Stock nginx plus two tools, three config
|
||||
# templates and the two partials they include.
|
||||
#
|
||||
# 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
|
||||
@@ -19,9 +20,11 @@
|
||||
#
|
||||
# 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 (plus the dev partial) are,
|
||||
# NO nginx.conf IS COPIED IN. All three templates (plus the two partials) are,
|
||||
# and entrypoint.sh picks one at container start. See nginx/entrypoint.sh for
|
||||
# that decision.
|
||||
# that decision. A new partial needs BOTH a COPY here and an envsubst render in
|
||||
# the entrypoint, or nginx fails at start with "open() ... failed" on the
|
||||
# include.
|
||||
# =============================================================================
|
||||
FROM nginx:1.27
|
||||
RUN rm -rf /etc/nginx/html/* && \
|
||||
@@ -34,6 +37,10 @@ COPY nginx_dev.conf.template /etc/nginx/nginx_dev.conf.template
|
||||
# (same envsubst allow-list) to /etc/nginx/nginx_dev_common.conf, which is the
|
||||
# path both `include` directives in nginx_dev.conf.template point at.
|
||||
COPY nginx_dev_common.conf.template /etc/nginx/nginx_dev_common.conf.template
|
||||
# The proxy route table shared by production and dev. entrypoint.sh renders it
|
||||
# (same envsubst allow-list) to /etc/nginx/nginx_routes.conf, the path
|
||||
# nginx.conf.template and nginx_dev_common.conf.template both `include`.
|
||||
COPY nginx_routes.conf.template /etc/nginx/nginx_routes.conf.template
|
||||
# Static security-header include, referenced from nginx.conf.template (and
|
||||
# any location that sets its own add_header). Not templated — no envsubst.
|
||||
COPY security_headers.conf /etc/nginx/security_headers.conf
|
||||
|
||||
+51
-9
@@ -6,8 +6,11 @@
|
||||
# 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. In dev it
|
||||
# also renders the shared server-block partial the dev template includes.
|
||||
# /etc/nginx/nginx.conf before starting nginx in the foreground. It also
|
||||
# renders the PARTIALS those templates `include`: the proxy route table
|
||||
# shared by production and dev (nginx_routes.conf, every boot path) and, in
|
||||
# dev only, the body shared by the two dev server blocks
|
||||
# (nginx_dev_common.conf). See RENDERED FILES below.
|
||||
# After nginx starts, a background watcher handles certificates appearing or
|
||||
# being renewed — see CERTIFICATE WATCHER at the bottom of this file.
|
||||
#
|
||||
@@ -47,6 +50,19 @@
|
||||
# Step (c) IS automatic now. A first deploy on a new domain no longer needs a
|
||||
# manual `docker compose restart nginx`; a restart remains a valid fallback.
|
||||
#
|
||||
# RENDERED FILES (template in the image -> path nginx reads)
|
||||
# nginx.conf.template | nginx_dev.conf.template | nginx_setup.conf.template
|
||||
# -> /etc/nginx/nginx.conf (one of three)
|
||||
# nginx_routes.conf.template -> /etc/nginx/nginx_routes.conf
|
||||
# The reverse-proxy locations common to production and dev. Included
|
||||
# by nginx.conf.template directly and by nginx_dev_common.conf. This is
|
||||
# where a new proxied route goes.
|
||||
# nginx_dev_common.conf.template -> /etc/nginx/nginx_dev_common.conf
|
||||
# Dev only: included by both server blocks of nginx_dev.conf.template.
|
||||
# The `include` directives name those rendered paths literally, so a partial
|
||||
# must be written BEFORE anything runs nginx (or `nginx -t`) against a config
|
||||
# that includes it.
|
||||
#
|
||||
# THE envsubst TEMPLATING PATTERN
|
||||
# The templates are plain nginx configs containing $VARIABLES. Two different
|
||||
# kinds of $VAR live in the same file:
|
||||
@@ -67,7 +83,6 @@
|
||||
# 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
|
||||
# SILVERBULLET_HOST / _PORT notes editor upstream (defaulted below)
|
||||
# SILVERBULLET_PUBLIC_HOST / _PORT
|
||||
# public notes viewer upstream (defaulted below)
|
||||
@@ -94,9 +109,26 @@ export SILVERBULLET_PUBLIC_HOST="${SILVERBULLET_PUBLIC_HOST:-silverbullet-public
|
||||
export SILVERBULLET_PUBLIC_PORT="${SILVERBULLET_PUBLIC_PORT:-3000}"
|
||||
|
||||
# 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} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
|
||||
# and by every partial, so the 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} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
|
||||
|
||||
# Render the shared proxy route table. Done ONCE, here, ahead of the three-way
|
||||
# decision, rather than inside each branch:
|
||||
# - dev and production both include it, so both need it before nginx starts;
|
||||
# - the setup branch does not include it, but the certificate watcher at the
|
||||
# bottom of this file later switches setup -> production by validating a
|
||||
# candidate production config with `nginx -t`, and that candidate includes
|
||||
# this path. Having it already on disk means the watcher has nothing extra
|
||||
# to render and no ordering to get wrong.
|
||||
# It is safe to write straight to the live path (no temp file + validate, as
|
||||
# the watcher does for nginx.conf): this runs before nginx has started, and
|
||||
# its content depends only on the image's template and the container's
|
||||
# environment, neither of which can change while the container lives — so
|
||||
# there is never a newer version to swap in under a running nginx.
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx_routes.conf.template \
|
||||
>/etc/nginx/nginx_routes.conf
|
||||
|
||||
# Check if DEV_MODE
|
||||
if [ "$DEV_MODE" = "true" ]; then
|
||||
@@ -113,7 +145,8 @@ if [ "$DEV_MODE" = "true" ]; then
|
||||
fi
|
||||
# In dev mode, so use nginx_dev.conf.template. Its two server blocks both
|
||||
# `include /etc/nginx/nginx_dev_common.conf`, so the shared partial has to be
|
||||
# rendered through the SAME allow-list, into exactly that path, first.
|
||||
# rendered through the SAME allow-list, into exactly that path, first. (That
|
||||
# partial in turn includes nginx_routes.conf, rendered above.)
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx_dev_common.conf.template \
|
||||
>/etc/nginx/nginx_dev_common.conf
|
||||
@@ -123,7 +156,8 @@ if [ "$DEV_MODE" = "true" ]; then
|
||||
CONFIG_MODE=dev
|
||||
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
|
||||
# In production with certificates already existing, so use nginx.conf.template.
|
||||
# It includes nginx_routes.conf, rendered above.
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx.conf.template \
|
||||
>/etc/nginx/nginx.conf
|
||||
@@ -131,7 +165,9 @@ elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencr
|
||||
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.
|
||||
# Only ${DOMAIN} is substituted: the setup config has no upstreams at all
|
||||
# (and does not include nginx_routes.conf — that file is on disk only so the
|
||||
# certificate watcher can switch to the production config later).
|
||||
envsubst '${DOMAIN}' </etc/nginx/nginx_setup.conf.template >/etc/nginx/nginx.conf
|
||||
CONFIG_MODE=setup
|
||||
fi
|
||||
@@ -203,6 +239,12 @@ CERT_WATCH_INTERVAL="${CERT_WATCH_INTERVAL:-60}"
|
||||
|
||||
# Render the production template to a temp file, validate it, and only then
|
||||
# install it. Returns non-zero (installing nothing) if either step fails.
|
||||
# The candidate `include`s /etc/nginx/nginx_routes.conf by absolute path, so
|
||||
# `nginx -t` here validates the shared route table too; that file was rendered
|
||||
# once at the top of this script and is deliberately NOT re-rendered here (it
|
||||
# cannot have changed — see the comment where it is rendered — and rewriting a
|
||||
# file the running nginx may be about to re-read would only add a window in
|
||||
# which it is truncated).
|
||||
render_prod_config() {
|
||||
_candidate=/tmp/nginx.conf.candidate
|
||||
envsubst "$ENVSUBST_VARS" </etc/nginx/nginx.conf.template >"$_candidate" 2>/dev/null || return 1
|
||||
|
||||
+43
-302
@@ -11,7 +11,7 @@
|
||||
# TEMPLATING
|
||||
# Only the names in the envsubst allow-list in nginx/entrypoint.sh are
|
||||
# substituted: DOMAIN, BACKEND_HOST/PORT/ENDPOINT, ICECAST_*, GITEA_*,
|
||||
# HASURA_*, SILVERBULLET_*, PYTHON_*, UPTIMEKUMA_*, WALLABAG_*. Every other dollar
|
||||
# SILVERBULLET_*, PYTHON_*. 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
|
||||
@@ -25,6 +25,16 @@
|
||||
# is exactly one canonical origin (important: cookies,
|
||||
# CORS and the SPA all assume www).
|
||||
# 3. :443 www -> the real site.
|
||||
#
|
||||
# WHERE THE PROXY ROUTES ARE
|
||||
# Not in this file. The reverse-proxied locations (/api, /radio, /gitea,
|
||||
# /notes, /sb, /py and the admin-gate subrequest) and the `set $upstream_*`
|
||||
# variables are shared with dev and live in nginx_routes.conf.template,
|
||||
# which the www server block includes. ADD NEW PROXIED ROUTES THERE. What
|
||||
# stays here is what only production has: TLS, the redirects, the security
|
||||
# headers, static-asset caching, the SPA fallback, the /uploads/ blocks
|
||||
# (which carry the security headers), the `graphql` rate-limit zone and its
|
||||
# location, and the limit_req_zone declarations the shared routes refer to.
|
||||
# =============================================================================
|
||||
events {
|
||||
worker_connections 1024;
|
||||
@@ -76,7 +86,9 @@ http {
|
||||
# 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.)
|
||||
# (Production only; the dev template omits it.
|
||||
# Its location is at the bottom of this file,
|
||||
# not in the shared route table.)
|
||||
# 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
|
||||
@@ -89,6 +101,11 @@ http {
|
||||
# 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.
|
||||
#
|
||||
# login, api, upload and hotel_search are USED from
|
||||
# nginx_routes.conf.template, which dev includes too — so
|
||||
# nginx_dev.conf.template must declare the same four zones, or the dev
|
||||
# config fails to load with "zero size shared memory zone".
|
||||
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;
|
||||
@@ -161,13 +178,9 @@ http {
|
||||
http2 on;
|
||||
server_name www.$DOMAIN;
|
||||
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_silverbullet http://$SILVERBULLET_HOST:$SILVERBULLET_PORT;
|
||||
set $upstream_silverbullet_public http://$SILVERBULLET_PUBLIC_HOST:$SILVERBULLET_PUBLIC_PORT;
|
||||
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||
# The `set $upstream_*` variables used by proxy_pass are declared in
|
||||
# nginx_routes.conf (included below), alongside the routes that use
|
||||
# them.
|
||||
|
||||
root /etc/nginx/html;
|
||||
index index.html;
|
||||
@@ -179,6 +192,9 @@ http {
|
||||
# included there instead of here, because any location that declares
|
||||
# so much as one add_header of its own otherwise inherits none of
|
||||
# these (nginx's add_header inheritance is all-or-nothing).
|
||||
# The shared proxy routes in nginx_routes.conf rely on exactly this
|
||||
# server-level include: none of them declares an add_header, so they
|
||||
# all inherit these headers here, and inherit nothing in dev.
|
||||
include /etc/nginx/security_headers.conf;
|
||||
|
||||
# Vite hashed assets - immutable, cache 1 year
|
||||
@@ -205,7 +221,7 @@ http {
|
||||
# PRIVATE attachments (admin-only). Attachments on *private* chat
|
||||
# messages are written by the backend to /backend/uploads/private/ and
|
||||
# must not be readable by the public, so this subpath is put behind the
|
||||
# same admin `auth_request` used for /hasura/ and /sb/. nginx picks
|
||||
# same admin `auth_request` used for /sb/. nginx picks
|
||||
# the LONGEST matching prefix location, so this block wins over the
|
||||
# public /uploads/ block below for /uploads/private/* regardless of
|
||||
# ordering. Same three hardening headers as the public block, because
|
||||
@@ -274,80 +290,25 @@ http {
|
||||
include /etc/nginx/security_headers.conf;
|
||||
}
|
||||
|
||||
# ---- Backend API -----------------------------------------------------
|
||||
# Two patterns repeat through every proxied location below:
|
||||
# ---- Shared proxy route table ----------------------------------------
|
||||
# Every reverse-proxied location (/api, /radio, /gitea, /notes, /sb,
|
||||
# /py), the admin auth_request gate and the `set $upstream_*` variables
|
||||
# come from nginx_routes.conf.template, rendered by the entrypoint to
|
||||
# this path and shared with the dev config. The prefix-strip rewrite,
|
||||
# the forwarding headers and the websocket upgrade are annotated there.
|
||||
#
|
||||
# 1. THE PREFIX-STRIP REWRITE
|
||||
# rewrite ^<PREFIX>/(.*)$ /$1 break;
|
||||
# The public URL carries a prefix (/api, /radio, /gitea, /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;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
# Position matters for one thing only: regex locations are tried in
|
||||
# file order, so the ACME regex above stays ahead of the /notes and
|
||||
# /py/hotels regexes inside this include, as it always was.
|
||||
include /etc/nginx/nginx_routes.conf;
|
||||
|
||||
# GraphQL, PRODUCTION ONLY — which is why it is here and not in the
|
||||
# shared table. Longest-prefix matching makes it win over the shared
|
||||
# $BACKEND_ENDPOINT/ catch-all, swapping the general `api` limit for
|
||||
# the tighter `graphql` zone declared at the top of this file. Dev has
|
||||
# no such location, so GraphQL there falls under `api`. Apart from the
|
||||
# limit_req line the body must stay identical to $BACKEND_ENDPOINT/ in
|
||||
# nginx_routes.conf.template.
|
||||
location $BACKEND_ENDPOINT/graphql {
|
||||
limit_req zone=graphql burst=10 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
@@ -358,226 +319,6 @@ http {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
# The icecast ADMIN UI (/radio/admin/*) is a full station-control
|
||||
# surface — kick sources, change metadata — protected only by the
|
||||
# icecast admin password, and it was reachable from the public
|
||||
# internet through this proxy. Put it behind the same admin
|
||||
# `auth_request` as /hasura/ and /sb/ so an admin session cookie is
|
||||
# required before the request ever reaches icecast. Longest-prefix
|
||||
# matching means this wins over /radio/ below; listener traffic
|
||||
# (/radio/$ICECAST_MOUNT, /radio/status.xsl) is untouched.
|
||||
location /radio/admin/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /gitea {
|
||||
return 301 /gitea/;
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
location /notes {
|
||||
return 301 /notes/;
|
||||
}
|
||||
|
||||
# PUBLIC notes viewer: a second, read-only SilverBullet over the same
|
||||
# vault the /sb/ editor edits. No auth_request — this is the public
|
||||
# site. See the silverbullet-public service in docker-compose.yml.
|
||||
#
|
||||
# THE DENY BLOCKS BELOW ARE THE PRIVACY BOUNDARY, not decoration.
|
||||
# SB_SPACE_IGNORE only hides paths from the file LIST. Everything else
|
||||
# happily serves them (all verified against 2.11.0 with curl):
|
||||
# /notes/.fs/private/x.md raw file, straight off disk
|
||||
# /notes/private/x the page URL: the server pre-renders the
|
||||
# note's content into the HTML shell
|
||||
# /notes/.fs/.git/... the vault's whole git repo, i.e. every
|
||||
# version of every private note ever
|
||||
# and gitignore semantics mean `private/` in SB_SPACE_IGNORE hides a
|
||||
# private/ folder at ANY depth from the list, so the block must too.
|
||||
#
|
||||
# 1. private/ or templates/ as any path segment, page URL or /.fs/.
|
||||
# ~* so Private/ is caught; (/|$) so the folder itself matches.
|
||||
# 2. Any dot-segment below the first: .git, .obsidian, .env, ... The
|
||||
# first segment is exempt because that is where SilverBullet's own
|
||||
# endpoints live (/.fs, /.config, /.client, /.events ...). Nothing
|
||||
# the client legitimately loads has a dot-segment deeper than that.
|
||||
# nginx matches against the normalised URI (percent-decoded, `..`
|
||||
# resolved, slashes merged), so %2F, // or ../ tricks cannot slip past.
|
||||
# Keep the folder list in step with SB_SPACE_IGNORE on
|
||||
# silverbullet-public. 404 rather than 403 so the response does not
|
||||
# confirm a private path exists.
|
||||
location ~* ^/notes/(.*/)?(private|templates)(/|$) {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ~ ^/notes/.+/\. {
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Revisions are read from the vault's own .git, i.e. the full history
|
||||
# of every file INCLUDING private/ and anything ever deleted.
|
||||
# SB_REVISIONS=disabled already turns this off upstream; this is the
|
||||
# second lock in case that env var is ever dropped. ^~ so no regex
|
||||
# location can take precedence.
|
||||
location ^~ /notes/.revisions {
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Same as /sb/: deliberately NO prefix-strip rewrite. The app is told
|
||||
# its base path via SB_URL_PREFIX=/notes and builds its service worker
|
||||
# scope and asset URLs from it; strip the prefix and it loads blank.
|
||||
# Upgrade/Connection are for its live-update event stream.
|
||||
location /notes/ {
|
||||
proxy_pass $upstream_silverbullet_public;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /sb {
|
||||
return 301 /sb/;
|
||||
}
|
||||
|
||||
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes.
|
||||
# Deliberately NO prefix-strip rewrite, unlike every other proxied app
|
||||
# here. SilverBullet is a PWA told its own base path via SB_URL_PREFIX=/sb,
|
||||
# and its service worker scope and asset URLs are built from that. Strip
|
||||
# the prefix and the app loads a blank page with no error in the log.
|
||||
# Upgrade/Connection are for its sync websocket.
|
||||
location /sb/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
proxy_pass $upstream_silverbullet;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# ---- Admin gate (/hasura/, /sb/, /radio/admin/, /uploads/private/) ----
|
||||
# `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 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;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -11,8 +11,7 @@
|
||||
# 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).
|
||||
# blocks therefore share one body, nginx_dev_common.conf.template.
|
||||
# - 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
|
||||
@@ -26,10 +25,13 @@
|
||||
# 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.
|
||||
# INCLUDE CHAIN
|
||||
# this file -> nginx_dev_common.conf (once per server block: the dev-only
|
||||
# /uploads/ and `/` locations) -> nginx_routes.conf (the proxy route table
|
||||
# shared with production). The prefix-strip rewrite, the four forwarding
|
||||
# headers, the websocket upgrade block and the auth_request admin gate are
|
||||
# annotated in nginx_routes.conf.template; the rate-limit reasoning is in
|
||||
# nginx.conf.template.
|
||||
# =============================================================================
|
||||
events {
|
||||
worker_connections 1024;
|
||||
@@ -46,6 +48,10 @@ http {
|
||||
|
||||
client_max_body_size 50M;
|
||||
|
||||
# These four zones are referenced by limit_req lines in the SHARED
|
||||
# nginx_routes.conf.template, so they must exist here with the same names
|
||||
# as in nginx.conf.template or nginx refuses to load the config. Rates are
|
||||
# kept equal to production so a limit that would bite there bites here too.
|
||||
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=upload:10m rate=5r/m;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# =============================================================================
|
||||
# nginx_dev.conf.template — SHARED BODY of the dev :80 and :443 server blocks.
|
||||
# nginx_dev_common.conf.template — SHARED BODY of the dev :80 and :443 server
|
||||
# blocks.
|
||||
#
|
||||
# WHY THIS FILE EXISTS
|
||||
# In dev the :80 and :443 server blocks are byte-for-byte identical apart
|
||||
@@ -16,26 +17,23 @@
|
||||
# the entrypoint, or it will reach nginx unsubstituted.
|
||||
#
|
||||
# WHAT BELONGS HERE
|
||||
# Everything inside a `server { ... }` block: the `set $upstream_*` vars and
|
||||
# every `location`. NOT `listen`, `server_name` or the ssl_certificate lines
|
||||
# (those differ between the two blocks), and NOT the enclosing braces — this
|
||||
# file must be brace-balanced on its own.
|
||||
# Only what dev does DIFFERENTLY from production inside a server block: the
|
||||
# /uploads/ locations without security headers, and `/` proxied to Vite.
|
||||
# Everything else — the `set $upstream_*` vars and every reverse-proxied
|
||||
# route — is in nginx_routes.conf.template, shared with production and
|
||||
# included at the bottom of this file. ADD NEW PROXIED ROUTES THERE, not
|
||||
# here.
|
||||
# NOT `listen`, `server_name` or the ssl_certificate lines (those differ
|
||||
# between the two blocks), and NOT the enclosing braces — this file must be
|
||||
# brace-balanced on its own.
|
||||
#
|
||||
# This is the DEV file only. Production uses a single :443 server block in
|
||||
# nginx.conf.template and needs no partial.
|
||||
# This is the DEV file only. Production's single :443 www server block in
|
||||
# nginx.conf.template includes nginx_routes.conf directly.
|
||||
# =============================================================================
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_silverbullet http://$SILVERBULLET_HOST:$SILVERBULLET_PORT;
|
||||
set $upstream_silverbullet_public http://$SILVERBULLET_PUBLIC_HOST:$SILVERBULLET_PUBLIC_PORT;
|
||||
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||
|
||||
# PRIVATE attachments (admin-only). Attachments on *private* chat
|
||||
# messages are written by the backend to /backend/uploads/private/ and
|
||||
# must not be readable by the public, so this subpath is put behind the
|
||||
# same admin `auth_request` used for /hasura/ and /sb/. nginx picks
|
||||
# same admin `auth_request` used for /sb/. nginx picks
|
||||
# the LONGEST matching prefix location, so this block wins over the
|
||||
# public /uploads/ block below for /uploads/private/* regardless of
|
||||
# ordering. Same three hardening headers as the public block, because
|
||||
@@ -49,6 +47,12 @@
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
# Both /uploads/ blocks are the production ones MINUS
|
||||
# `include security_headers.conf`: that file carries HSTS, which must
|
||||
# never be sent from localhost. That one line is why they are not in
|
||||
# the shared route table (see WHAT DOES NOT in
|
||||
# nginx_routes.conf.template). Keep the rest in step with
|
||||
# nginx.conf.template.
|
||||
location /uploads/ {
|
||||
alias /uploads/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
@@ -56,6 +60,7 @@
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
# The Vite dev server; Upgrade/Connection carry its HMR websocket.
|
||||
location / {
|
||||
proxy_pass http://vue:5173;
|
||||
proxy_http_version 1.1;
|
||||
@@ -64,214 +69,6 @@
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT {
|
||||
return 301 $BACKEND_ENDPOINT/;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
# The icecast ADMIN UI (/radio/admin/*) is a full station-control
|
||||
# surface — kick sources, change metadata — protected only by the
|
||||
# icecast admin password, and it was reachable from the public
|
||||
# internet through this proxy. Put it behind the same admin
|
||||
# `auth_request` as /hasura/ and /sb/ so an admin session cookie is
|
||||
# required before the request ever reaches icecast. Longest-prefix
|
||||
# matching means this wins over /radio/ below; listener traffic
|
||||
# (/radio/$ICECAST_MOUNT, /radio/status.xsl) is untouched.
|
||||
location /radio/admin/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /gitea {
|
||||
return 301 /gitea/;
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
location /notes {
|
||||
return 301 /notes/;
|
||||
}
|
||||
|
||||
# PUBLIC notes viewer (read-only SilverBullet). The deny blocks are
|
||||
# the privacy boundary: SB_SPACE_IGNORE hides files from the list but
|
||||
# NOT from a direct /.fs/ fetch, a page URL (server-rendered), or
|
||||
# /.fs/.git/. Full explanation in nginx.conf.template; keep the two in
|
||||
# step.
|
||||
location ~* ^/notes/(.*/)?(private|templates)(/|$) {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ~ ^/notes/.+/\. {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ^~ /notes/.revisions {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location /notes/ {
|
||||
proxy_pass $upstream_silverbullet_public;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /sb {
|
||||
return 301 /sb/;
|
||||
}
|
||||
|
||||
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes.
|
||||
# Deliberately NO prefix-strip rewrite, unlike every other proxied app
|
||||
# here. SilverBullet is a PWA told its own base path via SB_URL_PREFIX=/sb,
|
||||
# and its service worker scope and asset URLs are built from that. Strip
|
||||
# the prefix and the app loads a blank page with no error in the log.
|
||||
# Upgrade/Connection are for its sync websocket.
|
||||
location /sb/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
proxy_pass $upstream_silverbullet;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /py/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
# Every other route, shared with production. This file has no regex
|
||||
# locations of its own, so where the include sits is cosmetic.
|
||||
include /etc/nginx/nginx_routes.conf;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user