forge
Explore
Log in

Don't you dare go Hollow

Withdraw the calendar a demotion used to leave unreachable

Browse files at this commit

e879fd37dff334826c2cfd9166faa6f809d22142Ahmet Kaan GümüşParent: 0894a5e
  • fix
    • withdraw the calendar a demotion used to leave unreachable
Show full message
📅 fix: withdraw the calendar a demotion used to leave unreachable

`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.rsmodified+249 -21
@@ -15,16 +15,21 @@
15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16 16
17 use crate::constant::{17 use crate::constant::{
18- APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK,18+ APPOINTMENT_SLOT_TABLE, MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, ROLES,
19 };19 };
20 use crate::database::{Database, transaction_with_retry};20 use crate::database::{Database, transaction_with_retry};
21 use crate::domain::appointment::{APPOINTMENT_LOCK, Appointment};21 use crate::domain::appointment::{APPOINTMENT_LOCK, Appointment};
22+use crate::domain::cap;
22 use crate::domain::monotonic_id::next_ulid;23 use crate::domain::monotonic_id::next_ulid;
24+use crate::domain::role::Role;
23 use crate::domain::timestamp::Timestamp;25 use crate::domain::timestamp::Timestamp;
24 use crate::domain::user::UserId;26 use crate::domain::user::UserId;
25 use crate::error::{AppError, ValidationError};27 use crate::error::{AppError, ValidationError};
26 use crate::validate::validate_optional;28 use crate::validate::validate_optional;
27 29
30+/// The publisher fell below `teacher` while the publish was in flight.
31+const UNFIT_MARK: &str = "slot_not_staff";
32+
28 // Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish33 // Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish
29 // writes its whole expansion inside one millisecond, which random ULID low34 // writes its whole expansion inside one millisecond, which random ULID low
30 // bits would scramble against the `id` tie-break of the `ORDER BY starts_at,35 // bits would scramble against the `id` tie-break of the `ORDER BY starts_at,
@@ -197,9 +202,68 @@ impl AppointmentSlot {
197 .collect()202 .collect()
198 }203 }
199 204
200- async fn insert(slot: AppointmentSlot, db: &Database) -> Result<AppointmentSlot, AppError> {205+ /// Write a whole publish — one occurrence or fifty-two — while the publisher
201- let created: Option<AppointmentSlot> = db.create(slot.id.record()).content(slot).await?;206+ /// still *holds* a teaching role.
202- created.ok_or_else(|| AppError::Internal("failed to create appointment slot".into()))207+ ///
208+ /// Every row here names the teacher, so the write touches no key a demotion
209+ /// touches: [`crate::domain::user::User::set_role`] sweeps the slots its own
210+ /// snapshot can see, and a slot landing after that snapshot would survive it
211+ /// under a role that may not publish — reachable by no route afterwards,
212+ /// since the calendar hides a demoted teacher's slots and the deletes are
213+ /// `teacher`-gated. So the teacher's own record is claimed beside the insert
214+ /// ([`cap::role_claim`]), which is the key the demotion writes: either the
215+ /// sweep sees these slots, or this write sees the new role and publishes
216+ /// nothing.
217+ ///
218+ /// The bar is read off the hierarchy rather than spelled out, so a new role
219+ /// cannot drift out of it.
220+ ///
221+ /// Admissible for [`transaction_with_retry`]: the claim is `SELECT`/`UPDATE`
222+ /// only, and the `INSERT` carries freshly minted ULIDs on a table with no
223+ /// `UNIQUE` index, so no rival can make it answer "already exists".
224+ async fn insert_claimed(
225+ teacher: &UserId,
226+ rows: Vec<AppointmentSlot>,
227+ db: &Database,
228+ ) -> Result<Vec<AppointmentSlot>, AppError> {
229+ let staff = ROLES
230+ .iter()
231+ .filter(|role| role.at_least(Role::Teacher))
232+ .map(|role| format!("'{}'", role.as_str()))
233+ .collect::<Vec<_>>()
234+ .join(", ");
235+ let held = cap::role_claim("teacher", &format!("NOT IN [{staff}]"), UNFIT_MARK);
236+ let sql = format!(
237+ "BEGIN TRANSACTION;\n{};\nINSERT INTO {APPOINTMENT_SLOT_TABLE} $rows;\n\
238+ COMMIT TRANSACTION;",
239+ held.join(";\n")
240+ );
241+ let (mut result, mut errors) = transaction_with_retry(
242+ db,
243+ &sql,
244+ &[
245+ ("teacher".into(), teacher.record().into_value()),
246+ ("rows".into(), rows.into_value()),
247+ ],
248+ &[UNFIT_MARK],
249+ )
250+ .await?;
251+ // Demoted while this ran — the same refusal `RequireTeacher` makes a
252+ // moment earlier, and the only one that can arrive after it.
253+ if errors
254+ .values()
255+ .any(|error| error.to_string().contains(UNFIT_MARK))
256+ {
257+ return Err(AppError::Forbidden(
258+ "that account no longer holds a teaching role",
259+ ));
260+ }
261+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
262+ return Err(error.into());
263+ }
264+ // BEGIN plus the claim's own statements — counted, not tallied by hand,
265+ // so a statement added there cannot read back the wrong result.
266+ Ok(result.take::<Vec<AppointmentSlot>>(held.len() + 1)?)
203 }267 }
204 268
205 /// Does the teacher already have a published slot whose window collides with269 /// Does the teacher already have a published slot whose window collides with
@@ -274,8 +338,9 @@ impl AppointmentSlot {
274 "this time overlaps a slot you have already published".into(),338 "this time overlaps a slot you have already published".into(),
275 ));339 ));
276 }340 }
277- Self::insert(341+ Self::insert_claimed(
278- AppointmentSlot {342+ teacher,
343+ vec![AppointmentSlot {
279 id: AppointmentSlotId::generate(),344 id: AppointmentSlotId::generate(),
280 teacher: teacher.clone(),345 teacher: teacher.clone(),
281 starts_at,346 starts_at,
@@ -283,10 +348,13 @@ impl AppointmentSlot {
283 note,348 note,
284 series: None,349 series: None,
285 created_at: Timestamp::now(),350 created_at: Timestamp::now(),
286- },351+ }],
287 db,352 db,
288 )353 )
289- .await354+ .await?
355+ .into_iter()
356+ .next()
357+ .ok_or_else(|| AppError::Internal("failed to create appointment slot".into()))
290 }358 }
291 359
292 /// Publish the same weekly window repeatedly, up to `until`. Every row360 /// Publish the same weekly window repeatedly, up to `until`. Every row
@@ -344,22 +412,13 @@ impl AppointmentSlot {
344 created_at: now,412 created_at: now,
345 })413 })
346 .collect();414 .collect();
347- // One statement, therefore one transaction: SurrealDB rolls the whole415+ // One `INSERT`, therefore all-or-nothing: SurrealDB rolls the whole
348- // `INSERT` back on any error. The row-by-row loop this replaces did not416+ // publish back on any error. The row-by-row loop this replaces did not
349 // — a database error at week 7 of 10 answered 500 with six stray weeks417 // — a database error at week 7 of 10 answered 500 with six stray weeks
350 // already published, a half-series nobody asked for. It is also a single418 // already published, a half-series nobody asked for. It is also a single
351- // round trip, so the lock is now held for two queries whatever the419+ // round trip, so the lock is held for two queries whatever the
352 // occurrence count, instead of 1 + N (up to 52) sequential ones.420 // occurrence count, instead of 1 + N (up to 52) sequential ones.
353- //421+ let mut created = Self::insert_claimed(teacher, rows, db).await?;
354- // No `BEGIN`/`COMMIT` wrapper: those consume result slots in this
355- // version, and a lone statement is already atomic — the explicit form
356- // would buy nothing but an off-by-one waiting to happen.
357- let mut result = db
358- .query("INSERT INTO appointment_slot $rows")
359- .bind(("rows", rows))
360- .await?
361- .check()?;
362- let mut created = result.take::<Vec<AppointmentSlot>>(0)?;
363 if created.len() != windows.len() {422 if created.len() != windows.len() {
364 return Err(AppError::Internal(format!(423 return Err(AppError::Internal(format!(
365 "published {} of {} appointment slots",424 "published {} of {} appointment slots",
@@ -822,6 +881,175 @@ mod tests {
822 ));881 ));
823 }882 }
824 883
884+ /// The claim on the publisher's own record, asked exactly the way the race
885+ /// asks it: a publish whose `RequireTeacher` snapshot predates a demotion
886+ /// must not land, because the sweep in that demotion has already chosen the
887+ /// slots it will take and would leave this one behind — under a role that
888+ /// can neither list nor delete it.
889+ ///
890+ /// Both halves matter: a row that is *not there* claims nothing (every other
891+ /// test here publishes for a teacher with no user row at all), and a live
892+ /// teacher+ passes through untouched.
893+ #[tokio::test]
894+ async fn a_publish_by_someone_who_lost_the_role_is_refused() {
895+ let db = crate::database::init_mem().await.unwrap();
896+ // Written as a row rather than through `User` — the password hasher is
897+ // private to that module, and the only column this asks about is `role`.
898+ db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'")
899+ .await
900+ .unwrap()
901+ .check()
902+ .unwrap();
903+
904+ // The row says `student`, so the claim refuses — one-off and weekly
905+ // alike, since both go through the same write.
906+ let teacher = UserId::from_key("eski");
907+ assert!(matches!(
908+ AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db).await,
909+ Err(AppError::Forbidden(_))
910+ ));
911+ assert!(matches!(
912+ AppointmentSlot::publish_weekly(
913+ &teacher,
914+ at(1_000),
915+ at(2_000),
916+ None,
917+ at(1_000 + MILLIS_PER_WEEK),
918+ &db,
919+ )
920+ .await,
921+ Err(AppError::Forbidden(_))
922+ ));
923+ assert!(
924+ AppointmentSlot::list_for_teacher(&teacher, &db)
925+ .await
926+ .unwrap()
927+ .is_empty(),
928+ "a refused publish must write nothing"
929+ );
930+
931+ // Promoted, the very same publish lands.
932+ db.query("UPDATE user:eski SET role = 'teacher'")
933+ .await
934+ .unwrap()
935+ .check()
936+ .unwrap();
937+ AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db)
938+ .await
939+ .unwrap();
940+ assert_eq!(
941+ AppointmentSlot::list_for_teacher(&teacher, &db)
942+ .await
943+ .unwrap()
944+ .len(),
945+ 1
946+ );
947+ }
948+
949+ /// The other half of that claim: the publish that arrives *while* the
950+ /// demotion is running. Its sweep has already chosen the slots it will take
951+ /// ([`crate::domain::user::User::set_role`] reads them into `$slots` before
952+ /// it deletes), so a row landing after that read shares no key with anything
953+ /// the demotion writes and survives it — a slot owned by someone who can
954+ /// neither list nor delete it, forever. The claim on the user record is what
955+ /// puts the two transactions on one key.
956+ ///
957+ /// Real server, and `#[ignore]`d for it, like every other race here: the
958+ /// subject *is* the store's conflict detection, which `init_mem`'s embedded
959+ /// engine does not have — it commits both sides and answers `Ok` to each, so
960+ /// this passes there on broken code.
961+ ///
962+ /// The window is opened by the schema rather than by a lucky interleaving: a
963+ /// `DEFINE EVENT` on the sweep's own `DELETE` holds the demotion open inside
964+ /// its transaction, well past the read that chose `$slots`, so the publish
965+ /// lands in the middle of it every round.
966+ ///
967+ /// Stored state is the verdict, not the return value: whether the publish is
968+ /// refused outright or swept along with the rest of the calendar, no slot may
969+ /// outlive the role.
970+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
971+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
972+ async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() {
973+ use crate::domain::role::Role;
974+ use crate::domain::user::User;
975+
976+ let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await;
977+ let (mut raced, mut published, mut stranded) = (0, 0, 0);
978+ for round in 0..4 {
979+ let key = format!("t{round}");
980+ let teacher = UserId::from_key(&key);
981+ db.query(format!(
982+ "CREATE user:{key} SET username = '{key}', password_hash = 'x', \
983+ role = '{}';",
984+ Role::Teacher.as_str()
985+ ))
986+ .await
987+ .unwrap()
988+ .check()
989+ .unwrap();
990+ // A slot for the sweep to delete — that delete is the seam.
991+ AppointmentSlot::create(&teacher, at(1_000), at(2_000), None, &db)
992+ .await
993+ .unwrap();
994+ db.query(format!(
995+ "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {APPOINTMENT_SLOT_TABLE} \
996+ WHEN $event = 'DELETE' THEN {{ IF $before.teacher = \
997+ type::record('user', '{key}') {{ SLEEP 300ms }} }};"
998+ ))
999+ .await
1000+ .unwrap()
1001+ .check()
1002+ .unwrap();
1003+
1004+ let demoting = {
1005+ let db = db.clone();
1006+ let target = teacher.clone();
1007+ tokio::spawn(async move {
1008+ User::read(&target, &db)
1009+ .await
1010+ .unwrap()
1011+ .unwrap()
1012+ .set_role(Role::Student, &db)
1013+ .await
1014+ })
1015+ };
1016+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1017+ if !demoting.is_finished() {
1018+ raced += 1;
1019+ }
1020+ // The publish a `RequireTeacher` snapshot taken a moment ago allows.
1021+ let landed = AppointmentSlot::create(
1022+ &teacher,
1023+ at(MILLIS_PER_WEEK),
1024+ at(MILLIS_PER_WEEK + 1_000),
1025+ None,
1026+ &db,
1027+ )
1028+ .await;
1029+ let swept = demoting.await.unwrap();
1030+ assert!(swept.is_ok(), "round {round}: the demotion itself failed");
1031+ if landed.is_ok() {
1032+ published += 1;
1033+ }
1034+ if !AppointmentSlot::list_for_teacher(&teacher, &db)
1035+ .await
1036+ .unwrap()
1037+ .is_empty()
1038+ {
1039+ stranded += 1;
1040+ }
1041+ }
1042+ eprintln!(
1043+ "a publish racing a demotion: {raced}/4 rounds landed inside it, \
1044+ {published} publishes committed"
1045+ );
1046+ assert!(raced > 0, "no round ever reached the race");
1047+ assert_eq!(
1048+ stranded, 0,
1049+ "a slot survived under a role that can neither list nor delete it"
1050+ );
1051+ }
1052+
825 #[tokio::test]1053 #[tokio::test]
826 async fn weekly_publish_that_self_overlaps_is_refused() {1054 async fn weekly_publish_that_self_overlaps_is_refused() {
827 let db = crate::database::init_mem().await.unwrap();1055 let db = crate::database::init_mem().await.unwrap();
src/domain/user.rsmodified+162 -4
@@ -5,11 +5,13 @@ use argon2::{Argon2, PasswordHasher, PasswordVerifier};
5 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};5 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
6 6
7 use crate::constant::{7 use crate::constant::{
8- BOARD_TABLE, CLASS_GROUP_TABLE, CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE,8+ APPOINTMENT_SLOT_TABLE, APPOINTMENT_TABLE, BOARD_TABLE, CLASS_GROUP_TABLE,
9- DECOY_PASSWORD, ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE,9+ CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, DECOY_PASSWORD,
10- REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE,10+ ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD,
11+ REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE,
11 };12 };
12 use crate::database::{Database, transaction_with_retry, write_with_retry};13 use crate::database::{Database, transaction_with_retry, write_with_retry};
14+use crate::domain::appointment::AppointmentStatus;
13 use crate::domain::board::Board;15 use crate::domain::board::Board;
14 use crate::domain::field_update::FieldUpdate;16 use crate::domain::field_update::FieldUpdate;
15 use crate::domain::monotonic_id::next_ulid;17 use crate::domain::monotonic_id::next_ulid;
@@ -580,7 +582,22 @@ impl User {
580 /// can freeze, so it is deleted rather than skipped: skipped, it is582 /// can freeze, so it is deleted rather than skipped: skipped, it is
581 /// stranded forever (`unregister` 404s on the missing event).583 /// stranded forever (`unregister` 404s on the missing event).
582 /// * **Below teacher** gives up course staffing and homeroom-teacher584 /// * **Below teacher** gives up course staffing and homeroom-teacher
583- /// columns — only teacher+ may hold either.585+ /// columns — only teacher+ may hold either — and the published
586+ /// appointment calendar, whose live bookings are cancelled in the same
587+ /// breath. Nothing else could ever reach those: a slot is listed only on
588+ /// its own teacher's calendar and deleted only by a teacher+, so after the
589+ /// demotion neither its owner nor a manager has a route that yields its
590+ /// id, and a booking on it can be neither decided (teacher+ only) nor
591+ /// cancelled once its window opens — leaving the slot's `occupied` seat
592+ /// pinned at one and the slot itself undeletable forever. The requester
593+ /// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the
594+ /// reason on `cancel_reason`; the slot it pointed at is gone, so the
595+ /// booking renders without a window
596+ /// ([`crate::domain::appointment::Appointment`]'s reader already treats a
597+ /// vanished slot that way). There is no notification anywhere in
598+ /// this crate, so a settled row the person can read is the strongest
599+ /// defined end available — and the alternative, deleting it, would make a
600+ /// confirmed meeting vanish with no trace at all.
584 ///601 ///
585 /// The returned boards are the rooms whose roster this changed (plus those602 /// The returned boards are the rooms whose roster this changed (plus those
586 /// the user created, which cannot be changed and are returned so their room603 /// the user created, which cannot be changed and are returned so their room
@@ -668,6 +685,34 @@ impl User {
668 batch.push(format!(685 batch.push(format!(
669 "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr"686 "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr"
670 ));687 ));
688+ // The published calendar goes too, and the bookings on it are
689+ // settled first: a slot only its own teacher can list and only a
690+ // teacher+ can delete is reachable by nobody once that teacher is
691+ // demoted, and a live booking on one is worse — nobody can approve,
692+ // reject or (past its start) cancel it, so it pins the slot's
693+ // `occupied` seat forever. Cancelled rather than deleted so the
694+ // person who asked is left with a settled booking they can still
695+ // read, carrying who dropped it and why; the slot row (and with it
696+ // the seat) goes, which is what makes this convergent.
697+ batch.push(format!(
698+ "LET $slots = (SELECT VALUE id FROM {APPOINTMENT_SLOT_TABLE} WHERE teacher = $usr)"
699+ ));
700+ batch.push(format!(
701+ "UPDATE {APPOINTMENT_TABLE} SET status = '{cancelled}', cancelled_by = $usr, \
702+ cancel_reason = 'the teacher no longer holds a teaching role' \
703+ WHERE slot IN $slots AND status IN ['{pending}', '{approved}']",
704+ cancelled = AppointmentStatus::Cancelled.as_str(),
705+ pending = AppointmentStatus::Pending.as_str(),
706+ approved = AppointmentStatus::Approved.as_str(),
707+ ));
708+ // Deleting the slots is also what makes a *concurrent* booking safe:
709+ // `Appointment::book` claims the slot row this deletes, so the two
710+ // collide in the store and the loser re-sends. A slot *published*
711+ // concurrently shares no key with any of this, which is why
712+ // `AppointmentSlot::insert_claimed` claims the user row instead.
713+ batch.push(format!(
714+ "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots"
715+ ));
671 }716 }
672 let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n"));717 let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n"));
673 let (mut result, mut errors) = transaction_with_retry(718 let (mut result, mut errors) = transaction_with_retry(
@@ -866,6 +911,119 @@ mod tests {
866 );911 );
867 }912 }
868 913
914+ /// A demotion below `teacher` must take the published calendar with it and
915+ /// settle the bookings on it. Nothing else can: a slot is listed only on its
916+ /// own teacher's calendar (and hidden from every other reader once its owner
917+ /// is demoted), deleted only by a teacher+, and a booking on one can be
918+ /// decided only by a teacher+ and cancelled only by its requester — who is
919+ /// refused the moment the window opens. So a slot left behind here is a row
920+ /// no route can reach and a seat nothing can ever free.
921+ #[tokio::test]
922+ async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() {
923+ use crate::domain::appointment::{Appointment, AppointmentReason};
924+ use crate::domain::appointment_slot::AppointmentSlot;
925+
926+ let db = init_mem().await.unwrap();
927+ let staff = |name: &'static str, db: Database| async move {
928+ a_user(name, &db)
929+ .await
930+ .set_role(Role::Teacher, &db)
931+ .await
932+ .unwrap()
933+ .0
934+ };
935+ let teacher = staff("ogretmen", db.clone()).await;
936+ let other = staff("digerogretmen", db.clone()).await;
937+ let student = a_user("ogrenci", &db).await;
938+ let soon = |offset| Timestamp::from_millis(Timestamp::now().as_millis() + offset);
939+ let reason = || AppointmentReason::try_new("görüşme").unwrap();
940+ let slot = |owner: &User, offset: i64, db: Database| {
941+ let owner = owner.get_id().clone();
942+ async move {
943+ AppointmentSlot::create(&owner, soon(offset), soon(offset + 60_000), None, &db)
944+ .await
945+ .unwrap()
946+ }
947+ };
948+
949+ let free = slot(&teacher, 60_000, db.clone()).await;
950+ let asked = slot(&teacher, 180_000, db.clone()).await;
951+ let agreed = slot(&teacher, 300_000, db.clone()).await;
952+ let kept = slot(&other, 60_000, db.clone()).await;
953+
954+ let pending = Appointment::book(asked.get_id(), student.get_id(), reason(), &db)
955+ .await
956+ .unwrap();
957+ let approved = Appointment::book(agreed.get_id(), student.get_id(), reason(), &db)
958+ .await
959+ .unwrap();
960+ Appointment::approve(approved.get_id(), teacher.get_id(), &db)
961+ .await
962+ .unwrap();
963+ let elsewhere = Appointment::book(kept.get_id(), student.get_id(), reason(), &db)
964+ .await
965+ .unwrap();
966+
967+ teacher.clone().set_role(Role::Student, &db).await.unwrap();
968+
969+ // The calendar is gone, the booked weeks included.
970+ assert!(
971+ AppointmentSlot::list_for_teacher(teacher.get_id(), &db)
972+ .await
973+ .unwrap()
974+ .is_empty()
975+ );
976+ for slot in [&free, &asked, &agreed] {
977+ assert!(
978+ AppointmentSlot::read(slot.get_id(), &db)
979+ .await
980+ .unwrap()
981+ .is_none(),
982+ "a slot only a teacher+ could reach outlived the role"
983+ );
984+ }
985+ // Both bookings — the pending request and the confirmed meeting — ended
986+ // in a state their requester can still read, saying who dropped it.
987+ for booking in [&pending, &approved] {
988+ let after = Appointment::read(booking.get_id(), &db)
989+ .await
990+ .unwrap()
991+ .expect("the requester keeps the row");
992+ assert_eq!(after.get_status(), AppointmentStatus::Cancelled);
993+ assert_eq!(after.get_cancelled_by(), Some(teacher.get_id()));
994+ assert!(after.get_cancel_reason().is_some(), "and why");
995+ }
996+ // The seat each held died with its slot row, so nothing is pinned: no
997+ // live booking is left pointing at a slot that no longer exists.
998+ let mut result = db
999+ .query(
1000+ "SELECT VALUE id FROM appointment \
1001+ WHERE status IN ['pending', 'approved'] AND slot.starts_at = NONE",
1002+ )
1003+ .await
1004+ .unwrap()
1005+ .check()
1006+ .unwrap();
1007+ assert!(result.take::<Vec<RecordId>>(0).unwrap().is_empty());
1008+
1009+ // Another teacher's calendar is nobody else's business.
1010+ assert_eq!(
1011+ AppointmentSlot::list_for_teacher(other.get_id(), &db)
1012+ .await
1013+ .unwrap()
1014+ .len(),
1015+ 1
1016+ );
1017+ assert_eq!(
1018+ Appointment::read(elsewhere.get_id(), &db)
1019+ .await
1020+ .unwrap()
1021+ .unwrap()
1022+ .get_status(),
1023+ AppointmentStatus::Pending
1024+ );
1025+ }
1026+
869 #[tokio::test]1027 #[tokio::test]
870 async fn a_stale_profile_write_cannot_revert_a_role_change() {1028 async fn a_stale_profile_write_cannot_revert_a_role_change() {
871 let db = init_mem().await.unwrap();1029 let db = init_mem().await.unwrap();
src/web/appointments.rsmodified+10 -6
@@ -256,9 +256,11 @@ async fn one_appointment(
256 /// `teacher` column is a historical fact no demotion rewrites, so a grant read256 /// `teacher` column is a historical fact no demotion rewrites, so a grant read
257 /// off it has to re-read the live role or it outlives the role that earned it257 /// off it has to re-read the live role or it outlives the role that earned it
258 /// (see `courses::can_manage_course`, where trusting the callers instead cost258 /// (see `courses::can_manage_course`, where trusting the callers instead cost
259-/// exactly that). A demoted owner's outstanding bookings are not stranded: the259+/// exactly that). A demoted owner leaves nothing outstanding to strand: the
260-/// requester still cancels their own (`cancel` is requester-only and never260+/// demotion cancels their live bookings and deletes the slots under them
261-/// comes through here), and manager+ still approves, rejects or reschedules.261+/// ([`crate::domain::user::User::set_role`]) — which it must, since a manager+
262+/// passes this gate but has no route that yields such a booking's id, and past
263+/// its start the requester's own `cancel` is refused too.
262 fn can_manage(slot: &AppointmentSlot, user: &User) -> bool {264 fn can_manage(slot: &AppointmentSlot, user: &User) -> bool {
263 user.get_role().at_least(Role::Teacher)265 user.get_role().at_least(Role::Teacher)
264 && (slot.get_teacher() == user.get_id() || user.get_role().at_least(Role::Manager))266 && (slot.get_teacher() == user.get_id() || user.get_role().at_least(Role::Manager))
@@ -308,7 +310,7 @@ async fn for_decision(
308 (status = 201, description = "Slots published", body = Vec<SlotResponse>),310 (status = 201, description = "Slots published", body = Vec<SlotResponse>),
309 (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),311 (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),
310 (status = 401, description = "Not authenticated", body = ErrorResponse),312 (status = 401, description = "Not authenticated", body = ErrorResponse),
311- (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),313+ (status = 403, description = "Requires teacher role or higher — including an account demoted while this request ran, whose calendar the demotion is withdrawing", body = ErrorResponse),
312 (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),314 (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),
313 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),315 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
314 ),316 ),
@@ -355,8 +357,10 @@ async fn publish_slots(
355 /// included; everyone else sees every slot that has not started yet — the357 /// included; everyone else sees every slot that has not started yet — the
356 /// bookable calendar, bounded exactly as booking is, so a slot already underway358 /// bookable calendar, bounded exactly as booking is, so a slot already underway
357 /// is left out rather than offered for a request that could only answer `409`.359 /// is left out rather than offered for a request that could only answer `409`.
358-/// A slot whose teacher has since been demoted is left out too (and refused at360+/// A demotion below `teacher` withdraws that account's calendar outright, so
359-/// book time). Whether a slot is already taken is not carried361+/// there is normally nothing of theirs left to list; a slot an older build
362+/// stranded is left out here too (and refused at book time). Whether a slot is
363+/// already taken is not carried
360 /// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit364 /// here: booking a taken one answers `409`. Paged via `?limit=&offset=` (omit
361 /// `limit` for every slot); returns a `{items, total, limit, offset}` envelope.365 /// `limit` for every slot); returns a `{items, total, limit, offset}` envelope.
362 // ponytail: occupancy would be one query per slot with today's domain API; a366 // ponytail: occupancy would be one query per slot with today's domain API; a
src/web/users.rsmodified+7 -1
@@ -410,7 +410,13 @@ async fn update_user_preferences(
410 /// with the SurrealQL in the README, since the seed never promotes.410 /// with the SurrealQL in the README, since the seed never promotes.
411 /// Setting any non-`student` role also drops the user's course enrollments —411 /// Setting any non-`student` role also drops the user's course enrollments —
412 /// only students enroll, so a promoted user leaves every roster. Demoting below412 /// only students enroll, so a promoted user leaves every roster. Demoting below
413-/// `teacher` drops their course teaching assignments for the mirror reason.413+/// `teacher` drops their course teaching assignments for the mirror reason, and
414+/// withdraws their published appointment slots, cancelling the live bookings on
415+/// them: nothing could reach either afterwards — a slot is listed only on its
416+/// own teacher's calendar and deleted only by a teacher+, and a booking on one
417+/// is decided only by a teacher+ and cancelled only by its requester, who is
418+/// refused once the window opens. The requester keeps the booking as
419+/// `cancelled`, naming the ex-teacher and the reason.
414 /// Demoting to `parent` additionally gives back the seats they hold on420 /// Demoting to `parent` additionally gives back the seats they hold on
415 /// still-open event signup lists: a parent can no longer free them, and nobody421 /// still-open event signup lists: a parent can no longer free them, and nobody
416 /// else may. Seats on lists that have already closed stay as they are — that422 /// else may. Seats on lists that have already closed stay as they are — that