forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB69d4295Ahmet Kaan Gümüş2 months ago536 commits

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