forge
Explore
Log in

Don't you dare go Hollow

A school's registry row and its database are never one write

Browse files at this commit

8e58afe8d99cac08ced5355a99f948e887965314Ahmet Kaan GümüşParent: f8d7a2d
  • fix
    • a school's registry row and its database are never one write
Show full message
🐛 fix: a school's registry row and its database are never one write

Three consequences of that one fact — partial states the code could leave
behind and nothing could repair.

**A school is `provisioning` until its schema exists** (new control
migration). The row commits before the database does (`CREATE DATABASE` cannot
join that transaction), so a boot cut short in between used to advertise a
school that answered every request with a `500`; the next boot's
`reconcile_provisioning` now finishes it. While it is being made, the school's
own doors refuse it (`403`) and the two builder routes that need its database
(`enter`, `admin-password`) answer `409` instead of a table-less 500.
`provisioning` is the boot's word alone — the PATCH parser still refuses it,
and a client can never ask for it.

**`Tenants::drop` dropped the database last**, after destroying the memberships
and the entitlements: a transient failure left a school that still stood with
every one of its people locked out and nothing able to put them back. The
database goes first (it is the half that can fail on its own — `DROP DATABASE`
cannot join a transaction either) and everything after it is one transaction,
so a failure leaves "database gone, registry rows intact", which re-running the
same call completes.

**`PATCH /schools/{slug}` wrote name and status as two statements**; a failure
between them left half a patch. Both fields are one statement now, with
`COALESCE` over the row being written — an omitted field keeps its stored value
and a concurrent patch of the other field cannot be reverted.

Local: cargo nextest run --no-fail-fast → 1375 passed. clippy clean.
Live: a seeded `provisioning` row comes back `active` with a 70-table database
and the boot logs the finish; lifecycle probe 200/400/201/204 on the running
server; 8-boot template race 8/8 up, 0 refusals; 4-boot race on a fresh control
database 4/4 up.
README.mdmodified+5 -2
@@ -224,7 +224,10 @@ 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 boot224 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 and225 the sqlx migrator applies `migrations/control` to the control database and
226 ensures the school template; each school database runs `migrations/school`226 ensures the school template; each school database runs `migrations/school`
227-the same way at mint. Interactive API docs (Swagger UI) are served at227+the same way at mint. A school is registered as `provisioning` until that
228+migration has run, so a boot cut short mid-create leaves a row the next boot
229+finishes rather than a school that answers every request with a `500`.
230+Interactive API docs (Swagger UI) are served at
228 `/swagger`, the raw OpenAPI spec at `/api-docs/openapi.json`.231 `/swagger`, the raw OpenAPI spec at `/api-docs/openapi.json`.
229 232
230 ## Run in a container (podman)233 ## Run in a container (podman)
@@ -1362,7 +1365,7 @@ window filtering, before paging; negative values are a `400` naming the field.
1362 | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). |1365 | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). |
1363 | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. |1366 | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. |
1364 | GET | `/schools/{slug}` | builder | One school by slug. |1367 | GET | `/schools/{slug}` | builder | One school by slug. |
1365-| PATCH | `/schools/{slug}` | builder | Rename a school and/or flip it between `active` and `suspended`. Omitted fields keep their value. The slug itself is immutable in this cut — it is the cookie prefix and the blob directory — though it no longer names the database (the school's uuid does); a rename API is not offered yet. |1368+| PATCH | `/schools/{slug}` | builder | Rename a school and/or flip it between `active` and `suspended`. Omitted fields keep their value — both land in one statement, so a request that carries both is one write and never half a patch. The slug itself is immutable in this cut — it is the cookie prefix and the blob directory — though it no longer names the database (the school's uuid does); a rename API is not offered yet. |
1366 | DELETE | `/schools/{slug}` | builder | Delete a school: its database, its registry row, and its uploaded files. Irreversible — suspension is the reversible door. |1369 | DELETE | `/schools/{slug}` | builder | Delete a school: its database, its registry row, and its uploaded files. Irreversible — suspension is the reversible door. |
1367 | POST | `/schools/{slug}/admin-password` | builder | Reset an admin's password inside a school — the "we are locked out" call. Every session that account held is revoked with it, so a stolen cookie does not survive the reset. Works on a suspended school. |1370 | POST | `/schools/{slug}/admin-password` | builder | Reset an admin's password inside a school — the "we are locked out" call. Every session that account held is revoked with it, so a stolen cookie does not survive the reset. Works on a suspended school. |
1368 | POST | `/schools/{slug}/enter` | builder | Enter a school as one of its admins — support access, with the school's own session cookie (`<slug>.<token>`) and no builder power inside it. |1371 | POST | `/schools/{slug}/enter` | builder | Enter a school as one of its admins — support access, with the school's own session cookie (`<slug>.<token>`) and no builder power inside it. |
migrations/control/20260915000001_school_provisioning.sqladded+17 -0
@@ -0,0 +1,17 @@
1+-- A school is `provisioning` from the instant its registry row lands until its
2+-- database exists and carries the school schema.
3+--
4+-- The row commits before the database does — `CREATE DATABASE` cannot join the
5+-- transaction that claims the slug, so the two are never one write — and a boot
6+-- that dies in between used to leave a school the API advertised as ready while
7+-- its database had no tables at all (every request against it a 500, and
8+-- nothing able to tell "half-made" from "shipped"). With the third state, the
9+-- row says which it is, the boot finishes what the previous one started (see
10+-- `Tenants::reconcile_provisioning`), and the school's own doors refuse it
11+-- until then.
12+--
13+-- `active` and `suspended` remain the only two a client may ask for: the
14+-- PATCH body's parser still refuses anything else (see `SchoolStatus::try_from_str`).
15+ALTER TABLE school DROP CONSTRAINT school_status;
16+ALTER TABLE school
17+ ADD CONSTRAINT school_status CHECK (status IN ('active', 'suspended', 'provisioning'));
\ No newline at end of file\ No newline at end of file
src/database.rsmodified+10 -4
@@ -83,7 +83,12 @@ pub async fn init(cfg: &Config) -> Result<Tenants, AppError> {
83 let template = format!("{control_db}_school_template");83 let template = format!("{control_db}_school_template");
84 ensure_template(&control, &base, &template).await?;84 ensure_template(&control, &base, &template).await?;
85 85
86- Ok(Tenants::new(control, base, control_db))86+ let tenants = Tenants::new(control, base, control_db);
87+ // Schools a previous boot left half-made (its registry row committed, its
88+ // database not yet there) are finished before this one serves anything.
89+ tenants.reconcile_provisioning().await?;
90+
91+ Ok(tenants)
87 }92 }
88 93
89 /// Parse `DATABASE_URL` into dial options plus the control database's name —94 /// Parse `DATABASE_URL` into dial options plus the control database's name —
@@ -795,9 +800,10 @@ async fn ensure_test_template(maintenance: &PgPool, base: &PgConnectOptions) ->
795 )))800 )))
796 .execute(&mut *session)801 .execute(&mut *session)
797 .await802 .await
798- && !is_duplicate_database(&err) {803+ && !is_duplicate_database(&err)
799- panic!("create the school template {name}: {err}");804+ {
800- }805+ panic!("create the school template {name}: {err}");
806+ }
801 let pool = pool_options(1)807 let pool = pool_options(1)
802 .connect_with(base.clone().database(&name))808 .connect_with(base.clone().database(&name))
803 .await809 .await
src/db/person.rsmodified+10 -6
@@ -128,13 +128,17 @@ pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Re
128 Ok(())128 Ok(())
129 }129 }
130 130
131-/// Drop every membership pointing at a school — [`crate::tenant::Tenants::drop`]'s131+/// Drop every membership pointing at a school — the control-plane half of
132-/// first control-plane half, so `ON DELETE NO ACTION` never refuses the132+/// [`crate::tenant::Tenants::drop`], inside the transaction that also drops the
133-/// registry delete. Persons themselves survive: a person is a global133+/// entitlements and the registry row, so `ON DELETE NO ACTION` never refuses
134-/// account, not the school's.134+/// the registry delete and a failure leaves none of the three behind. Persons
135-pub async fn delete_memberships_by_school(db: &Database, school: &SchoolId) -> Result<(), AppError> {135+/// themselves survive: a person is a global account, not the school's.
136+pub async fn delete_memberships_by_school(
137+ exe: impl sqlx::PgExecutor<'_>,
138+ school: &SchoolId,
139+) -> Result<(), AppError> {
136 sqlx::query!("DELETE FROM person_school WHERE school = $1", school.uuid())140 sqlx::query!("DELETE FROM person_school WHERE school = $1", school.uuid())
137- .execute(db)141+ .execute(exe)
138 .await?;142 .await?;
139 Ok(())143 Ok(())
140 }144 }
src/lib.rsmodified+1 -1
@@ -51,7 +51,7 @@ use crate::web::module_gate::gate;
51 tags(51 tags(
52 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),52 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),
53 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),53 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
54- (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),54+ (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),
55 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),55 (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),
56 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),56 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
57 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),57 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
src/tenant.rsmodified+121 -32
@@ -116,6 +116,13 @@ pub fn school_db_name(control_db: &str, id: Uuid) -> String {
116 /// Whether a school may be reached at all. Suspension is immediate and total:116 /// Whether a school may be reached at all. Suspension is immediate and total:
117 /// [`Tenants::get`] refuses before any handler runs, and login is no exception.117 /// [`Tenants::get`] refuses before any handler runs, and login is no exception.
118 ///118 ///
119+/// [`SchoolStatus::Provisioning`] is the boot's bookkeeping, not the vendor's:
120+/// it marks the window between the registry row committing and the school's
121+/// database carrying the schema (the two cannot be one write). A client can
122+/// never ask for it — [`SchoolStatus::try_from_str`] refuses the word — and a
123+/// boot closes the window by finishing the provisioning or leaving the row for
124+/// the next one.
125+///
119 /// Stored as a bare lowercase string, like [`crate::domain::role::Role`].126 /// Stored as a bare lowercase string, like [`crate::domain::role::Role`].
120 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, sqlx::Type)]127 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, sqlx::Type)]
121 #[sqlx(type_name = "TEXT", rename_all = "lowercase")]128 #[sqlx(type_name = "TEXT", rename_all = "lowercase")]
@@ -123,6 +130,7 @@ pub fn school_db_name(control_db: &str, id: Uuid) -> String {
123 pub enum SchoolStatus {130 pub enum SchoolStatus {
124 Active,131 Active,
125 Suspended,132 Suspended,
133+ Provisioning,
126 }134 }
127 135
128 impl SchoolStatus {136 impl SchoolStatus {
@@ -130,9 +138,13 @@ impl SchoolStatus {
130 match self {138 match self {
131 SchoolStatus::Active => "active",139 SchoolStatus::Active => "active",
132 SchoolStatus::Suspended => "suspended",140 SchoolStatus::Suspended => "suspended",
141+ SchoolStatus::Provisioning => "provisioning",
133 }142 }
134 }143 }
135 144
145+ /// The statuses a *client* may name. `provisioning` is deliberately absent:
146+ /// it is the boot's word for a school that is being made, so a PATCH that
147+ /// asks for it is a validation error rather than a state anyone can enter.
136 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {148 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
137 match value {149 match value {
138 "active" => Ok(SchoolStatus::Active),150 "active" => Ok(SchoolStatus::Active),
@@ -265,17 +277,27 @@ impl School {
265 Ok((rows, total))277 Ok((rows, total))
266 }278 }
267 279
268- /// Rename a school — its display `name`, not its slug. The slug is280+ /// Rename a school and/or flip its status — its display `name`, not its
269- /// immutable in this cut (it is the cookie prefix and the files281+ /// slug, which is immutable in this cut (it is the cookie prefix and the
270- /// subdirectory), though it no longer names the database: the uuid does.282+ /// files subdirectory), though it no longer names the database: the uuid
271- pub async fn update_name(283+ /// does.
284+ ///
285+ /// Both fields land in **one** statement, so a patch that carries both can
286+ /// never leave half of itself behind, and an omitted field is kept by
287+ /// `COALESCE` over the row being written — never over a snapshot the caller
288+ /// read, so a concurrent patch of the other field cannot be reverted
289+ /// either.
290+ pub async fn update(
272 slug: &Slug,291 slug: &Slug,
273- name: &str,292+ name: Option<&str>,
293+ status: Option<SchoolStatus>,
274 control: &Database,294 control: &Database,
275 ) -> Result<School, AppError> {295 ) -> Result<School, AppError> {
276 sqlx::query_as::<_, School>(296 sqlx::query_as::<_, School>(
277 "WITH updated AS (297 "WITH updated AS (
278- UPDATE school SET name = $1 WHERE slug = $2298+ UPDATE school
299+ SET name = COALESCE($1, name), status = COALESCE($2, status)
300+ WHERE slug = $3
279 RETURNING id, slug, name, status, created_at301 RETURNING id, slug, name, status, created_at
280 )302 )
281 SELECT u.id, u.slug, u.name, u.status, u.created_at,303 SELECT u.id, u.slug, u.name, u.status, u.created_at,
@@ -285,6 +307,7 @@ impl School {
285 GROUP BY u.id, u.slug, u.name, u.status, u.created_at",307 GROUP BY u.id, u.slug, u.name, u.status, u.created_at",
286 )308 )
287 .bind(name)309 .bind(name)
310+ .bind(status)
288 .bind(slug.as_str())311 .bind(slug.as_str())
289 .fetch_optional(control)312 .fetch_optional(control)
290 .await?313 .await?
@@ -366,7 +389,8 @@ impl Tenants {
366 389
367 /// The handle for a school a request may use, or the refusal a request390 /// The handle for a school a request may use, or the refusal a request
368 /// gets: unknown → `401` (a wrong school is a wrong credential, and a `404`391 /// gets: unknown → `401` (a wrong school is a wrong credential, and a `404`
369- /// would enumerate the customer list), suspended → `403`.392+ /// would enumerate the customer list), suspended → `403`, still being
393+ /// provisioned → `403` as well (its database has no schema to serve yet).
370 ///394 ///
371 /// corner-cut: the registry row is read on every request, so a suspension395 /// corner-cut: the registry row is read on every request, so a suspension
372 /// takes effect on the next call with no invalidation protocol. That is one396 /// takes effect on the next call with no invalidation protocol. That is one
@@ -387,6 +411,10 @@ impl Tenants {
387 self.evict(school.get_id()).await;411 self.evict(school.get_id()).await;
388 Err(AppError::Forbidden("school is suspended"))412 Err(AppError::Forbidden("school is suspended"))
389 }413 }
414+ Some(school) if school.status == SchoolStatus::Provisioning => {
415+ self.evict(school.get_id()).await;
416+ Err(AppError::Forbidden("school is still being provisioned"))
417+ }
390 Some(school) => Ok(ResolvedTenant {418 Some(school) => Ok(ResolvedTenant {
391 slug: slug.clone(),419 slug: slug.clone(),
392 db: self.handle(school.get_id()).await?,420 db: self.handle(school.get_id()).await?,
@@ -397,11 +425,17 @@ impl Tenants {
397 425
398 /// [`Tenants::get`] for builder tooling, which must still reach a suspended426 /// [`Tenants::get`] for builder tooling, which must still reach a suspended
399 /// school to un-suspend or inspect it. Unknown → `404`, because a builder is427 /// school to un-suspend or inspect it. Unknown → `404`, because a builder is
400- /// authenticated and there is nothing to hide from them.428+ /// authenticated and there is nothing to hide from them. A school that is
429+ /// still being provisioned is a `409`: the two routes that come through
430+ /// here (`enter`, `reset_admin_password`) need its database to answer, and a
431+ /// table-less one would surface as a `500` instead of "not ready yet".
401 pub async fn get_any_status(&self, slug: &Slug) -> Result<(Database, SchoolStatus), AppError> {432 pub async fn get_any_status(&self, slug: &Slug) -> Result<(Database, SchoolStatus), AppError> {
402 let school = School::read(slug, &self.control)433 let school = School::read(slug, &self.control)
403 .await?434 .await?
404 .ok_or(AppError::NotFound)?;435 .ok_or(AppError::NotFound)?;
436+ if school.status == SchoolStatus::Provisioning {
437+ return Err(AppError::Conflict("school is still being provisioned"));
438+ }
405 Ok((self.handle(school.get_id()).await?, school.status))439 Ok((self.handle(school.get_id()).await?, school.status))
406 }440 }
407 441
@@ -431,7 +465,7 @@ impl Tenants {
431 .bind(id.uuid())465 .bind(id.uuid())
432 .bind(slug.as_str())466 .bind(slug.as_str())
433 .bind(name)467 .bind(name)
434- .bind(SchoolStatus::Active)468+ .bind(SchoolStatus::Provisioning)
435 .bind(Timestamp::now().as_millis())469 .bind(Timestamp::now().as_millis())
436 .execute(&mut *tx)470 .execute(&mut *tx)
437 .await;471 .await;
@@ -521,23 +555,26 @@ impl Tenants {
521 pool.close().await;555 pool.close().await;
522 migrated?;556 migrated?;
523 }557 }
558+ // The schema is there, so the school stops saying it is being made
559+ // (see [`SchoolStatus::Provisioning`]). Both callers want exactly this:
560+ // the create that minted the row a moment ago, and the boot that is
561+ // finishing one a previous boot left behind.
562+ sqlx::query("UPDATE school SET status = $1 WHERE id = $2")
563+ .bind(SchoolStatus::Active)
564+ .bind(id.uuid())
565+ .execute(&self.control)
566+ .await?;
524 Ok(pool)567 Ok(pool)
525 }568 }
526 569
527- /// Flip a school between active and suspended. Suspending also drops the570+ /// Flip a school between `active` and `suspended` — the one-field form of
528- /// cached pool, so nothing that already resolved keeps serving.571+ /// [`School::update`], which is where the write itself lives. Suspending
572+ /// also drops the cached pool, so nothing that already resolved keeps
573+ /// serving.
529 pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> {574 pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> {
530- let updated: Option<Uuid> =575+ let school = School::update(slug, None, Some(status), &self.control).await?;
531- sqlx::query_scalar("UPDATE school SET status = $1 WHERE slug = $2 RETURNING id")
532- .bind(status)
533- .bind(slug.as_str())
534- .fetch_optional(&self.control)
535- .await?;
536- let Some(id) = updated else {
537- return Err(AppError::NotFound);
538- };
539 if status == SchoolStatus::Suspended {576 if status == SchoolStatus::Suspended {
540- self.evict(SchoolId(id)).await;577+ self.evict(school.get_id()).await;
541 }578 }
542 Ok(())579 Ok(())
543 }580 }
@@ -589,30 +626,82 @@ impl Tenants {
589 // database is about to go away, and `WITH (FORCE)` should never find626 // database is about to go away, and `WITH (FORCE)` should never find
590 // one of our connections to kill.627 // one of our connections to kill.
591 self.evict(id).await;628 self.evict(id).await;
592- // The control-plane rows pointing at the school by uuid — membership629+ // The database goes first — it is the half that can fail on its own
593- // and entitlement alike — go first: `ON DELETE NO ACTION` would refuse630+ // (`DROP DATABASE` cannot join a transaction) — and everything after it
594- // the registry delete while any stand. Person sessions carry no631+ // is one transaction. A failure can then only leave "database gone,
595- // school, so only memberships go — the persons themselves survive (a632+ // registry rows intact", which re-running this same call completes,
596- // person is a global account, not the school's).633+ // rather than a destroyed membership set on a school that still stands
597- crate::db::person::delete_memberships_by_school(&self.control, &id).await?;634+ // (every one of its people locked out, nothing able to put them back).
598- sqlx::query("DELETE FROM school_module WHERE school = $1")
599- .bind(id.uuid())
600- .execute(&self.control)
601- .await?;
602 let db_name = school_db_name(&self.control_db, id.uuid());635 let db_name = school_db_name(&self.control_db, id.uuid());
603 sqlx::query(sqlx::AssertSqlSafe(636 sqlx::query(sqlx::AssertSqlSafe(
604 create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)",637 create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)",
605 ))638 ))
606 .execute(&self.control)639 .execute(&self.control)
607 .await?;640 .await?;
641+ // The control-plane rows pointing at the school by uuid — membership
642+ // and entitlement alike — go as one write: `ON DELETE NO ACTION` would
643+ // refuse the registry delete while any stand. Person sessions carry no
644+ // school, so only memberships go — the persons themselves survive (a
645+ // person is a global account, not the school's).
646+ let mut tx = self.control.begin().await?;
647+ crate::db::person::delete_memberships_by_school(&mut *tx, &id).await?;
648+ sqlx::query("DELETE FROM school_module WHERE school = $1")
649+ .bind(id.uuid())
650+ .execute(&mut *tx)
651+ .await?;
608 sqlx::query("DELETE FROM school WHERE id = $1")652 sqlx::query("DELETE FROM school WHERE id = $1")
609 .bind(id.uuid())653 .bind(id.uuid())
610- .execute(&self.control)654+ .execute(&mut *tx)
611 .await?;655 .await?;
656+ tx.commit().await?;
612 657
613 Ok(())658 Ok(())
614 }659 }
615 660
661+ /// Finish the schools a previous boot left half-made.
662+ ///
663+ /// A school's registry row commits before its database exists — the two
664+ /// cannot be one write, `CREATE DATABASE` being the one statement Postgres
665+ /// refuses inside a transaction — so a boot that dies in between leaves a
666+ /// row marked [`SchoolStatus::Provisioning`] and no schema behind it. This
667+ /// runs the half that boot could not: create the database, migrate it, and
668+ /// take the row to `active` (all of it [`Tenants::bring_up`]). A school that
669+ /// fails again stays `provisioning` and is retried on the next boot, and the
670+ /// builder can always `DELETE` it.
671+ ///
672+ /// What it cannot do is seed a first admin — that only ever lived in the web
673+ /// create path, after this point — so a finished school may have no account
674+ /// anybody can log into. The builder sees it in the list and either
675+ /// `DELETE`s it and creates it again, or uses an account it already has.
676+ pub async fn reconcile_provisioning(&self) -> Result<(), AppError> {
677+ let rows: Vec<(Uuid,)> =
678+ sqlx::query_as("SELECT id FROM school WHERE status = $1 ORDER BY created_at")
679+ .bind(SchoolStatus::Provisioning)
680+ .fetch_all(&self.control)
681+ .await?;
682+ for (id,) in rows {
683+ let id = SchoolId(id);
684+ match self.bring_up(id).await {
685+ Ok(pool) => {
686+ // Nothing has dialled it: this boot's pool is the cache's
687+ // only candidate and no request exists yet, so closing it
688+ // costs nothing and keeps the gauge honest.
689+ pool.close().await;
690+ tracing::info!(
691+ school = %id.uuid(),
692+ "finished provisioning a school the previous boot left half-made — \
693+ its first admin was never seeded, so DELETE and re-create it if nobody can enter"
694+ );
695+ }
696+ Err(err) => tracing::warn!(
697+ school = %id.uuid(),
698+ "a school is still provisioning after a retry ({err}) — the next boot tries again"
699+ ),
700+ }
701+ }
702+ Ok(())
703+ }
704+
616 /// Forget a school's pool and close it. The next request dials a fresh705 /// Forget a school's pool and close it. The next request dials a fresh
617 /// one.706 /// one.
618 ///707 ///
src/web/builder.rsmodified+25 -22
@@ -97,8 +97,10 @@ struct SchoolResponse {
97 slug: String,97 slug: String,
98 #[schema(example = "Ata Koleji")]98 #[schema(example = "Ata Koleji")]
99 name: String,99 name: String,
100- /// `active` or `suspended`. A suspended school refuses every one of its own100+ /// `active` or `suspended` — plus `provisioning`, which a boot writes only
101- /// users, login included.101+ /// while it is finishing a school a previous boot left half-made (nothing
102+ /// serves one, and the next boot retries it). A suspended school refuses
103+ /// every one of its own users, login included.
102 #[schema(example = "active")]104 #[schema(example = "active")]
103 status: String,105 status: String,
104 /// Registered at, UTC unix-milliseconds.106 /// Registered at, UTC unix-milliseconds.
@@ -148,7 +150,8 @@ struct CreateSchool {
148 struct UpdateSchool {150 struct UpdateSchool {
149 #[schema(example = "Ata Koleji", max_length = 120)]151 #[schema(example = "Ata Koleji", max_length = 120)]
150 name: Option<String>,152 name: Option<String>,
151- /// `active` or `suspended`.153+ /// `active` or `suspended` — `provisioning` is the boot's own word and is
154+ /// refused here.
152 #[schema(example = "suspended")]155 #[schema(example = "suspended")]
153 status: Option<String>,156 status: Option<String>,
154 }157 }
@@ -449,9 +452,14 @@ async fn get_school(
449 }452 }
450 453
451 /// Rename a school and/or flip it between `active` and `suspended`. Omitted454 /// Rename a school and/or flip it between `active` and `suspended`. Omitted
452-/// fields keep their value. The slug itself is immutable in this cut — it is455+/// fields keep their value — both land in one statement, so a request that
453-/// the cookie prefix and the blob directory — though it no longer names the456+/// carries both is one write and never half a patch. The slug itself is
454-/// database (the school's uuid does); a rename API is not offered yet.457+/// immutable in this cut — it is the cookie prefix and the blob directory —
458+/// though it no longer names the database (the school's uuid does); a rename
459+/// API is not offered yet.
460+///
461+/// `provisioning` is not a status a client can ask for: it is the boot's word
462+/// for a school that is still being made, and asking for it is a `400`.
455 ///463 ///
456 /// Suspending is immediate and total for the school's own users: their next464 /// Suspending is immediate and total for the school's own users: their next
457 /// request is a `403`, live session or not.465 /// request is a `403`, live session or not.
@@ -484,21 +492,16 @@ async fn update_school(
484 .map(SchoolStatus::try_from_str)492 .map(SchoolStatus::try_from_str)
485 .transpose()?;493 .transpose()?;
486 494
487- let control = st.tenants.control();495+ // Both fields are one statement: an omitted one keeps its stored value, and
488- // An empty patch on an unknown school is still a 404, so the existence496+ // a patch that carries both can never leave half of itself behind. An empty
489- // check is not left to whichever field happened to be present.497+ // patch on an unknown school is still a 404 — the update answers it, rather
490- School::read(&slug, control)498+ // than whichever field happened to be present.
491- .await?499+ let school = School::update(&slug, name.as_deref(), status, st.tenants.control()).await?;
492- .ok_or(AppError::NotFound)?;500+ if status == Some(SchoolStatus::Suspended) {
493- if let Some(name) = name {501+ // A suspension evicts the pool so nothing that already resolved keeps
494- School::update_name(&slug, &name, control).await?;502+ // serving; un-suspending needs no invalidation, the next request dials.
503+ st.tenants.evict(school.get_id()).await;
495 }504 }
496- if let Some(status) = status {
497- st.tenants.set_status(&slug, status).await?;
498- }
499- let school = School::read(&slug, control)
500- .await?
501- .ok_or(AppError::NotFound)?;
502 Ok(Json(SchoolResponse::new(&school)))505 Ok(Json(SchoolResponse::new(&school)))
503 }506 }
504 507
@@ -766,7 +769,7 @@ async fn patch_school_modules(
766 (status = 400, description = "Invalid password", body = ErrorResponse),769 (status = 400, description = "Invalid password", body = ErrorResponse),
767 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),770 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
768 (status = 404, description = "No such school, or no such account in it", body = ErrorResponse),771 (status = 404, description = "No such school, or no such account in it", body = ErrorResponse),
769- (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse),772+ (status = 409, description = "That account exists but is not an admin of this school, or the school is still being provisioned", body = ErrorResponse),
770 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),773 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
771 ),774 ),
772 )]775 )]
@@ -813,7 +816,7 @@ async fn reset_admin_password(
813 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),816 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
814 (status = 403, description = "The school is suspended", body = ErrorResponse),817 (status = 403, description = "The school is suspended", body = ErrorResponse),
815 (status = 404, description = "No such school, or no such account in it", body = ErrorResponse),818 (status = 404, description = "No such school, or no such account in it", body = ErrorResponse),
816- (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse),819+ (status = 409, description = "That account exists but is not an admin of this school, or the school is still being provisioned", body = ErrorResponse),
817 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),820 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
818 ),821 ),
819 )]822 )]
tests/builder_api.rsmodified+18 -13
@@ -295,7 +295,9 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
295 assert_eq!(renamed.body["status"], "active");295 assert_eq!(renamed.body["status"], "active");
296 assert_eq!(renamed.body["slug"], "beta");296 assert_eq!(renamed.body["slug"], "beta");
297 assert_eq!(renamed.body["created_at"], before.body["created_at"]);297 assert_eq!(renamed.body["created_at"], before.body["created_at"]);
298- // An empty patch is a no-op read, and a bad status is a 400.298+ // An empty patch is a no-op read, and a bad status is a 400 — including
299+ // `provisioning`, which is the boot's own word for a school that is still
300+ // being made and not a state a vendor can ask for.
299 let untouched = send(301 let untouched = send(
300 &app,302 &app,
301 "PATCH",303 "PATCH",
@@ -305,18 +307,21 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
305 )307 )
306 .await;308 .await;
307 assert_eq!(untouched.body["name"], "Beta Koleji");309 assert_eq!(untouched.body["name"], "Beta Koleji");
308- assert_eq!(310+ for refused in ["closed", "provisioning"] {
309- send(311+ assert_eq!(
310- &app,312+ send(
311- "PATCH",313+ &app,
312- "/schools/beta",314+ "PATCH",
313- Some(&builder),315+ "/schools/beta",
314- Some(json!({ "status": "closed" })),316+ Some(&builder),
315- )317+ Some(json!({ "status": refused })),
316- .await318+ )
317- .status,319+ .await
318- StatusCode::BAD_REQUEST320+ .status,
319- );321+ StatusCode::BAD_REQUEST,
322+ "status {refused:?}"
323+ );
324+ }
320 325
321 // A live cookie, taken out before the suspension.326 // A live cookie, taken out before the suspension.
322 let live = school_login(&app, "beta", "admin", "secret1")327 let live = school_login(&app, "beta", "admin", "secret1")
tests/persistence.rsmodified+68 -0
@@ -929,6 +929,74 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() {
929 assert_eq!(before, after, "a re-run must not disturb school rows");929 assert_eq!(before, after, "a re-run must not disturb school rows");
930 }930 }
931 931
932+/// A boot cut short mid-create leaves a `provisioning` row and no school
933+/// database. The next boot finishes it — the row goes `active` and the
934+/// school's own doors answer — instead of leaving a school the API advertises
935+/// as ready while its database has no tables (every request a `500`).
936+///
937+/// Both halves of the window are pinned: while the row says `provisioning` its
938+/// own doors refuse it (`403`-class, not a `500` from a table-less database),
939+/// and after reconciliation the schema is really there.
940+#[tokio::test]
941+async fn a_half_made_school_is_finished_by_the_next_boot() {
942+ let tenants = database::init_test_tenants().await;
943+ let control = tenants.control().clone();
944+ let slug = Slug::try_new("half-made").unwrap();
945+ let id = hezarfen_backend::tenant::SchoolId::generate();
946+
947+ // Exactly what `Tenants::create` commits before it mints a database: the
948+ // registry row (as `provisioning`) and its entitlements.
949+ sqlx::query(
950+ "INSERT INTO school (id, slug, name, status, created_at) VALUES ($1, $2, $3, $4, $5)",
951+ )
952+ .bind(id.uuid())
953+ .bind(slug.as_str())
954+ .bind("Half Made")
955+ .bind("provisioning")
956+ .bind(hezarfen_backend::domain::timestamp::Timestamp::now().as_millis())
957+ .execute(&control)
958+ .await
959+ .expect("seed a half-made school row");
960+
961+ assert!(
962+ tenants.get(&slug).await.is_err(),
963+ "a school that is still being made must not serve"
964+ );
965+ assert_eq!(status_of(&control, "half-made").await, "provisioning");
966+
967+ tenants
968+ .reconcile_provisioning()
969+ .await
970+ .expect("the boot finishes what the previous one started");
971+
972+ assert_eq!(status_of(&control, "half-made").await, "active");
973+ let db = tenants
974+ .get(&slug)
975+ .await
976+ .expect("the finished school answers");
977+ let users: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user")
978+ .fetch_one(&db)
979+ .await
980+ .expect("the school schema is really there, not merely the row's word");
981+ assert_eq!(users, 0, "a finished school starts empty");
982+
983+ // The database the reconciliation minted is this test's, so it goes with
984+ // the test (the harness only drops what `create` minted).
985+ tenants
986+ .drop(&slug)
987+ .await
988+ .expect("clean up the minted school");
989+}
990+
991+/// One school's stored status, straight off the registry row.
992+async fn status_of(control: &Database, slug: &str) -> String {
993+ sqlx::query_scalar("SELECT status FROM school WHERE slug = $1")
994+ .bind(slug)
995+ .fetch_one(control)
996+ .await
997+ .unwrap()
998+}
999+
932 /// Every school row as `(slug, name, status, modules)`, in slug order — the1000 /// Every school row as `(slug, name, status, modules)`, in slug order — the
933 /// modules aggregated off the `school_module` child table, as every read path1001 /// modules aggregated off the `school_module` child table, as every read path
934 /// assembles them.1002 /// assembles them.