forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

mod.rs659 lines, 24.8 KiBHistoryRawDownload
1//! HTTP layer: axum routers, request/response DTOs (serde), and the auth
2//! extractors. DTOs are plain strings on the wire; handlers parse them into
3//! validated domain newtypes before doing anything. Role-gated endpoints take a
4//! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`.
5
6pub mod academic_years;
7pub mod ai;
8pub mod appointments;
9pub mod attendance;
10pub mod auth;
11pub mod bank_questions;
12pub mod board_ws;
13pub mod boards;
14pub mod builder;
15pub mod chatbot;
16pub mod classes;
17pub mod course_notes;
18pub mod courses;
19pub mod etag;
20pub mod events;
21pub mod exam_weights;
22pub mod exam_ws;
23pub mod exams;
24pub mod homework;
25pub mod holidays;
26pub mod insights;
27pub mod instances;
28pub mod limits;
29pub mod marks;
30pub mod meals;
31pub mod messages;
32pub mod module_gate;
33pub mod modules;
34pub mod notes;
35pub mod offering_subjects;
36pub mod offerings;
37pub mod payments;
38pub mod podcast;
39pub mod pomodoro;
40pub mod questions;
41pub mod rag;
42pub mod room;
43pub mod school;
44pub mod sessions;
45pub mod settings;
46pub mod subjects;
47pub mod terms;
48pub mod users;
49pub mod weekly_plan;
50pub mod work;
51
52pub mod tenant_state;
53
54mod dto;
55// `pub(crate)` for `AiPrincipal`: the AI bridge injects it as an extension on
56// the requests it dispatches into the router (see `ai::server`).
57pub(crate) mod extractor;
58mod image;
59mod page;
60
61pub use dto::{
62 CourseResponse, ExamResponse, HomeworkResponse, PersonRef, SessionResponse, SubjectResponse,
63 UserResponse, course_people, person_map,
64};
65pub use extractor::{
66 BUILDER_COOKIE_PREFIX, CurrentUser, PERSON_COOKIE_PREFIX, RequireAdmin, RequireBuilder,
67 RequireManager, RequireStudent, RequireTeacher,
68};
69pub(crate) use image::{ImageUpload, read_image_upload, store_blob};
70pub use page::{Page, PageParams, Scheduled, WindowParams, paginate};
71
72use std::path::{Path as FsPath, PathBuf};
73
74use axum::Json;
75use axum::extract::Multipart;
76use axum::extract::multipart::MultipartError;
77use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
78use axum::http::{HeaderValue, StatusCode};
79use axum::response::{IntoResponse, Response};
80use serde::{Deserialize, Deserializer};
81use serde_json::json;
82use utoipa::ToSchema;
83
84use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS};
85use crate::database::Database;
86use crate::domain::exam_question::{Choice, ChoiceInput};
87use crate::domain::note_file::FileContentType;
88use crate::domain::role::Role;
89use crate::domain::timestamp::Timestamp;
90use crate::domain::user::UserId;
91use crate::error::{AppError, ValidationError};
92
93/// Close the window between "this account is teacher+" and the write that
94/// records a teacher-only assignment (a class's homeroom teacher, a course's
95/// teacher list). Call it *after* the write, with the account it named.
96///
97/// WHY: the demotion sweeps in `set_role` run **once**, over the rows that
98/// exist at that moment. A `PATCH /users/{id}/role` interleaving between a
99/// handler's role check and its write sweeps nothing — and nothing ever
100/// re-sweeps — so the assignment stands forever, naming an account that may no
101/// longer be a teacher at all. Re-reading the live role after the write is what
102/// makes the pair ordered: either the sweep sees the row, or this read sees the
103/// demotion.
104///
105/// The undo is the very sweep `set_role` owed, and both halves of it are
106/// conditional writes scoped to *this* user (`teacher = $usr`,
107/// `$usr IN teachers`), so a legitimate concurrent assignment of somebody else
108/// is untouched — no lock, the repo's existing idiom. Both are run, not just
109/// the caller's own: a demoted account may hold neither, and the row this
110/// request did not write is exactly the one a lost sweep left behind.
111///
112/// The Sender half of one SSE turn stream. Shared by the chatbot and RAG
113/// nests, which stream a finished answer identically.
114pub(crate) type EventSender =
115 tokio::sync::mpsc::Sender<Result<axum::response::sse::Event, axum::Error>>;
116
117/// Queue one SSE event. `Err` means the client hung up — stop streaming.
118pub(crate) async fn sse_send(
119 tx: &EventSender,
120 name: &str,
121 data: serde_json::Value,
122) -> Result<(), ()> {
123 let event = axum::response::sse::Event::default()
124 .event(name)
125 .json_data(&data)
126 .unwrap_or_else(|err| {
127 tracing::error!("could not encode an SSE event: {err}");
128 axum::response::sse::Event::default()
129 .event("error")
130 .data("{\"code\":\"internal\"}")
131 });
132 tx.send(Ok(event)).await.map_err(|_| ())
133}
134
135/// Queue the terminal `error` event, with a stable code the frontend branches
136/// on and a human-readable message.
137pub(crate) async fn sse_error(tx: &EventSender, code: &str, message: &str) {
138 let _ = sse_send(
139 tx,
140 "error",
141 serde_json::json!({ "code": code, "message": message }),
142 )
143 .await;
144}
145
146/// Cut a finished answer into a handful of `delta` chunks.
147///
148/// Fake streaming: `hab/2` is unary, so the whole text is already in hand and
149/// this only lets the UI paint it progressively instead of in one jump. The
150/// day the protocol grows chunk frames, this is the single function that goes
151/// away — nothing else in the stream knows where a chunk came from.
152///
153/// Splits on character boundaries (never bytes: a clipped UTF-8 sequence would
154/// render as garbage), and never returns an empty chunk. Short answers stay
155/// whole — dribbling "hi" out one letter at a time is worse than not
156/// pretending to stream at all.
157pub(crate) fn slice_reply(text: &str) -> Vec<String> {
158 let chars: Vec<char> = text.chars().collect();
159 if chars.is_empty() {
160 return Vec::new();
161 }
162 let size = chars
163 .len()
164 .div_ceil(crate::constant::REPLY_CHUNKS)
165 .max(crate::constant::MIN_CHUNK_CHARS);
166 chars
167 .chunks(size)
168 .map(|chunk| chunk.iter().collect())
169 .collect()
170}
171
172/// A missing user counts as demoted. The ordinary path is one extra read and no
173/// write at all.
174pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<(), AppError> {
175 if crate::service::user::read(db, target)
176 .await?
177 .is_some_and(|user| user.get_role().at_least(Role::Teacher))
178 {
179 return Ok(());
180 }
181 crate::service::class_group::unassign_everywhere(db, target).await?;
182 crate::db::class_course_teacher::unassign_everywhere(db, target).await?;
183 Err(AppError::Conflict(
184 "that user was demoted below teacher while this request ran — the assignment was undone; re-read their role and retry",
185 ))
186}
187
188/// If both ends are present, `ends_at` must not precede `starts_at`. Shared by
189/// everything that carries a time range (events, course sessions). The PATCH
190/// paths re-check this at write time via
191/// [`crate::db::field_update::FieldUpdate::ordered`], which answers with the
192/// same error — this is the pre-flight, that is the race closer.
193pub(crate) fn check_time_range(
194 starts_at: Option<Timestamp>,
195 ends_at: Option<Timestamp>,
196) -> Result<(), AppError> {
197 if let (Some(starts), Some(ends)) = (starts_at, ends_at)
198 && ends < starts
199 {
200 return Err(crate::domain::timestamp::range_error());
201 }
202 Ok(())
203}
204
205/// A schedule instant a request explicitly sets must not lie in the past —
206/// nothing can be scheduled to start (or end) before now. Applies only to
207/// values the request itself carries: stored values merged into a PATCH are
208/// exempt, because a running exam's `starts_at` is legitimately past and a
209/// title-only edit must not trip over it. `SCHEDULE_PAST_GRACE_MS` keeps
210/// "starts now" from failing by the width of its own round trip.
211pub(crate) fn check_not_past(
212 field: &'static str,
213 value: Option<Timestamp>,
214) -> Result<(), AppError> {
215 if let Some(value) = value
216 && value.as_millis() < Timestamp::now().as_millis() - SCHEDULE_PAST_GRACE_MS
217 {
218 return Err(AppError::Validation(ValidationError::Invalid {
219 field,
220 reason: "must not be in the past",
221 }));
222 }
223 Ok(())
224}
225
226// ---- uploaded blobs ---------------------------------------------------------
227// Note files and question images share one story: bytes on disk under the
228// configured directory in a file named by a server-generated ULID (user input
229// never shapes a path), metadata in a row. Upload writes the blob before the
230// row; delete removes the row before the blob — so a stored row always points
231// at a real blob and a crash strands at worst an unreachable file.
232
233/// Where a stored row's blob lives: one file under the configured directory,
234/// named by the row's server-generated key.
235pub(crate) fn blob_path(files_path: &FsPath, key: &str) -> PathBuf {
236 files_path.join(key)
237}
238
239/// Make sure a school's blob directory exists before writing into it.
240///
241/// `FILES_PATH` is the deployment root and `main` creates only that; each
242/// school's subdirectory appears the first time that school stores a file, so
243/// nothing has to be provisioned when a school is created.
244pub(crate) async fn ensure_files_dir(files_path: &FsPath) -> Result<(), AppError> {
245 tokio::fs::create_dir_all(files_path).await.map_err(|err| {
246 AppError::Internal(format!(
247 "failed to create the files directory {}: {err}",
248 files_path.display()
249 ))
250 })
251}
252
253/// Best-effort blob removal after its row is gone. Failure only strands an
254/// unreachable file on disk, so it is logged rather than surfaced.
255pub(crate) async fn remove_blob(files_path: &FsPath, key: &str) {
256 let path = blob_path(files_path, key);
257 if let Err(err) = tokio::fs::remove_file(&path).await
258 && err.kind() != std::io::ErrorKind::NotFound
259 {
260 tracing::warn!("failed to remove blob {}: {err}", path.display());
261 }
262}
263
264/// How much of a stored blob is read per chunk, and how many chunks its body
265/// may have in flight. 4 × 64 KiB is the whole memory ceiling one stream
266/// costs, however large the file behind it. Shared by every streaming blob
267/// door (podcast audio, the insight report document).
268const BLOB_CHUNK_BYTES: usize = 64 * 1024;
269const BLOB_CHUNKS_IN_FLIGHT: usize = 4;
270
271/// A stored file as a byte stream: a reader task hands chunks to the body over
272/// a bounded channel, so a client that stops reading parks the pump at the
273/// next send instead of pinning the whole file in memory, and a closed body
274/// ends the task by itself.
275pub(crate) fn pump(
276 file: tokio::fs::File,
277) -> impl tokio_stream::Stream<Item = Result<axum::body::Bytes, std::io::Error>> + Send + 'static
278{
279 let (tx, rx) = tokio::sync::mpsc::channel::<Result<axum::body::Bytes, std::io::Error>>(
280 BLOB_CHUNKS_IN_FLIGHT,
281 );
282 tokio::spawn(async move {
283 let mut file = file;
284 let mut buf = vec![0u8; BLOB_CHUNK_BYTES];
285 loop {
286 match tokio::io::AsyncReadExt::read(&mut file, &mut buf).await {
287 Ok(0) => break,
288 Ok(n) => {
289 if tx
290 .send(Ok(axum::body::Bytes::copy_from_slice(&buf[..n])))
291 .await
292 .is_err()
293 {
294 break;
295 }
296 }
297 Err(err) => {
298 let _ = tx.send(Err(err)).await;
299 break;
300 }
301 }
302 }
303 });
304 tokio_stream::wrappers::ReceiverStream::new(rx)
305}
306
307/// The declared content type of an inline-displayed image upload, held to the
308/// raster allowlist — SVG stays out (it can script) since these bytes are
309/// rendered inline to whole classes. Shared by exam question images and pool
310/// question photos.
311pub(crate) fn image_content_type(raw: &str) -> Result<FileContentType, AppError> {
312 let content_type = FileContentType::try_new(raw)?;
313 if !QUESTION_IMAGE_CONTENT_TYPES.contains(&content_type.as_str()) {
314 return Err(AppError::Validation(ValidationError::Invalid {
315 field: "content_type",
316 reason: "must be image/png, image/jpeg, image/webp, or image/gif",
317 }));
318 }
319 Ok(content_type)
320}
321
322/// A stored blob as an inline-displayable response: the declared (and
323/// allowlisted) content type, `nosniff`, and `no-store` — moderated/exam
324/// content has no business in shared caches, and a replaced image must not
325/// linger.
326pub(crate) async fn serve_inline_blob(
327 files_path: &FsPath,
328 file: &str,
329 content_type: &FileContentType,
330) -> Result<Response, AppError> {
331 let bytes = tokio::fs::read(blob_path(files_path, file))
332 .await
333 .map_err(|err| {
334 // The row exists but its blob doesn't — server-side damage (a lost
335 // volume path), not a client 404.
336 AppError::Internal(format!("missing blob for image {file}: {err}"))
337 })?;
338 let content_type = HeaderValue::from_str(content_type.as_str())
339 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
340 Ok((
341 [
342 (CONTENT_TYPE, content_type),
343 (X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
344 (CACHE_CONTROL, HeaderValue::from_static("private, no-store")),
345 ],
346 bytes,
347 )
348 .into_response())
349}
350
351/// Multipart read failures: the route-level body cap maps to 413 like the
352/// school-limit check; anything else is a malformed body.
353pub(crate) fn multipart_error(err: MultipartError) -> AppError {
354 if err.status() == StatusCode::PAYLOAD_TOO_LARGE {
355 AppError::PayloadTooLarge("the upload exceeds the server's absolute body cap".to_string())
356 } else {
357 AppError::Validation(ValidationError::Invalid {
358 field: "file",
359 reason: "malformed multipart body",
360 })
361 }
362}
363
364/// Schema-only mirror of an upload form; the handlers read the multipart
365/// stream directly.
366#[derive(ToSchema)]
367#[allow(dead_code)]
368pub(crate) struct UploadFileForm {
369 /// The file part. Its `Content-Type` (and, where required, `filename`)
370 /// are stored alongside the bytes.
371 #[schema(value_type = String, format = Binary)]
372 file: String,
373}
374
375/// One uploaded file's raw parts, as the client sent them — the caller
376/// validates what it cares about (notes need a filename, images an
377/// allowlisted content type).
378pub(crate) struct UploadedFile {
379 pub name: Option<String>,
380 pub content_type: Option<String>,
381 pub data: Vec<u8>,
382}
383
384/// Pull the `file` field out of a multipart body, reading it chunkwise so an
385/// oversized upload dies at `limit`, not after buffering whole — the check is
386/// on real bytes received, so a lying `Content-Length` can't sneak past it.
387/// Empty files are refused; stray extra fields are ignored.
388pub(crate) async fn read_upload(
389 multipart: &mut Multipart,
390 limit: i64,
391) -> Result<UploadedFile, AppError> {
392 let mut field = loop {
393 match multipart.next_field().await.map_err(multipart_error)? {
394 Some(field) if field.name() == Some("file") => break field,
395 Some(_) => continue,
396 None => {
397 return Err(AppError::Validation(ValidationError::Invalid {
398 field: "file",
399 reason: "the multipart body must carry a 'file' field",
400 }));
401 }
402 }
403 };
404 let name = field.file_name().map(str::to_string);
405 let content_type = field.content_type().map(str::to_string);
406
407 let mut data = Vec::new();
408 while let Some(chunk) = field.chunk().await.map_err(multipart_error)? {
409 if data.len() + chunk.len() > limit as usize {
410 return Err(AppError::PayloadTooLarge(format!(
411 "the file exceeds the school's limit of {limit} bytes"
412 )));
413 }
414 data.extend_from_slice(&chunk);
415 }
416 if data.is_empty() {
417 return Err(AppError::Validation(ValidationError::Empty("file")));
418 }
419 Ok(UploadedFile {
420 name,
421 content_type,
422 data,
423 })
424}
425
426/// One option of a choice question as a client sends it — the wire form of
427/// [`crate::domain::exam_question::ChoiceInput`], shared by the exam-question
428/// and bank-template routes.
429///
430/// `id` is the option's key within the payload: send back the `id` the server
431/// returned to keep that option (and its picture) across an edit, or any fresh
432/// string to introduce a new one. The server mints the stored id either way, so
433/// nothing a client sends here ever reaches storage.
434#[derive(Debug, Clone, Deserialize, ToSchema)]
435pub(crate) struct ChoiceBody {
436 #[serde(default)]
437 pub id: Option<String>,
438 #[schema(example = "42", max_length = 500)]
439 pub text: String,
440}
441
442impl ChoiceBody {
443 pub(crate) fn into_input(self) -> ChoiceInput {
444 ChoiceInput {
445 id: self.id,
446 text: self.text,
447 }
448 }
449
450 /// The whole submitted list, or `None` when the field was omitted/cleared.
451 pub(crate) fn into_inputs(choices: Option<Vec<Self>>) -> Option<Vec<ChoiceInput>> {
452 choices.map(|list| list.into_iter().map(Self::into_input).collect())
453 }
454
455 /// The stored choices as a payload that re-submits them unchanged — how a
456 /// PATCH that omits `choices` keeps every option's identity.
457 pub(crate) fn from_stored(choices: Option<&[Choice]>) -> Option<Vec<ChoiceInput>> {
458 choices.map(|list| {
459 list.iter()
460 .map(|choice| ChoiceInput {
461 id: Some(choice.get_id().as_str().to_string()),
462 text: choice.get_text().as_str().to_string(),
463 })
464 .collect()
465 })
466 }
467}
468
469/// Distinguishes an *absent* PATCH field from an explicit `null`: absent never
470/// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the
471/// stored value); `null` or a value lands here as `Some(inner)` (clear or set).
472pub(crate) fn set_or_clear<'de, D, T>(de: D) -> Result<Option<Option<T>>, D::Error>
473where
474 D: Deserializer<'de>,
475 T: Deserialize<'de>,
476{
477 Option::<T>::deserialize(de).map(Some)
478}
479
480/// The AI-unavailable `503`. Shared by every route that can refuse because no
481/// AI service is reachable: built here rather than as an `AppError` variant —
482/// `AppError`'s 503s all mean "the database is reconnecting", which this is
483/// not. No `Retry-After` — when a service will dial back in is unknowable.
484pub(crate) fn ai_unavailable(message: &str) -> Response {
485 (
486 StatusCode::SERVICE_UNAVAILABLE,
487 Json(json!({ "error": message })),
488 )
489 .into_response()
490}
491
492#[cfg(test)]
493mod tests {
494 use super::*;
495
496 /// The demotion-vs-assign race, driven in the order the race produces it:
497 /// both assignments are already written (the handler's role check has
498 /// passed), *then* the account drops below `teacher` with no sweep — which
499 /// is exactly what `set_role`'s one-shot sweep leaves behind when it runs
500 /// before the write. The post-write re-read must undo both columns and
501 /// refuse; with the account still staff it must undo nothing at all.
502 ///
503 /// Asserted on stored state, never on a return value: the in-memory engine
504 /// forges those (see [`crate::db::cap`]).
505 #[tokio::test]
506 async fn undo_if_demoted_repairs_both_assignments_or_neither() {
507 use crate::domain::class_group::ClassName;
508 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
509 use crate::domain::user::Username;
510
511 let (db, _leases) = crate::database::init_test_db().await;
512 let office = crate::db::class_member::tests::fixture_user(&db, "office").await;
513 // Staffing an instance is the office's call: `assign_teacher` is
514 // manager+, and the fixture mints a plain student.
515 sqlx::query("UPDATE app_user SET role = 'manager' WHERE id = $1")
516 .bind(office.uuid())
517 .execute(&db)
518 .await
519 .unwrap();
520 let teacher = crate::service::user::create(&db, Username::try_new("ada").unwrap(), None)
521 .await
522 .unwrap();
523 crate::service::user::set_role(&db, teacher.get_id(), Role::Teacher)
524 .await
525 .unwrap();
526 // The two assignments the undo owes: the section's homeroom teacher, and
527 // a teacher assigned to one of its instances (the catalog's own
528 // assignment list is gone with D6 — who teaches is per instance).
529 let assigned = async |db: &Database| {
530 let class = crate::service::class_group::create(
531 db,
532 &office,
533 ClassName::try_new("9-A").unwrap(),
534 crate::domain::grade::GradeLevel::new(9).unwrap(),
535 None,
536 Some(*teacher.get_id()),
537 )
538 .await
539 .unwrap();
540 let course = crate::service::course::create(
541 db,
542 &office,
543 CourseTitle::try_new("algebra").unwrap(),
544 CourseDescription::try_new("").unwrap(),
545 CourseKind::course(),
546 )
547 .await
548 .unwrap();
549 let instance =
550 crate::service::class_course::attach(db, class.get_id(), course.get_id(), &office)
551 .await
552 .unwrap();
553 crate::service::class_course::assign_teacher(
554 db,
555 instance.get_id(),
556 teacher.get_id(),
557 &office,
558 )
559 .await
560 .unwrap();
561 (class, instance)
562 };
563 /// `(the class's stored homeroom teacher, the instance's teacher list)`.
564 async fn stored(
565 class: &crate::domain::class_group::ClassGroupId,
566 instance: &crate::domain::class_course::ClassCourseId,
567 db: &Database,
568 ) -> (Option<UserId>, Vec<UserId>) {
569 (
570 crate::service::class_group::read(db, class)
571 .await
572 .unwrap()
573 .unwrap()
574 .get_teacher()
575 .cloned(),
576 crate::db::class_course_teacher::list_for_instance(db, instance)
577 .await
578 .unwrap(),
579 )
580 }
581
582 // Still staff: one read, and not a single write.
583 let (class, instance) = assigned(&db).await;
584 undo_if_demoted(teacher.get_id(), &db)
585 .await
586 .expect("an account that is still teacher+ keeps what it was given");
587 assert_eq!(
588 stored(class.get_id(), instance.get_id(), &db).await,
589 (Some(*teacher.get_id()), vec![*teacher.get_id()]),
590 "nothing may be undone while the bar still holds"
591 );
592
593 // Demoted with no sweep — the state a lost race leaves.
594 sqlx::query("UPDATE app_user SET role = 'student' WHERE id = $1")
595 .bind(teacher.get_id().uuid())
596 .execute(&db)
597 .await
598 .unwrap();
599 let refused = undo_if_demoted(teacher.get_id(), &db).await;
600 assert!(
601 matches!(refused, Err(AppError::Conflict(message)) if message.contains("demoted")),
602 "a demotion mid-request must be a 409 naming it: {refused:?}"
603 );
604 assert_eq!(
605 stored(class.get_id(), instance.get_id(), &db).await,
606 (None, Vec::new()),
607 "…with both assignments taken back, not just the caller's own"
608 );
609
610 // A user that is gone counts as demoted, and the repair is idempotent.
611 assert!(
612 undo_if_demoted(&UserId::from_key("ghost"), &db)
613 .await
614 .is_err()
615 );
616 assert!(undo_if_demoted(teacher.get_id(), &db).await.is_err());
617 assert_eq!(
618 stored(class.get_id(), instance.get_id(), &db).await,
619 (None, Vec::new())
620 );
621 }
622
623 #[tokio::test]
624 async fn check_time_range_orders_the_ends() {
625 let at = |ms| Some(Timestamp::from_millis(ms));
626 assert!(check_time_range(at(1), at(2)).is_ok());
627 assert!(check_time_range(at(1), at(1)).is_ok());
628 assert!(check_time_range(at(2), at(1)).is_err());
629 // A missing end never fails the range check.
630 assert!(check_time_range(None, at(1)).is_ok());
631 assert!(check_time_range(at(1), None).is_ok());
632 assert!(check_time_range(None, None).is_ok());
633 }
634
635 #[tokio::test]
636 async fn check_not_past_rejects_backdating_but_keeps_the_grace() {
637 let now = Timestamp::now().as_millis();
638 // Absent and future values pass.
639 assert!(check_not_past("starts_at", None).is_ok());
640 assert!(check_not_past("starts_at", Some(Timestamp::from_millis(now + 60_000))).is_ok());
641 // Inside the grace passes — "starts now" survives its round trip.
642 assert!(
643 check_not_past(
644 "starts_at",
645 Some(Timestamp::from_millis(now - SCHEDULE_PAST_GRACE_MS / 2)),
646 )
647 .is_ok()
648 );
649 // Beyond the grace is a validation error naming the field.
650 let past = Timestamp::from_millis(now - SCHEDULE_PAST_GRACE_MS - 60_000);
651 assert!(matches!(
652 check_not_past("ends_at", Some(past)),
653 Err(AppError::Validation(ValidationError::Invalid {
654 field: "ends_at",
655 ..
656 }))
657 ));
658 }
659}