From e879fd37dff334826c2cfd9166faa6f809d22142 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 5 Aug 2026 22:17:51 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=85=20fix:=20withdraw=20the=20calendar?= =?UTF-8?q?=20a=20demotion=20used=20to=20leave=20unreachable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `set_role`'s below-teacher arm dropped course staffing and the homeroom column and stopped there, so a demoted teacher's `appointment_slot` rows outlived the role that published them — and no route could reach them again: the teacher+ branch of `list_slots` lists the caller's OWN slots, so no manager ever learns the id; the below-teacher branch filters out slots whose owner is no longer staff, so neither students nor the demoted owner see them; and both slot deletes are `RequireTeacher`. One undeletable row per slot ever published, forever. A live booking on one was worse. `approve`/`reject`/`reschedule` go through `for_decision`, which needs `can_manage` AND `RequireTeacher`: the demoted owner fails the extractor, and the manager who would pass `can_manage` has no route that yields the id. The requester's `cancel` is refused once the window opens. So the booking sat `pending` in their list for good, pinning the slot's `occupied` at one — which also makes `delete_free`'s `(occupied ?? 0) = 0` guard unsatisfiable. The sweep now runs in the role write's own transaction, beside the other arms: live bookings are flipped to `cancelled` with the ex-teacher on `cancelled_by` and the reason on `cancel_reason`, then the slots go. Cancelled rather than deleted, deliberately. Deleting them is what the slot's own delete cascade does, but that path refuses while a booking is live — precisely because someone is expecting the meeting — and a demotion cannot refuse. This crate has no notification of any kind, so the strongest defined end available to a requester is a settled row they can still read, naming who dropped it and why; deleting it would make a confirmed meeting vanish with no trace at all. The slot goes either way, which is what releases the seat and keeps this convergent; the booking then renders without a window, the shape `AppointmentResponse` already documents for a vanished slot. The race is closed at both ends. A booking landing mid-demotion claims the slot row the sweep deletes, so the store settles it. A slot *published* mid-demotion shared no key with anything the demotion wrote and survived it, so `AppointmentSlot::create`/`publish_weekly` now claim the publisher's own record (`cap::role_claim`, the enrollment/registration pattern): either the sweep sees the slot, or the publish sees the new role and answers 403. Tests: the sweep and the refusal are unit-tested (both go RED on the reverted fix), and the publish-vs-demotion race is a real-server test held open with a DEFINE EVENT — 4/4 rounds strand a slot without the claim, 0/4 with it. --- src/domain/appointment_slot.rs | 270 ++++++++++++++++++++++++++++++--- src/domain/user.rs | 166 +++++++++++++++++++- src/web/appointments.rs | 16 +- src/web/users.rs | 8 +- 4 files changed, 428 insertions(+), 32 deletions(-) diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index 8311100..921fc98 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -15,16 +15,21 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, + APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, ROLES, }; use crate::database::{Database, transaction_with_retry}; use crate::domain::appointment::{APPOINTMENT_LOCK, Appointment}; +use crate::domain::cap; use crate::domain::monotonic_id::next_ulid; +use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_optional; +/// The publisher fell below `teacher` while the publish was in flight. +const UNFIT_MARK: &str = "slot_not_staff"; + // Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish // writes its whole expansion inside one millisecond, which random ULID low // bits would scramble against the `id` tie-break of the `ORDER BY starts_at, @@ -197,9 +202,68 @@ impl AppointmentSlot { .collect() } - async fn insert(slot: AppointmentSlot, db: &Database) -> Result { - let created: Option = db.create(slot.id.record()).content(slot).await?; - created.ok_or_else(|| AppError::Internal("failed to create appointment slot".into())) + /// Write a whole publish — one occurrence or fifty-two — while the publisher + /// still *holds* a teaching role. + /// + /// Every row here names the teacher, so the write touches no key a demotion + /// touches: [`crate::domain::user::User::set_role`] sweeps the slots its own + /// snapshot can see, and a slot landing after that snapshot would survive it + /// under a role that may not publish — reachable by no route afterwards, + /// since the calendar hides a demoted teacher's slots and the deletes are + /// `teacher`-gated. So the teacher's own record is claimed beside the insert + /// ([`cap::role_claim`]), which is the key the demotion writes: either the + /// sweep sees these slots, or this write sees the new role and publishes + /// nothing. + /// + /// The bar is read off the hierarchy rather than spelled out, so a new role + /// cannot drift out of it. + /// + /// Admissible for [`transaction_with_retry`]: the claim is `SELECT`/`UPDATE` + /// only, and the `INSERT` carries freshly minted ULIDs on a table with no + /// `UNIQUE` index, so no rival can make it answer "already exists". + async fn insert_claimed( + teacher: &UserId, + rows: Vec, + db: &Database, + ) -> Result, AppError> { + let staff = ROLES + .iter() + .filter(|role| role.at_least(Role::Teacher)) + .map(|role| format!("'{}'", role.as_str())) + .collect::>() + .join(", "); + let held = cap::role_claim("teacher", &format!("NOT IN [{staff}]"), UNFIT_MARK); + let sql = format!( + "BEGIN TRANSACTION;\n{};\nINSERT INTO {APPOINTMENT_SLOT_TABLE} $rows;\n\ + COMMIT TRANSACTION;", + held.join(";\n") + ); + let (mut result, mut errors) = transaction_with_retry( + db, + &sql, + &[ + ("teacher".into(), teacher.record().into_value()), + ("rows".into(), rows.into_value()), + ], + &[UNFIT_MARK], + ) + .await?; + // Demoted while this ran — the same refusal `RequireTeacher` makes a + // moment earlier, and the only one that can arrive after it. + if errors + .values() + .any(|error| error.to_string().contains(UNFIT_MARK)) + { + return Err(AppError::Forbidden( + "that account no longer holds a teaching role", + )); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // BEGIN plus the claim's own statements — counted, not tallied by hand, + // so a statement added there cannot read back the wrong result. + Ok(result.take::>(held.len() + 1)?) } /// Does the teacher already have a published slot whose window collides with @@ -274,8 +338,9 @@ impl AppointmentSlot { "this time overlaps a slot you have already published".into(), )); } - Self::insert( - AppointmentSlot { + Self::insert_claimed( + teacher, + vec![AppointmentSlot { id: AppointmentSlotId::generate(), teacher: teacher.clone(), starts_at, @@ -283,10 +348,13 @@ impl AppointmentSlot { note, series: None, created_at: Timestamp::now(), - }, + }], db, ) - .await + .await? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to create appointment slot".into())) } /// Publish the same weekly window repeatedly, up to `until`. Every row @@ -344,22 +412,13 @@ impl AppointmentSlot { created_at: now, }) .collect(); - // One statement, therefore one transaction: SurrealDB rolls the whole - // `INSERT` back on any error. The row-by-row loop this replaces did not + // One `INSERT`, therefore all-or-nothing: SurrealDB rolls the whole + // publish back on any error. The row-by-row loop this replaces did not // — a database error at week 7 of 10 answered 500 with six stray weeks // already published, a half-series nobody asked for. It is also a single - // round trip, so the lock is now held for two queries whatever the + // round trip, so the lock is held for two queries whatever the // occurrence count, instead of 1 + N (up to 52) sequential ones. - // - // No `BEGIN`/`COMMIT` wrapper: those consume result slots in this - // version, and a lone statement is already atomic — the explicit form - // would buy nothing but an off-by-one waiting to happen. - let mut result = db - .query("INSERT INTO appointment_slot $rows") - .bind(("rows", rows)) - .await? - .check()?; - let mut created = result.take::>(0)?; + let mut created = Self::insert_claimed(teacher, rows, db).await?; if created.len() != windows.len() { return Err(AppError::Internal(format!( "published {} of {} appointment slots", @@ -822,6 +881,175 @@ mod tests { )); } + /// The claim on the publisher's own record, asked exactly the way the race + /// asks it: a publish whose `RequireTeacher` snapshot predates a demotion + /// must not land, because the sweep in that demotion has already chosen the + /// slots it will take and would leave this one behind — under a role that + /// can neither list nor delete it. + /// + /// Both halves matter: a row that is *not there* claims nothing (every other + /// test here publishes for a teacher with no user row at all), and a live + /// teacher+ passes through untouched. + #[tokio::test] + async fn a_publish_by_someone_who_lost_the_role_is_refused() { + let db = crate::database::init_mem().await.unwrap(); + // Written as a row rather than through `User` — the password hasher is + // private to that module, and the only column this asks about is `role`. + db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'") + .await + .unwrap() + .check() + .unwrap(); + + // The row says `student`, so the claim refuses — one-off and weekly + // alike, since both go through the same write. + let teacher = UserId::from_key("eski"); + assert!(matches!( + AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db).await, + Err(AppError::Forbidden(_)) + )); + assert!(matches!( + AppointmentSlot::publish_weekly( + &teacher, + at(1_000), + at(2_000), + None, + at(1_000 + MILLIS_PER_WEEK), + &db, + ) + .await, + Err(AppError::Forbidden(_)) + )); + assert!( + AppointmentSlot::list_for_teacher(&teacher, &db) + .await + .unwrap() + .is_empty(), + "a refused publish must write nothing" + ); + + // Promoted, the very same publish lands. + db.query("UPDATE user:eski SET role = 'teacher'") + .await + .unwrap() + .check() + .unwrap(); + AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db) + .await + .unwrap(); + assert_eq!( + AppointmentSlot::list_for_teacher(&teacher, &db) + .await + .unwrap() + .len(), + 1 + ); + } + + /// The other half of that claim: the publish that arrives *while* the + /// demotion is running. Its sweep has already chosen the slots it will take + /// ([`crate::domain::user::User::set_role`] reads them into `$slots` before + /// it deletes), so a row landing after that read shares no key with anything + /// the demotion writes and survives it — a slot owned by someone who can + /// neither list nor delete it, forever. The claim on the user record is what + /// puts the two transactions on one key. + /// + /// Real server, and `#[ignore]`d for it, like every other race here: the + /// subject *is* the store's conflict detection, which `init_mem`'s embedded + /// engine does not have — it commits both sides and answers `Ok` to each, so + /// this passes there on broken code. + /// + /// The window is opened by the schema rather than by a lucky interleaving: a + /// `DEFINE EVENT` on the sweep's own `DELETE` holds the demotion open inside + /// its transaction, well past the read that chose `$slots`, so the publish + /// lands in the middle of it every round. + /// + /// Stored state is the verdict, not the return value: whether the publish is + /// refused outright or swept along with the rest of the calendar, no slot may + /// outlive the role. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() { + use crate::domain::role::Role; + use crate::domain::user::User; + + let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await; + let (mut raced, mut published, mut stranded) = (0, 0, 0); + for round in 0..4 { + let key = format!("t{round}"); + let teacher = UserId::from_key(&key); + db.query(format!( + "CREATE user:{key} SET username = '{key}', password_hash = 'x', \ + role = '{}';", + Role::Teacher.as_str() + )) + .await + .unwrap() + .check() + .unwrap(); + // A slot for the sweep to delete — that delete is the seam. + AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db) + .await + .unwrap(); + db.query(format!( + "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {APPOINTMENT_SLOT_TABLE} \ + WHEN $event = 'DELETE' THEN {{ IF $before.teacher = \ + type::record('user', '{key}') {{ SLEEP 300ms }} }};" + )) + .await + .unwrap() + .check() + .unwrap(); + + let demoting = { + let db = db.clone(); + let target = teacher.clone(); + tokio::spawn(async move { + User::read(&target, &db) + .await + .unwrap() + .unwrap() + .set_role(Role::Student, &db) + .await + }) + }; + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + if !demoting.is_finished() { + raced += 1; + } + // The publish a `RequireTeacher` snapshot taken a moment ago allows. + let landed = AppointmentSlot::create( + &teacher, + at(MILLIS_PER_WEEK), + at(MILLIS_PER_WEEK + 1_000), + None, + &db, + ) + .await; + let swept = demoting.await.unwrap(); + assert!(swept.is_ok(), "round {round}: the demotion itself failed"); + if landed.is_ok() { + published += 1; + } + if !AppointmentSlot::list_for_teacher(&teacher, &db) + .await + .unwrap() + .is_empty() + { + stranded += 1; + } + } + eprintln!( + "a publish racing a demotion: {raced}/4 rounds landed inside it, \ + {published} publishes committed" + ); + assert!(raced > 0, "no round ever reached the race"); + assert_eq!( + stranded, 0, + "a slot survived under a role that can neither list nor delete it" + ); + } + #[tokio::test] async fn weekly_publish_that_self_overlaps_is_refused() { let db = crate::database::init_mem().await.unwrap(); diff --git a/src/domain/user.rs b/src/domain/user.rs index a81b560..d3071b9 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -5,11 +5,13 @@ use argon2::{Argon2, PasswordHasher, PasswordVerifier}; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - BOARD_TABLE, CLASS_GROUP_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, - DECOY_PASSWORD, ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, - REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, + APPOINTMENT_SLOT_TABLE, APPOINTMENT_TABLE, BOARD_TABLE, CLASS_GROUP_TABLE, + CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, DECOY_PASSWORD, + ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD, + REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, }; use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::domain::appointment::AppointmentStatus; use crate::domain::board::Board; use crate::domain::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; @@ -580,7 +582,22 @@ impl User { /// can freeze, so it is deleted rather than skipped: skipped, it is /// stranded forever (`unregister` 404s on the missing event). /// * **Below teacher** gives up course staffing and homeroom-teacher - /// columns — only teacher+ may hold either. + /// columns — only teacher+ may hold either — and the published + /// appointment calendar, whose live bookings are cancelled in the same + /// breath. Nothing else could ever reach those: a slot is listed only on + /// its own teacher's calendar and deleted only by a teacher+, so after the + /// demotion neither its owner nor a manager has a route that yields its + /// id, and a booking on it can be neither decided (teacher+ only) nor + /// cancelled once its window opens — leaving the slot's `occupied` seat + /// pinned at one and the slot itself undeletable forever. The requester + /// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the + /// reason on `cancel_reason`; the slot it pointed at is gone, so the + /// booking renders without a window + /// ([`crate::domain::appointment::Appointment`]'s reader already treats a + /// vanished slot that way). There is no notification anywhere in + /// this crate, so a settled row the person can read is the strongest + /// defined end available — and the alternative, deleting it, would make a + /// confirmed meeting vanish with no trace at all. /// /// The returned boards are the rooms whose roster this changed (plus those /// the user created, which cannot be changed and are returned so their room @@ -668,6 +685,34 @@ impl User { batch.push(format!( "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr" )); + // The published calendar goes too, and the bookings on it are + // settled first: a slot only its own teacher can list and only a + // teacher+ can delete is reachable by nobody once that teacher is + // demoted, and a live booking on one is worse — nobody can approve, + // reject or (past its start) cancel it, so it pins the slot's + // `occupied` seat forever. Cancelled rather than deleted so the + // person who asked is left with a settled booking they can still + // read, carrying who dropped it and why; the slot row (and with it + // the seat) goes, which is what makes this convergent. + batch.push(format!( + "LET $slots = (SELECT VALUE id FROM {APPOINTMENT_SLOT_TABLE} WHERE teacher = $usr)" + )); + batch.push(format!( + "UPDATE {APPOINTMENT_TABLE} SET status = '{cancelled}', cancelled_by = $usr, \ + cancel_reason = 'the teacher no longer holds a teaching role' \ + WHERE slot IN $slots AND status IN ['{pending}', '{approved}']", + cancelled = AppointmentStatus::Cancelled.as_str(), + pending = AppointmentStatus::Pending.as_str(), + approved = AppointmentStatus::Approved.as_str(), + )); + // Deleting the slots is also what makes a *concurrent* booking safe: + // `Appointment::book` claims the slot row this deletes, so the two + // collide in the store and the loser re-sends. A slot *published* + // concurrently shares no key with any of this, which is why + // `AppointmentSlot::insert_claimed` claims the user row instead. + batch.push(format!( + "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots" + )); } let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n")); let (mut result, mut errors) = transaction_with_retry( @@ -866,6 +911,119 @@ mod tests { ); } + /// A demotion below `teacher` must take the published calendar with it and + /// settle the bookings on it. Nothing else can: a slot is listed only on its + /// own teacher's calendar (and hidden from every other reader once its owner + /// is demoted), deleted only by a teacher+, and a booking on one can be + /// decided only by a teacher+ and cancelled only by its requester — who is + /// refused the moment the window opens. So a slot left behind here is a row + /// no route can reach and a seat nothing can ever free. + #[tokio::test] + async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { + use crate::domain::appointment::{Appointment, AppointmentReason}; + use crate::domain::appointment_slot::AppointmentSlot; + + let db = init_mem().await.unwrap(); + let staff = |name: &'static str, db: Database| async move { + a_user(name, &db) + .await + .set_role(Role::Teacher, &db) + .await + .unwrap() + .0 + }; + let teacher = staff("ogretmen", db.clone()).await; + let other = staff("digerogretmen", db.clone()).await; + let student = a_user("ogrenci", &db).await; + let soon = |offset| Timestamp::from_millis(Timestamp::now().as_millis() + offset); + let reason = || AppointmentReason::try_new("görüşme").unwrap(); + let slot = |owner: &User, offset: i64, db: Database| { + let owner = owner.get_id().clone(); + async move { + AppointmentSlot::create(&owner, soon(offset), soon(offset + 60_000), None, &db) + .await + .unwrap() + } + }; + + let free = slot(&teacher, 60_000, db.clone()).await; + let asked = slot(&teacher, 180_000, db.clone()).await; + let agreed = slot(&teacher, 300_000, db.clone()).await; + let kept = slot(&other, 60_000, db.clone()).await; + + let pending = Appointment::book(asked.get_id(), student.get_id(), reason(), &db) + .await + .unwrap(); + let approved = Appointment::book(agreed.get_id(), student.get_id(), reason(), &db) + .await + .unwrap(); + Appointment::approve(approved.get_id(), teacher.get_id(), &db) + .await + .unwrap(); + let elsewhere = Appointment::book(kept.get_id(), student.get_id(), reason(), &db) + .await + .unwrap(); + + teacher.clone().set_role(Role::Student, &db).await.unwrap(); + + // The calendar is gone, the booked weeks included. + assert!( + AppointmentSlot::list_for_teacher(teacher.get_id(), &db) + .await + .unwrap() + .is_empty() + ); + for slot in [&free, &asked, &agreed] { + assert!( + AppointmentSlot::read(slot.get_id(), &db) + .await + .unwrap() + .is_none(), + "a slot only a teacher+ could reach outlived the role" + ); + } + // Both bookings — the pending request and the confirmed meeting — ended + // in a state their requester can still read, saying who dropped it. + for booking in [&pending, &approved] { + let after = Appointment::read(booking.get_id(), &db) + .await + .unwrap() + .expect("the requester keeps the row"); + assert_eq!(after.get_status(), AppointmentStatus::Cancelled); + assert_eq!(after.get_cancelled_by(), Some(teacher.get_id())); + assert!(after.get_cancel_reason().is_some(), "and why"); + } + // The seat each held died with its slot row, so nothing is pinned: no + // live booking is left pointing at a slot that no longer exists. + let mut result = db + .query( + "SELECT VALUE id FROM appointment \ + WHERE status IN ['pending', 'approved'] AND slot.starts_at = NONE", + ) + .await + .unwrap() + .check() + .unwrap(); + assert!(result.take::>(0).unwrap().is_empty()); + + // Another teacher's calendar is nobody else's business. + assert_eq!( + AppointmentSlot::list_for_teacher(other.get_id(), &db) + .await + .unwrap() + .len(), + 1 + ); + assert_eq!( + Appointment::read(elsewhere.get_id(), &db) + .await + .unwrap() + .unwrap() + .get_status(), + AppointmentStatus::Pending + ); + } + #[tokio::test] async fn a_stale_profile_write_cannot_revert_a_role_change() { let db = init_mem().await.unwrap(); diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 0ebaafb..5ed4a31 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -256,9 +256,11 @@ async fn one_appointment( /// `teacher` column is a historical fact no demotion rewrites, so a grant read /// off it has to re-read the live role or it outlives the role that earned it /// (see `courses::can_manage_course`, where trusting the callers instead cost -/// exactly that). A demoted owner's outstanding bookings are not stranded: the -/// requester still cancels their own (`cancel` is requester-only and never -/// comes through here), and manager+ still approves, rejects or reschedules. +/// exactly that). A demoted owner leaves nothing outstanding to strand: the +/// demotion cancels their live bookings and deletes the slots under them +/// ([`crate::domain::user::User::set_role`]) — which it must, since a manager+ +/// passes this gate but has no route that yields such a booking's id, and past +/// its start the requester's own `cancel` is refused too. fn can_manage(slot: &AppointmentSlot, user: &User) -> bool { user.get_role().at_least(Role::Teacher) && (slot.get_teacher() == user.get_id() || user.get_role().at_least(Role::Manager)) @@ -308,7 +310,7 @@ async fn for_decision( (status = 201, description = "Slots published", body = Vec), (status = 400, description = "Invalid note, time range, times in the past, `until` missing with `repeat_weekly`, more than 52 occurrences, or a window too far ahead to shift by a week", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher — including an account demoted while this request ran, whose calendar the demotion is withdrawing", body = ErrorResponse), (status = 409, description = "The window overlaps one the caller has already published, or (weekly) two occurrences overlap each other — the whole publish is refused, nothing is written", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), @@ -355,8 +357,10 @@ async fn publish_slots( /// included; everyone else sees every slot that has not started yet — the /// bookable calendar, bounded exactly as booking is, so a slot already underway /// is left out rather than offered for a request that could only answer `409`. -/// A slot whose teacher has since been demoted is left out too (and refused at -/// book time). Whether a slot is already taken is not carried +/// A demotion below `teacher` withdraws that account's calendar outright, so +/// there is normally nothing of theirs left to list; a slot an older build +/// stranded is left out here too (and refused at book time). Whether a slot is +/// already taken is not carried /// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit /// `limit` for every slot); returns a `{items, total, limit, offset}` envelope. // ponytail: occupancy would be one query per slot with today's domain API; a diff --git a/src/web/users.rs b/src/web/users.rs index 52c039a..4e0f37d 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -410,7 +410,13 @@ async fn update_user_preferences( /// with the SurrealQL in the README, since the seed never promotes. /// Setting any non-`student` role also drops the user's course enrollments — /// only students enroll, so a promoted user leaves every roster. Demoting below -/// `teacher` drops their course teaching assignments for the mirror reason. +/// `teacher` drops their course teaching assignments for the mirror reason, and +/// withdraws their published appointment slots, cancelling the live bookings on +/// them: nothing could reach either afterwards — a slot is listed only on its +/// own teacher's calendar and deleted only by a teacher+, and a booking on one +/// is decided only by a teacher+ and cancelled only by its requester, who is +/// refused once the window opens. The requester keeps the booking as +/// `cancelled`, naming the ex-teacher and the reason. /// Demoting to `parent` additionally gives back the seats they hold on /// still-open event signup lists: a parent can no longer free them, and nobody /// else may. Seats on lists that have already closed stay as they are — that