forge
Explore
Log in

Don't you dare go Hollow

🏷️ answer a manual class refusal with the pump's own code

Browse files at this commit

574b9778019b58cf439cd7863a169e3c327cc8e4Ahmet Kaan GümüşParent: 4889fd9
  • feat
    • 🏷️ answer a manual class refusal with the pump's own code
Show full message
feat: 🏷️ answer a manual class refusal with the pump's own code

Attaching a course or adding a member by hand refused with an English
sentence, while the very same conditions reached through a blueprint
pump had just become machine codes. One cause, two shapes β€” and the
client that has to word them is bilingual.

The vocabulary now has one home on the pump's own refusal type, the
blueprint's skip list reads it from there, and the two manual routes
carry it as a code beside the sentence they already sent. Prose is
unchanged and no other route gains the field.

Coding these also exposed a claim this series had been making wrongly:
a pump attaches a course it has just proved alive, so it can never
report a stale link. Only a member add walks the section's existing
courses, and only it can answer that one.
README.mdmodified+16 -4
@@ -843,10 +843,10 @@ window filtering, before paging; negative values are a `400` naming the field.
843 | GET | `/classes/{id}` | teacher | Get one class |843 | GET | `/classes/{id}` | teacher | Get one class |
844 | PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_id`; `409` if the `term_id` it moves off changed since the read β€” nothing written, re-read and retry) |844 | PATCH | `/classes/{id}` | manager | Edit a class (`null` clears `grade`/`term_id`/`teacher_id`; `409` if the `term_id` it moves off changed since the read β€” nothing written, re-read and retry) |
845 | DELETE | `/classes/{id}` | manager | Delete a class β€” `409` while it still holds students or courses |845 | DELETE | `/classes/{id}` | manager | Delete a class β€” `409` while it still holds students or courses |
846-| POST | `/classes/{id}/members` | manager | `{user_id}` β€” add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists β€” detach that link first β€” if already a member, or once the class holds `max_class_members`) |846+| POST | `/classes/{id}/members` | manager | `{user_id}` β€” add a **student**; enrolls them into every attached course (`409` if one is full, naming it, if one of them no longer exists β€” detach that link first β€” if already a member, or once the class holds `max_class_members`; every one of those carries a machine `code`) |
847 | GET | `/classes/{id}/members` | teacher | List the class roster, newest added first Β· paged |847 | GET | `/classes/{id}/members` | teacher | List the class roster, newest added first Β· paged |
848 | DELETE | `/classes/{id}/members/{user}` | manager | Remove a member β€” sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |848 | DELETE | `/classes/{id}/members/{user}` | manager | Remove a member β€” sweeps only the enrollments **this class** pumped for them (one another class still claims is re-tagged to it; hand-placed rows stay) |
849-| POST | `/classes/{id}/courses` | teacher | `{course_id}` β€” attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`) |849+| POST | `/classes/{id}/courses` | teacher | `{course_id}` β€” attach a course (that **course's** manager); enrolls the whole roster (`409` if it cannot hold them all, if already attached, or once the class holds `max_class_courses`; every one of those carries a machine `code`) |
850 | GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first Β· paged |850 | GET | `/classes/{id}/courses` | teacher | List the class's attached courses, newest attached first Β· paged |
851 | DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) β€” the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |851 | DELETE | `/classes/{id}/courses/{course}` | teacher | Detach a course (that course's manager) β€” the same sweep along the course axis; a link left behind by a **deleted** course detaches too, rather than `404`-ing forever |
852 | POST | `/classes/blueprints` | manager | Create a grade's course blueprint and stock every section already at that grade (best-effort; returns `matched` + `skipped`) |852 | POST | `/classes/blueprints` | manager | Create a grade's course blueprint and stock every section already at that grade (best-effort; returns `matched` + `skipped`) |
@@ -2977,14 +2977,26 @@ whole grade β€” the sections after the first one are not asked again β€” and nev
2977 again on a later pump), `class_at_course_ceiling`, `class_roster_too_large`2977 again on a later pump), `class_at_course_ceiling`, `class_roster_too_large`
2978 (the section holds more students than one attach may enroll at once),2978 (the section holds more students than one attach may enroll at once),
2979 `course_full` (no free2979 `course_full` (no free
2980-seat for the whole section), `linked_course_missing` (another course2980+seat for the whole section), and
2981-already attached to that section no longer exists β€” detach it first), and
2982 `blueprint_deleted` (the template itself was deleted while the pump ran β€”2981 `blueprint_deleted` (the template itself was deleted while the pump ran β€”
2983 nothing was attached, and there is nothing left to retry). That last one **ends2982 nothing was attached, and there is nothing left to retry). That last one **ends
2984 the run**: it says nothing about the (section, course) pair it names, so every2983 the run**: it says nothing about the (section, course) pair it names, so every
2985 remaining section would only repeat it. It is reported once, the sections2984 remaining section would only repeat it. It is reported once, the sections
2986 already stocked stay stocked, and the call still succeeds.2985 already stocked stay stocked, and the call still succeeds.
2987 2986
2987+**The manual attaches answer the same vocabulary.** A `409` from
2988+`POST /classes/{id}/members` or `POST /classes/{id}/courses` is
2989+`{"error": "<sentence>", "code": "<machine code>"}` β€” the prose unchanged, the
2990+code out of the set above plus two a pump never reports: `duplicate` (already a
2991+member / already attached) and `linked_course_missing` (another course already
2992+attached to that section no longer exists β€” detach it first), which only
2993+`POST /classes/{id}/members` can meet, since a member add is the one attach
2994+that walks the section's existing course links while a pump attaches a course
2995+it has just proved alive. One cause therefore reads the same whether a manager
2996+hit it by hand or a pump hit it in bulk, which is what lets a bilingual client
2997+branch and word it once. `code` is published on those two routes only and is simply **absent**
2998+from every other error body.
2999+
2988 **Removal spares what a human placed.** Every attachment a blueprint makes is3000 **Removal spares what a human placed.** Every attachment a blueprint makes is
2989 tagged with it. Dropping a course from the list detaches it only where the3001 tagged with it. Dropping a course from the list detaches it only where the
2990 blueprint attached it (sweeping the enrollments it pumped, repairing to a rival3002 blueprint attached it (sweeping the enrollments it pumped, repairing to a rival
src/domain/class_blueprint.rsmodified+27 -29
@@ -158,36 +158,19 @@ struct Held {
158 course: CourseId,158 course: CourseId,
159 }159 }
160 160
161-/// Why this attach did not land, or `None` when it did. A duplicate is not a161+/// Why this attach did not land, or `None` when it did β€” the shared vocabulary
162-/// skip: the course is already on the class, which is exactly what the162+/// of [`Attached::refusal_code`], which is where the codes and the set they
163-/// blueprint asks for, and re-running a pump must therefore report nothing.163+/// close over are documented.
164 ///164 ///
165-/// A machine code, not a sentence: the client owns the wording and this API165+/// One divergence, and it lives here because only a pump has it: a duplicate is
166-/// only says *which* refusal it was, the shape every other enum here has166+/// not a skip. The course is already on the class, which is exactly what the
167-/// (roles, course kinds, the badge catalog). The set is closed and documented167+/// blueprint asks for, so re-running a pump must report nothing β€” while a *hand*
168-/// on `SkipResponse.reason`.168+/// attach's duplicate is a genuine refusal (`duplicate`), because that call
169-///169+/// asked for the row and did not get it.
170-/// Each code names the record that actually failed. The pump's two "gone"
171-/// answers are a *class* delete ([`Attached::Gone`] β†’ `class_deleted`, the
172-/// class counter's claim matching nothing on a row a re-read no longer finds)
173-/// and a *course* delete ([`Attached::PivotGone`] β†’ `course_deleted`, the
174-/// course's own claim matching nothing) β€” and telling a manager the class
175-/// vanished when the course did sends them to look at a section that is
176-/// standing right there. `linked_course_missing` is a third: *another* course
177-/// already attached to this class no longer exists, and it must be detached
178-/// before this attach can be retried. `blueprint_deleted` is the pump losing
179-/// the template itself mid-run β€” the only skip that says nothing about the
180-/// (class, course) pair it names.
181 fn skip_reason(landed: &Attached<ClassCourse>) -> Option<&'static str> {170 fn skip_reason(landed: &Attached<ClassCourse>) -> Option<&'static str> {
182 match landed {171 match landed {
183- Attached::Made(_) | Attached::Duplicate => None,172+ Attached::Duplicate => None,
184- Attached::Gone => Some("class_deleted"),173+ other => other.refusal_code(),
185- Attached::PivotGone => Some("course_deleted"),
186- Attached::ClassFull => Some("class_at_course_ceiling"),
187- Attached::ClassOverloaded => Some("class_roster_too_large"),
188- Attached::Full(_) => Some("course_full"),
189- Attached::CourseGone(_) => Some("linked_course_missing"),
190- Attached::SourceGone => Some("blueprint_deleted"),
191 }174 }
192 }175 }
193 176
@@ -1106,11 +1089,21 @@ mod tests {
1106 /// vocabulary a bilingual client branches and translates on, so a reworded1089 /// vocabulary a bilingual client branches and translates on, so a reworded
1107 /// one is a silent contract break. A new [`Attached`] variant fails the1090 /// one is a silent contract break. A new [`Attached`] variant fails the
1108 /// match arm above, and this pins what the existing ones say.1091 /// match arm above, and this pins what the existing ones say.
1092+ ///
1093+ /// Each one is also checked against [`Attached::refusal_code`], the manual
1094+ /// routes' half of the same vocabulary: `duplicate` is the *only* place the
1095+ /// two are allowed to differ, so a second spelling of any other code cannot
1096+ /// drift in on either side.
1109 #[test]1097 #[test]
1110 fn every_refusal_the_pump_can_answer_is_a_skip() {1098 fn every_refusal_the_pump_can_answer_is_a_skip() {
1111- // `Made` shares `Duplicate`'s arm, and building one needs a live link1099+ // `Made` is the other `None` there, and building one needs a live link
1112- // row β€” the arm itself is the only thing to check there.1100+ // row β€” the arm itself is the only thing to check for it.
1113 assert!(skip_reason(&Attached::Duplicate).is_none());1101 assert!(skip_reason(&Attached::Duplicate).is_none());
1102+ assert_eq!(
1103+ Attached::<ClassCourse>::Duplicate.refusal_code(),
1104+ Some("duplicate"),
1105+ "a hand attach's duplicate is a refusal even though a pump's is not"
1106+ );
1114 for (refusal, code) in [1107 for (refusal, code) in [
1115 (Attached::Gone, "class_deleted"),1108 (Attached::Gone, "class_deleted"),
1116 (Attached::PivotGone, "course_deleted"),1109 (Attached::PivotGone, "course_deleted"),
@@ -1128,6 +1121,11 @@ mod tests {
1128 Some(code),1121 Some(code),
1129 "{refusal:?} must be reported as its own code, not swallowed or reworded"1122 "{refusal:?} must be reported as its own code, not swallowed or reworded"
1130 );1123 );
1124+ assert_eq!(
1125+ refusal.refusal_code(),
1126+ skip_reason(&refusal),
1127+ "{refusal:?} must read the same on a manual 409 as in a pump's skip list"
1128+ );
1131 }1129 }
1132 }1130 }
1133 }1131 }
src/domain/class_course.rsmodified+34 -19
@@ -93,31 +93,45 @@ impl ClassCourse {
93 attached_by: &UserId,93 attached_by: &UserId,
94 db: &Database,94 db: &Database,
95 ) -> Result<ClassCourse, AppError> {95 ) -> Result<ClassCourse, AppError> {
96- match Self::attach_sourced(class, course, attached_by, None, db).await? {96+ let landed = Self::attach_sourced(class, course, attached_by, None, db).await?;
97+ // Read off the refusal, never respelled here: this route and a
98+ // blueprint pump answer one vocabulary. `Made` is the only `None`, and
99+ // it takes the `Ok` arm below.
100+ let code = landed.refusal_code().unwrap_or_default();
101+ match landed {
97 Attached::Made(saved) => Ok(saved),102 Attached::Made(saved) => Ok(saved),
98- Attached::Duplicate => Err(AppError::Conflict("the course is already on this class")),103+ Attached::Duplicate => Err(AppError::ConflictCoded {
104+ code,
105+ message: "the course is already on this class".into(),
106+ }),
99 // The class or the course: either end of the link being gone is a107 // The class or the course: either end of the link being gone is a
100 // 404 on this route, and only a blueprint's skip list needs them108 // 404 on this route, and only a blueprint's skip list needs them
101 // told apart.109 // told apart.
102 Attached::Gone | Attached::PivotGone => Err(AppError::NotFound),110 Attached::Gone | Attached::PivotGone => Err(AppError::NotFound),
103- Attached::ClassFull => Err(AppError::ConflictOwned(format!(111+ Attached::ClassFull => Err(AppError::ConflictCoded {
104- "this class already holds {MAX_CLASS_COURSES} courses"112+ code,
105- ))),113+ message: format!("this class already holds {MAX_CLASS_COURSES} courses"),
114+ }),
106 // The other axis: attaching one course enrolls the whole roster, so115 // The other axis: attaching one course enrolls the whole roster, so
107 // a class over *that* ceiling cannot take a course however few it116 // a class over *that* ceiling cannot take a course however few it
108 // carries. Only a class predating the ceiling can be here.117 // carries. Only a class predating the ceiling can be here.
109- Attached::ClassOverloaded => Err(AppError::ConflictOwned(format!(118+ Attached::ClassOverloaded => Err(AppError::ConflictCoded {
110- "this class holds more than {MAX_CLASS_MEMBERS} students β€” \119+ code,
111- remove some before attaching a course"120+ message: format!(
112- ))),121+ "this class holds more than {MAX_CLASS_MEMBERS} students β€” \
113- Attached::Full(full) => Err(AppError::ConflictOwned(format!(122+ remove some before attaching a course"
114- "{full} cannot hold the whole class"123+ ),
115- ))),124+ }),
125+ Attached::Full(full) => Err(AppError::ConflictCoded {
126+ code,
127+ message: format!("{full} cannot hold the whole class"),
128+ }),
116 // Another of the class's links points at a deleted course. This129 // Another of the class's links points at a deleted course. This
117 // axis claims its own pivot, so it is never *this* course.130 // axis claims its own pivot, so it is never *this* course.
118- Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!(131+ Attached::CourseGone(course) => Err(AppError::ConflictCoded {
119- "{course} no longer exists β€” detach it from this class first"132+ code,
120- ))),133+ message: format!("{course} no longer exists β€” detach it from this class first"),
134+ }),
121 // This path passes no source, so the claim that answers this is135 // This path passes no source, so the claim that answers this is
122 // never in the transaction it ran.136 // never in the transaction it ran.
123 Attached::SourceGone => Err(AppError::Internal(137 Attached::SourceGone => Err(AppError::Internal(
@@ -250,8 +264,8 @@ mod tests {
250 264
251 let again = ClassCourse::attach(&class, &algebra, &manager, &db).await;265 let again = ClassCourse::attach(&class, &algebra, &manager, &db).await;
252 assert!(266 assert!(
253- matches!(again, Err(AppError::Conflict(_))),267+ matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"),
254- "a second attach is a 409: {again:?}"268+ "a second attach is a 409 coded `duplicate`: {again:?}"
255 );269 );
256 }270 }
257 271
@@ -271,8 +285,9 @@ mod tests {
271 285
272 let refused = ClassCourse::attach(&class, &tight, &manager, &db).await;286 let refused = ClassCourse::attach(&class, &tight, &manager, &db).await;
273 assert!(287 assert!(
274- matches!(refused, Err(AppError::ConflictOwned(ref message)) if message.contains(tight.key())),288+ matches!(refused, Err(AppError::ConflictCoded { code, ref message })
275- "the refusal must name the course: {refused:?}"289+ if code == "course_full" && message.contains(tight.key())),
290+ "the refusal must be coded `course_full` and name the course: {refused:?}"
276 );291 );
277 assert_eq!(292 assert_eq!(
278 rows("SELECT VALUE id FROM enrollment", &db).await,293 rows("SELECT VALUE id FROM enrollment", &db).await,
src/domain/class_member.rsmodified+36 -21
@@ -88,7 +88,7 @@ impl ClassMember {
88 added_by: added_by.clone(),88 added_by: added_by.clone(),
89 added_at: Some(Timestamp::now()),89 added_at: Some(Timestamp::now()),
90 };90 };
91- match attach(91+ let landed = attach(
92 class,92 class,
93 Axis::Member,93 Axis::Member,
94 &member.id.record(),94 &member.id.record(),
@@ -98,32 +98,45 @@ impl ClassMember {
98 None,98 None,
99 db,99 db,
100 )100 )
101- .await?101+ .await?;
102- {102+ // Read off the refusal, never respelled here: this route and a
103+ // blueprint pump answer one vocabulary. `Made` is the only `None`, and
104+ // it takes the `Ok` arm below.
105+ let code = landed.refusal_code().unwrap_or_default();
106+ match landed {
103 Attached::Made(saved) => Ok(saved),107 Attached::Made(saved) => Ok(saved),
104- Attached::Duplicate => Err(AppError::Conflict("the student is already in this class")),108+ Attached::Duplicate => Err(AppError::ConflictCoded {
109+ code,
110+ message: "the student is already in this class".into(),
111+ }),
105 // The member axis claims no pivot, so `PivotGone` cannot arrive112 // The member axis claims no pivot, so `PivotGone` cannot arrive
106 // here; the class being gone is the only 404 this route can see.113 // here; the class being gone is the only 404 this route can see.
107 Attached::Gone | Attached::PivotGone => Err(AppError::NotFound),114 Attached::Gone | Attached::PivotGone => Err(AppError::NotFound),
108- Attached::ClassFull => Err(AppError::ConflictOwned(format!(115+ Attached::ClassFull => Err(AppError::ConflictCoded {
109- "this class already holds {MAX_CLASS_MEMBERS} students"116+ code,
110- ))),117+ message: format!("this class already holds {MAX_CLASS_MEMBERS} students"),
118+ }),
111 // The other axis: adding one student enrolls them into every119 // The other axis: adding one student enrolls them into every
112 // attached course, so a class over *that* ceiling cannot take a120 // attached course, so a class over *that* ceiling cannot take a
113 // member however much room its roster has.121 // member however much room its roster has.
114- Attached::ClassOverloaded => Err(AppError::ConflictOwned(format!(122+ Attached::ClassOverloaded => Err(AppError::ConflictCoded {
115- "this class holds more than {MAX_CLASS_COURSES} courses β€” \123+ code,
116- detach some before adding a student"124+ message: format!(
117- ))),125+ "this class holds more than {MAX_CLASS_COURSES} courses β€” \
118- Attached::Full(course) => Err(AppError::ConflictOwned(format!(126+ detach some before adding a student"
119- "{course} is full, so the class cannot take this student"127+ ),
120- ))),128+ }),
129+ Attached::Full(course) => Err(AppError::ConflictCoded {
130+ code,
131+ message: format!("{course} is full, so the class cannot take this student"),
132+ }),
121 // Not a capacity problem, and told apart from one on purpose: no133 // Not a capacity problem, and told apart from one on purpose: no
122 // number anyone can raise unblocks this class, only detaching the134 // number anyone can raise unblocks this class, only detaching the
123 // link the deleted course left behind.135 // link the deleted course left behind.
124- Attached::CourseGone(course) => Err(AppError::ConflictOwned(format!(136+ Attached::CourseGone(course) => Err(AppError::ConflictCoded {
125- "{course} no longer exists β€” detach it from this class first"137+ code,
126- ))),138+ message: format!("{course} no longer exists β€” detach it from this class first"),
139+ }),
127 // Only an attach run on a blueprint's behalf states that claim, and140 // Only an attach run on a blueprint's behalf states that claim, and
128 // a membership is nobody's but its own.141 // a membership is nobody's but its own.
129 Attached::SourceGone => Err(AppError::Internal(142 Attached::SourceGone => Err(AppError::Internal(
@@ -355,8 +368,8 @@ pub(crate) mod tests {
355 368
356 let again = ClassMember::add(&class, &student, &manager, &db).await;369 let again = ClassMember::add(&class, &student, &manager, &db).await;
357 assert!(370 assert!(
358- matches!(again, Err(AppError::Conflict(_))),371+ matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"),
359- "a second add is a 409: {again:?}"372+ "a second add is a 409 coded `duplicate`: {again:?}"
360 );373 );
361 assert_eq!(374 assert_eq!(
362 counter("class_member_count", class.record(), &db).await,375 counter("class_member_count", class.record(), &db).await,
@@ -388,8 +401,10 @@ pub(crate) mod tests {
388 let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key());401 let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key());
389 let refused = ClassMember::add(&class, &student, &manager, &db).await;402 let refused = ClassMember::add(&class, &student, &manager, &db).await;
390 assert!(403 assert!(
391- matches!(refused, Err(AppError::ConflictOwned(ref message)) if message.contains(&named)),404+ matches!(refused, Err(AppError::ConflictCoded { code, ref message })
392- "the refusal must name the course that had no seat as {named}: {refused:?}"405+ if code == "course_full" && message.contains(&named)),
406+ "the refusal must be coded `course_full` and name the course that had no seat \
407+ as {named}: {refused:?}"
393 );408 );
394 assert_eq!(409 assert_eq!(
395 rows("SELECT VALUE id FROM enrollment", &db).await,410 rows("SELECT VALUE id FROM enrollment", &db).await,
src/domain/class_pump.rsmodified+38 -0
@@ -126,6 +126,44 @@ pub(crate) enum Attached<T> {
126 SourceGone,126 SourceGone,
127 }127 }
128 128
129+impl<T> Attached<T> {
130+ /// This refusal as a **machine code**, or `None` for the attach that
131+ /// landed. The client owns the wording and the language; this only says
132+ /// *which* refusal it was β€” the shape every other enum here has (roles,
133+ /// course kinds, the badge catalog).
134+ ///
135+ /// The single home for that vocabulary, because both readers answer it: a
136+ /// blueprint pump reports it as a skip
137+ /// ([`crate::domain::class_blueprint`]) and a hand attach as the `code` on
138+ /// its `409` ([`crate::error::AppError::ConflictCoded`]). Spelled once, so
139+ /// one cause can never grow two codes.
140+ ///
141+ /// Each code names the record that actually failed. The two "gone" answers
142+ /// are a *class* delete ([`Attached::Gone`] β†’ `class_deleted`, the class
143+ /// counter's claim matching nothing on a row a re-read no longer finds) and
144+ /// a *course* delete ([`Attached::PivotGone`] β†’ `course_deleted`, the
145+ /// course's own claim matching nothing) β€” and telling a manager the class
146+ /// vanished when the course did sends them to look at a section that is
147+ /// standing right there. `linked_course_missing` is a third: *another*
148+ /// course already attached to this class no longer exists, and it must be
149+ /// detached before this attach can be retried. `blueprint_deleted` is a
150+ /// pump losing the template itself mid-run β€” the only refusal that says
151+ /// nothing about the (class, course) pair it names.
152+ pub(crate) fn refusal_code(&self) -> Option<&'static str> {
153+ match self {
154+ Attached::Made(_) => None,
155+ Attached::Duplicate => Some("duplicate"),
156+ Attached::Gone => Some("class_deleted"),
157+ Attached::PivotGone => Some("course_deleted"),
158+ Attached::ClassFull => Some("class_at_course_ceiling"),
159+ Attached::ClassOverloaded => Some("class_roster_too_large"),
160+ Attached::Full(_) => Some("course_full"),
161+ Attached::CourseGone(_) => Some("linked_course_missing"),
162+ Attached::SourceGone => Some("blueprint_deleted"),
163+ }
164+ }
165+}
166+
129 /// Which way the pump runs: the loop below needs a `(course, user)` pair per167 /// Which way the pump runs: the loop below needs a `(course, user)` pair per
130 /// enrollment, and each caller supplies one side as a constant and reads the168 /// enrollment, and each caller supplies one side as a constant and reads the
131 /// other off the class's *other* link table.169 /// other off the class's *other* link table.
src/error.rsmodified+20 -0
@@ -10,6 +10,12 @@ use utoipa::ToSchema;
10 pub struct ErrorResponse {10 pub struct ErrorResponse {
11 /// Human-readable failure reason.11 /// Human-readable failure reason.
12 pub error: String,12 pub error: String,
13+ /// Machine-readable refusal code, present only where a route documents its
14+ /// vocabulary (today: the two manual class-attach routes, which answer the
15+ /// codes a blueprint pump reports as a skip). Absent everywhere else, so a
16+ /// client branches on it where it is published and reads `error` otherwise.
17+ #[serde(skip_serializing_if = "Option::is_none")]
18+ pub code: Option<String>,
13 }19 }
14 20
15 /// Why a newtype refused to be constructed from raw input. Always maps to `400`.21 /// Why a newtype refused to be constructed from raw input. Always maps to `400`.
@@ -57,6 +63,12 @@ pub enum AppError {
57 /// [`AppError::Conflict`].63 /// [`AppError::Conflict`].
58 #[error("conflict: {0}")]64 #[error("conflict: {0}")]
59 ConflictOwned(String),65 ConflictOwned(String),
66+ /// A 409 that also carries a **machine code**, so a client branches on the
67+ /// cause instead of parsing the sentence (which it cannot translate). The
68+ /// prose is unchanged from what the same refusal always said β€” `code` is
69+ /// additive, and only a route that publishes its vocabulary uses this.
70+ #[error("conflict: {message}")]
71+ ConflictCoded { code: &'static str, message: String },
60 /// A request body (file upload) over the allowed size. Owned string: the72 /// A request body (file upload) over the allowed size. Owned string: the
61 /// school-configured limit is only known at runtime.73 /// school-configured limit is only known at runtime.
62 #[error("payload too large: {0}")]74 #[error("payload too large: {0}")]
@@ -148,6 +160,14 @@ impl IntoResponse for AppError {
148 )160 )
149 .into_response();161 .into_response();
150 }162 }
163+ // The one conflict with a second key, so it builds its body here.
164+ AppError::ConflictCoded { code, message } => {
165+ return (
166+ StatusCode::CONFLICT,
167+ Json(json!({ "error": message, "code": code })),
168+ )
169+ .into_response();
170+ }
151 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),171 AppError::Validation(v) => (StatusCode::BAD_REQUEST, v.to_string()),
152 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),172 AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
153 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),173 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
src/lib.rsmodified+1 -1
@@ -50,7 +50,7 @@ use crate::state::AppState;
50 (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing β€” one colliding occurrence refuses the whole series. Students and parents book one with a required reason β€” a parent books for themselves, this is the parent-teacher conference β€” and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel β€” declining included, since a decline *is* a cancel β€” only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) β€” visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"),50 (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing β€” one colliding occurrence refuses the whole series. Students and parents book one with a required reason β€” a parent books for themselves, this is the parent-teacher conference β€” and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel β€” declining included, since a decline *is* a cancel β€” only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) β€” visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"),
51 (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"),51 (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"),
52 (name = "courses", description = "Courses β€” kind `course` (a regular taught course), `study` (etΓΌt, a supervised study session), or `club` (kulΓΌp, a student club; same behavior, different label) β€” optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) β€” empty the roster first"),52 (name = "courses", description = "Courses β€” kind `course` (a regular taught course), `study` (etΓΌt, a supervised study session), or `club` (kulΓΌp, a student club; same behavior, different label) β€” optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) β€” empty the roster first"),
53- (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership β€” adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class β€” the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept β€” and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent β€” the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sΔ±nΔ±f âğretmeni) with `teacher_id` β€” any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role β€” staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions β€” creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort β€” a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry β€” unpaged, since the set is the şube one school runs at one grade β€” because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and a course in the template that no longer exists reads as missing everywhere until the next pump drops the dangling id. Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached β€” they still carry that blueprint's tag, so dropping one from that template still detaches them β€” and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `linked_course_missing`, `blueprint_deleted`), like every other enum here. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list β€” the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives β€” the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"),53+ (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership β€” adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class β€” the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept β€” and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent β€” the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sΔ±nΔ±f âğretmeni) with `teacher_id` β€” any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role β€” staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions β€” creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort β€” a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry β€” unpaged, since the set is the şube one school runs at one grade β€” because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and a course in the template that no longer exists reads as missing everywhere until the next pump drops the dangling id. Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached β€” they still carry that blueprint's tag, so dropping one from that template still detaches them β€” and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary: a `409` from `POST /classes/{id}/members` or `POST /classes/{id}/courses` carries a `code` beside its sentence, out of the same set plus two a pump never reports β€” `duplicate` (already attached / already a member β€” a refusal there, and no skip for a pump, which asked for a row that is already in place) and `linked_course_missing` (another course on that section no longer exists β€” detach it first), which only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list β€” the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives β€” the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"),
54 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson credits its teacher's `lessons_held_total` once, and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"),54 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson credits its teacher's `lessons_held_total` once, and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"),
55 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),55 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
56 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend β€” the backend records only focus stints"),56 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend β€” the backend records only focus stints"),
src/web/board_ws.rsmodified+4 -0
@@ -567,6 +567,10 @@ fn error_frame(err: &AppError, client_seq: Option<u64>) -> Value {
567 AppError::Conflict(message) if *message == board_stroke::BOARD_LOCKED => "locked",567 AppError::Conflict(message) if *message == board_stroke::BOARD_LOCKED => "locked",
568 AppError::Conflict(message) if *message == board_stroke::BOARD_CLOSED => "board_closed",568 AppError::Conflict(message) if *message == board_stroke::BOARD_CLOSED => "board_closed",
569 AppError::Conflict(message) if *message == board_stroke::CANVAS_BLANK => "canvas_blank",569 AppError::Conflict(message) if *message == board_stroke::CANVAS_BLANK => "canvas_blank",
570+ // A refusal that already carries its own code keeps it β€” no board path
571+ // raises one today, but re-labelling one "conflict" would throw the
572+ // only machine answer it has away.
573+ AppError::ConflictCoded { code, .. } => code,
570 // Everything else, `BOARD_MOVED` included: retryable, never terminal.574 // Everything else, `BOARD_MOVED` included: retryable, never terminal.
571 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",575 AppError::Conflict(_) | AppError::ConflictOwned(_) => "conflict",
572 AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid",576 AppError::Validation(_) | AppError::PayloadTooLarge(_) => "invalid",
src/web/classes.rsmodified+14 -5
@@ -726,7 +726,7 @@ async fn delete_class(
726 (status = 401, description = "Not authenticated", body = ErrorResponse),726 (status = 401, description = "Not authenticated", body = ErrorResponse),
727 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),727 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
728 (status = 404, description = "Class not found", body = ErrorResponse),728 (status = 404, description = "Class not found", body = ErrorResponse),
729- (status = 409, description = "Already in this class, the class is at its student ceiling (max_class_members), one of its courses is full, or one of them no longer exists (a stale attachment β€” detach it)", body = ErrorResponse),729+ (status = 409, description = "Already in this class, the class is at its student ceiling (max_class_members), one of its courses is full, or one of them no longer exists (a stale attachment β€” detach it). The body carries a machine `code` beside the prose, out of the same closed set a blueprint pump reports: `duplicate`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `linked_course_missing`", body = ErrorResponse),
730 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),730 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
731 ),731 ),
732 )]732 )]
@@ -853,7 +853,7 @@ async fn remove_member(
853 (status = 401, description = "Not authenticated", body = ErrorResponse),853 (status = 401, description = "Not authenticated", body = ErrorResponse),
854 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),854 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
855 (status = 404, description = "Class not found", body = ErrorResponse),855 (status = 404, description = "Class not found", body = ErrorResponse),
856- (status = 409, description = "Already attached, the class is at its course ceiling (max_class_courses), or the course cannot hold the whole class", body = ErrorResponse),856+ (status = 409, description = "Already attached, the class is at its course ceiling (max_class_courses), or the course cannot hold the whole class. The body carries a machine `code` beside the prose, out of the same closed set a blueprint pump reports: `duplicate`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`", body = ErrorResponse),
857 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),857 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
858 ),858 ),
859 )]859 )]
@@ -1034,12 +1034,21 @@ struct SkipResponse {
1034 /// `class_at_course_ceiling` (the1034 /// `class_at_course_ceiling` (the
1035 /// section already holds `max_class_courses`), `class_roster_too_large`1035 /// section already holds `max_class_courses`), `class_roster_too_large`
1036 /// (the section holds more students than one attach may enroll at once),1036 /// (the section holds more students than one attach may enroll at once),
1037- /// `course_full` (the course has no free seat for the whole section),1037+ /// `course_full` (the course has no free seat for the whole section), and
1038- /// `linked_course_missing` (another course already attached to this
1039- /// section no longer exists β€” detach it before retrying), and
1040 /// `blueprint_deleted` (the blueprint itself was deleted while the pump1038 /// `blueprint_deleted` (the blueprint itself was deleted while the pump
1041 /// ran; nothing was attached, and there is nothing left to retry β€” it ends1039 /// ran; nothing was attached, and there is nothing left to retry β€” it ends
1042 /// the run, so it appears once however many sections were left).1040 /// the run, so it appears once however many sections were left).
1041+ ///
1042+ /// The **same vocabulary** answers the manual routes: a `409` from
1043+ /// `POST /classes/{id}/members` or `POST /classes/{id}/courses` carries
1044+ /// these codes as its `code` field, plus two a pump never reports β€”
1045+ /// `duplicate`, a refusal there (the call asked for a row and did not get
1046+ /// it) but not here (the course is already on the class, which is what the
1047+ /// blueprint asks for), and `linked_course_missing` (another course
1048+ /// already attached to that section no longer exists β€” detach it first),
1049+ /// which only a member add can meet: it is the one attach that walks the
1050+ /// section's existing course links, while a pump attaches a course it has
1051+ /// just proved alive.
1043 #[schema(example = "course_full")]1052 #[schema(example = "course_full")]
1044 reason: String,1053 reason: String,
1045 }1054 }
src/web/room.rsmodified+3 -1
@@ -87,7 +87,9 @@ pub(crate) fn public_message(err: &AppError, room: &str) -> String {
87 AppError::Unauthorized => "unauthorized".to_string(),87 AppError::Unauthorized => "unauthorized".to_string(),
88 AppError::Forbidden(message) => (*message).to_string(),88 AppError::Forbidden(message) => (*message).to_string(),
89 AppError::Conflict(message) => (*message).to_string(),89 AppError::Conflict(message) => (*message).to_string(),
90- AppError::ConflictOwned(message) => message.clone(),90+ AppError::ConflictOwned(message) | AppError::ConflictCoded { message, .. } => {
91+ message.clone()
92+ }
91 AppError::PayloadTooLarge(message) => message.clone(),93 AppError::PayloadTooLarge(message) => message.clone(),
92 AppError::TooManyRequests { .. } => "too many requests".to_string(),94 AppError::TooManyRequests { .. } => "too many requests".to_string(),
93 AppError::DbUnavailable => {95 AppError::DbUnavailable => {
tests/regress_blueprints.rsmodified+76 -0
@@ -664,6 +664,82 @@ async fn a_class_that_does_not_fit_is_reported_not_aborted() {
664 assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0);664 assert_eq!(rows("SELECT VALUE id FROM enrollment", &db).await, 0);
665 }665 }
666 666
667+/// One cause, one code, whichever door it came through: the `409` a manager's
668+/// own `POST /classes/{id}/courses` answers carries the *same* machine code the
669+/// pump reports as a skip for the state that class is in. The two used to be a
670+/// code and an English sentence, and a bilingual client cannot translate the
671+/// sentence β€” so this pins them equal, over HTTP, on one shared state.
672+#[tokio::test]
673+async fn a_manual_attach_answers_the_code_the_pump_reports() {
674+ let (app, db) = app_and_db().await;
675+ let manager = login_as(&app, &db, "mgr", "manager").await;
676+ // One seat, two students: neither door can put this course on this class.
677+ let tight = create_capped_course(&app, &manager, "seminar", 1).await;
678+ let class = create_class(&app, &manager, "9-A", "9").await;
679+ student_in(&app, &db, &class, &manager, "ali").await;
680+ student_in(&app, &db, &class, &manager, "veli").await;
681+
682+ let by_hand = send(
683+ &app,
684+ "POST",
685+ &format!("/classes/{class}/courses"),
686+ Some(&manager),
687+ Some(json!({ "course_id": tight.clone() })),
688+ )
689+ .await;
690+ assert_eq!(by_hand.status, StatusCode::CONFLICT, "{:?}", by_hand.body);
691+ assert_eq!(
692+ by_hand.body["code"], "course_full",
693+ "the manual 409 must carry the machine code, not prose alone: {:?}",
694+ by_hand.body
695+ );
696+ assert!(
697+ by_hand.body["error"].as_str().unwrap_or_default().len() > 10,
698+ "…beside the sentence it always sent β€” the code is additive: {:?}",
699+ by_hand.body
700+ );
701+
702+ // The same refusal through the pump, on the very same class and course.
703+ let pumped = send(
704+ &app,
705+ "POST",
706+ "/classes/blueprints",
707+ Some(&manager),
708+ Some(json!({ "grade": "9", "course_ids": [tight.clone()] })),
709+ )
710+ .await;
711+ assert_eq!(pumped.status, StatusCode::CREATED, "{:?}", pumped.body);
712+ let skipped = skips(&pumped);
713+ assert_eq!(skipped.len(), 1, "{skipped:?}");
714+ assert_eq!(
715+ skipped[0]["reason"], by_hand.body["code"],
716+ "one cause must read the same in a skip list and on a manual 409"
717+ );
718+
719+ // And the other end of the vocabulary: a duplicate, which *is* a refusal by
720+ // hand and deliberately not a skip for the pump.
721+ let roomy = create_course(&app, &manager, "algebra").await;
722+ let attached = send(
723+ &app,
724+ "POST",
725+ &format!("/classes/{class}/courses"),
726+ Some(&manager),
727+ Some(json!({ "course_id": roomy.clone() })),
728+ )
729+ .await;
730+ assert_eq!(attached.status, StatusCode::CREATED, "{:?}", attached.body);
731+ let again = send(
732+ &app,
733+ "POST",
734+ &format!("/classes/{class}/courses"),
735+ Some(&manager),
736+ Some(json!({ "course_id": roomy })),
737+ )
738+ .await;
739+ assert_eq!(again.status, StatusCode::CONFLICT, "{:?}", again.body);
740+ assert_eq!(again.body["code"], "duplicate", "{:?}", again.body);
741+}
742+
667 /// The provenance rule, both halves: dropping a course from the template743 /// The provenance rule, both halves: dropping a course from the template
668 /// detaches it wherever the *blueprint* attached it, and leaves it standing744 /// detaches it wherever the *blueprint* attached it, and leaves it standing
669 /// wherever a human did.745 /// wherever a human did.
tests/regress_classes.rsmodified+17 -7
@@ -215,6 +215,13 @@ async fn a_member_add_names_a_stale_link_rather_than_calling_it_full() {
215 !message.contains("full"),215 !message.contains("full"),
216 "a course that does not exist is not a full one: {message}"216 "a course that does not exist is not a full one: {message}"
217 );217 );
218+ // …and it says so as a machine code too, the one a pump's skip list spells
219+ // for this cause. A bilingual client branches on this, never on the words.
220+ assert_eq!(
221+ refused.body["code"], "linked_course_missing",
222+ "the stale-link refusal must carry its machine code: {:?}",
223+ refused.body
224+ );
218 assert_eq!(225 assert_eq!(
219 rows("SELECT VALUE id FROM class_member", &db).await,226 rows("SELECT VALUE id FROM class_member", &db).await,
220 0,227 0,
@@ -646,9 +653,10 @@ async fn a_class_refuses_the_member_past_its_ceiling() {
646 .expect("the place under the ceiling is still free");653 .expect("the place under the ceiling is still free");
647 let refused = ClassMember::add(&class, &UserId::from_key("over"), &manager, &db).await;654 let refused = ClassMember::add(&class, &UserId::from_key("over"), &manager, &db).await;
648 assert!(655 assert!(
649- matches!(refused, Err(AppError::ConflictOwned(ref message))656+ matches!(refused, Err(AppError::ConflictCoded { code, ref message })
650- if message.contains(&MAX_CLASS_MEMBERS.to_string())),657+ if code == "class_at_course_ceiling"
651- "a full class is a 409 naming its ceiling, never a 404: {refused:?}"658+ && message.contains(&MAX_CLASS_MEMBERS.to_string())),
659+ "a full class is a 409 naming its ceiling and coded, never a 404: {refused:?}"
652 );660 );
653 assert_eq!(661 assert_eq!(
654 counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,662 counter("SELECT VALUE class_member_count ?? 0 FROM class_group", &db).await,
@@ -711,8 +719,9 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
711 719
712 let refused = ClassCourse::attach(&class, &algebra, &manager, &db).await;720 let refused = ClassCourse::attach(&class, &algebra, &manager, &db).await;
713 assert!(721 assert!(
714- matches!(refused, Err(AppError::ConflictOwned(ref message))722+ matches!(refused, Err(AppError::ConflictCoded { code, ref message })
715- if message.contains(&MAX_CLASS_MEMBERS.to_string())),723+ if code == "class_roster_too_large"
724+ && message.contains(&MAX_CLASS_MEMBERS.to_string())),
716 "the refusal must name the axis that is over, not the one with room: {refused:?}"725 "the refusal must name the axis that is over, not the one with room: {refused:?}"
717 );726 );
718 assert_eq!(727 assert_eq!(
@@ -768,8 +777,9 @@ async fn a_class_over_the_course_ceiling_takes_no_member() {
768 777
769 let refused = ClassMember::add(&class, &UserId::from_key("ali"), &manager, &db).await;778 let refused = ClassMember::add(&class, &UserId::from_key("ali"), &manager, &db).await;
770 assert!(779 assert!(
771- matches!(refused, Err(AppError::ConflictOwned(ref message))780+ matches!(refused, Err(AppError::ConflictCoded { code, ref message })
772- if message.contains(&MAX_CLASS_COURSES.to_string())),781+ if code == "class_roster_too_large"
782+ && message.contains(&MAX_CLASS_COURSES.to_string())),
773 "the refusal must name the courses, not the roster: {refused:?}"783 "the refusal must name the courses, not the roster: {refused:?}"
774 );784 );
775 assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);785 assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
tests/spec_bounds.rsmodified+27 -0
@@ -1120,3 +1120,30 @@ async fn the_image_meta_bodies_stay_the_same_shape() {
1120 );1120 );
1121 }1121 }
1122 }1122 }
1123+
1124+/// The class refusal codes are a **published** vocabulary: a blueprint pump
1125+/// reports them as a skip `reason`, and the two manual attach routes answer
1126+/// them as the `code` on their `409`. A client branches on them, so a code the
1127+/// spec never names is one nobody can build against β€” this asserts the emitted
1128+/// document still spells every one of them, wherever it does it.
1129+#[tokio::test]
1130+async fn the_class_refusal_codes_stay_published() {
1131+ let spec = spec().await;
1132+ let text = spec.to_string();
1133+ for code in [
1134+ "duplicate",
1135+ "class_deleted",
1136+ "course_deleted",
1137+ "class_at_course_ceiling",
1138+ "class_roster_too_large",
1139+ "course_full",
1140+ "linked_course_missing",
1141+ "blueprint_deleted",
1142+ ] {
1143+ assert!(
1144+ text.contains(code),
1145+ "the OpenAPI document no longer names the refusal code `{code}` β€” it is answered \
1146+ by `Attached::refusal_code` and must stay documented on the class routes"
1147+ );
1148+ }
1149+}