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

constant.rs1477 lines, 78.6 KiBHistoryRawDownload
1//! Validation limits, in one place.
2
3/// A school's display name.
4pub const MAX_SCHOOL_NAME_LEN: usize = 120;
5
6pub const MIN_USERNAME_LEN: usize = 3;
7pub const MAX_USERNAME_LEN: usize = 32;
8
9/// A student's school-issued number. Free text rather than digits on purpose —
10/// schools prefix, slash and hyphenate them ("9-B/17") — bounded like the other
11/// short labels. Only students hold one (the write paths enforce the role, and
12/// the role cascade clears it), and it is unique inside the school (the partial
13/// unique index is the enforcement).
14pub const MAX_STUDENT_NUMBER_LEN: usize = 32;
15
16/// Separators allowed inside a username (never at the edges, never doubled).
17pub const USERNAME_SEPARATORS: [char; 3] = ['.', '_', '-'];
18
19/// Names nobody may claim through `/auth/register`: they read as staff and
20/// invite impersonation. Enforced at the registration endpoint, not in
21/// `Username` itself, so the `ADMIN_USERNAME` bootstrap can still seed
22/// accounts like `admin`.
23pub const RESERVED_USERNAMES: [&str; 7] = [
24 "admin",
25 "administrator",
26 "root",
27 "support",
28 "system",
29 "moderator",
30 "staff",
31];
32
33pub const MIN_PASSWORD_LEN: usize = 6;
34pub const MAX_PASSWORD_LEN: usize = 128;
35
36pub const MAX_NAME_LEN: usize = 100;
37
38/// Profile fields: the self-chosen name a user is shown under, the free
39/// text under it, and the postal address.
40pub const MAX_DISPLAY_NAME_LEN: usize = 50;
41pub const MAX_BIO_LEN: usize = 500;
42pub const MAX_ADDRESS_LEN: usize = 500;
43
44/// How many **section** rows one profile read embeds — the block is one row
45/// per section, so this counts sections, not catalogue courses. A cap on the
46/// response, not on membership — the full lists stay at `/courses/me` and
47/// `/classes/me`. 100 because a teacher's sections are their courses
48/// multiplied by the classes they teach, so the course-era figure truncated a
49/// real timetable, while one course row's own cap (`MAX_COURSE_SECTIONS`)
50/// bounds only a single row.
51pub const MAX_PROFILE_COURSES: usize = 100;
52pub const MAX_PROFILE_CLASSES: usize = 5;
53
54/// RFC 5321's practical upper bound for a full address.
55pub const MAX_EMAIL_LEN: usize = 254;
56
57/// Digit-count bounds for a phone number (E.164 allows at most 15).
58pub const MIN_PHONE_DIGITS: usize = 7;
59pub const MAX_PHONE_DIGITS: usize = 15;
60
61pub const MAX_NOTE_TITLE_LEN: usize = 200;
62pub const MAX_NOTE_CONTENT_LEN: usize = 10_000;
63
64/// How many files one note may carry.
65pub const MAX_NOTE_FILES: usize = 10;
66
67/// How many files one course note may carry.
68pub const MAX_COURSE_NOTE_FILES: usize = 10;
69
70pub const MAX_MESSAGE_SUBJECT_LEN: usize = 200;
71pub const MAX_MESSAGE_BODY_LEN: usize = 10_000;
72/// A message's optional sender-chosen tag ("Study", "Exam", …) — free text,
73/// rendered as a badge by the UI.
74pub const MAX_MESSAGE_LABEL_LEN: usize = 50;
75
76/// Bounds for a note file's original filename and its MIME content type.
77pub const MAX_FILE_NAME_LEN: usize = 255;
78pub const MAX_FILE_CONTENT_TYPE_LEN: usize = 100;
79
80/// The school-adjustable per-file upload size limit (`max_file_bytes` in
81/// settings): its default and the inclusive range a manager may set. The
82/// ceiling is a server-protection hard cap — uploads buffer in memory and land
83/// in single disk files, so it must stay modest no matter the school's wish.
84pub const DEFAULT_MAX_FILE_BYTES: i64 = 5 * 1024 * 1024;
85pub const MIN_MAX_FILE_BYTES: i64 = 1024;
86pub const MAX_MAX_FILE_BYTES: i64 = 25 * 1024 * 1024;
87
88/// Headroom on top of `MAX_MAX_FILE_BYTES` for the upload route's HTTP body
89/// cap: multipart boundaries, part headers, and the filename ride alongside
90/// the file bytes themselves.
91pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024;
92
93/// The content types an uploaded inline image (exam question images, pool
94/// question photos) may declare — raster formats only. SVG is deliberately
95/// out: it can carry scripts, and these bytes are served for inline display
96/// to whole classes.
97pub const QUESTION_IMAGE_CONTENT_TYPES: [&str; 4] =
98 ["image/png", "image/jpeg", "image/webp", "image/gif"];
99
100/// Bounds for a pool question (the student-asked Q&A pool) and its solutions.
101pub const MAX_POOL_QUESTION_TITLE_LEN: usize = 200;
102pub const MAX_POOL_QUESTION_BODY_LEN: usize = 10_000;
103pub const MAX_SOLUTION_BODY_LEN: usize = 10_000;
104
105pub const MAX_EVENT_TITLE_LEN: usize = 200;
106pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000;
107
108pub const MAX_EXAM_TITLE_LEN: usize = 200;
109pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000;
110
111pub const MAX_COURSE_TITLE_LEN: usize = 200;
112pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000;
113
114/// A class section is named like a course. `MAX_CLASS_GRADE_LEN` is gone with
115/// the free-text grade it bounded: a class now carries a validated ladder
116/// position (`MIN_GRADE_LEVEL`..=`MAX_GRADE_LEVEL`, `0` = anaokulu), which
117/// needs a length bound no more than a week day does.
118pub const MAX_CLASS_NAME_LEN: usize = 200;
119
120/// The grade ladder every class section and course template sits on. `0` is
121/// anaokulu (kindergarten), `1..=12` the school years; [`MAX_GRADE_LEVEL`]
122/// graduating is expressed by the absence of a promotion, not a 13th rung.
123pub const MIN_GRADE_LEVEL: i16 = 0;
124pub const MAX_GRADE_LEVEL: i16 = 12;
125
126/// How big one class may get, on each of its two axes. These are not comfort
127/// numbers: attaching a course to a class writes one enrollment per member and
128/// adding a member writes one per attached course, both in a *single*
129/// transaction, so each axis's counter is the bound on the other axis's write
130/// loop — a class with no ceiling is an unbounded transaction anyone with the
131/// manager role can trigger. A section is a homeroom (`MAX_HOMEWORK_ASSIGNED`
132/// shares the 200) and its timetable is a school week, not a catalogue.
133///
134/// Which is also why each write is refused on the *other* axis: a class created
135/// before these numbers existed can stand above one of them, and the axis being
136/// added to having room says nothing about the loop's length — that is set by
137/// the axis it multiplies against. So the pump refuses a member while the class
138/// holds more than `MAX_CLASS_COURSES` courses and a course while it holds more
139/// than `MAX_CLASS_MEMBERS` students, and only shrinking the overloaded side
140/// clears it.
141pub const MAX_CLASS_MEMBERS: i64 = 200;
142pub const MAX_CLASS_COURSES: i64 = 50;
143
144/// Weekly lesson hours of a class×course instance (D8's report-card weight). Bounded
145/// so a typo cannot make one instance dominate the year average.
146pub const MIN_DERS_SAATI: i64 = 1;
147pub const MAX_DERS_SAATI: i64 = 40;
148
149/// How many slots one owner's weekly plan may hold. A slot is where one of
150/// the week's lesson hours lands, and a course teaches at most
151/// `MAX_DERS_SAATI` (40) hours a week — so 40 bounds any honest timetable
152/// (the bounds are the same number by construction) and stops a pathological
153/// client at the bound every other weekly-hours loop already answers to.
154pub const MAX_WEEKLY_SLOTS: usize = MAX_DERS_SAATI as usize;
155
156/// The earliest minute a weekly-plan slot may start or end: midnight.
157pub const MIN_SLOT_MINUTE: i64 = 0;
158
159/// The latest minute a weekly-plan slot may start or end: 23:59. (A `TIME`
160/// column has no `24:00` to carry a midnight end, and the
161/// minutes-past-midnight wire form never lies about it.)
162pub const MAX_SLOT_MINUTE: i64 = 24 * 60 - 1;
163
164/// The default grade-display bands: the Turkish 5-point scale (85–100 = 5,
165/// … 0–44 = 1). Schools edit the list via `PATCH /settings`; the report-card
166/// verdict reads the band labelled `"2"` as the pass boundary.
167pub const DEFAULT_GRADE_BANDS: [(i64, &str); 5] =
168 [(85, "5"), (70, "4"), (55, "3"), (45, "2"), (0, "1")];
169
170pub const MAX_SUBJECT_NAME_LEN: usize = 200;
171pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000;
172
173pub const MAX_HOMEWORK_TITLE_LEN: usize = 200;
174pub const MAX_HOMEWORK_DESCRIPTION_LEN: usize = 2_000;
175
176/// A homework submission's optional free-text note, sent alongside its files.
177pub const MAX_HOMEWORK_TEXT_LEN: usize = 5_000;
178
179/// How many files one homework submission may carry.
180pub const MAX_HOMEWORK_FILES_PER_SUBMISSION: usize = 10;
181
182/// How many students a homework may be narrowed to. The whole-course default
183/// carries no assigned list at all, so this caps only an explicit subset.
184pub const MAX_HOMEWORK_ASSIGNED: usize = 200;
185
186/// The default attendance states, and also the mandatory core: a school may
187/// add its own statuses via `PATCH /settings`, but these four can never be
188/// removed — the attendance rate's semantics are defined over them.
189pub const DEFAULT_ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"];
190
191pub const MAX_SESSION_TOPIC_LEN: usize = 200;
192
193/// The default exam kinds with their weights; schools replace the list via
194/// `PATCH /settings`. An exam's kind decides how heavily it counts into the
195/// course average — the defaults all weigh 1 (a plain average) so weighting
196/// is opt-in policy, not baked-in opinion. The defaults are the Turkish K12
197/// classroom's own: written, oral, practice.
198pub const DEFAULT_EXAM_KINDS: [(&str, i64); 3] = [("yazili", 1), ("sozlu", 1), ("uygulama", 1)];
199
200/// Bounds for the school-editable lists in settings (exam kinds, attendance
201/// statuses): entry count and per-entry character length.
202pub const MAX_SETTINGS_LIST_LEN: usize = 20;
203pub const MAX_SETTINGS_ITEM_LEN: usize = 50;
204
205/// Bounds for the grade-display bands in settings.
206pub const MAX_GRADE_BANDS: usize = 20;
207pub const MAX_GRADE_LABEL_LEN: usize = 20;
208
209/// How many times a read-then-compare-and-set path (`PATCH /settings`, `PATCH
210/// /bank/{bid}`, every appointment decision) re-reads and retries when a
211/// concurrent edit lands between its snapshot and its save. A miss normally
212/// re-validates into a `409`, so this only covers a write racing a legal
213/// transition.
214pub const CAS_UPDATE_RETRIES: usize = 3;
215
216pub const MAX_TERM_NAME_LEN: usize = 100;
217
218/// An academic year is named like a term ("2026-2027").
219pub const MAX_ACADEMIC_YEAR_NAME_LEN: usize = 100;
220
221/// The per-term absence limits a school may configure; a bound so a typo
222/// cannot disable the rule or make it absurd.
223pub const MAX_ABSENCE_DAYS: i64 = 365;
224
225/// The timezone a school's day-bucketing falls back to when none is set, and
226/// the one the default deployment runs in.
227pub const DEFAULT_TIMEZONE: &str = "Europe/Istanbul";
228
229/// The timezones a school may configure. A short allow-list on purpose: the
230/// backend has no timezone database of its own, and day-bucketing needs the
231/// offset to be trustworthy.
232pub const TIMEZONES: [&str; 2] = ["Europe/Istanbul", "UTC"];
233
234/// A published availability slot's optional note ("bring your report card").
235pub const MAX_APPOINTMENT_NOTE_LEN: usize = 500;
236
237/// Why a requester wants the meeting — required, and read by a human, so it
238/// stays short.
239pub const MAX_APPOINTMENT_REASON_LEN: usize = 1_000;
240
241/// How many concrete slot rows one recurring publish may expand into. Weekly
242/// occurrences over a full school year fit inside this; a runaway `until`
243/// (a decade out) is refused instead of writing thousands of rows.
244pub const MAX_SLOT_OCCURRENCES: usize = 52;
245
246/// A holiday is named for a human reader ("29 Ekim Cumhuriyet Bayramı").
247pub const MAX_HOLIDAY_NAME_LEN: usize = 100;
248
249/// The only accepted holiday kinds. `resmi`: an official public holiday.
250/// `dini`: a religious observance. `idari`: an administrative closure the
251/// school itself declares. `ara`: a break inside the year (yarım yıl arası).
252pub const HOLIDAY_KINDS: [&str; 4] = ["resmi", "dini", "idari", "ara"];
253
254/// The holiday table's name, for the same builder-shaped writes every other
255/// table names through its constant.
256pub const HOLIDAY_TABLE: &str = "holiday";
257
258/// The longest `from`/`to` span one materialize call may cover, in days. A
259/// school year fits; a decade is a typo and is refused.
260pub const MAX_MATERIALIZE_DAYS: i64 = 366;
261
262/// The most lessons one materialize call may write. Forty slots a week is the
263/// plan cap, so a full year is far under this; the ceiling is what stops a
264/// runaway range from writing thousands of rows in one request.
265pub const MAX_MATERIALIZE_SESSIONS: usize = 500;
266
267/// How many sections one catalogue course row may embed. A course taught in
268/// more sections than this still lists them at `/instances`; the catalogue
269/// row carries the untruncated total beside the array.
270pub const MAX_COURSE_SECTIONS: usize = 50;
271
272/// The default meal slots; schools replace the list via `PATCH /settings`, and
273/// a published menu snapshots the slot it was written for, so retiring a slot
274/// never rewrites history.
275pub const DEFAULT_MEAL_SLOTS: [&str; 3] = ["breakfast", "lunch", "snack"];
276
277/// The default dietary tags. A student's profile and a dish both carry tags
278/// from this school-editable list, which is how "this dish is safe for them"
279/// is answered without the backend knowing any nutrition.
280pub const DEFAULT_DIETARY_TAGS: [&str; 5] = [
281 "vegetarian",
282 "vegan",
283 "gluten_free",
284 "lactose_free",
285 "nut_allergy",
286];
287
288/// Bounds on one menu and the dishes hanging off it.
289pub const MAX_DISH_NAME_LEN: usize = 100;
290pub const MAX_DISH_DESCRIPTION_LEN: usize = 500;
291pub const MAX_DISHES_PER_MENU: usize = 50;
292pub const MAX_DISH_TAGS: usize = 10;
293
294/// How many students one menu may seat. Absent capacity means uncapped, the
295/// same shape a course's `capacity` uses.
296pub const MAX_MENU_CAPACITY: i64 = 10_000;
297
298/// Bounds on a student's dietary profile: one row per student, so the tag list
299/// is the whole payload plus a free-text note for the kitchen.
300pub const MAX_DIETARY_TAGS: usize = 10;
301pub const MAX_DIETARY_NOTE_LEN: usize = 500;
302
303/// Money is **minor units** as `i64` everywhere — never a decimal and
304/// never a float. `MAX_DISH_PRICE_MINOR` caps one dish (10 000 ₺);
305/// `MAX_LEDGER_AMOUNT_MINOR` caps one ledger line (100 000 ₺), which is wide
306/// enough for a term's prepayment.
307pub const MAX_DISH_PRICE_MINOR: i64 = 1_000_000;
308pub const MAX_LEDGER_AMOUNT_MINOR: i64 = 10_000_000;
309
310/// Bounds on the free-text a ledger line carries: how the money moved, and why.
311pub const MAX_LEDGER_METHOD_LEN: usize = 50;
312pub const MAX_LEDGER_NOTE_LEN: usize = 500;
313
314/// How many times one seat may be taken on one menu: the first booking plus
315/// nine re-bookings after a cancel.
316///
317/// A cap on *storage*, not on indecision. Every cycle appends two permanent,
318/// undeletable ledger lines — the charge and its reversal, both keyed to the
319/// attempt — and nothing else bounded them: at the API's own request ceiling
320/// one account could grow its statement by hundreds of thousands of rows a
321/// day, which every later balance read then answers for. Ten is far past what
322/// a family changing its mind about lunch needs, and a menu whose seat really
323/// must move again is the canteen's to cancel.
324pub const MAX_MEAL_BOOKING_ATTEMPTS: i64 = 10;
325
326/// Ceiling on the settings knob that closes booking (and cancelling) ahead of
327/// a meal — one week. The knob itself is optional: absent means no cutoff.
328pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60;
329
330/// Inclusive ceiling for a meal slot's `serving_minute` — minutes past
331/// midnight on the menu's date, so `0` = 00:00 and `1439` = 23:59. The cutoff
332/// above counts back from that instant.
333///
334/// **The clock is UTC.** This backend deliberately stores no school timezone
335/// (rejected feature), so staff enter the serving time in UTC: a UTC+3 school
336/// types `540` (09:00) to mean noon locally. Optional per slot — and a slot
337/// without one has **no cutoff at all**, since there is no instant to count a
338/// deadline back from; the cutoff knob starts binding that slot the day the
339/// school sets its hour.
340pub const MAX_MEAL_SERVING_MINUTE: i64 = 24 * 60 - 1;
341
342/// The only accepted course kinds. `course`: a regular class. `study`: a
343/// supervised study session. Behaviorally identical — the kind is a
344/// label for the UI, everything else (enrollment, exams, sessions, marks)
345/// works the same.
346pub const COURSE_KINDS: [&str; 3] = ["course", "study", "club"];
347
348/// The only accepted exam modes. `sync`: everyone sits the exam inside one
349/// fixed window. `async`: each student starts inside the window and gets their
350/// own `duration_ms` slice of it. `open`: no window — students sit anytime,
351/// with an optional per-attempt `duration_ms` (absent = unlimited time). An
352/// exam with no mode at all is an offline-graded draft and cannot be sat.
353pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"];
354
355/// The only accepted homework grades. `done`: submitted and complete;
356/// `incomplete`: submitted but lacking; `missing`: not done. A teacher-set
357/// `missing` is a deliberate verdict, distinct from the roster's *computed*
358/// missing (unsubmitted past due). The `HomeworkStatus` newtype enforces the
359/// set; the DDL carries no ASSERT (repo convention), exactly like `EXAM_MODES`.
360pub const HOMEWORK_STATUSES: [&str; 3] = ["done", "incomplete", "missing"];
361
362/// The only accepted meal-booking states. A cancel flips the status and stamps
363/// `cancelled_at` instead of deleting the row, so a seat freed after the cutoff
364/// is still auditable against the ledger line it charged.
365pub const MEAL_BOOKING_STATUSES: [&str; 2] = ["booked", "cancelled"];
366
367/// The only accepted meal-attendance states — did the student actually eat.
368/// Deliberately *not* the school's `attendance_statuses`: a canteen line has no
369/// "late" or "excused", and mixing the two would let a school edit one meaning
370/// while changing the other.
371pub const MEAL_ATTENDANCE_STATUSES: [&str; 2] = ["served", "missed"];
372
373/// The only accepted ledger kinds. `charge`: a booking billed the student.
374/// `credit`: money in (a payment, or an opening balance). `reversal`: a charge
375/// undone — the ledger is append-only, so a cancelled booking writes a new
376/// opposing line rather than editing or deleting the charge.
377pub const MEAL_LEDGER_KINDS: [&str; 3] = ["charge", "credit", "reversal"];
378
379/// The only accepted school-payment ledger kinds. `charge`: an installment the
380/// student owes, appended when a fee plan is assigned. `credit`: money in,
381/// against one named charge. `refund`: money paid back out, against one named
382/// credit. `reversal`: a mistaken `charge` or `refund` undone — the ledger is
383/// append-only, so the opposing line is appended rather than the line edited.
384/// A mistaken *credit* is corrected by a `refund`, which is why `reversal`
385/// never points at one.
386pub const PAYMENT_LEDGER_KINDS: [&str; 4] = ["charge", "credit", "reversal", "refund"];
387
388/// Bounds on a fee plan: its name, and how many installments it may carry.
389/// Sixty covers a monthly plan over five years — well past any school year,
390/// and low enough that one assignment cannot append a thousand ledger lines.
391pub const MAX_FEE_PLAN_NAME_LEN: usize = 120;
392pub const MAX_FEE_PLAN_INSTALLMENTS: usize = 60;
393
394/// How many students one `POST /payments/plans/{id}/assignments` may name.
395/// Bulk placement is a whole class at a time, not the whole school.
396pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200;
397
398/// How many charge lines one assignment request may append: the students it
399/// names times the plan's installments. The student cap alone cannot see the
400/// schedule — 200 students on a 60-installment plan is 12 000 sequential
401/// writes in one HTTP request, and nothing in the stack times a request out.
402/// Three thousand leaves the ordinary shapes whole (200 students up to a
403/// 15-installment plan, 50 students on the largest plan there is) and the
404/// refusal tells the caller to split the batch.
405pub const MAX_FEE_PLAN_ASSIGN_WRITES: usize = 3_000;
406
407/// How many lines may be applied to one ledger line — the payments under a
408/// charge, the refunds under a payment, and every reversal among them. The
409/// over-payment cap folds that whole subtree one query per line while holding
410/// the process-global payment lock, so an unbounded subtree is an unbounded
411/// stall for every other payment in the school: 2 000 one-minor-unit payments make
412/// the next one issue 2 001 queries with the lock held. Twenty pieces is
413/// already a pathological way to settle a single installment.
414pub const MAX_LEDGER_APPLIED_LINES: usize = 20;
415
416/// Ceiling on the client-chosen `request_key` that makes a credit or a refund
417/// retry-safe: it becomes part of the ledger line's record id, so it is bounded
418/// and drawn from `[A-Za-z0-9-]` — `_` joins the parts of a ledger id, so a key
419/// carrying one could spell another line's id. Sixty-four characters take a
420/// UUID or a receipt number comfortably.
421pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64;
422
423/// Bounds on a whiteboard: its title, and how many people the creator may name
424/// onto it. Two hundred is a big club or a whole grade, not the school; every
425/// participant may draw, so this is also what bounds one board's writer count.
426///
427/// It was fifty while a roster could only be typed one id at a time. Bulk
428/// invite (`POST /boards/{id}/invite`) resolves a class section, a course or an
429/// event's roster in one call, and fifty refused an ordinary club — so the
430/// ceiling moved to the size of the largest group a school actually puts on one
431/// canvas. Raising it can only widen what an existing row is allowed to hold.
432pub const MAX_BOARD_TITLE_LEN: usize = 200;
433pub const MAX_BOARD_PARTICIPANTS: usize = 200;
434
435/// Ceiling on one stroke's serialized payload. A stroke is a short path — a
436/// handful of points, a colour, a width — and it is stored verbatim and fanned
437/// out to every socket in the room, so it is bounded at the wire rather than at
438/// the canvas: 4 KiB takes a long freehand curve and still keeps the worst-case
439/// board (`MAX_BOARD_STROKES` of them) inside a couple hundred megabytes.
440pub const MAX_STROKE_PAYLOAD_LEN: usize = 4_096;
441
442/// The two growth caps, both counted on the board row (see the counter fields
443/// below). They are different kinds of full on purpose:
444///
445/// `MAX_EPOCH_STROKES` caps the *live* canvas — the strokes since the last
446/// clear. Hitting it is recoverable: the creator clears, the epoch counter
447/// resets to zero and drawing resumes. Nothing is deleted by that clear.
448///
449/// `MAX_BOARD_STROKES` caps the board's total *storage*, and never resets,
450/// because a clear keeps its history for playback. Hitting it stamps
451/// `closed_at`: the board turns permanently read-only, but stays fully
452/// readable and replayable — a closed board loses no stroke it ever carried.
453pub const MAX_EPOCH_STROKES: i64 = 5_000;
454pub const MAX_BOARD_STROKES: i64 = 50_000;
455
456/// How many boards one creator may hold. Without it the two caps above cost an
457/// attacker nothing — a full board is answered by opening the next one — so
458/// this is the counter that actually bounds a single account's storage. Kept on
459/// the user row, the same shape as `CHATBOT_THREAD_COUNT_FIELD`.
460pub const MAX_BOARDS_PER_CREATOR: i64 = 200;
461
462/// The only accepted stroke kinds. `stroke`: a drawn path, carrying its
463/// payload. `clear`: the marker row that ends an epoch — it deletes nothing,
464/// it is the epoch index, so replaying across it reconstructs the whole
465/// session.
466pub const BOARD_STROKE_KINDS: [&str; 2] = ["stroke", "clear"];
467
468/// Ceiling on a `board_id` arriving on the board WebSocket, for the same reason
469/// as [`MAX_QUESTION_ID_LEN`]: the field is a record key — a 26-char ULID in
470/// every real payload — and the error frame *echoes* it back, so an unbounded
471/// id lets a client make its own room reflect a 64 MiB frame at it. Checked
472/// before any database work.
473pub const MAX_BOARD_ID_LEN: usize = 64;
474
475/// Inclusive bounds for an exam's per-attempt duration, milliseconds
476/// (1 minute to 24 hours). Required for `async`, optional for `open`.
477pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;
478pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000;
479
480/// Upper bound for an exam's attempt limit; `UNLIMITED_EXAM_ATTEMPTS` (zero)
481/// is the wire-and-storage spelling of "no limit". A limit of 1 — the
482/// default — is the classic single sitting.
483pub const MAX_EXAM_ATTEMPTS: i64 = 100;
484pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0;
485/// Ceiling on a single HTTP request. Backstop for requests that reached the
486/// database in the window between the socket dying and the keepalive noticing:
487/// without it they park until the database returns, which can be hours.
488/// Generous enough not to clip a legitimate slow upload at `max_file_bytes`.
489pub const REQUEST_TIMEOUT_SECS: u64 = 30;
490
491/// The longest caller-supplied `x-request-id` header the server will carry.
492///
493/// The id lands on `http.request.id` of every span, so anything a client puts
494/// there it can export: free text and unbounded cardinality both. A header
495/// longer than this (or one carrying anything outside `[A-Za-z0-9._-]`) is
496/// dropped and a UUID minted in its place — the request still succeeds, it
497/// just stops being correlatable by the caller's own id, which is exactly why
498/// a client needs to know the bound.
499pub const MAX_REQUEST_ID_LEN: usize = 64;
500
501/// Backoff ceiling for the boot connection retry. The database is usually a
502/// sibling container coming up in parallel, so the first attempts fail; the
503/// process retries forever rather than exiting, because exiting turns a
504/// few-second wait into a container restart loop that outruns its budget and
505/// stays down.
506pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5;
507
508/// Cadence of the `state` ticks on the student exam-room WebSocket
509/// (`GET /exams/{id}/attempt/ws`).
510pub const EXAM_WS_TICK_SECS: u64 = 2;
511
512/// Cadence of the keepalive ticks on the whiteboard-room WebSocket. Slower than
513/// the exam room's, because a board room carries no countdown a client renders
514/// against — the tick only keeps an idle socket from being reaped.
515pub const BOARD_WS_TICK_SECS: u64 = 15;
516
517/// How many strokes one replay message carries when a socket joins. The join
518/// replays the current epoch, which is `MAX_EPOCH_STROKES` at worst, so it is
519/// sent in batches rather than as one frame that could reach the WebSocket
520/// frame limit on a busy board.
521pub const BOARD_REPLAY_CHUNK: usize = 200;
522
523/// Depth of one board room's fan-out channel: how far a slow socket may lag the
524/// strokes being drawn before it is dropped and has to rejoin (which replays
525/// the epoch from storage anyway, so nothing is lost by the drop).
526pub const BOARD_HUB_CAPACITY: usize = 256;
527
528/// Ceiling on a `question_id` arriving on the exam-room WebSocket. The field is
529/// a record key — a 26-char ULID in every real payload — not free text, so this
530/// is generous by a factor of two and change. The cap exists because the
531/// per-question error frame *echoes* the id back: axum's default WebSocket
532/// frame limit is 64 MiB, so without it a client can make its own room reflect
533/// that whole payload. Rejected before any database work, and unattributed — an
534/// unusable id names no question, so nothing of it is sent back.
535pub const MAX_QUESTION_ID_LEN: usize = 64;
536
537/// The only accepted question kinds. `choice`: pick one of the listed
538/// choices, auto-scorable. `text`: free text, judged by the grader.
539pub const QUESTION_KINDS: [&str; 2] = ["choice", "text"];
540
541pub const MAX_QUESTION_TEXT_LEN: usize = 2_000;
542
543/// Inclusive bounds for a question's points (its share of the auto-score).
544pub const MIN_QUESTION_POINTS: i64 = 1;
545pub const MAX_QUESTION_POINTS: i64 = 100;
546
547/// Bounds for a choice question's option list and each option's text.
548pub const MIN_QUESTION_CHOICES: usize = 2;
549pub const MAX_QUESTION_CHOICES: usize = 10;
550pub const MAX_CHOICE_TEXT_LEN: usize = 500;
551
552pub const MAX_ANSWER_TEXT_LEN: usize = 10_000;
553
554/// Inclusive bounds for an exam mark.
555pub const MIN_MARK: i64 = 0;
556pub const MAX_MARK: i64 = 100;
557
558/// Inclusive bounds for an exam kind's weight in the course average. The
559/// minimum of 1 keeps every graded exam counted and the average's denominator
560/// non-zero.
561pub const MIN_EXAM_KIND_WEIGHT: i64 = 1;
562pub const MAX_EXAM_KIND_WEIGHT: i64 = 100;
563
564pub const SESSION_DURATION_DAYS: i64 = 7;
565
566/// How far in the past a request-supplied schedule instant (exam window,
567/// lesson, event time) may lie before it is rejected as backdated. The grace
568/// absorbs request latency and modest client-clock skew — a "starts now"
569/// submission must survive its own round trip — while still refusing
570/// genuinely past deadlines.
571pub const SCHEDULE_PAST_GRACE_MS: i64 = 60 * 1000;
572
573/// Upper bound on a list endpoint's `limit` page-size parameter. Omitting
574/// `limit` returns every (remaining) row; when supplied it must be
575/// `1..=MAX_PAGE_LIMIT`. The `#[param(maximum = ...)]` and the "1 and 500"
576/// wording in `web::page` mirror this literal — keep them in step.
577pub const MAX_PAGE_LIMIT: i64 = 500;
578
579/// Wire-protocol identifier for the AI bridge, sent in [`crate::ai::protocol::Hello`]
580/// and used as the QUIC ALPN. Bump both together on a breaking frame change:
581/// ALPN mismatch rejects an old service at the TLS handshake, before it can
582/// send a frame we would misparse.
583pub const AI_PROTOCOL: &str = "hab/2";
584pub const AI_ALPN: &[u8] = b"hab/2";
585
586/// Hard ceiling on one AI-bridge frame. Checked against the length prefix
587/// before the body buffer is allocated. Generous because a payload may carry a
588/// base64 question image, but bounded so a bad length cannot exhaust memory.
589pub const AI_MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
590
591/// Default wait for one AI request before the stream is abandoned
592/// (`AI_REQUEST_TIMEOUT_SECS`). Model inference is slow, so this is far longer
593/// than [`REQUEST_TIMEOUT_SECS`] — AI calls must not sit on an HTTP request
594/// path that the outer timeout would kill first.
595pub const AI_DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 30;
596
597/// Upper bound on a worker's self-declared `max_concurrent`, and the value
598/// used when it declares none. A worker that claims a huge number would let
599/// the registry pile every request onto one service.
600pub const AI_MAX_CONCURRENT_PER_WORKER: usize = 64;
601pub const AI_DEFAULT_CONCURRENT_PER_WORKER: usize = 8;
602
603/// QUIC idle timeout and keepalive for a service connection. The keepalive is
604/// well under the idle timeout so an idle-but-healthy service is never dropped
605/// for being quiet; a service that actually died is deregistered within the
606/// idle window without any application-level heartbeat frame.
607///
608/// Must stay strictly above [`AI_BLOB_WRITE_STALL_SECS`]. A stalled blob write
609/// resets that stream; if the two bounds are equal, a busy runtime lets the
610/// idle timeout win and the whole connection dies as `TimedOut` instead.
611pub const AI_IDLE_TIMEOUT_SECS: u64 = 30;
612pub const AI_KEEPALIVE_SECS: u64 = 10;
613
614/// How long a blob body may make *no* progress before its stream is reset.
615/// A STALL bound, not a transfer cap: the clock is per write, so a slow peer
616/// that keeps reading streams a whole `max_file_bytes` file for as long as it
617/// takes, while a service that opens a blob stream and never reads it stops
618/// pinning a task and an open file descriptor once the QUIC stream window
619/// fills. A wall-clock deadline on the transfer could not tell the two apart.
620///
621/// Strictly under [`AI_IDLE_TIMEOUT_SECS`]: the stream reset has to land
622/// before the connection idle timeout, or a stalled reader kills every other
623/// stream on that connection.
624pub const AI_BLOB_WRITE_STALL_SECS: u64 = 15;
625
626const _: () = assert!(
627 AI_BLOB_WRITE_STALL_SECS + 5 < AI_IDLE_TIMEOUT_SECS,
628 "a stalled blob write must reset the stream before the connection idle timeout"
629);
630
631/// The capability an AI service declares to answer chatbot turns. The bridge
632/// routes a chat request to any worker carrying it; with none registered the
633/// chat endpoints report the service as unavailable.
634pub const AI_CHAT_CAPABILITY: &str = "chat.reply";
635
636/// The capability an AI service declares to index a course note for retrieval.
637/// The backend dispatches on it after a note (or one of its files) changes;
638/// with no worker carrying it the trigger is a silent no-op — indexing is a
639/// bonus on top of the note, never a condition of storing one.
640pub const AI_RAG_INDEX_CAPABILITY: &str = "rag.index";
641
642/// Deadline on one `rag.index` round trip. Longer than a chat turn
643/// ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`]): chunking and embedding a note with
644/// ten attachments is batch work, and nobody is waiting on it — the dispatch
645/// is fire-and-forget, off the HTTP request path.
646pub const AI_RAG_INDEX_TIMEOUT_SECS: u64 = 120;
647
648/// The capability an AI service declares to answer a RAG question over a
649/// school's course-note corpus. Separate from [`AI_CHAT_CAPABILITY`] on
650/// purpose: retrieval-then-answer is its own service with its own corpus, and
651/// a deployment may run one without the other. With no worker carrying it the
652/// RAG endpoints report the service as unavailable.
653pub const AI_RAG_CHAT_CAPABILITY: &str = "rag.chat";
654
655/// Deadline on one `rag.chat` round trip. Much longer than a plain chat turn
656/// ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`]): the service first retrieves the
657/// relevant passages and only then generates an answer, so a question that
658/// touches several course notes is retrieval plus inference, not inference
659/// alone.
660pub const AI_RAG_CHAT_TIMEOUT_SECS: u64 = 90;
661
662/// The capability an AI service declares to summarize one page/span range of
663/// one school's course-note corpus. One-shot and synchronous, unlike
664/// [`AI_RAG_CHAT_CAPABILITY`]: the caller names exactly one `(sinif, ders)`
665/// corpus plus the range inside it and waits for the summary itself — no
666/// thread, no stored row. With no worker carrying it the door reports the
667/// service as unavailable.
668pub const AI_RAG_SUMMARIZE_CAPABILITY: &str = "rag.summarize";
669
670/// Deadline on one `rag.summarize` round trip, and deliberately the short
671/// waiting-door budget of this family: the door **waits** for the summary and
672/// every HTTP request shares one envelope, [`REQUEST_TIMEOUT_SECS`] (30 s).
673/// That middleware drops the handler future wherever it stands and answers its
674/// own `503`, whose prose is written for a request that may have written
675/// something — wrong for a door that stores nothing. So the dispatch deadline
676/// stays **under** the ceiling: the service gets 25 s and this side's own error
677/// path fires first with the honest verdict (the service did not answer).
678/// Raising this value needs the middleware ceiling raised with it.
679pub const AI_RAG_SUMMARIZE_TIMEOUT_SECS: u64 = 25;
680
681/// The capability an AI service declares to generate practice questions over
682/// one page/span range of one school's course-note corpus, with the answers
683/// bounded to that range. Like [`AI_RAG_SUMMARIZE_CAPABILITY`] it is one-shot
684/// and synchronous — nothing is stored — and it is its own capability because a
685/// deployment may serve summaries without serving question generation.
686pub const AI_RAG_QUESTIONS_CAPABILITY: &str = "rag.questions";
687
688/// Deadline on one `rag.questions` round trip. The same waiting-door budget as
689/// [`AI_RAG_SUMMARIZE_TIMEOUT_SECS`] for the same reason: generating N
690/// questions is one model round trip the caller waits on, and it must finish
691/// inside the middleware's [`REQUEST_TIMEOUT_SECS`] envelope rather than be cut
692/// by it mid-flight.
693pub const AI_RAG_QUESTIONS_TIMEOUT_SECS: u64 = 25;
694
695/// The capability an AI service declares to analyse one student (ZEKA,
696/// `hezarfen_zeka`). It is the on-demand half of ZEKA — the service also
697/// recomputes on its own schedule — and it is what a teacher's "calculate" is
698/// routed to. The service reads the student's own data back through the
699/// bridge's api reads and has the backend write its `zeka_*` rows — no AI
700/// service holds a school database credential here (see the storage-surface
701/// constants below).
702pub const AI_INSIGHT_STUDENT_CAPABILITY: &str = "insight.student";
703
704/// Deadline on one `insight.student` round trip. Computing one student reads
705/// several of the school's sources (marks, attendance, submissions, study
706/// stints) and writes the derived rows before answering, so it is
707/// batch-shaped work — the same ceiling [`AI_RAG_INDEX_TIMEOUT_SECS`] gives a
708/// note with ten attachments. Nobody waits on it: the dispatch runs detached
709/// and a reader polls the stored rows.
710pub const AI_INSIGHT_STUDENT_TIMEOUT_SECS: u64 = 120;
711
712/// The capability an AI service declares to analyse one class×course (a
713/// section's own instance of a course). Declared here so the name exists in one
714/// place, but **no door dispatches it yet**: the request would name a course
715/// the service has to enumerate a roster for, and the bridge's read allowlist
716/// carries no member listing — that half of the contract is still open
717/// (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md`, item 3).
718pub const AI_INSIGHT_CLASS_CAPABILITY: &str = "insight.class";
719
720/// The capability an AI service declares to recompute a whole school's
721/// insights. A batch job: the service works through its configured student
722/// list under its own time budget and has the backend write its run ledger. Like ZEKA's own
723/// schedule, this is optional on top of the service's own cadence — it is
724/// what lets the office trigger a sweep from the UI.
725pub const AI_INSIGHT_REFRESH_CAPABILITY: &str = "insight.refresh";
726
727/// Deadline on one `insight.refresh` round trip — the longest AI deadline in
728/// this file. The service answers when its batch is over: the ceiling is
729/// sized well past ZEKA's default 60s per-school budget (a raised
730/// `ZEKA_BUDGET_MS` included) and well inside its hourly default cadence. The
731/// run's progress does not depend on it — ZEKA writes its own `zeka_run`
732/// ledger — this only bounds how long the detached task waits for the
733/// summary.
734pub const AI_INSIGHT_REFRESH_TIMEOUT_SECS: u64 = 300;
735
736/// The capability an AI service declares to render a school-level report
737/// document. The service computes nothing here: the backend already holds
738/// every row the document is built from (the `zeka_*` tables), sends them in
739/// the request, and stores the self-contained HTML the service answers with.
740/// The rendering lives in the service because the reader/report-package
741/// contract does — the backend never composes an insight document, the same
742/// way it never composes an insight row.
743pub const AI_INSIGHT_REPORT_CAPABILITY: &str = "insight.report";
744
745/// Deadline on one `insight.report` round trip, and deliberately the shortest
746/// whole-school deadline in this file: the report door is the one insight
747/// dispatch that **waits** — it stores the returned document before it answers
748/// — and every HTTP request shares one envelope, [`REQUEST_TIMEOUT_SECS`].
749/// That middleware drops the handler future wherever it stands, mid-write
750/// included, and answers its own `503` whose prose ("the write may or may not
751/// have applied") is wrong for a door that knows nothing was stored.
752///
753/// So the dispatch deadline stays **under** the middleware ceiling: the
754/// service gets 25 s, and the door's own error path fires first with the
755/// honest answer (nothing was stored; no temp file was ever opened). The
756/// school-wide row reads happen before the dispatch and share the same
757/// envelope, which is why the margin is not spent here. Raising this value
758/// needs the middleware ceiling raised with it.
759pub const AI_INSIGHT_REPORT_TIMEOUT_SECS: u64 = 25;
760
761// ---- zeka's storage surface (capabilities the *backend* serves) ------------
762//
763// The three constants above are capabilities an AI service *declares*: the
764// backend dispatches `insight.student`/`insight.refresh` to ZEKA and ZEKA
765// answers. The nine below run the other way and are the reason this section
766// exists: no AI service may touch a school database directly, so every read
767// and write ZEKA needs against its own `zeka_*` tables is a named operation
768// the backend performs on its behalf, on the same bridge, on a
769// client-initiated stream (`src/ai/server.rs::serve_client_stream`).
770//
771// They are deliberately *not* declared here as worker capabilities: a worker
772// never announces them, and `AiBridge::dispatch` never routes them. They are
773// the backend's own surface, dispatched by capability name against
774// `crate::ai::insight`'s table — an operation, never a query: no capability
775// takes a database, a schema, a table or a SQL fragment, and the school is
776// the frame's own field, resolved to that school's database before any
777// statement runs.
778
779/// ZEKA stores one student's computed summary (and that student's attention
780/// items, replaced wholesale) for one school.
781pub const AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY: &str = "insight.summary.upsert";
782
783/// ZEKA stores the recommendation cards a run produced. The backend mints the
784/// rows' ids — an id is the writer's, and the writer is now the backend.
785pub const AI_INSIGHT_RECOMMENDATION_UPSERT_CAPABILITY: &str = "insight.recommendation.upsert";
786
787/// ZEKA stores its question-segment labels (and each question's dimension
788/// split, replaced wholesale).
789pub const AI_INSIGHT_SEGMENT_UPSERT_CAPABILITY: &str = "insight.segment.upsert";
790
791/// ZEKA stores a student's per-dimension segment profile.
792pub const AI_INSIGHT_PROFILE_UPSERT_CAPABILITY: &str = "insight.profile.upsert";
793
794/// ZEKA stores one compute run's ledger row (and the run's pending students
795/// and failed modules, both replaced wholesale).
796pub const AI_INSIGHT_RUN_UPSERT_CAPABILITY: &str = "insight.run.upsert";
797
798/// ZEKA reads back the students the freshest run left pending — where the
799/// next run starts.
800pub const AI_INSIGHT_PENDING_LIST_CAPABILITY: &str = "insight.pending.list";
801
802/// ZEKA asks the backend to sweep every `zeka_*` table of rows whose
803/// retention window has closed.
804pub const AI_INSIGHT_RETENTION_SWEEP_CAPABILITY: &str = "insight.retention.sweep";
805
806/// ZEKA asks the backend to delete the derived rows of students who are no
807/// longer enrolled.
808pub const AI_INSIGHT_DEPARTED_PURGE_CAPABILITY: &str = "insight.departed.purge";
809
810/// The one deployment-scoped operation: the active schools a shared AI fleet
811/// schedules over. The frame carries no school because its answer is the
812/// directory itself — the same reason [`crate::ai::protocol::Hello`] carries
813/// none.
814pub const AI_INSIGHT_SCHOOLS_LIST_CAPABILITY: &str = "insight.schools.list";
815
816/// The most rows one of the four bulk writes may carry in a single call. The
817/// service's own batch size (`store.BATCH_SIZE` in `hezarfen_zeka`) — it
818/// chunks its nightly output at exactly this, and a call one row past it is
819/// refused (`too_many_rows`) rather than truncated, because a silently
820/// shortened batch would read as a written student.
821pub const MAX_INSIGHT_BATCH_ROWS: usize = 500;
822
823/// The most students `insight.pending.list` will answer with. The list is
824/// handed over whole — the service resumes its next run from it, so a
825/// clipped list would silently drop students — and a school past this bound
826/// is refused (`too_many_rows`) instead.
827pub const MAX_INSIGHT_PENDING_STUDENTS: usize = 20_000;
828
829/// The most students one `insight.departed.purge` call may name. Same shape
830/// as [`MAX_INSIGHT_PENDING_STUDENTS`]: over it the call is refused, and the
831/// empty list is refused too — an empty roster is a fetch that failed, and
832/// deleting every derived row on that reading would be the worst available
833/// mistake.
834pub const MAX_INSIGHT_PURGE_STUDENTS: usize = 20_000;
835
836/// The most students one `insight.refresh` may carry when its door fills an
837/// empty request body from the school's own roster. The service works through
838/// the list in its own batches (`ZEKA_REFRESH_BATCH`, 25 at a time) and
839/// records the rest as pending for its next run, so the ceiling is the frame's,
840/// not one run's — [`MAX_INSIGHT_PENDING_STUDENTS`]'s size class. Over it the
841/// door **refuses** rather than clipping: a clipped roster would leave students
842/// unanalysed while the run's ledger read as complete.
843pub const MAX_INSIGHT_REFRESH_STUDENTS: usize = 20_000;
844
845/// How long a `rag.chat` turn may sit `pending` before a reader projects it as
846/// failed. The RAG nest mirrors the chatbot's asynchronous send
847/// ([`CHATBOT_PENDING_STALE_SECS`]): the round trip outlives the request that
848/// started it, and a restart mid-inference strands the row rather than letting
849/// anyone answer it, so the same staleness window applies.
850pub const RAG_PENDING_STALE_SECS: i64 = CHATBOT_PENDING_STALE_SECS;
851
852// ---- podcast ---------------------------------------------------------------
853//
854// The podcast service turns one stored source into an audio episode, which is
855// a *job*. The backend owns the job's record: `POST /podcast/jobs` mints the
856// id, writes the `podcast_job` row, and dispatches `podcast.submit`; the
857// service reports every transition back through the client-initiated
858// `podcast.report` capability and uploads the finished mp3 as raw bytes. The
859// read doors (`GET /podcast/jobs/{id}`, `.../result`, `.../audio`) answer from
860// the row, so a service restart or a wiped service volume costs liveness at
861// most. Only submit and cancel are dispatched to a worker, and both answer
862// immediately — the pipeline runs in the service's own pool — so neither needs
863// a per-capability deadline: the bridge's ordinary request timeout covers a
864// job-store write.
865
866/// The capability an AI service declares to accept a podcast job. The backend
867/// dispatches on it from `POST /podcast/jobs`, and the payload carries the
868/// **backend-minted** job id — the id the row, the service's own record, and
869/// the audio blob are all keyed by.
870pub const AI_PODCAST_SUBMIT_CAPABILITY: &str = "podcast.submit";
871
872/// The capability the **backend** serves for one podcast job's state reports.
873/// The service calls it — on a client-initiated stream, the same shape as
874/// ZEKA's storage surface — once per transition, echoing the job's identity
875/// (`job_id`, `source_id`, `user_id`) and the state it moved to. The backend
876/// validates the echo, the transition and the retention window, and writes its
877/// own row; there is no state the service holds that the backend does not.
878pub const AI_PODCAST_REPORT_CAPABILITY: &str = "podcast.report";
879
880/// The capability an AI service declares to cancel one podcast job. Its own
881/// capability rather than a flag on submit: the cancel is a write on the
882/// service's queue, and the capability is what decides whether a deployment
883/// can offer the door at all.
884pub const AI_PODCAST_CANCEL_CAPABILITY: &str = "podcast.cancel";
885
886/// The largest episode the backend will ingest from a service
887/// (`BlobUploadRequest`). A ceiling, not a quota: a two-hour episode at a
888/// generous bitrate is well under it, and anything above is refused before a
889/// byte reaches disk — a service bug must not be able to fill the host.
890pub const PODCAST_AUDIO_MAX_BYTES: usize = 256 * 1024 * 1024;
891
892/// How long a finished podcast job's record and audio stay readable. Past it
893/// the doors answer `410` — the record is history, and the blob is no longer
894/// served. Sized like the RAG outputs' retention window: long enough for a
895/// listener to come back for yesterday's episode, short enough that a shared
896/// host does not accumulate every episode ever made.
897pub const PODCAST_JOB_RETENTION_SECS: i64 = 7 * 24 * 60 * 60;
898
899/// The floor of the read-side staleness window: a `queued`/`running` job
900/// nobody has updated for at least this long is presented as
901/// `failed`/`interrupted`. The window is
902/// `max(PODCAST_JOB_STALE_FLOOR_SECS, eta_secs × PODCAST_JOB_STALE_ETA_FACTOR)`
903/// so a queue wait the service itself estimated as long is never declared
904/// dead mid-flight.
905pub const PODCAST_JOB_STALE_FLOOR_SECS: i64 = 600;
906
907/// How many times a job's own ETA the service may exceed before the read side
908/// stops believing it is still running. Three: past three times its own
909/// estimate, the honest reading is that the process that owned it is gone.
910pub const PODCAST_JOB_STALE_ETA_FACTOR: i64 = 3;
911
912/// The `error_code` a job carries when *this backend* concluded it died: a
913/// dispatch that never reached a worker, a cancel of a job the service no
914/// longer has, or a read-side projection of a stale row. Deliberately the
915/// service's own word for the same fact (its restart sweep writes it too), so
916/// a client sees one vocabulary however the job died.
917pub const PODCAST_INTERRUPTED_CODE: &str = "interrupted";
918
919/// The most `(class, course)` scope pairs one `rag.chat` request may carry. The
920/// corpus is routed by the **pair** — a grade and a subject list sent
921/// separately would cross-product into combinations the asker never named — so
922/// this is the number of pairs handed to the service in one call, bounding
923/// both the frame size and the service's routing work. A request carrying more
924/// is refused rather than silently narrowed: dropping pairs would answer a
925/// question the asker did not ask, scoped to corpora they did not name.
926pub const MAX_RAG_SCOPE_PAIRS: usize = 200;
927
928/// The most practice questions one `rag.questions` request may ask for. The
929/// caller waits on the generation, so this is the ceiling on one model round
930/// trip — not a corpus sweep — and the door refuses a larger set before it
931/// dispatches anything. Published at `GET /limits` (`rag.max_questions`) so a
932/// client bounds its own input instead of hard-coding the number.
933pub const MAX_RAG_QUESTIONS: u32 = 20;
934
935/// Default per-minute message limit for the RAG nest, when the school sets
936/// none — a lower ceiling than the chatbot's, since every message here spends
937/// a retrieval over the whole course-note corpus before it generates anything.
938pub const DEFAULT_RAG_RATE_LIMIT: u32 = 600;
939
940/// The most citations one `rag.chat` answer may carry into its stored reply.
941/// The service is a trust boundary — everything it sends is written verbatim
942/// into a school's database — so an answer citing more is refused whole rather
943/// than trimmed: dropping entries would leave `[N]` markers in the answer text
944/// pointing at nothing, and a reader cannot tell a clipped citation list from
945/// a complete one.
946pub const MAX_RAG_CITATIONS: usize = 50;
947
948/// The most pages one citation may name, the second axis of the same bound.
949/// One reply's citations are therefore at most
950/// `MAX_RAG_CITATIONS × MAX_RAG_CITATION_PAGES` page numbers, so however a
951/// service distributes them it cannot turn a single stored answer into an
952/// unbounded payload — the same storage-protection shape as
953/// [`MAX_NOTE_FILES`], but for a body this backend does not compose.
954pub const MAX_RAG_CITATION_PAGES: usize = 50;
955
956/// Hard ceiling on one chat message's characters — the newtype bound, above
957/// which no school setting can reach. Sized for a pasted question with its
958/// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.
959pub const MAX_CHATBOT_MESSAGE_LEN: usize = 8_000;
960
961/// The school-adjustable per-message character cap (`max_chatbot_message_len` in
962/// settings): its default and the inclusive range a manager may set. The
963/// ceiling is [`MAX_CHATBOT_MESSAGE_LEN`] — a longer prompt costs the AI service
964/// context it needs for the history.
965pub const DEFAULT_MAX_CHATBOT_MESSAGE_LEN: i64 = 4_000;
966pub const MIN_MAX_CHATBOT_MESSAGE_LEN: i64 = 100;
967pub const MAX_MAX_CHATBOT_MESSAGE_LEN: i64 = MAX_CHATBOT_MESSAGE_LEN as i64;
968
969/// Bound on a chat thread's display name. A thread is named by hand or not at
970/// all — nothing auto-titles one — so this only has to fit a line a user typed.
971pub const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200;
972
973/// How many prior user/assistant turns of a thread are replayed to the
974/// AI service as context (`chatbot_history_turns` in settings): its default and
975/// the inclusive range a manager may set. Every turn is re-sent on every
976/// request, so the ceiling bounds both the frame size and the inference cost.
977pub const DEFAULT_CHATBOT_HISTORY_TURNS: i64 = 10;
978pub const MIN_CHATBOT_HISTORY_TURNS: i64 = 1;
979pub const MAX_CHATBOT_HISTORY_TURNS: i64 = 50;
980
981/// How many threads one user may keep (`max_chatbot_threads` in
982/// settings): its default and the inclusive range a manager may set. Reached,
983/// the user deletes an old thread before starting a new one — the cap is
984/// storage protection, not a usage quota.
985pub const DEFAULT_MAX_CHATBOT_THREADS: i64 = 50;
986pub const MIN_MAX_CHATBOT_THREADS: i64 = 1;
987pub const MAX_MAX_CHATBOT_THREADS: i64 = 500;
988
989/// How often the chat stream re-reads a `pending` assistant message while it
990/// waits for the answer. The reply lands in the database from whichever task
991/// owns the bridge stream, so the reader polls rather than sharing state.
992pub const CHAT_STREAM_POLL_MS: u64 = 200;
993
994/// How long an assistant message may sit `pending` before a reader gives up on
995/// it and reports it failed. Comfortably past
996/// [`AI_DEFAULT_REQUEST_TIMEOUT_SECS`] (which `AI_REQUEST_TIMEOUT_SECS` may
997/// raise), because the answering task normally stamps the failure itself —
998/// this only catches the row whose task died with the process.
999pub const CHATBOT_PENDING_STALE_SECS: i64 = 300;
1000
1001/// The largest per-request AI deadline a deployment may configure
1002/// (`AI_REQUEST_TIMEOUT_SECS`). Anything above it is clamped down to it at
1003/// startup, loudly — see [`crate::config`].
1004///
1005/// A sanity ceiling, well under [`CHATBOT_PENDING_STALE_SECS`]: a reply that
1006/// arrives after the staleness window is discarded by the read-time
1007/// projection, so a deadline anywhere near it could never produce an answer a
1008/// user sees — it would only hold a task and a worker slot open for nothing.
1009/// A school that genuinely needs longer raises this and the staleness window
1010/// together.
1011pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = 60;
1012
1013/// How long a dialling AI service has to complete its `Hello`/`Welcome`
1014/// exchange before the connection is dropped. Short: the handshake is one
1015/// frame each way, and an unauthenticated connection must not be able to
1016/// occupy the listener indefinitely.
1017pub const AI_HANDSHAKE_TIMEOUT_SECS: u64 = 10;
1018
1019/// The only REST paths an AI service may read over the bridge — deny-by-default,
1020/// matched segment-wise by [`crate::ai::api`] with `{x}` standing for exactly
1021/// one segment. This list *is* the services' access scope, so it is a service
1022/// contract documented in `README.md`, not a tunable published at `/limits`
1023/// (string arrays are exempt from that completeness gate).
1024///
1025/// JSON-only, and only what a study-companion needs: who the user is, their
1026/// notes, their course's notes, their homework, and their own progress reports.
1027/// Byte-serving routes
1028/// (note files, submission files, avatars, question images) are left out — the
1029/// frames carry JSON, and a blob has no business crossing this seam yet.
1030pub const AI_API_ALLOWLIST: &[&str] = &[
1031 "/auth/me",
1032 "/users/me/profile",
1033 "/users/{id}/profile",
1034 "/notes",
1035 "/notes/{id}",
1036 "/course-notes",
1037 "/course-notes/{id}",
1038 "/course-notes/{id}/files",
1039 "/homework",
1040 "/homework/{id}",
1041 "/homework/{id}/result",
1042 "/homework/{id}/submission",
1043 "/homework/report/{user}",
1044 "/marks/me",
1045 "/marks/{user}",
1046 "/attendance/me",
1047 "/attendance/{user}",
1048 "/pomodoro/me",
1049 "/pomodoro/{user}",
1050];
1051
1052// --- rate limiting -----------------------------------------------------
1053
1054/// Default requests-per-minute-per-IP for `/auth/login` + `/auth/register`.
1055pub const DEFAULT_AUTH_RATE_LIMIT: u32 = 1_000;
1056/// Default requests-per-minute-per-IP across the whole API.
1057pub const DEFAULT_API_RATE_LIMIT: u32 = 30_000;
1058/// Default chatbot messages per minute *per user*. Sits far above a human
1059/// typing while still blunting a scripted fan-out at the AI service behind the
1060/// bridge — which is the cost this tier rations, not this process.
1061pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 2_000;
1062
1063/// Once the bucket map holds this many distinct clients, a new key sweeps out
1064/// the expired entries and, if that frees nothing, evicts the least-spent live
1065/// buckets — **never an exhausted one** — down to three quarters of this.
1066/// Evicting a bucket that had reached its limit would hand back the very
1067/// refusal it was enforcing, so a flood cannot make the limiter fail open; the
1068/// concession is that while the map is saturated with exhausted buckets a
1069/// never-before-seen client gets no bucket of its own and is metered against
1070/// the one shared [`RATE_LIMIT_OVERFLOW_MAX`] budget instead — so newcomers
1071/// during a flood can be refused, while every client already in the map keeps
1072/// its own counter untouched. Keeps memory bounded without a reaper task.
1073pub const PURGE_AT: usize = 10_000;
1074
1075/// Requests per window every client that finds the bucket map saturated shares
1076/// between them — one aggregate counter, no key, no map entry.
1077///
1078/// It is the bound on the fail-open path: without it a new key arriving at a
1079/// full map is admitted unmetered, so an attacker who first fills the map with
1080/// exhausted buckets buys unlimited throughput from fresh keys. With it that
1081/// bypass is capped at this many requests a minute, fleet-wide, and a genuine
1082/// newcomer gets in on whatever of it is left — an attacker who burns the lot
1083/// does `429` the newcomers, which refusing them outright would have done for
1084/// free. Clients already in the map are unaffected throughout. Sized for the
1085/// genuine side: this is a *request* budget, not a client one (a keyless client
1086/// spends it on every request, not just its first), so roughly 1000 requests a
1087/// second for all newcomers together, and only ever in force while 10k buckets
1088/// sit exhausted at once, which is an attack and not a school day.
1089pub const RATE_LIMIT_OVERFLOW_MAX: u32 = 60_000;
1090
1091/// The shared counter the limiter folds its local admits into, so a window's
1092/// budget survives a restart (see [`crate::rate_limit`]).
1093pub const RATE_LIMIT_TABLE: &str = "rate_limit";
1094
1095/// How often a limiter pushes its admits and reads the window's total back.
1096/// The knob that decides the worst case: within one interval a just-started
1097/// process can admit up to its full local budget before the total tightens it, so
1098/// short enough to matter and long enough to stay one query per tier per tick.
1099pub const RATE_SYNC_INTERVAL_SECS: u64 = 2;
1100
1101/// How long one sync round may wait on the database. The SDK *parks* a query
1102/// while the socket is down instead of failing it, so the liveness flag alone
1103/// cannot stop a round wedging the task forever — this is the backstop that
1104/// keeps the limiter purely local through an outage instead of stalled.
1105pub const RATE_SYNC_TIMEOUT_SECS: u64 = 5;
1106
1107/// How many client buckets one round syncs. A round is a single query holding
1108/// one statement per bucket, so this bounds both its size and the write volume
1109/// a burst of distinct clients can put on the database.
1110pub const RATE_SYNC_MAX_KEYS: usize = 512;
1111
1112// --- time spans --------------------------------------------------------
1113
1114pub const MILLIS_PER_DAY: i64 = 24 * 60 * 60 * 1000;
1115
1116/// One week, the only recurrence step this backend expands.
1117pub const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY;
1118
1119/// The record key `User::ai_principal` carries. A literal, not a ULID, so it
1120/// can never collide with a minted user row — and the row is never written.
1121pub const AI_PRINCIPAL_KEY: &str = "ai_service";
1122
1123/// A `palette_color` preference is `#` plus exactly six hex digits — the length
1124/// of the whole string, `#` included.
1125pub const PALETTE_COLOR_LEN: usize = 7;
1126
1127/// The shape a `palette_color` must match, as a regular expression. This
1128/// describes what the server **accepts**, so it is case-insensitive — the value
1129/// is normalized to lowercase on store, and a client that sent `#FEFAE0` reads
1130/// `#fefae0` back. Publishing the lowercase-only form would have a client
1131/// reject its own valid input.
1132///
1133/// Deliberately an open value set: any valid hex accent color, not a closed
1134/// list of the frontend's palette, so a new palette entry needs no backend
1135/// change.
1136pub const PALETTE_COLOR_PATTERN: &str = "^#[0-9a-fA-F]{6}$";
1137
1138/// The two lifecycle states of a pool question. `pending`: awaiting teacher+
1139/// approval, visible only to the asker and to teacher+. `approved`: in the
1140/// pool, school-wide. Rejection is not a state — a teacher+ simply deletes the
1141/// question.
1142pub const STATUS_PENDING: &str = "pending";
1143pub const STATUS_APPROVED: &str = "approved";
1144pub const POOL_QUESTION_STATUSES: [&str; 2] = [STATUS_PENDING, STATUS_APPROVED];
1145
1146/// The two reaches of a bank question template: the author's own drawer, or
1147/// published to the whole school.
1148pub const BANK_VISIBILITY_PRIVATE: &str = "private";
1149pub const BANK_VISIBILITY_SCHOOL: &str = "school";
1150
1151// --- fixed keys and literals -------------------------------------------
1152
1153/// A fixed password whose hash is the login decoy (see
1154/// [`crate::domain::user::PasswordHash::verify_decoy`]). Not a secret — it
1155/// never matches a real account.
1156pub const DECOY_PASSWORD: &str = "decoy-password-not-a-secret";
1157
1158/// The `error_code` a stale `pending` chatbot row presents as. Distinct from
1159/// the boot sweep's `interrupted`: this one was never repaired, only projected.
1160pub const STALE_ERROR_CODE: &str = "timed_out";
1161
1162/// Ceiling on a stored `error_code`. Codes are short slugs, but one arrives
1163/// from an out-of-process AI service — a trust boundary — so it is trimmed
1164/// rather than trusted.
1165pub const MAX_ERROR_CODE_LEN: usize = 64;
1166
1167/// Replacements applied *after* lowercasing, in order. One table, two
1168/// consumers ([`crate::domain::text_fold::search_fold`] and
1169/// [`crate::domain::text_fold::search_fold_sql`]): the needle and the column
1170/// are folded by the same rules by construction, which is the whole point.
1171pub const TEXT_FOLD_REPLACEMENTS: &[(&str, &str)] = &[
1172 ("\u{307}", ""), // combining dot above, left behind by İ → i̇
1173 ("ı", "i"),
1174 ("ş", "s"),
1175 ("ğ", "g"),
1176 ("ç", "c"),
1177 ("ö", "o"),
1178 ("ü", "u"),
1179 ("â", "a"),
1180 ("î", "i"),
1181 ("û", "u"),
1182];
1183
1184// --- response shaping --------------------------------------------------
1185
1186/// Bodies larger than this are streamed through without buffering — JSON pages
1187/// sit far below it, so the cap only bounds worst-case memory. A response whose
1188/// `Content-Length` exceeds it (or is absent, i.e. a stream) skips the ETag
1189/// middleware.
1190pub const MAX_ETAG_BODY_BYTES: u64 = 1 << 20; // 1 MiB
1191
1192/// How many `delta` events a completed chatbot answer is cut into, and the
1193/// shortest chunk worth emitting.
1194pub const REPLY_CHUNKS: usize = 8;
1195pub const MIN_CHUNK_CHARS: usize = 24;
1196
1197// --- database tables ---------------------------------------------------
1198
1199pub const NOTE_TABLE: &str = "note";
1200pub const MESSAGE_TABLE: &str = "message";
1201pub const NOTE_FILE_TABLE: &str = "note_file";
1202pub const COURSE_NOTE_TABLE: &str = "course_note";
1203pub const COURSE_NOTE_FILE_TABLE: &str = "course_note_file";
1204pub const RAG_OUTPUT_TABLE: &str = "rag_output";
1205pub const EVENT_TABLE: &str = "event";
1206pub const ATTENDANCE_TABLE: &str = "attendance";
1207pub const REGISTRATION_TABLE: &str = "registration";
1208pub const EXAM_TABLE: &str = "exam";
1209pub const EXAM_RESULT_TABLE: &str = "exam_result";
1210pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt";
1211pub const EXAM_QUESTION_TABLE: &str = "exam_question";
1212pub const QUESTION_IMAGE_TABLE: &str = "question_image";
1213pub const EXAM_ANSWER_TABLE: &str = "exam_answer";
1214pub const ANSWER_IMAGE_TABLE: &str = "answer_image";
1215pub const BANK_QUESTION_TABLE: &str = "bank_question";
1216pub const BANK_QUESTION_IMAGE_TABLE: &str = "bank_question_image";
1217pub const COURSE_TABLE: &str = "course";
1218pub const ENROLLMENT_TABLE: &str = "enrollment";
1219pub const CLASS_GROUP_TABLE: &str = "class_group";
1220pub const CLASS_MEMBER_TABLE: &str = "class_member";
1221pub const CLASS_COURSE_TABLE: &str = "class_course";
1222pub const CLASS_BLUEPRINT_TABLE: &str = "class_blueprint";
1223pub const PARENT_LINK_TABLE: &str = "parent_link";
1224pub const COURSE_SESSION_TABLE: &str = "course_session";
1225pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance";
1226pub const WORK_ENTRY_TABLE: &str = "work_entry";
1227pub const POMODORO_SESSION_TABLE: &str = "pomodoro_session";
1228pub const SETTINGS_TABLE: &str = "settings";
1229pub const TERM_TABLE: &str = "term";
1230pub const SUBJECT_TABLE: &str = "subject";
1231pub const POOL_QUESTION_TABLE: &str = "pool_question";
1232pub const POOL_QUESTION_IMAGE_TABLE: &str = "pool_question_image";
1233pub const SOLUTION_TABLE: &str = "solution";
1234pub const SOLUTION_IMAGE_TABLE: &str = "solution_image";
1235pub const HOMEWORK_TABLE: &str = "homework";
1236pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission";
1237pub const HOMEWORK_FILE_TABLE: &str = "homework_file";
1238pub const HOMEWORK_RESULT_TABLE: &str = "homework_result";
1239pub const CHATBOT_THREAD_TABLE: &str = "chatbot_thread";
1240pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message";
1241pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";
1242pub const APPOINTMENT_TABLE: &str = "appointment";
1243pub const MENU_TABLE: &str = "menu";
1244pub const MENU_DISH_TABLE: &str = "menu_dish";
1245pub const DIETARY_PROFILE_TABLE: &str = "dietary_profile";
1246pub const MEAL_BOOKING_TABLE: &str = "meal_booking";
1247pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";
1248pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
1249pub const FEE_PLAN_TABLE: &str = "fee_plan";
1250pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";
1251pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";
1252pub const BOARD_TABLE: &str = "board";
1253/// One row per badge a user has earned, keyed by the pair. A table of its own
1254/// rather than an array column on the user row: an `array<…>` there breaks
1255/// every `PATCH` of that row, and awards are append-only facts with their own
1256/// timestamp (see [`crate::domain::badge`]).
1257pub const BADGE_AWARD_TABLE: &str = "badge_award";
1258/// One row per *name* the school's settings offer, keyed by the name itself:
1259/// how many rows still reference it, and whether it has been retired out of the
1260/// list (see the reference counters in [`crate::db::cap`]).
1261pub const KIND_REF_TABLE: &str = "kind_ref";
1262pub const SLOT_REF_TABLE: &str = "slot_ref";
1263
1264// --- stored cap counters -------------------------------------------------
1265
1266/// The counter columns behind the count caps (see [`crate::db::cap`]).
1267/// Each one lives on the *parent* row, because a single-record conditional
1268/// `UPDATE` is the only guard a concurrent writer cannot outrun (a lock is
1269/// released around the round trip). Spelled here rather than at the call site
1270/// so the field a claim
1271/// increments and the field a delete decrements cannot drift apart; the
1272/// definitions themselves are in `MIGRATION`, and a typo there is caught by
1273/// SCHEMAFULL refusing the write.
1274pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count";
1275pub const REGISTRATION_COUNT_FIELD: &str = "registration_count";
1276/// The two refcounts on a class row: how many students it holds and how many
1277/// courses it is attached to. A class may only be dropped at zero on both.
1278pub const CLASS_MEMBER_COUNT_FIELD: &str = "class_member_count";
1279pub const CLASS_COURSE_COUNT_FIELD: &str = "class_course_count";
1280/// Classes belonging to an academic year, the second half of the year's delete
1281/// guard. Its own column: a class's share is never confused with another
1282/// roster's count.
1283pub const ACADEMIC_YEAR_CLASS_COUNT_FIELD: &str = "class_count";
1284/// A refcount too, and the whole of the fee-plan edit *and* delete guard: how
1285/// many students are on this plan. A plan may only be edited or deleted at
1286/// zero, and the count is claimed in the same transaction as the assignment
1287/// row, so a manager's edit and a concurrent assign contend on the plan row
1288/// rather than on a `SELECT` the edit had already outrun. Nothing ever
1289/// releases it — an assignment is never unassigned, because the charges it
1290/// raised are history.
1291pub const FEE_PLAN_ASSIGNMENT_COUNT_FIELD: &str = "assignment_count";
1292/// The condition itself, spelled once: a plan is editable and deletable
1293/// exactly while nobody is on it. The `??` is parenthesized on purpose —
1294/// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every*
1295/// row and would license editing a plan a family is already being billed for.
1296pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0";
1297pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
1298pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
1299/// The column a *grant* claim moves and puts back, so its transaction writes
1300/// the holder's own `user` record — the one key
1301/// [`crate::service::user::set_role`] writes (see
1302/// [`crate::db::cap::role_claim`]). Any `option<int>` on the row would do:
1303/// the claim nets zero and never reads it, so this is an alias rather than a
1304/// column of its own — a new one would mean a migration on a SCHEMAFULL table
1305/// for a value nothing ever observes.
1306pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD;
1307/// The lifetime totals behind the badges, all on the user row. Not caps: each
1308/// one counts something the person *did*. A counter comes down in exactly one
1309/// shape, and the two cases that qualify share a reason: the account credited
1310/// is the account that can delete what earned it, so a strictly monotonic
1311/// counter is a farm. A student withdrawing their own submission gives the two
1312/// homework counters back (else one homework becomes fifty by
1313/// submit/delete/submit), and a teacher un-grading gives back
1314/// `MARKS_GIVEN` — with `HIGH_MARK` on the exam side, credited to the student
1315/// by the same act (else one exam becomes fifty by grade/ungrade/regrade).
1316/// The exam and pomodoro totals never decrease at all, and each earns that by
1317/// counting something a repeat cannot re-earn rather than by anyone's restraint:
1318/// `EXAM_SAT_TOTAL` counts *exams sat*, moving only on a student's first sitting
1319/// of an exam (`seq == 1`), because retakes are a loop the student drives alone —
1320/// an open exam with unlimited attempts is start/finish/start, no teacher in it —
1321/// and a stint is a span of time that has to be lived through to be finished.
1322/// Nothing else decrements: the cascades (an exam, a homework or
1323/// a course delete, which do take the attempt and result rows with them) leave
1324/// them alone, since history a teacher erased is still history the student
1325/// lived. A badge already earned is never taken back either, whatever a counter
1326/// does afterwards — [`crate::domain::badge`] only ever adds award rows. Floored
1327/// at zero, and absent means zero: an account older than the columns reads
1328/// exactly like a fresh one.
1329//
1330// corner-cut: that cascade ruling is also the farm's long way round — delete the
1331// *exam* instead of the mark and the credit stands, so the loop still climbs,
1332// at a couple of requests a point rather than two. Closing it means
1333// `Exam::delete`, `Homework::delete` and `Course::delete` refunding per swept
1334// row the way `ExamResult::remove` now does, which is a policy call (a course
1335// delete would then have to walk every mark it drops) rather than an oversight.
1336pub const HOMEWORK_SUBMITTED_TOTAL_FIELD: &str = "homework_submitted_total";
1337pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total";
1338pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total";
1339pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total";
1340pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total";
1341/// The bookkeeping behind the counted-stint rule below: which UTC day the
1342/// student last had a stint counted on, and how many counted that day. Internal
1343/// state like the two streak columns — no badge reads either, `/limits` names
1344/// neither, no profile key serves them. The day rolls the tally back to zero.
1345pub const POMODORO_COUNTED_DAY_FIELD: &str = "pomodoro_counted_day";
1346pub const POMODORO_COUNTED_TODAY_FIELD: &str = "pomodoro_counted_today";
1347/// What makes a finished stint *count* towards `pomodoro_finished_total` and
1348/// `pomodoro_focus_ms_total` (and towards the study streak): it must have run at
1349/// least this long, and it must be within the day's quota.
1350///
1351/// Without them the pair is the farm [`crate::db::pool_question::approve`]
1352/// reasons about from the other end: `finish` is self-service, a stint costs two
1353/// requests and no second person, so a counter moved once per round-trip is
1354/// farmable — 200 pairs in a minute and a half bought `pomodoro_finished_200`,
1355/// permanently, since a badge is never revoked.
1356///
1357/// Five minutes is well under a conventional 25-minute pomodoro on purpose: a
1358/// student who breaks off early still focused, and the counter should not
1359/// punish that. It is four orders of magnitude above a scripted round-trip,
1360/// which is the whole distance that matters — the cheat now costs the wall
1361/// clock it claims. Sixteen a day is likewise above any honest school day
1362/// (sixteen full pomodoros is over six hours of pure focus) while capping the
1363/// minimum-length farm at eighty minutes of real waiting per day, so
1364/// `pomodoro_finished_200` takes at least thirteen calendar days to buy instead
1365/// of ninety seconds. Both are read `>=`/`<`, i.e. a stint of exactly the
1366/// minimum counts and the sixteenth of the day counts.
1367pub const MIN_COUNTED_POMODORO_MS: i64 = 300_000;
1368pub const MAX_COUNTED_POMODORO_PER_DAY: i64 = 16;
1369/// A stint's optional student-given label — the student's own name for what
1370/// the stint is for ("math", "mock exam"), free text rather than a subject
1371/// link, bounded like the other short labels.
1372pub const MAX_POMODORO_LABEL_LEN: usize = 100;
1373/// The staff-side and second student-side totals, same shape and same rules:
1374/// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and
1375/// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the
1376/// approvals a teacher hands out and `POOL_PUBLISHED` the questions whose
1377/// author got approved — credited at approval, which is why the name says
1378/// published rather than asked.
1379pub const MARKS_GIVEN_TOTAL_FIELD: &str = "marks_given_total";
1380pub const LESSONS_HELD_TOTAL_FIELD: &str = "lessons_held_total";
1381pub const POOL_APPROVED_TOTAL_FIELD: &str = "pool_approved_total";
1382pub const POOL_PUBLISHED_TOTAL_FIELD: &str = "pool_published_total";
1383pub const LESSONS_ATTENDED_TOTAL_FIELD: &str = "lessons_attended_total";
1384pub const HIGH_MARK_TOTAL_FIELD: &str = "high_mark_total";
1385/// The longest run of consecutive days the student has studied, and the two
1386/// bookkeeping columns the write site needs to compute it: the run in progress
1387/// and the last day counted (both plain day numbers, midnight UTC — the same
1388/// boundary every other day calculation here uses).
1389///
1390/// Only the longest is a badge counter: it never comes down, which is what
1391/// keeps it on the ordinary `>=` rule with no second catalog shape. The other
1392/// two are internal state — no badge reads them, `/limits` never names them,
1393/// and no profile key serves them.
1394pub const STUDY_STREAK_LONGEST_FIELD: &str = "study_streak_longest";
1395pub const STUDY_STREAK_CURRENT_FIELD: &str = "study_streak_current";
1396pub const STUDY_STREAK_LAST_DAY_FIELD: &str = "study_streak_last_day";
1397/// When a lesson was first counted towards its teacher's `lessons_held_total`,
1398/// stamped on the `course_session` row by the first roll call taken for it.
1399/// Bookkeeping like the two streak columns above: no badge reads it, `/limits`
1400/// never names it, no profile key serves it. Its only job is the once-per-
1401/// session guard — a lesson is credited when it is *taken*, and the thirtieth
1402/// student marked must credit nothing further.
1403pub const LESSON_COUNTED_AT_FIELD: &str = "held_counted_at";
1404/// What counts as a high mark, out of `MAX_MARK`. Hardcoded next to the badge
1405/// thresholds rather than read from the school's grade bands: those are
1406/// renameable display labels, and a badge id must never depend on a value a
1407/// school can change at runtime — `high_mark_10` has to mean the same thing in
1408/// every deployment, forever.
1409pub const HIGH_MARK_MIN: i64 = 90;
1410
1411/// Cap 1, not N: an appointment slot holds at most one live booking, so this
1412/// counter is really an "is it taken" flag kept in the shape every other cap
1413/// uses (`claim`/`release`), which is what makes rejecting or cancelling a
1414/// booking give the slot back.
1415pub const SLOT_OCCUPIED_FIELD: &str = "occupied";
1416/// Not caps either, and uncapped by design: how many exam questions and how
1417/// many homework still point at a subject. A subject may be deleted exactly
1418/// while both read zero, so the delete's own `WHERE` decides it — the
1419/// cross-table "does anything reference this?" count it replaces was already
1420/// stale when the delete landed.
1421pub const SUBJECT_QUESTION_COUNT_FIELD: &str = "exam_question_count";
1422pub const SUBJECT_HOMEWORK_COUNT_FIELD: &str = "homework_count";
1423/// How many marks an exam carries. Uncapped too, and the only counter its
1424/// entity carries as a field: the exam's save is a whole-row `CONTENT` write,
1425/// which would wipe a column the struct did not know about. That save pins it,
1426/// which is what makes "this exam has no marks" — the gate a kind change is
1427/// refused on — decided at write time rather than at read time.
1428pub const EXAM_RESULT_COUNT_FIELD: &str = "result_count";
1429/// The two columns of a reference-counter row (`kind_ref`, `slot_ref`): how
1430/// many rows still point at the name, and whether it has left the school's
1431/// list. Both `option<…>`, absent meaning zero references and in service.
1432pub const REF_COUNT_FIELD: &str = "count";
1433pub const REF_RETIRED_FIELD: &str = "retired";
1434/// Seats held on one menu — the meal capacity cap.
1435pub const MENU_SEAT_COUNT_FIELD: &str = "seats_booked";
1436/// Not a cap: the menu's revision, bumped by every write that can change what
1437/// a seat costs (a dish added, re-priced or removed, the capacity moved). A
1438/// booking claims its seat only at the revision it read the price at, so the
1439/// price frozen onto the row is one the menu really carried at that instant.
1440pub const MENU_VERSION_FIELD: &str = "version";
1441
1442/// Not a cap either: the grade that froze a homework submission, absent while
1443/// the submission is still open. Every student-side write to a submission (its
1444/// text, its files) carries `graded_by_result = NONE` as a condition, so the
1445/// "not graded yet" decision and the write it licenses are one conditional
1446/// single-record write rather than a cross-table read a concurrent grade can
1447/// outrun. Set by grading, cleared by un-grading, never by the student.
1448pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";
1449/// The condition itself, spelled once: a submission is writable exactly while
1450/// its grade stamp is absent.
1451pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE";
1452/// A signup list has **frozen**: the event takes registrations at all *and* it
1453/// started, or — for an ends_at-only event (a pure signup deadline) — that end
1454/// passed. A timeless event never freezes. Matched against `$now` in millis, on
1455/// an `event` row.
1456///
1457/// This is `Event::registration_capacity`'s `Conflict` arm re-spelled in
1458/// SurrealQL, because the role cascade (`service::user::set_role`) frees a demoted
1459/// parent's seats *inside* its transaction and cannot call Rust from there. The
1460/// audience conjunct is what keeps it that arm and only that arm: an event that
1461/// takes no registrations is refused earlier, by the `Validation` arm, so a
1462/// stray row on one is deleted rather than frozen — which is what the pre-fold
1463/// sweep did, and dropping the conjunct would silently change it. Two spellings
1464/// of one rule is a drift risk, so it is spelled once here and
1465/// `event::tests::the_sql_freeze_guard_matches_the_rust_one` fails the suite the
1466/// day the two disagree.
1467pub const REGISTRATION_FROZEN_GUARD: &str = "audience.kind = 'registration' \
1468 AND (starts_at ?? ends_at) != NONE AND (starts_at ?? ends_at) <= $now";
1469
1470/// How hard a counter write tries before giving up, and the first backoff step
1471/// it sleeps between attempts (doubling, plus jitter). Contention on one record
1472/// is the guard working as designed, and SurrealDB answers it by aborting the
1473/// loser's transaction — so these two numbers are what turn "retry the
1474/// transaction" into a queue. Sized for one HTTP burst of racers on a single
1475/// parent: seven doublings from 2ms is a quarter of a second of patience.
1476pub const CAP_WRITE_TRIES: usize = 8;
1477pub const CAP_WRITE_BACKOFF_MS: u64 = 2;