diff --git a/README.md b/README.md index 00a6ab3..25792ce 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,10 @@ prepare database those checks run against, and the committed `.sqlx` cache lets a build run with `SQLX_OFFLINE=true` and no database at all. On boot the sqlx migrator applies `migrations/control` to the control database and ensures the school template; each school database runs `migrations/school` -the same way at mint. Interactive API docs (Swagger UI) are served at +the same way at mint. A school is registered as `provisioning` until that +migration has run, so a boot cut short mid-create leaves a row the next boot +finishes rather than a school that answers every request with a `500`. +Interactive API docs (Swagger UI) are served at `/swagger`, the raw OpenAPI spec at `/api-docs/openapi.json`. ## Run in a container (podman) @@ -1362,7 +1365,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). | | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. | | GET | `/schools/{slug}` | builder | One school by slug. | -| 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. | +| 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. | | DELETE | `/schools/{slug}` | builder | Delete a school: its database, its registry row, and its uploaded files. Irreversible — suspension is the reversible door. | | 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. | | POST | `/schools/{slug}/enter` | builder | Enter a school as one of its admins — support access, with the school's own session cookie (`.`) and no builder power inside it. | diff --git a/migrations/control/20260915000001_school_provisioning.sql b/migrations/control/20260915000001_school_provisioning.sql new file mode 100644 index 0000000..f672a94 --- /dev/null +++ b/migrations/control/20260915000001_school_provisioning.sql @@ -0,0 +1,17 @@ +-- A school is `provisioning` from the instant its registry row lands until its +-- database exists and carries the school schema. +-- +-- The row commits before the database does — `CREATE DATABASE` cannot join the +-- transaction that claims the slug, so the two are never one write — and a boot +-- that dies in between used to leave a school the API advertised as ready while +-- its database had no tables at all (every request against it a 500, and +-- nothing able to tell "half-made" from "shipped"). With the third state, the +-- row says which it is, the boot finishes what the previous one started (see +-- `Tenants::reconcile_provisioning`), and the school's own doors refuse it +-- until then. +-- +-- `active` and `suspended` remain the only two a client may ask for: the +-- PATCH body's parser still refuses anything else (see `SchoolStatus::try_from_str`). +ALTER TABLE school DROP CONSTRAINT school_status; +ALTER TABLE school + ADD CONSTRAINT school_status CHECK (status IN ('active', 'suspended', 'provisioning')); \ No newline at end of file diff --git a/src/database.rs b/src/database.rs index 765aec6..6afa12c 100644 --- a/src/database.rs +++ b/src/database.rs @@ -83,7 +83,12 @@ pub async fn init(cfg: &Config) -> Result { let template = format!("{control_db}_school_template"); ensure_template(&control, &base, &template).await?; - Ok(Tenants::new(control, base, control_db)) + let tenants = Tenants::new(control, base, control_db); + // Schools a previous boot left half-made (its registry row committed, its + // database not yet there) are finished before this one serves anything. + tenants.reconcile_provisioning().await?; + + Ok(tenants) } /// 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) -> ))) .execute(&mut *session) .await - && !is_duplicate_database(&err) { - panic!("create the school template {name}: {err}"); - } + && !is_duplicate_database(&err) + { + panic!("create the school template {name}: {err}"); + } let pool = pool_options(1) .connect_with(base.clone().database(&name)) .await diff --git a/src/db/person.rs b/src/db/person.rs index 2ac1868..3ee23a2 100644 --- a/src/db/person.rs +++ b/src/db/person.rs @@ -128,13 +128,17 @@ pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Re Ok(()) } -/// Drop every membership pointing at a school — [`crate::tenant::Tenants::drop`]'s -/// first control-plane half, so `ON DELETE NO ACTION` never refuses the -/// registry delete. Persons themselves survive: a person is a global -/// account, not the school's. -pub async fn delete_memberships_by_school(db: &Database, school: &SchoolId) -> Result<(), AppError> { +/// Drop every membership pointing at a school — the control-plane half of +/// [`crate::tenant::Tenants::drop`], inside the transaction that also drops the +/// entitlements and the registry row, so `ON DELETE NO ACTION` never refuses +/// the registry delete and a failure leaves none of the three behind. Persons +/// themselves survive: a person is a global account, not the school's. +pub async fn delete_memberships_by_school( + exe: impl sqlx::PgExecutor<'_>, + school: &SchoolId, +) -> Result<(), AppError> { sqlx::query!("DELETE FROM person_school WHERE school = $1", school.uuid()) - .execute(db) + .execute(exe) .await?; Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index ca6e80e..c36c733 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,7 +51,7 @@ use crate::web::module_gate::gate; tags( (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"), (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"), - (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."), + (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."), (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 `.` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.` 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"), (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"), (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`"), diff --git a/src/tenant.rs b/src/tenant.rs index 99a3256..fa8cb24 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -116,6 +116,13 @@ pub fn school_db_name(control_db: &str, id: Uuid) -> String { /// Whether a school may be reached at all. Suspension is immediate and total: /// [`Tenants::get`] refuses before any handler runs, and login is no exception. /// +/// [`SchoolStatus::Provisioning`] is the boot's bookkeeping, not the vendor's: +/// it marks the window between the registry row committing and the school's +/// database carrying the schema (the two cannot be one write). A client can +/// never ask for it — [`SchoolStatus::try_from_str`] refuses the word — and a +/// boot closes the window by finishing the provisioning or leaving the row for +/// the next one. +/// /// Stored as a bare lowercase string, like [`crate::domain::role::Role`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, sqlx::Type)] #[sqlx(type_name = "TEXT", rename_all = "lowercase")] @@ -123,6 +130,7 @@ pub fn school_db_name(control_db: &str, id: Uuid) -> String { pub enum SchoolStatus { Active, Suspended, + Provisioning, } impl SchoolStatus { @@ -130,9 +138,13 @@ impl SchoolStatus { match self { SchoolStatus::Active => "active", SchoolStatus::Suspended => "suspended", + SchoolStatus::Provisioning => "provisioning", } } + /// The statuses a *client* may name. `provisioning` is deliberately absent: + /// it is the boot's word for a school that is being made, so a PATCH that + /// asks for it is a validation error rather than a state anyone can enter. pub fn try_from_str(value: &str) -> Result { match value { "active" => Ok(SchoolStatus::Active), @@ -265,17 +277,27 @@ impl School { Ok((rows, total)) } - /// Rename a school — its display `name`, not its slug. The slug is - /// immutable in this cut (it is the cookie prefix and the files - /// subdirectory), though it no longer names the database: the uuid does. - pub async fn update_name( + /// Rename a school and/or flip its status — its display `name`, not its + /// slug, which is immutable in this cut (it is the cookie prefix and the + /// files subdirectory), though it no longer names the database: the uuid + /// does. + /// + /// Both fields land in **one** statement, so a patch that carries both can + /// never leave half of itself behind, and an omitted field is kept by + /// `COALESCE` over the row being written — never over a snapshot the caller + /// read, so a concurrent patch of the other field cannot be reverted + /// either. + pub async fn update( slug: &Slug, - name: &str, + name: Option<&str>, + status: Option, control: &Database, ) -> Result { sqlx::query_as::<_, School>( "WITH updated AS ( - UPDATE school SET name = $1 WHERE slug = $2 + UPDATE school + SET name = COALESCE($1, name), status = COALESCE($2, status) + WHERE slug = $3 RETURNING id, slug, name, status, created_at ) SELECT u.id, u.slug, u.name, u.status, u.created_at, @@ -285,6 +307,7 @@ impl School { GROUP BY u.id, u.slug, u.name, u.status, u.created_at", ) .bind(name) + .bind(status) .bind(slug.as_str()) .fetch_optional(control) .await? @@ -366,7 +389,8 @@ impl Tenants { /// The handle for a school a request may use, or the refusal a request /// gets: unknown → `401` (a wrong school is a wrong credential, and a `404` - /// would enumerate the customer list), suspended → `403`. + /// would enumerate the customer list), suspended → `403`, still being + /// provisioned → `403` as well (its database has no schema to serve yet). /// /// corner-cut: the registry row is read on every request, so a suspension /// takes effect on the next call with no invalidation protocol. That is one @@ -387,6 +411,10 @@ impl Tenants { self.evict(school.get_id()).await; Err(AppError::Forbidden("school is suspended")) } + Some(school) if school.status == SchoolStatus::Provisioning => { + self.evict(school.get_id()).await; + Err(AppError::Forbidden("school is still being provisioned")) + } Some(school) => Ok(ResolvedTenant { slug: slug.clone(), db: self.handle(school.get_id()).await?, @@ -397,11 +425,17 @@ impl Tenants { /// [`Tenants::get`] for builder tooling, which must still reach a suspended /// school to un-suspend or inspect it. Unknown → `404`, because a builder is - /// authenticated and there is nothing to hide from them. + /// authenticated and there is nothing to hide from them. A school that is + /// still being provisioned is a `409`: the two routes that come through + /// here (`enter`, `reset_admin_password`) need its database to answer, and a + /// table-less one would surface as a `500` instead of "not ready yet". pub async fn get_any_status(&self, slug: &Slug) -> Result<(Database, SchoolStatus), AppError> { let school = School::read(slug, &self.control) .await? .ok_or(AppError::NotFound)?; + if school.status == SchoolStatus::Provisioning { + return Err(AppError::Conflict("school is still being provisioned")); + } Ok((self.handle(school.get_id()).await?, school.status)) } @@ -431,7 +465,7 @@ impl Tenants { .bind(id.uuid()) .bind(slug.as_str()) .bind(name) - .bind(SchoolStatus::Active) + .bind(SchoolStatus::Provisioning) .bind(Timestamp::now().as_millis()) .execute(&mut *tx) .await; @@ -521,23 +555,26 @@ impl Tenants { pool.close().await; migrated?; } + // The schema is there, so the school stops saying it is being made + // (see [`SchoolStatus::Provisioning`]). Both callers want exactly this: + // the create that minted the row a moment ago, and the boot that is + // finishing one a previous boot left behind. + sqlx::query("UPDATE school SET status = $1 WHERE id = $2") + .bind(SchoolStatus::Active) + .bind(id.uuid()) + .execute(&self.control) + .await?; Ok(pool) } - /// Flip a school between active and suspended. Suspending also drops the - /// cached pool, so nothing that already resolved keeps serving. + /// Flip a school between `active` and `suspended` — the one-field form of + /// [`School::update`], which is where the write itself lives. Suspending + /// also drops the cached pool, so nothing that already resolved keeps + /// serving. pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> { - let updated: Option = - sqlx::query_scalar("UPDATE school SET status = $1 WHERE slug = $2 RETURNING id") - .bind(status) - .bind(slug.as_str()) - .fetch_optional(&self.control) - .await?; - let Some(id) = updated else { - return Err(AppError::NotFound); - }; + let school = School::update(slug, None, Some(status), &self.control).await?; if status == SchoolStatus::Suspended { - self.evict(SchoolId(id)).await; + self.evict(school.get_id()).await; } Ok(()) } @@ -589,30 +626,82 @@ impl Tenants { // database is about to go away, and `WITH (FORCE)` should never find // one of our connections to kill. self.evict(id).await; - // The control-plane rows pointing at the school by uuid — membership - // and entitlement alike — go first: `ON DELETE NO ACTION` would refuse - // the registry delete while any stand. Person sessions carry no - // school, so only memberships go — the persons themselves survive (a - // person is a global account, not the school's). - crate::db::person::delete_memberships_by_school(&self.control, &id).await?; - sqlx::query("DELETE FROM school_module WHERE school = $1") - .bind(id.uuid()) - .execute(&self.control) - .await?; + // The database goes first — it is the half that can fail on its own + // (`DROP DATABASE` cannot join a transaction) — and everything after it + // is one transaction. A failure can then only leave "database gone, + // registry rows intact", which re-running this same call completes, + // rather than a destroyed membership set on a school that still stands + // (every one of its people locked out, nothing able to put them back). let db_name = school_db_name(&self.control_db, id.uuid()); sqlx::query(sqlx::AssertSqlSafe( create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)", )) .execute(&self.control) .await?; + // The control-plane rows pointing at the school by uuid — membership + // and entitlement alike — go as one write: `ON DELETE NO ACTION` would + // refuse the registry delete while any stand. Person sessions carry no + // school, so only memberships go — the persons themselves survive (a + // person is a global account, not the school's). + let mut tx = self.control.begin().await?; + crate::db::person::delete_memberships_by_school(&mut *tx, &id).await?; + sqlx::query("DELETE FROM school_module WHERE school = $1") + .bind(id.uuid()) + .execute(&mut *tx) + .await?; sqlx::query("DELETE FROM school WHERE id = $1") .bind(id.uuid()) - .execute(&self.control) + .execute(&mut *tx) .await?; + tx.commit().await?; Ok(()) } + /// Finish the schools a previous boot left half-made. + /// + /// A school's registry row commits before its database exists — the two + /// cannot be one write, `CREATE DATABASE` being the one statement Postgres + /// refuses inside a transaction — so a boot that dies in between leaves a + /// row marked [`SchoolStatus::Provisioning`] and no schema behind it. This + /// runs the half that boot could not: create the database, migrate it, and + /// take the row to `active` (all of it [`Tenants::bring_up`]). A school that + /// fails again stays `provisioning` and is retried on the next boot, and the + /// builder can always `DELETE` it. + /// + /// What it cannot do is seed a first admin — that only ever lived in the web + /// create path, after this point — so a finished school may have no account + /// anybody can log into. The builder sees it in the list and either + /// `DELETE`s it and creates it again, or uses an account it already has. + pub async fn reconcile_provisioning(&self) -> Result<(), AppError> { + let rows: Vec<(Uuid,)> = + sqlx::query_as("SELECT id FROM school WHERE status = $1 ORDER BY created_at") + .bind(SchoolStatus::Provisioning) + .fetch_all(&self.control) + .await?; + for (id,) in rows { + let id = SchoolId(id); + match self.bring_up(id).await { + Ok(pool) => { + // Nothing has dialled it: this boot's pool is the cache's + // only candidate and no request exists yet, so closing it + // costs nothing and keeps the gauge honest. + pool.close().await; + tracing::info!( + school = %id.uuid(), + "finished provisioning a school the previous boot left half-made — \ + its first admin was never seeded, so DELETE and re-create it if nobody can enter" + ); + } + Err(err) => tracing::warn!( + school = %id.uuid(), + "a school is still provisioning after a retry ({err}) — the next boot tries again" + ), + } + } + Ok(()) + } + /// Forget a school's pool and close it. The next request dials a fresh /// one. /// diff --git a/src/web/builder.rs b/src/web/builder.rs index 959072f..65e3f3d 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -97,8 +97,10 @@ struct SchoolResponse { slug: String, #[schema(example = "Ata Koleji")] name: String, - /// `active` or `suspended`. A suspended school refuses every one of its own - /// users, login included. + /// `active` or `suspended` — plus `provisioning`, which a boot writes only + /// while it is finishing a school a previous boot left half-made (nothing + /// serves one, and the next boot retries it). A suspended school refuses + /// every one of its own users, login included. #[schema(example = "active")] status: String, /// Registered at, UTC unix-milliseconds. @@ -148,7 +150,8 @@ struct CreateSchool { struct UpdateSchool { #[schema(example = "Ata Koleji", max_length = 120)] name: Option, - /// `active` or `suspended`. + /// `active` or `suspended` — `provisioning` is the boot's own word and is + /// refused here. #[schema(example = "suspended")] status: Option, } @@ -449,9 +452,14 @@ async fn get_school( } /// 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. +/// 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. +/// +/// `provisioning` is not a status a client can ask for: it is the boot's word +/// for a school that is still being made, and asking for it is a `400`. /// /// Suspending is immediate and total for the school's own users: their next /// request is a `403`, live session or not. @@ -484,21 +492,16 @@ async fn update_school( .map(SchoolStatus::try_from_str) .transpose()?; - let control = st.tenants.control(); - // An empty patch on an unknown school is still a 404, so the existence - // check is not left to whichever field happened to be present. - School::read(&slug, control) - .await? - .ok_or(AppError::NotFound)?; - if let Some(name) = name { - School::update_name(&slug, &name, control).await?; + // Both fields are one statement: an omitted one keeps its stored value, and + // a patch that carries both can never leave half of itself behind. An empty + // patch on an unknown school is still a 404 — the update answers it, rather + // than whichever field happened to be present. + let school = School::update(&slug, name.as_deref(), status, st.tenants.control()).await?; + if status == Some(SchoolStatus::Suspended) { + // A suspension evicts the pool so nothing that already resolved keeps + // serving; un-suspending needs no invalidation, the next request dials. + st.tenants.evict(school.get_id()).await; } - if let Some(status) = status { - st.tenants.set_status(&slug, status).await?; - } - let school = School::read(&slug, control) - .await? - .ok_or(AppError::NotFound)?; Ok(Json(SchoolResponse::new(&school))) } @@ -766,7 +769,7 @@ async fn patch_school_modules( (status = 400, description = "Invalid password", body = ErrorResponse), (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), (status = 404, description = "No such school, or no such account in it", body = ErrorResponse), - (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse), + (status = 409, description = "That account exists but is not an admin of this school, or the school is still being provisioned", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -813,7 +816,7 @@ async fn reset_admin_password( (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), (status = 403, description = "The school is suspended", body = ErrorResponse), (status = 404, description = "No such school, or no such account in it", body = ErrorResponse), - (status = 409, description = "That account exists but is not an admin of this school", body = ErrorResponse), + (status = 409, description = "That account exists but is not an admin of this school, or the school is still being provisioned", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] diff --git a/tests/builder_api.rs b/tests/builder_api.rs index 273f302..672ddff 100644 --- a/tests/builder_api.rs +++ b/tests/builder_api.rs @@ -295,7 +295,9 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { assert_eq!(renamed.body["status"], "active"); assert_eq!(renamed.body["slug"], "beta"); assert_eq!(renamed.body["created_at"], before.body["created_at"]); - // An empty patch is a no-op read, and a bad status is a 400. + // An empty patch is a no-op read, and a bad status is a 400 — including + // `provisioning`, which is the boot's own word for a school that is still + // being made and not a state a vendor can ask for. let untouched = send( &app, "PATCH", @@ -305,18 +307,21 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { ) .await; assert_eq!(untouched.body["name"], "Beta Koleji"); - assert_eq!( - send( - &app, - "PATCH", - "/schools/beta", - Some(&builder), - Some(json!({ "status": "closed" })), - ) - .await - .status, - StatusCode::BAD_REQUEST - ); + for refused in ["closed", "provisioning"] { + assert_eq!( + send( + &app, + "PATCH", + "/schools/beta", + Some(&builder), + Some(json!({ "status": refused })), + ) + .await + .status, + StatusCode::BAD_REQUEST, + "status {refused:?}" + ); + } // A live cookie, taken out before the suspension. let live = school_login(&app, "beta", "admin", "secret1") diff --git a/tests/persistence.rs b/tests/persistence.rs index f935e6a..f166c9c 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -929,6 +929,74 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() { assert_eq!(before, after, "a re-run must not disturb school rows"); } +/// A boot cut short mid-create leaves a `provisioning` row and no school +/// database. The next boot finishes it — the row goes `active` and the +/// school's own doors answer — instead of leaving a school the API advertises +/// as ready while its database has no tables (every request a `500`). +/// +/// Both halves of the window are pinned: while the row says `provisioning` its +/// own doors refuse it (`403`-class, not a `500` from a table-less database), +/// and after reconciliation the schema is really there. +#[tokio::test] +async fn a_half_made_school_is_finished_by_the_next_boot() { + let tenants = database::init_test_tenants().await; + let control = tenants.control().clone(); + let slug = Slug::try_new("half-made").unwrap(); + let id = hezarfen_backend::tenant::SchoolId::generate(); + + // Exactly what `Tenants::create` commits before it mints a database: the + // registry row (as `provisioning`) and its entitlements. + sqlx::query( + "INSERT INTO school (id, slug, name, status, created_at) VALUES ($1, $2, $3, $4, $5)", + ) + .bind(id.uuid()) + .bind(slug.as_str()) + .bind("Half Made") + .bind("provisioning") + .bind(hezarfen_backend::domain::timestamp::Timestamp::now().as_millis()) + .execute(&control) + .await + .expect("seed a half-made school row"); + + assert!( + tenants.get(&slug).await.is_err(), + "a school that is still being made must not serve" + ); + assert_eq!(status_of(&control, "half-made").await, "provisioning"); + + tenants + .reconcile_provisioning() + .await + .expect("the boot finishes what the previous one started"); + + assert_eq!(status_of(&control, "half-made").await, "active"); + let db = tenants + .get(&slug) + .await + .expect("the finished school answers"); + let users: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user") + .fetch_one(&db) + .await + .expect("the school schema is really there, not merely the row's word"); + assert_eq!(users, 0, "a finished school starts empty"); + + // The database the reconciliation minted is this test's, so it goes with + // the test (the harness only drops what `create` minted). + tenants + .drop(&slug) + .await + .expect("clean up the minted school"); +} + +/// One school's stored status, straight off the registry row. +async fn status_of(control: &Database, slug: &str) -> String { + sqlx::query_scalar("SELECT status FROM school WHERE slug = $1") + .bind(slug) + .fetch_one(control) + .await + .unwrap() +} + /// Every school row as `(slug, name, status, modules)`, in slug order — the /// modules aggregated off the `school_module` child table, as every read path /// assembles them.