Drop keepalive-era telemetry instruments + tighten claim-fn visibility
Browse files at this commita2a344c462746fb61110dfc29bb2601b14f1cc72Parent: 3d61a9e- chore
- drop keepalive-era telemetry instruments + tighten claim-fn visibility
- Postgres docs (README/CLAUDE.md)
- ship migrations/ in the image
8 changed files +170 -186
- CLAUDE.md +16 -10
- Containerfile +4 -0
- README.md +146 -159
- src/db/appointment.rs +1 -1
- src/db/exam_attempt.rs +1 -1
- src/db/fee_plan_assignment.rs +1 -1
- src/db/registration.rs +1 -1
- src/telemetry.rs +0 -13
CLAUDE.mdmodified+16 -10
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | # hezarfen_backend |
| 2 | 2 | |
| 3 | 3 | Rust/axum school-management API (auth, roles, exams, notes, messaging, |
| 4 | -courses, attendance, pomodoro, meals) on SurrealDB v3. Swagger UI at `/swagger`. | |
| 4 | +courses, attendance, pomodoro, meals) on PostgreSQL (sqlx). Swagger UI at `/swagger`. | |
| 5 | 5 | |
| 6 | 6 | ## Project docs — query the knowledge base, do NOT read README.md |
| 7 | 7 | |
| @@ -30,23 +30,27 @@ python3 ~/.claude/kb/ingest.py README.md | KB | ||
| 30 | 30 | python3 ~/.claude/kb/ingest-endpoints.py README.md | KB |
| 31 | 31 | ``` |
| 32 | 32 | |
| 33 | -The project's own SurrealDB (container `hezarfen-surrealdb`, ns/db | |
| 34 | -`hezarfen`) is runtime data — never write knowledge-base rows there. | |
| 33 | +The project's own PostgreSQL (container `hezarfen-postgres`) is runtime data — | |
| 34 | +never write knowledge-base rows there (the KB lives in `~/.claude/kb/kb.db`). | |
| 35 | 35 | |
| 36 | 36 | ## Code map — orient here, skip discovery greps |
| 37 | 37 | |
| 38 | -Pattern: `src/domain/<x>.rs` = validated newtypes + entity + its own | |
| 39 | -persistence (SurrealValue). `src/web/<x>.rs` = DTOs + axum handlers, one file | |
| 40 | -per resource, routes wired in `lib.rs`. | |
| 38 | +Pattern: `src/domain/<x>.rs` = validated newtypes + entity. `src/db/<x>.rs` = | |
| 39 | +its SQL (the only layer that executes queries). `src/service/<x>.rs` = | |
| 40 | +workflows (one `tx_with_retry` transaction per invariant). `src/web/<x>.rs` = | |
| 41 | +DTOs + axum handlers, one file per resource, routes wired in `lib.rs`. | |
| 41 | 42 | |
| 42 | 43 | - core: `main`(bootstrap) `lib`(build_router+OpenAPI) `config` `constant`(limits) |
| 43 | - `validate` `error` `database`(connect+SCHEMAFULL migration) | |
| 44 | + `validate` `error` `database`(PgPool + tx_with_retry + the two sqlx migrator sets) | |
| 44 | 45 | `rate_limit`(fixed-window per-IP) `state` |
| 45 | 46 | - `domain/`: user role session timestamp profile preferences note note_file |
| 46 | 47 | message parent_link event attendance registration course course_session |
| 47 | 48 | session_attendance enrollment subject term settings work_entry pomodoro |
| 48 | 49 | exam exam_attempt exam_question exam_answer exam_result question_image |
| 49 | 50 | menu menu_dish dietary_profile meal_booking meal_attendance meal_ledger |
| 51 | +- `db/`: per-resource SQL; `cap`(count-cap CTE recipes + verdict types) | |
| 52 | + `field_update` `page`(PagedList) | |
| 53 | +- `service/`: per-resource workflows (booking, minting, cascades) | |
| 50 | 54 | - `ai/`: QUIC bridge to the out-of-process AI services (backend listens, |
| 51 | 55 | services dial in). `protocol`(frames) `server`(AiBridge: listen+dispatch) |
| 52 | 56 | `registry`(workers, capability routing) `tls` `error`. Off unless |
| @@ -55,9 +59,11 @@ per resource, routes wired in `lib.rs`. | ||
| 55 | 59 | responses) `page`(pagination) `exam_ws`(exam-room WebSocket) + per-resource: |
| 56 | 60 | auth users notes messages events courses subjects sessions exams marks work |
| 57 | 61 | pomodoro attendance settings terms meals |
| 58 | -- `tests/`: integration(oneshot+mem db) e2e(real TCP+cookies) rate_limit | |
| 59 | - pagination persistence ai_bridge(real QUIC + fake AI service) | |
| 60 | - ai_protocol(hab/1 wire contract; raw byte-level client, imports no protocol | |
| 62 | +- `tests/`: integration(oneshot over per-test Postgres databases — tests/common | |
| 63 | + mints `init_test_tenants`/`init_test_db`/`deployment_with`, template-clone) | |
| 64 | + e2e(real TCP+cookies) rate_limit | |
| 65 | + pagination persistence(idempotent re-migration over a live db) ai_bridge(real QUIC + fake AI service) | |
| 66 | + ai_protocol(hab/2 wire contract; raw byte-level client, imports no protocol | |
| 61 | 67 | types — the only suite that catches a wire-format change) |
| 62 | 68 | |
| 63 | 69 | Note: README `## Layout` lags src/ (missing newer domain files); this map + |
Containerfilemodified+4 -0
| @@ -13,6 +13,9 @@ COPY src ./src | ||
| 13 | 13 | # so the build must never reach for a live database. |
| 14 | 14 | ENV SQLX_OFFLINE=true |
| 15 | 15 | COPY .sqlx ./.sqlx |
| 16 | +# The migrators read these at boot/mint (control set on the control pool, | |
| 17 | +# school set for the template + every school database). | |
| 18 | +COPY migrations ./migrations | |
| 16 | 19 | |
| 17 | 20 | # Cache mounts keep the registry and incremental build artifacts between |
| 18 | 21 | # builds. The binary must be copied out of /app/target inside the same RUN, |
| @@ -32,6 +35,7 @@ RUN apt-get update && \ | ||
| 32 | 35 | mkdir /data && chown hezarfen:hezarfen /data |
| 33 | 36 | |
| 34 | 37 | COPY --from=builder /usr/local/bin/hezarfen_backend /usr/local/bin/hezarfen_backend |
| 38 | +COPY --from=builder /app/migrations /app/migrations | |
| 35 | 39 | |
| 36 | 40 | USER hezarfen |
| 37 | 41 |
README.mdmodified+146 -159
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # hezarfen_backend |
| 2 | 2 | |
| 3 | -Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · axum · SurrealDB 3 (server, WebSocket) · tokio.** | |
| 3 | +Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · axum · PostgreSQL (sqlx) · tokio.** | |
| 4 | 4 | |
| 5 | 5 | Session-cookie auth with five hierarchical roles (`parent < student < teacher |
| 6 | 6 | < manager < admin`). A **`parent`** observes and changes nothing: admins tie |
| @@ -201,24 +201,31 @@ represented. Those restrictions are published rather than left to be guessed: | ||
| 201 | 201 | **`GET /limits`** (no auth) serves every fixed bound and closed value set the |
| 202 | 202 | API enforces, read straight from the constants the newtypes use, so a frontend |
| 203 | 203 | validates against the server's own rules instead of a hand-kept copy (see |
| 204 | -"Validation limits"). Those same types derive `surrealdb::types::SurrealValue`, so one | |
| 205 | -typed value flows from HTTP request into the `SCHEMAFULL` database. Record ids | |
| 206 | -are ULIDs (time-sortable). | |
| 204 | +"Validation limits"). Persistence is PostgreSQL through sqlx: every statement | |
| 205 | +is checked at compile time against the schema (see `## Run`), and a row is a | |
| 206 | +plain typed struct in `src/db/`. Ids are UUIDv7s (time-sortable), served in | |
| 207 | +the hyphenated wire form. | |
| 207 | 208 | |
| 208 | 209 | ## Run |
| 209 | 210 | |
| 210 | 211 | ```sh |
| 211 | -surreal start --user root --pass root surrealkv:./data/hezarfen.db # the DB server | |
| 212 | -cp .env.example .env # optional | |
| 212 | +podman compose up -d postgres # PostgreSQL 18 on 127.0.0.1:5432 (hezarfen/hezarfen) | |
| 213 | +cp .env.example .env # recommended: DATABASE_URL feeds the build too | |
| 213 | 214 | cargo run |
| 214 | 215 | ``` |
| 215 | 216 | |
| 216 | -Boots on `http://127.0.0.1:8080`, talking to the SurrealDB server at | |
| 217 | -`DB_URL` (default `ws://127.0.0.1:8000`, root credentials via | |
| 218 | -`DB_USER`/`DB_PASS`) and storing uploaded note files in | |
| 219 | -`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs | |
| 220 | -(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at | |
| 221 | -`/api-docs/openapi.json`. | |
| 217 | +Boots on `http://127.0.0.1:8080`, talking to PostgreSQL at `DATABASE_URL` | |
| 218 | +(default `postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control` — | |
| 219 | +the control database) and storing uploaded note files in `./data/files/` | |
| 220 | +(`FILES_PATH`, created at startup). `DATABASE_URL` is also read by sqlx's | |
| 221 | +compile-time query macros, so `cargo check` prepares every query against a | |
| 222 | +live database; `scripts/prepare_db.sh` refreshes the one union-schema | |
| 223 | +prepare database those checks run against, and the committed `.sqlx` cache | |
| 224 | +lets a build run with `SQLX_OFFLINE=true` and no database at all. On boot | |
| 225 | +the sqlx migrator applies `migrations/control` to the control database and | |
| 226 | +ensures the school template; each school database runs `migrations/school` | |
| 227 | +the same way at mint. Interactive API docs (Swagger UI) are served at | |
| 228 | +`/swagger`, the raw OpenAPI spec at `/api-docs/openapi.json`. | |
| 222 | 229 | |
| 223 | 230 | ## Run in a container (podman) |
| 224 | 231 | |
| @@ -229,11 +236,15 @@ podman compose down # stop (data survives in the volume) | ||
| 229 | 236 | ``` |
| 230 | 237 | |
| 231 | 238 | The `Containerfile` is a two-stage build (Rust builder with cargo cache |
| 232 | -mounts, `debian:trixie-slim` runtime, non-root user). Two services: the | |
| 233 | -`surrealdb` server (official image, surrealkv storage) and the backend, which | |
| 234 | -waits for the server's healthcheck and connects over `ws://surrealdb:8000`. | |
| 235 | -Each has its own named volume — `surreal-data` holds the database, | |
| 236 | -`hezarfen-data` the uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the | |
| 239 | +mounts, `debian:trixie-slim` runtime, non-root user, `SQLX_OFFLINE=true` | |
| 240 | +so the build never touches a database — the macros read the committed | |
| 241 | +`.sqlx` cache). Two primary services: `postgres` (the official | |
| 242 | +`postgres:18-alpine` image, `max_connections=500` so the test suite's | |
| 243 | +parallel control+school pools fit) and the backend, which waits for the | |
| 244 | +database's healthcheck and connects over `DATABASE_URL` | |
| 245 | +(`postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control`). Each has | |
| 246 | +its own named volume — `pgdata` holds the database, `hezarfen-data` the | |
| 247 | +uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the | |
| 237 | 248 | container so the published port works. Production knobs (`COOKIE_SECURE`, |
| 238 | 249 | `CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in |
| 239 | 250 | `compose.yaml` — uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset |
| @@ -257,27 +268,20 @@ http/protobuf` instead. | ||
| 257 | 268 | |
| 258 | 269 | The backend survives the database going away, at boot and at runtime. |
| 259 | 270 | |
| 260 | -At boot it retries the connection (1s doubling to 5s) until the server | |
| 261 | -answers, rather than exiting. Exiting looks tidier but is worse: the container | |
| 262 | -runtime restarts the process, it fails again in milliseconds, and a few | |
| 263 | -seconds of startup skew burns the whole restart budget and leaves the backend | |
| 264 | -down for good. | |
| 265 | - | |
| 266 | -At runtime a keepalive query every 5s doubles as a liveness probe. This | |
| 267 | -matters more than it sounds: a query issued while the socket is down does | |
| 268 | -*not* fail — the SDK's reconnect loop stops draining its request queue, so the | |
| 269 | -query parks until the database returns and only *then* runs. Left alone, a | |
| 270 | -request waits out the entire outage and any write it carries lands long after | |
| 271 | -the caller gave up. | |
| 272 | - | |
| 273 | -So while the probe says the socket is down, requests are refused at the edge | |
| 274 | -with `503` and `Retry-After: 1`, before they can reach the database. Nothing | |
| 275 | -is queued, which is what makes that retry safe. Requests that slip through in | |
| 276 | -the window between the socket dying and the probe noticing are capped at 30s | |
| 277 | -and answer `503` *without* `Retry-After`, with a message saying the write may | |
| 278 | -or may not have applied — they were already queued, so retrying them could | |
| 279 | -apply the same write twice. WebSocket and SSE routes are unaffected: both | |
| 280 | -return their response immediately and stream afterwards. | |
| 271 | +At boot it retries the connection (a one-second cadence, indefinitely) | |
| 272 | +until the server answers, rather than exiting. Exiting looks tidier but is | |
| 273 | +worse: the container runtime restarts the process, it fails again in | |
| 274 | +milliseconds, and a few seconds of startup skew burns the whole restart | |
| 275 | +budget and leaves the backend down for good. | |
| 276 | + | |
| 277 | +At runtime nothing queues behind a dead server: a request that cannot get | |
| 278 | +a connection is refused with `503`. The two flavors are distinguished | |
| 279 | +honestly — an acquire that times out means nothing executed, so the | |
| 280 | +answer is retry-safe; a request whose connection died mid-flight may have | |
| 281 | +applied server-side (the commit can race the connection dropping), so its | |
| 282 | +503 says the write may or may not have landed and must not be blindly | |
| 283 | +retried. When the database comes back the pool dials again on the next | |
| 284 | +request; there is nothing to re-arm. | |
| 281 | 285 | |
| 282 | 286 | Without compose: |
| 283 | 287 | |
| @@ -288,13 +292,13 @@ podman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backe | ||
| 288 | 292 | |
| 289 | 293 | ## Multi-school (SaaS) |
| 290 | 294 | |
| 291 | -One deployment serves many schools. Every school gets a SurrealDB **database** | |
| 292 | -of its own inside the one namespace (`DB_NAMESPACE`, default `hezarfen`), | |
| 293 | -named by its slug, next to a **control** database (`DB_DATABASE`, default | |
| 294 | -`control`) that holds the school registry, the builder accounts and the shared | |
| 295 | -rate-limit window. Isolation is the store's, not the handlers': a school | |
| 296 | -database sees only its own rows, so no query carries a `WHERE school = ...` | |
| 297 | -somebody could forget. | |
| 295 | +One deployment serves many schools. Every school gets a PostgreSQL | |
| 296 | +**database** of its own, named `{control}_school_{slug}` after the | |
| 297 | +**control** database `DATABASE_URL` points at (`hezarfen_control` by | |
| 298 | +default), which holds the school registry, the builder accounts and the | |
| 299 | +shared rate-limit window. Isolation is the store's, not the handlers': a | |
| 300 | +school database sees only its own rows, so no query carries a | |
| 301 | +`WHERE school = ...` somebody could forget. | |
| 298 | 302 | |
| 299 | 303 | **Slugs.** 2-32 characters of `a-z`, `0-9` and `-`, starting with a letter or |
| 300 | 304 | digit (`MIN_SLUG_LEN`/`MAX_SLUG_LEN`); `builder` and `control` are reserved and |
| @@ -916,21 +920,22 @@ That admin can then promote everyone else through `PATCH /users/{id}/role`. | ||
| 916 | 920 | The admin set cannot be emptied through the API: an admin never changes their |
| 917 | 921 | own role, and a `PATCH /users/{id}/role` that would demote the last admin |
| 918 | 922 | answers `409` — including when two admins demote each other at the same |
| 919 | -instant, since that guard is serialized school-wide rather than left to the | |
| 920 | -database (which conflict-checks neither a cross-record count nor a read). | |
| 923 | +instant, since the guard is a predicate on the role write itself: the | |
| 924 | +`UPDATE` that lowers the row counts the remaining admins in the same | |
| 925 | +statement, so the count and the write it guards contend on the row lock | |
| 926 | +like any other write. | |
| 921 | 927 | |
| 922 | 928 | A locked-out school is the builder's `POST /schools/{slug}/admin-password`, |
| 923 | 929 | which re-keys an admin that still exists. Manual fallback (the recovery path |
| 924 | 930 | if an older build already emptied a school's admin set): run |
| 925 | 931 | |
| 926 | -```surql | |
| 927 | -UPDATE user SET role = 'admin' WHERE username = 'ada'; | |
| 932 | +```sql | |
| 933 | +UPDATE app_user SET role = 'admin' WHERE username = 'ada'; | |
| 928 | 934 | ``` |
| 929 | 935 | |
| 930 | -against the SurrealDB server, with `--db` naming the **school's** database (its | |
| 931 | -slug), not the control one — e.g. | |
| 932 | -`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db demo` | |
| 933 | -(in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`). | |
| 936 | +against the **school's** database (`{control}_school_{slug}`), not the | |
| 937 | +control one — e.g. `podman exec -it hezarfen-postgres psql -U hezarfen -d | |
| 938 | +hezarfen_control_school_demo` for the compose stack. | |
| 934 | 939 | |
| 935 | 940 | ## Endpoints |
| 936 | 941 | |
| @@ -1344,7 +1349,7 @@ A course may carry a `term_id` (`null` = unassigned); on `PATCH | ||
| 1344 | 1349 | /courses/{id}`, an omitted `term_id` keeps the link and an explicit `null` |
| 1345 | 1350 | clears it. |
| 1346 | 1351 | `role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are |
| 1347 | -ULIDs. `parent` accounts are made by an admin (register as `student`, then | |
| 1352 | +hyphenated UUIDv7s. `parent` accounts are made by an admin (register as `student`, then | |
| 1348 | 1353 | `PATCH /users/{id}/role`) and observe only the students an admin tied to them |
| 1349 | 1354 | — see "Roles & access control". |
| 1350 | 1355 | An exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row, |
| @@ -1991,7 +1996,7 @@ asker withdrawing, or teacher+ moderating — takes its solutions and every | ||
| 1991 | 1996 | photo blob (its own and its solutions') with it. Each question row reports |
| 1992 | 1997 | its `solution_count`, and questions and solutions embed their people as |
| 1993 | 1998 | person refs (`{id, username, display_name}`), so the UI never shows a raw |
| 1994 | -ULID. | |
| 1999 | +uuid. | |
| 1995 | 2000 | |
| 1996 | 2001 | ## Per-school policy (settings & terms) |
| 1997 | 2002 | |
| @@ -2257,7 +2262,7 @@ teacher or manager ordering a child's lunch is a `403`. | ||
| 2257 | 2262 | is a decision, not a side effect. |
| 2258 | 2263 | - **The capacity check is a single conditional write, decided by the |
| 2259 | 2264 | database.** Counting rows and then writing one would be write-skew — |
| 2260 | - SurrealDB does not conflict-check a cross-record count against a concurrent | |
| 2265 | + a count read in one statement does not conflict-check against a concurrent | |
| 2261 | 2266 | insert, so 24 students racing for 3 seats would all pass the count — so the |
| 2262 | 2267 | seat is instead claimed on a counter kept on the **menu row itself**, taken |
| 2263 | 2268 | and spent by one `UPDATE … WHERE` that also places the booking row in the |
| @@ -2469,7 +2474,7 @@ is a counter that can drift. | ||
| 2469 | 2474 | the separator inside a ledger line's id) and the line is keyed |
| 2470 | 2475 | `<student>_k_<key>`, so a client retry after a network timeout returns the |
| 2471 | 2476 | line the first attempt wrote instead of crediting the money twice. Without |
| 2472 | - one the id is a fresh ulid and a resent request is a second credit, as a desk | |
| 2477 | + one the id is a fresh uuid and a resent request is a second credit, as a desk | |
| 2473 | 2478 | taking the same amount twice really is — and since nothing here edits or |
| 2474 | 2479 | deletes a line, that doubled credit can only be corrected by a compensating |
| 2475 | 2480 | one. The same key with a different `amount_minor` is a `409`, never the |
| @@ -2624,16 +2629,17 @@ account. | ||
| 2624 | 2629 | room back and the charge **can be paid again** — and reversing that refund |
| 2625 | 2630 | takes the room back with it. Money that came back out is not money the school |
| 2626 | 2631 | still holds. |
| 2627 | -- **The over-payment cap is not the database's.** The `409` past a charge's or | |
| 2628 | - a credit's worth is a cross-record fold, which SurrealDB cannot enforce on | |
| 2629 | - its own; it holds because the backend is one process and the fold, and the | |
| 2630 | - append it authorizes, are taken under one lock. Should an over-payment ever | |
| 2632 | +- **The over-payment cap is not the database's.** The `409` past a charge's or a | |
| 2633 | + credit's worth is a cross-record fold, which no constraint can enforce on | |
| 2634 | + its own; it holds because the fold, and the append it authorizes, are | |
| 2635 | + taken under the target's ancestor-chain row locks (`FOR UPDATE`) — writers | |
| 2636 | + on one subtree take turns, different subtrees never contend. Should an over-payment ever | |
| 2631 | 2637 | be recorded anyway it is not a crisis: this is human data entry at an office |
| 2632 | 2638 | desk, the outcome is an over-paid charge that is plainly visible in the |
| 2633 | 2639 | statement, and it is undone by appending a refund. Both lines are true |
| 2634 | 2640 | records of money that really arrived — refusing them would be the worse lie. |
| 2635 | 2641 | - **A line carries at most 20 applied lines.** The cap above is folded one |
| 2636 | - query per line of the target's subtree, all of them while that single lock is | |
| 2642 | + query per line of the target's subtree, all of them while those row locks are | |
| 2637 | 2643 | held, so a charge settled in a thousand pieces would stall every other |
| 2638 | 2644 | payment in the school behind its own arithmetic. Past 20 (payments under a |
| 2639 | 2645 | charge, refunds under a payment, and the reversals among them) a further |
| @@ -2803,24 +2809,12 @@ question + answer images (blobs included) along with results; unenrolling mid-ex | ||
| 2803 | 2809 | hides the student from the monitor roster but keeps the attempt and mark |
| 2804 | 2810 | rows, mirroring the marks report. |
| 2805 | 2811 | |
| 2806 | -> **Upgrading a pre-course database**: `exam` rows created before courses | |
| 2807 | -> existed lack the now-required `course` field and will fail to deserialize. | |
| 2808 | -> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data, | |
| 2809 | -> backfill manually with the SurrealDB CLI (server stopped), e.g. | |
| 2810 | -> `UPDATE exam SET course = course:<id> WHERE course = NONE;` | |
| 2811 | -> after creating a course to attach them to. | |
| 2812 | -> | |
| 2813 | -> **Upgrading to the attempts/rejoin build needs nothing manual**: the boot | |
| 2814 | -> migration backfills `max_attempts = 1`, `allow_rejoin = true`, and attempt | |
| 2815 | -> `seq = 1` on existing rows, and swaps the single-attempt unique index for | |
| 2816 | -> the per-sitting one. Pre-upgrade attempts keep their record ids and count | |
| 2817 | -> as sitting #1. | |
| 2818 | -> | |
| 2819 | -> **Upgrading to the kind-weight build is a clean break**: weights moved off | |
| 2820 | -> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with | |
| 2821 | -> no data migration. A database from an older build has string kinds and a | |
| 2822 | -> per-exam `weight` column the code no longer understands — delete | |
| 2823 | -> `./data/hezarfen.db` and reboot. | |
| 2812 | +> **Schema changes are migrations, not boot batches.** The sqlx migrator | |
| 2813 | +> applies `migrations/control` to the control database at boot and | |
| 2814 | +> `migrations/school` to the school template and every newly minted school | |
| 2815 | +> database, tracked in `_sqlx_migrations` — an up-to-date database boots | |
| 2816 | +> without touching a row, and there is no manual backfill. The SurrealDB-era | |
| 2817 | +> `surreal sql` repair notes died with the old store. | |
| 2824 | 2818 | |
| 2825 | 2819 | ## Taking an exam: questions, answers & the exam room |
| 2826 | 2820 | |
| @@ -2907,7 +2901,7 @@ no-store`. The metadata rides the answer as `answer_image: {content_type, | ||
| 2907 | 2901 | size} | null` on both the sitting view and the grading sheet. To the backend |
| 2908 | 2902 | it is a normal raster PNG; the frontend piggybacks its editable stroke data in |
| 2909 | 2903 | a PNG `tEXt` chunk, opaque here — stored on disk under `Config::files_path` |
| 2910 | -by a ULID, metadata in the `answer_image` table, structurally identical to | |
| 2904 | +under a fresh uuid, metadata in the `answer_image` table, structurally identical to | |
| 2911 | 2905 | question images. |
| 2912 | 2906 | |
| 2913 | 2907 | **Grading view** (course-management rights): `GET /exams/{id}/attempts/{user}/answers` returns |
| @@ -3439,7 +3433,7 @@ way — the ambiguity `matched` closes on the grade-wide pumps). | ||
| 3439 | 3433 | Stocking is best-effort all the way to the end of that route: a template that |
| 3440 | 3434 | could not be read, or a pump that faulted part-way, leaves `stocked_from` null |
| 3441 | 3435 | rather than turning a class that *exists* into a `500` whose caller never learns |
| 3442 | -its id — a class id is a ULID and `POST /classes` is the only place it is | |
| 3436 | +its id — a class id is a uuid and `POST /classes` is the only place it is | |
| 3443 | 3437 | returned from, unlike a blueprint, whose id is the grade label the caller sent. |
| 3444 | 3438 | The retry is `POST /classes/{id}/blueprint`, which is idempotent and is also |
| 3445 | 3439 | what a caller runs when there is genuinely no template, so the two cases need |
| @@ -4557,9 +4551,9 @@ const send = (payload) => | ||
| 4557 | 4551 | The backend runs as **one process against one database**, and that buys less |
| 4558 | 4552 | than it sounds like: every request is an async task, dozens are in flight at |
| 4559 | 4553 | once, and each of them awaits the database in the middle of its work. So |
| 4560 | -"read, decide, write" is never safe on its own — SurrealDB does not | |
| 4561 | -conflict-check a cross-record `count()` against a concurrent insert | |
| 4562 | -(write-skew), and that fires between two tasks in one process exactly as it | |
| 4554 | +"read, decide, write" is never safe on its own — under `READ COMMITTED` a | |
| 4555 | +count read in one statement does not conflict-check against a concurrent | |
| 4556 | +insert (write-skew), and that fires between two tasks in one process exactly as it | |
| 4563 | 4557 | would between two machines. The mutex-only design this replaced was already |
| 4564 | 4558 | losing races at one process. Every invariant is therefore guarded where the |
| 4565 | 4559 | database itself decides the winner. Three tiers: |
| @@ -4569,8 +4563,11 @@ database itself decides the winner. Three tiers: | ||
| 4569 | 4563 | atomic, so of N concurrent tasks exactly the allowed number get a non-empty |
| 4570 | 4564 | result: the database decides the winner, the loser retries |
| 4571 | 4565 | (`CAS_UPDATE_RETRIES`) or gets a 409. |
| 4572 | -2. **In-transaction `IF … THROW` gates** — the check runs inside the same | |
| 4573 | - statement as the write it authorizes, so it is atomic with it. Used where | |
| 4566 | +2. **One-statement gates** — the check runs inside the same statement as | |
| 4567 | + the write it authorizes, so it is atomic with it: a guarded | |
| 4568 | + `UPDATE … WHERE` (the last-admin floor), an | |
| 4569 | + `INSERT … SELECT … WHERE EXISTS` behind a real `FOREIGN KEY` (the | |
| 4570 | + existence proofs), the CTE recipes in `db::cap`. Used where | |
| 4574 | 4571 | the rule reads the row being written (state machines, delete guards). |
| 4575 | 4572 | "Is anything still attached?" is answered the same way, by a counter on the |
| 4576 | 4573 | row being deleted rather than a `SELECT` over the children: a course is |
| @@ -4583,52 +4580,43 @@ database itself decides the winner. Three tiers: | ||
| 4583 | 4580 | Where the child also carries a deterministic id — one enrollment per |
| 4584 | 4581 | (course, user), one registration per (event, user), one fee-plan assignment |
| 4585 | 4582 | per (plan, student) — the seat and the row |
| 4586 | - are claimed in one transaction (`cap::claim_and_create`), so a duplicate | |
| 4587 | - `CREATE` rolls its own seat back instead of costing a stranger their place. | |
| 4588 | -3. **Three accepted races**, reviewed and deliberately left open: | |
| 4583 | + are claimed in one statement (`db::cap`'s `claim_and_create` recipes), so a | |
| 4584 | + duplicate insert rolls its own seat back instead of costing a stranger their | |
| 4585 | + place. Where no single statement can decide the rule — an appointment | |
| 4586 | + approval reads other rows that may not exist yet — that one decision | |
| 4587 | + escalates to `SERIALIZABLE`, and `tx_with_retry` re-sends it when Postgres | |
| 4588 | + aborts the loser (`40001`); the re-run sees the winner committed and | |
| 4589 | + refuses with the ordinary `409`. | |
| 4590 | +3. **Two accepted races**, reviewed and deliberately left open: | |
| 4589 | 4591 | - *Attempt-seq late save* — an exam-room socket writes into the sitting it |
| 4590 | 4592 | joined with, a choice made before any lock is taken, so a save racing a |
| 4591 | 4593 | retake can stamp an answer onto the just-terminal previous sitting. |
| 4592 | 4594 | Damage: one history row; the grade of record (latest `seq`) is never |
| 4593 | 4595 | touched. |
| 4594 | - - *Approved-overlap* — two approvals landing in the same instant can | |
| 4595 | - double-book a teacher. Damage: one overlapping half-hour, visible to both | |
| 4596 | - parties, fixable by cancelling either side. | |
| 4597 | 4596 | - *Archive-vs-write* — the archived-term guard is a pre-flight read on the |
| 4598 | 4597 | term row, so an archive committing in the same instant as a write already |
| 4599 | 4598 | in flight lets that one write through. Damage: one write on a |
| 4600 | 4599 | just-archived term; nothing corrupts, and every later write is refused. |
| 4601 | 4600 | |
| 4602 | -In-process locks remain, and they are a *second* line, never the guarantee: | |
| 4603 | -`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional | |
| 4604 | --write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is | |
| 4605 | -the cap — the lock only tames the retry loop, and keeps the tests' in-memory | |
| 4606 | -engine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in | |
| 4607 | -front of a rule no single-record write can express. Removing one of them costs | |
| 4608 | -throughput or an accepted race; removing the conditional write behind it costs | |
| 4609 | -the invariant. | |
| 4610 | - | |
| 4611 | -Boot is unconditional: the schema batches, the backfills and the admin seed all | |
| 4612 | -run on every start, because exactly one process ever starts (the one exception | |
| 4613 | -is the marked one-time repair below). Deployment is | |
| 4614 | -stop-the-world — `podman compose down` then `up`, never overlapping — and a | |
| 4615 | -release that adds or renames a stored counter *requires* it. An old binary | |
| 4616 | -writes rows without touching the new counter, the `= NONE` backfill guard | |
| 4617 | -(correctly) refuses to re-seed, and the resulting permanent under-count lets a | |
| 4618 | -guard approve exactly what it exists to refuse. The one exception is a counter | |
| 4619 | -that is not an opinion but a plain row count — a board's `total_stroke_count`, | |
| 4620 | -recomputed from its strokes on every boot rather than seeded once, which is why | |
| 4621 | -that repair heals an under-count the `= NONE` guard would have skipped. | |
| 4622 | -In-flight work does not survive | |
| 4623 | -a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`. | |
| 4624 | - | |
| 4625 | -The one thing boot does *not* redo is tracked in `migration_mark` — one row per | |
| 4626 | -backfill that is genuinely one-time, keyed by the backfill's own name. Most | |
| 4627 | -backfills converge to a `WHERE` that matches nothing and are free to re-run, so | |
| 4628 | -they carry no mark; the board-roster repair is different because its cost is | |
| 4629 | -the **scan** (a `user` pass per board) rather than the write, so it is gated on | |
| 4630 | -`migration_mark:board_roster` and skipped entirely once done. A volume that | |
| 4631 | -never ran the repair holds no mark and still gets repaired on its next boot. | |
| 4601 | +One in-process lock remains, and it is a *second* line, never the guarantee: | |
| 4602 | +`PRESENCE_LOCK` guards the exam-room presence map (in-process socket state; | |
| 4603 | +there is no row to conditional-write). The other two are gone with the old | |
| 4604 | +store: `CLAIM_LOCK` tamed a retry loop that `tx_with_retry` now owns, and | |
| 4605 | +what `APPOINTMENT_LOCK` serialized is three database guarantees — the seat | |
| 4606 | +claim's one-statement write, the publish-overlap exclusion constraint, and | |
| 4607 | +the serializable approval. | |
| 4608 | + | |
| 4609 | +Boot is idempotent: the sqlx migrators apply `migrations/control` to the | |
| 4610 | +control database (and `migrations/school` to the school template, and to | |
| 4611 | +every school database at mint), tracked in `_sqlx_migrations`, so a second | |
| 4612 | +boot touches nothing; the builder seed runs on every start but writes only | |
| 4613 | +when the username is absent. A release that adds a migration simply applies | |
| 4614 | +it on the next boot — there is no stop-the-world counter backfill to | |
| 4615 | +schedule and no `migration_mark`: the counters the guards lean on | |
| 4616 | +(`total_stroke_count` among them) are maintained by the same conditional | |
| 4617 | +writes that spend them. In-flight work does not survive a restart either: | |
| 4618 | +a chatbot turn left `pending` by a dead process reads back as `failed` | |
| 4619 | +(a read-time projection, not a sweep). | |
| 4632 | 4620 | |
| 4633 | 4621 | ## Layout |
| 4634 | 4622 | |
| @@ -4640,19 +4628,26 @@ src/ | ||
| 4640 | 4628 | constant.rs validation limits |
| 4641 | 4629 | validate.rs field validators (used by every newtype's try_new) |
| 4642 | 4630 | error.rs ValidationError + AppError -> HTTP responses |
| 4643 | - database.rs SurrealDB server connect (ws) + SCHEMAFULL migration; init() | |
| 4644 | - brings up the control database, migrate() a school's | |
| 4645 | - tenant.rs Slug · SchoolStatus · School · Tenants: one database per | |
| 4646 | - school inside one namespace, plus the control database that | |
| 4647 | - registers them (DEMO_SLUG is the in-memory test school) | |
| 4648 | - migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR, | |
| 4649 | - MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them, | |
| 4650 | - and CONTROL_MIGRATION_BATCHES for the control database | |
| 4631 | + database.rs PgPool + tx_with_retry (a guarded BEGIN…COMMIT that re-runs | |
| 4632 | + while Postgres says "contended") + the two sqlx migrator | |
| 4633 | + sets; init() brings up the control database, a mint | |
| 4634 | + migrates a school's from the shared template | |
| 4635 | + tenant.rs Slug · SchoolStatus · School · Tenants: one Postgres | |
| 4636 | + database per school (`{control}_school_{slug}`), plus the | |
| 4637 | + control database that registers them (DEMO_SLUG is the | |
| 4638 | + tests' school) | |
| 4639 | + db/ the only layer that executes queries: per-table SQL, one | |
| 4640 | + file per resource · cap.rs (the count-cap CTE recipes and | |
| 4641 | + their verdict types) · field_update.rs (one UPDATE … SET | |
| 4642 | + from only the fields a PATCH carried) · page.rs (PagedList: | |
| 4643 | + one paged SELECT — the window and its `total`) | |
| 4644 | + service/ workflows the handlers call: each multi-step invariant is | |
| 4645 | + one tx_with_retry-guarded transaction | |
| 4651 | 4646 | module.rs Module (one router nest a school may buy) · Package · |
| 4652 | 4647 | ModuleSet: dependency edges, validation, stored names |
| 4653 | 4648 | rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier |
| 4654 | 4649 | state.rs AppState { db, tenants, files_path, cookie_secure, rate_limit, |
| 4655 | - chatbot_limit, exam_presence, board_hub, db_up, ai } | |
| 4650 | + chatbot_limit, exam_presence, board_hub, ai, metrics } | |
| 4656 | 4651 | ai/ QUIC bridge to the out-of-process AI services |
| 4657 | 4652 | (see "AI bridge (QUIC)"; the HTTP half is web/ai.rs) |
| 4658 | 4653 | protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing |
| @@ -4665,33 +4660,23 @@ src/ | ||
| 4665 | 4660 | changed, so its stored output is refreshed in a background task |
| 4666 | 4661 | api.rs AI_API_ALLOWLIST: the exact REST paths an AI service may read |
| 4667 | 4662 | (deny-by-default, segment-for-segment, no wildcard tail) |
| 4668 | - domain/ validated newtypes + entities (derive SurrealValue), | |
| 4669 | - each owning its persistence | |
| 4663 | + domain/ validated newtypes + entities (pure data and validation; | |
| 4664 | + persistence lives in db/) | |
| 4670 | 4665 | user.rs UserId · Username · Password · PasswordHash · User (has role) |
| 4671 | 4666 | role.rs Role enum (student < teacher < manager < admin), at_least() |
| 4672 | - field_update.rs FieldUpdate: one UPDATE ... SET built from only the fields a | |
| 4673 | - PATCH actually carried (an omitted field is never written) | |
| 4674 | - monotonic_id.rs next_ulid: ids that sort in write order — one process-wide | |
| 4675 | - Generator, so same-millisecond rows never scramble | |
| 4667 | + monotonic_id.rs next_uuid: UUIDv7 ids that sort in write order — one | |
| 4668 | + process-wide ContextV7, so same-millisecond rows never scramble | |
| 4676 | 4669 | key.rs sitting(): the deterministic per-sitting record key shared by |
| 4677 | 4670 | attempts, answers, answer images and results (seq 1 stays bare) |
| 4678 | - cap.rs claim()/release(): the count caps the database enforces — an | |
| 4679 | - atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter | |
| 4680 | - column of the parent row, replacing count-then-write mutexes | |
| 4681 | - that could not see a concurrent insert; | |
| 4682 | - claim_and_create() commits that seat and the child row in | |
| 4683 | - one transaction, for children with a deterministic id | |
| 4684 | 4671 | text_fold.rs case- and diacritic-insensitive folding for search, shared by |
| 4685 | - the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…) | |
| 4686 | - page.rs PagedList: one paged SELECT — the window and its `total`, both | |
| 4687 | - done by the database rather than by slicing a full scan | |
| 4672 | + the Rust needle and the SQL column (Turkish İ/ı, ü, ö…) | |
| 4688 | 4673 | session.rs SessionId · SessionToken · Session (7-day expiry) |
| 4689 | 4674 | builder.rs BuilderId · Builder · BuilderSession: the deployment operator |
| 4690 | 4675 | who creates and suspends schools, in the control database |
| 4691 | 4676 | timestamp.rs Timestamp (unix-millisecond instant) |
| 4692 | 4677 | note.rs NoteId · NoteTitle · NoteContent · Note |
| 4693 | 4678 | note_file.rs NoteFileId · FileName · FileContentType · NoteFile (metadata row; |
| 4694 | - blob on disk under FILES_PATH, named by the row's ULID) | |
| 4679 | + blob on disk under FILES_PATH, named by the row's uuid) | |
| 4695 | 4680 | event.rs EventId · EventTitle · EventDescription · Event |
| 4696 | 4681 | attendance.rs AttendanceId · AttendanceStatus · Attendance |
| 4697 | 4682 | course.rs CourseId · CourseTitle · CourseDescription · Course |
| @@ -4842,19 +4827,21 @@ src/ | ||
| 4842 | 4827 | limits.rs GET /limits: every constant.rs bound served as JSON |
| 4843 | 4828 | ``` |
| 4844 | 4829 | |
| 4845 | -Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory | |
| 4846 | -db), rate-limit (both tiers, proxy-header and peer-address keying, shipped | |
| 4830 | +Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` over | |
| 4831 | +per-test PostgreSQL databases), rate-limit (both tiers, proxy-header and peer-address keying, shipped | |
| 4847 | 4832 | limits over every route, two limiters sharing one budget over one db), e2e |
| 4848 | 4833 | (real TCP + reqwest cookie jar), persistence |
| 4849 | -(tempfile file engine, including close + reopen), ai-bridge (real QUIC on | |
| 4834 | +(an idempotent re-migration over a live database must leave its seeded rows | |
| 4835 | +intact), ai-bridge (real QUIC on | |
| 4850 | 4836 | loopback against a fake AI service), ai-protocol (the `hab/2` wire contract, |
| 4851 | 4837 | driven by a client that shares no code with the backend). |
| 4852 | 4838 | |
| 4853 | -The cross-school isolation probes run twice: once in memory mode, once against | |
| 4854 | -a **real** SurrealDB, because production is remote mode and there a school is a | |
| 4855 | -database inside one namespace rather than its own datastore. So `cargo test` | |
| 4856 | -starts a throwaway `surreal start … memory` server on a free port, taken from | |
| 4857 | -`~/.surrealdb/surreal`, and kills it when the last test using it finishes. A | |
| 4858 | -missing binary is a hard failure, not a skip — install it with | |
| 4859 | -`curl -sSf https://install.surrealdb.com | sh`, or set `HEZARFEN_SKIP_REMOTE=1` | |
| 4860 | -to skip the remote half deliberately. | |
| 4839 | +Every suite runs against a **real** PostgreSQL, because production is real | |
| 4840 | +PostgreSQL. The harness (tests/common) mints each test a private pair of | |
| 4841 | +databases on one server — `heztest_<16 hex>` for the control side and its | |
| 4842 | +`heztest_<…>_school_demo` school, template-cloned so a schema edit migrates | |
| 4843 | +the shared template once — and drops them when the deployment's last handle | |
| 4844 | +dies; a janitor sweeps what a crashed run left behind. The server comes from | |
| 4845 | +`HEZARFEN_TEST_DATABASE_URL` (default: the compose stack's maintenance | |
| 4846 | +database). A missing server is a hard failure, not a skip — start it with | |
| 4847 | +`podman compose up -d postgres`. |
src/db/appointment.rsmodified+1 -1
| @@ -245,7 +245,7 @@ pub async fn list_for_slot( | ||
| 245 | 245 | /// bump back with it. Zero rows means "full, or the slot was deleted since |
| 246 | 246 | /// the caller read it": the marker is one, and the caller re-reads to pick |
| 247 | 247 | /// the 404/409. |
| 248 | -pub async fn claim_slot_and_create( | |
| 248 | +pub(crate) async fn claim_slot_and_create( | |
| 249 | 249 | db: &Database, |
| 250 | 250 | appointment: Appointment, |
| 251 | 251 | ) -> Result<Claimed<Appointment>, AppError> { |
src/db/exam_attempt.rsmodified+1 -1
| @@ -360,7 +360,7 @@ pub(crate) async fn create_in( | ||
| 360 | 360 | /// [`create_in`]. Retried while Postgres answers "contended"; a duplicate |
| 361 | 361 | /// or a missing student row is a verdict, not a conflict, and is never |
| 362 | 362 | /// re-sent. |
| 363 | -pub async fn create( | |
| 363 | +pub(crate) async fn create( | |
| 364 | 364 | db: &Database, |
| 365 | 365 | attempt: &ExamAttempt, |
| 366 | 366 | count_sitting: bool, |
src/db/fee_plan_assignment.rsmodified+1 -1
| @@ -41,7 +41,7 @@ pub async fn read( | ||
| 41 | 41 | /// pair first; their row is the answer); zero rows → [`Claimed::Full`] (the |
| 42 | 42 | /// counter is uncapped, so the only miss is a plan a concurrent delete |
| 43 | 43 | /// already removed); one row → [`Claimed::Made`]. |
| 44 | -pub async fn create( | |
| 44 | +pub(crate) async fn create( | |
| 45 | 45 | db: &Database, |
| 46 | 46 | plan: &FeePlanId, |
| 47 | 47 | student: &UserId, |
src/db/registration.rsmodified+1 -1
| @@ -61,7 +61,7 @@ pub async fn list_for_event(db: &Database, event: &EventId) -> Result<Vec<Regist | ||
| 61 | 61 | /// `registration_event_user`); `Full` — the event is at its capacity, was |
| 62 | 62 | /// deleted, or the holder fell to `parent` (all one marker; the caller |
| 63 | 63 | /// re-reads to pick the message). |
| 64 | -pub async fn claim_seat( | |
| 64 | +pub(crate) async fn claim_seat( | |
| 65 | 65 | db: &Database, |
| 66 | 66 | event: &EventId, |
| 67 | 67 | user: &UserId, |
src/telemetry.rsmodified+0 -13
| @@ -143,10 +143,6 @@ pub struct Metrics { | ||
| 143 | 143 | pub panics_total: Counter<u64>, |
| 144 | 144 | /// Requests refused by the rate limiter (attr: `tier`). |
| 145 | 145 | pub rate_limit_rejections_total: Counter<u64>, |
| 146 | - /// Database keepalive ping latency in seconds. | |
| 147 | - pub db_ping_duration: Histogram<f64>, | |
| 148 | - /// 1 when the last database ping answered, 0 when it did not. | |
| 149 | - pub db_up: Gauge<u64>, | |
| 150 | 146 | /// AI services currently registered on the QUIC bridge. |
| 151 | 147 | pub ai_workers: Gauge<u64>, |
| 152 | 148 | /// AI requests dispatched and not yet answered. |
| @@ -197,15 +193,6 @@ impl Metrics { | ||
| 197 | 193 | .u64_counter("rate_limit_rejections_total") |
| 198 | 194 | .with_description("Requests refused by a rate limit tier") |
| 199 | 195 | .build(), |
| 200 | - db_ping_duration: meter | |
| 201 | - .f64_histogram("db_ping_duration") | |
| 202 | - .with_unit("s") | |
| 203 | - .with_description("Database keepalive ping round trip") | |
| 204 | - .build(), | |
| 205 | - db_up: meter | |
| 206 | - .u64_gauge("db_up") | |
| 207 | - .with_description("1 when the last database ping answered") | |
| 208 | - .build(), | |
| 209 | 196 | ai_workers: meter |
| 210 | 197 | .u64_gauge("ai_workers") |
| 211 | 198 | .with_description("AI services registered on the QUIC bridge") |