forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

constant.rs1224 lines, 63.6 KiBHistoryRawDownload
1//! Validation limits, in one place.
2
3use crate::domain::badge::BadgeStat;
4use crate::domain::message::Folder;
5use crate::domain::preferences::{Language, Theme};
6use crate::domain::role::Role;
7
8/// A school slug's length bounds — the name in front of the dot in the session
9/// cookie, which is also the school's database name and its blob directory
10/// (see [`crate::tenant::Slug`]).
11pub const MIN_SLUG_LEN: usize = 2;
12pub const MAX_SLUG_LEN: usize = 32;
13
14/// A school's display name — free text, unlike its slug.
15pub const MAX_SCHOOL_NAME_LEN: usize = 120;
16
17pub const MIN_USERNAME_LEN: usize = 3;
18pub const MAX_USERNAME_LEN: usize = 32;
19
20/// Separators allowed inside a username (never at the edges, never doubled).
21pub const USERNAME_SEPARATORS: [char; 3] = ['.', '_', '-'];
22
23/// Names nobody may claim through `/auth/register`: they read as staff and
24/// invite impersonation. Enforced at the registration endpoint, not in
25/// `Username` itself, so the `ADMIN_USERNAME` bootstrap can still seed
26/// accounts like `admin`.
27pub const RESERVED_USERNAMES: [&str; 7] = [
28 "admin",
29 "administrator",
30 "root",
31 "support",
32 "system",
33 "moderator",
34 "staff",
35];
36
37pub const MIN_PASSWORD_LEN: usize = 6;
38pub const MAX_PASSWORD_LEN: usize = 128;
39
40pub const MAX_NAME_LEN: usize = 100;
41
42/// Profile fields: the self-chosen name a user is shown under, and the free
43/// text under it.
44pub const MAX_DISPLAY_NAME_LEN: usize = 50;
45pub const MAX_BIO_LEN: usize = 500;
46
47/// How many course and class references one profile read embeds. A cap on the
48/// response, not on membership — the full lists stay at `/courses/me` and
49/// `/classes/me`.
50pub const MAX_PROFILE_COURSES: usize = 20;
51pub const MAX_PROFILE_CLASSES: usize = 5;
52
53/// RFC 5321's practical upper bound for a full address.
54pub const MAX_EMAIL_LEN: usize = 254;
55
56/// Digit-count bounds for a phone number (E.164 allows at most 15).
57pub const MIN_PHONE_DIGITS: usize = 7;
58pub const MAX_PHONE_DIGITS: usize = 15;
59
60pub const MAX_NOTE_TITLE_LEN: usize = 200;
61pub const MAX_NOTE_CONTENT_LEN: usize = 10_000;
62
63/// How many files one note may carry.
64pub const MAX_NOTE_FILES: usize = 10;
65
66/// How many files one course note may carry.
67pub const MAX_COURSE_NOTE_FILES: usize = 10;
68
69pub const MAX_MESSAGE_SUBJECT_LEN: usize = 200;
70pub const MAX_MESSAGE_BODY_LEN: usize = 10_000;
71/// A message's optional sender-chosen tag ("Etüt", "Sınav", …) — free text,
72/// rendered as a badge by the UI.
73pub const MAX_MESSAGE_LABEL_LEN: usize = 50;
74
75/// Bounds for a note file's original filename and its MIME content type.
76pub const MAX_FILE_NAME_LEN: usize = 255;
77pub const MAX_FILE_CONTENT_TYPE_LEN: usize = 100;
78
79/// The school-adjustable per-file upload size limit (`max_file_bytes` in
80/// settings): its default and the inclusive range a manager may set. The
81/// ceiling is a server-protection hard cap — uploads buffer in memory and land
82/// in single disk files, so it must stay modest no matter the school's wish.
83pub const DEFAULT_MAX_FILE_BYTES: i64 = 5 * 1024 * 1024;
84pub const MIN_MAX_FILE_BYTES: i64 = 1024;
85pub const MAX_MAX_FILE_BYTES: i64 = 25 * 1024 * 1024;
86
87/// Headroom on top of `MAX_MAX_FILE_BYTES` for the upload route's HTTP body
88/// cap: multipart boundaries, part headers, and the filename ride alongside
89/// the file bytes themselves.
90pub const UPLOAD_BODY_OVERHEAD_BYTES: usize = 64 * 1024;
91
92/// The content types an uploaded inline image (exam question images, pool
93/// question photos) may declare — raster formats only. SVG is deliberately
94/// out: it can carry scripts, and these bytes are served for inline display
95/// to whole classes.
96pub const QUESTION_IMAGE_CONTENT_TYPES: [&str; 4] =
97 ["image/png", "image/jpeg", "image/webp", "image/gif"];
98
99/// Bounds for a pool question (the student-asked Q&A pool) and its solutions.
100pub const MAX_POOL_QUESTION_TITLE_LEN: usize = 200;
101pub const MAX_POOL_QUESTION_BODY_LEN: usize = 10_000;
102pub const MAX_SOLUTION_BODY_LEN: usize = 10_000;
103
104pub const MAX_EVENT_TITLE_LEN: usize = 200;
105pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000;
106
107pub const MAX_EXAM_TITLE_LEN: usize = 200;
108pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000;
109
110pub const MAX_COURSE_TITLE_LEN: usize = 200;
111pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000;
112
113/// A class section (şube) is named like a course, but its optional `grade` is
114/// a free-text label the school picks ("9", "10-A", "anaokulu") — a line of
115/// display text, so it is bounded like the other short labels, not like a
116/// description.
117pub const MAX_CLASS_NAME_LEN: usize = 200;
118pub const MAX_CLASS_GRADE_LEN: usize = 20;
119
120/// How big one class may get, on each of its two axes. These are not comfort
121/// numbers: attaching a course to a class writes one enrollment per member and
122/// adding a member writes one per attached course, both in a *single*
123/// transaction, so each axis's counter is the bound on the other axis's write
124/// loop — a class with no ceiling is an unbounded transaction anyone with the
125/// manager role can trigger. A section is a homeroom (`MAX_HOMEWORK_ASSIGNED`
126/// shares the 200) and its timetable is a school week, not a catalogue.
127///
128/// Which is also why each write is refused on the *other* axis: a class created
129/// before these numbers existed can stand above one of them, and the axis being
130/// added to having room says nothing about the loop's length — that is set by
131/// the axis it multiplies against. So the pump refuses a member while the class
132/// holds more than `MAX_CLASS_COURSES` courses and a course while it holds more
133/// than `MAX_CLASS_MEMBERS` students, and only shrinking the overloaded side
134/// clears it.
135pub const MAX_CLASS_MEMBERS: i64 = 200;
136pub const MAX_CLASS_COURSES: i64 = 50;
137
138pub const MAX_SUBJECT_NAME_LEN: usize = 200;
139pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000;
140
141pub const MAX_HOMEWORK_TITLE_LEN: usize = 200;
142pub const MAX_HOMEWORK_DESCRIPTION_LEN: usize = 2_000;
143
144/// A homework submission's optional free-text note, sent alongside its files.
145pub const MAX_HOMEWORK_TEXT_LEN: usize = 5_000;
146
147/// How many files one homework submission may carry.
148pub const MAX_HOMEWORK_FILES_PER_SUBMISSION: usize = 10;
149
150/// How many students a homework may be narrowed to. The whole-course default
151/// carries no assigned list at all, so this caps only an explicit subset.
152pub const MAX_HOMEWORK_ASSIGNED: usize = 200;
153
154/// The default attendance states, and also the mandatory core: a school may
155/// add its own statuses via `PATCH /settings`, but these four can never be
156/// removed — the attendance rate's semantics are defined over them.
157pub const DEFAULT_ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"];
158
159pub const MAX_SESSION_TOPIC_LEN: usize = 200;
160
161/// The default exam kinds with their weights; schools replace the list via
162/// `PATCH /settings`. An exam's kind decides how heavily it counts into the
163/// course average — the defaults all weigh 1 (a plain average) so weighting
164/// is opt-in policy, not baked-in opinion.
165pub const DEFAULT_EXAM_KINDS: [(&str, i64); 6] = [
166 ("homework", 1),
167 ("quiz", 1),
168 ("midterm", 1),
169 ("final", 1),
170 ("project", 1),
171 ("oral", 1),
172];
173
174/// Bounds for the school-editable lists in settings (exam kinds, attendance
175/// statuses): entry count and per-entry character length.
176pub const MAX_SETTINGS_LIST_LEN: usize = 20;
177pub const MAX_SETTINGS_ITEM_LEN: usize = 50;
178
179/// Bounds for the grade-display bands in settings.
180pub const MAX_GRADE_BANDS: usize = 20;
181pub const MAX_GRADE_LABEL_LEN: usize = 20;
182
183/// How many times a read-then-compare-and-set path (`PATCH /settings`, `PATCH
184/// /bank/{bid}`, every appointment decision) re-reads and retries when a
185/// concurrent edit lands between its snapshot and its save. A miss normally
186/// re-validates into a `409`, so this only covers a write racing a legal
187/// transition.
188pub const CAS_UPDATE_RETRIES: usize = 3;
189
190pub const MAX_TERM_NAME_LEN: usize = 100;
191
192/// A published availability slot's optional note ("bring your report card").
193pub const MAX_APPOINTMENT_NOTE_LEN: usize = 500;
194
195/// Why a requester wants the meeting — required, and read by a human, so it
196/// stays short.
197pub const MAX_APPOINTMENT_REASON_LEN: usize = 1_000;
198
199/// How many concrete slot rows one recurring publish may expand into. Weekly
200/// occurrences over a full school year fit inside this; a runaway `until`
201/// (a decade out) is refused instead of writing thousands of rows.
202pub const MAX_SLOT_OCCURRENCES: usize = 52;
203
204/// The default meal slots; schools replace the list via `PATCH /settings`, and
205/// a published menu snapshots the slot it was written for, so retiring a slot
206/// never rewrites history.
207pub const DEFAULT_MEAL_SLOTS: [&str; 3] = ["breakfast", "lunch", "snack"];
208
209/// The default dietary tags. A student's profile and a dish both carry tags
210/// from this school-editable list, which is how "this dish is safe for them"
211/// is answered without the backend knowing any nutrition.
212pub const DEFAULT_DIETARY_TAGS: [&str; 5] = [
213 "vegetarian",
214 "vegan",
215 "gluten_free",
216 "lactose_free",
217 "nut_allergy",
218];
219
220/// Bounds on one menu and the dishes hanging off it.
221pub const MAX_DISH_NAME_LEN: usize = 100;
222pub const MAX_DISH_DESCRIPTION_LEN: usize = 500;
223pub const MAX_DISHES_PER_MENU: usize = 50;
224pub const MAX_DISH_TAGS: usize = 10;
225
226/// How many students one menu may seat. Absent capacity means uncapped, the
227/// same shape a course's `capacity` uses.
228pub const MAX_MENU_CAPACITY: i64 = 10_000;
229
230/// Bounds on a student's dietary profile: one row per student, so the tag list
231/// is the whole payload plus a free-text note for the kitchen.
232pub const MAX_DIETARY_TAGS: usize = 10;
233pub const MAX_DIETARY_NOTE_LEN: usize = 500;
234
235/// Money is **minor units** (kuruş) as `i64` everywhere — never a decimal and
236/// never a float. `MAX_DISH_PRICE_MINOR` caps one dish (10 000 ₺);
237/// `MAX_LEDGER_AMOUNT_MINOR` caps one ledger line (100 000 ₺), which is wide
238/// enough for a term's prepayment.
239pub const MAX_DISH_PRICE_MINOR: i64 = 1_000_000;
240pub const MAX_LEDGER_AMOUNT_MINOR: i64 = 10_000_000;
241
242/// Bounds on the free-text a ledger line carries: how the money moved, and why.
243pub const MAX_LEDGER_METHOD_LEN: usize = 50;
244pub const MAX_LEDGER_NOTE_LEN: usize = 500;
245
246/// How many times one seat may be taken on one menu: the first booking plus
247/// nine re-bookings after a cancel.
248///
249/// A cap on *storage*, not on indecision. Every cycle appends two permanent,
250/// undeletable ledger lines — the charge and its reversal, both keyed to the
251/// attempt — and nothing else bounded them: at the API's own request ceiling
252/// one account could grow its statement by hundreds of thousands of rows a
253/// day, which every later balance read then answers for. Ten is far past what
254/// a family changing its mind about lunch needs, and a menu whose seat really
255/// must move again is the canteen's to cancel.
256pub const MAX_MEAL_BOOKING_ATTEMPTS: i64 = 10;
257
258/// Ceiling on the settings knob that closes booking (and cancelling) ahead of
259/// a meal — one week. The knob itself is optional: absent means no cutoff.
260pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60;
261
262/// Inclusive ceiling for a meal slot's `serving_minute` — minutes past
263/// midnight on the menu's date, so `0` = 00:00 and `1439` = 23:59. The cutoff
264/// above counts back from that instant.
265///
266/// **The clock is UTC.** This backend deliberately stores no school timezone
267/// (rejected feature), so staff enter the serving time in UTC: a UTC+3 school
268/// types `540` (09:00) to mean noon locally. Optional per slot — and a slot
269/// without one has **no cutoff at all**, since there is no instant to count a
270/// deadline back from; the cutoff knob starts binding that slot the day the
271/// school sets its hour.
272pub const MAX_MEAL_SERVING_MINUTE: i64 = 24 * 60 - 1;
273
274/// The only accepted course kinds. `course`: a regular class (ders). `study`:
275/// a supervised study session (etüt). Behaviorally identical — the kind is a
276/// label for the UI, everything else (enrollment, exams, sessions, marks)
277/// works the same.
278pub const COURSE_KINDS: [&str; 3] = ["course", "study", "club"];
279
280/// The only accepted exam modes. `sync`: everyone sits the exam inside one
281/// fixed window. `async`: each student starts inside the window and gets their
282/// own `duration_ms` slice of it. `open`: no window — students sit anytime,
283/// with an optional per-attempt `duration_ms` (absent = unlimited time). An
284/// exam with no mode at all is an offline-graded draft and cannot be sat.
285pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"];
286
287/// The only accepted homework grades. `done`: submitted and complete;
288/// `incomplete`: submitted but lacking; `missing`: not done. A teacher-set
289/// `missing` is a deliberate verdict, distinct from the roster's *computed*
290/// missing (unsubmitted past due). The `HomeworkStatus` newtype enforces the
291/// set; the DDL carries no ASSERT (repo convention), exactly like `EXAM_MODES`.
292pub const HOMEWORK_STATUSES: [&str; 3] = ["done", "incomplete", "missing"];
293
294/// The only accepted meal-booking states. A cancel flips the status and stamps
295/// `cancelled_at` instead of deleting the row, so a seat freed after the cutoff
296/// is still auditable against the ledger line it charged.
297pub const MEAL_BOOKING_STATUSES: [&str; 2] = ["booked", "cancelled"];
298
299/// The only accepted meal-attendance states — did the student actually eat.
300/// Deliberately *not* the school's `attendance_statuses`: a canteen line has no
301/// "late" or "excused", and mixing the two would let a school edit one meaning
302/// while changing the other.
303pub const MEAL_ATTENDANCE_STATUSES: [&str; 2] = ["served", "missed"];
304
305/// The only accepted ledger kinds. `charge`: a booking billed the student.
306/// `credit`: money in (a payment, or an opening balance). `reversal`: a charge
307/// undone — the ledger is append-only, so a cancelled booking writes a new
308/// opposing line rather than editing or deleting the charge.
309pub const MEAL_LEDGER_KINDS: [&str; 3] = ["charge", "credit", "reversal"];
310
311/// The only accepted school-payment ledger kinds. `charge`: an installment the
312/// student owes, appended when a fee plan is assigned. `credit`: money in,
313/// against one named charge. `refund`: money paid back out, against one named
314/// credit. `reversal`: a mistaken `charge` or `refund` undone — the ledger is
315/// append-only, so the opposing line is appended rather than the line edited.
316/// A mistaken *credit* is corrected by a `refund`, which is why `reversal`
317/// never points at one.
318pub const PAYMENT_LEDGER_KINDS: [&str; 4] = ["charge", "credit", "reversal", "refund"];
319
320/// Bounds on a fee plan: its name, and how many installments it may carry.
321/// Sixty covers a monthly plan over five years — well past any school year,
322/// and low enough that one assignment cannot append a thousand ledger lines.
323pub const MAX_FEE_PLAN_NAME_LEN: usize = 120;
324pub const MAX_FEE_PLAN_INSTALLMENTS: usize = 60;
325
326/// How many students one `POST /payments/plans/{id}/assignments` may name.
327/// Bulk placement is a whole class at a time, not the whole school.
328pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200;
329
330/// How many charge lines one assignment request may append: the students it
331/// names times the plan's installments. The student cap alone cannot see the
332/// schedule — 200 students on a 60-installment plan is 12 000 sequential
333/// writes in one HTTP request, and nothing in the stack times a request out.
334/// Three thousand leaves the ordinary shapes whole (200 students up to a
335/// 15-installment plan, 50 students on the largest plan there is) and the
336/// refusal tells the caller to split the batch.
337pub const MAX_FEE_PLAN_ASSIGN_WRITES: usize = 3_000;
338
339/// How many lines may be applied to one ledger line — the payments under a
340/// charge, the refunds under a payment, and every reversal among them. The
341/// over-payment cap folds that whole subtree one query per line while holding
342/// the process-global payment lock, so an unbounded subtree is an unbounded
343/// stall for every other payment in the school: 2 000 one-kuruş payments make
344/// the next one issue 2 001 queries with the lock held. Twenty pieces is
345/// already a pathological way to settle a single installment.
346pub const MAX_LEDGER_APPLIED_LINES: usize = 20;
347
348/// Ceiling on the client-chosen `request_key` that makes a credit or a refund
349/// retry-safe: it becomes part of the ledger line's record id, so it is bounded
350/// and drawn from `[A-Za-z0-9-]` — `_` joins the parts of a ledger id, so a key
351/// carrying one could spell another line's id. Sixty-four characters take a
352/// UUID or a receipt number comfortably.
353pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64;
354
355/// Bounds on a whiteboard: its title, and how many people the creator may name
356/// onto it. Two hundred is a big club or a whole grade, not the school; every
357/// participant may draw, so this is also what bounds one board's writer count.
358///
359/// It was fifty while a roster could only be typed one id at a time. Bulk
360/// invite (`POST /boards/{id}/invite`) resolves a class section, a course or an
361/// event's roster in one call, and fifty refused an ordinary club — so the
362/// ceiling moved to the size of the largest group a school actually puts on one
363/// canvas. Raising it can only widen what an existing row is allowed to hold.
364pub const MAX_BOARD_TITLE_LEN: usize = 200;
365pub const MAX_BOARD_PARTICIPANTS: usize = 200;
366
367/// Ceiling on one stroke's serialized payload. A stroke is a short path — a
368/// handful of points, a colour, a width — and it is stored verbatim and fanned
369/// out to every socket in the room, so it is bounded at the wire rather than at
370/// the canvas: 4 KiB takes a long freehand curve and still keeps the worst-case
371/// board (`MAX_BOARD_STROKES` of them) inside a couple hundred megabytes.
372pub const MAX_STROKE_PAYLOAD_LEN: usize = 4_096;
373
374/// The two growth caps, both counted on the board row (see the counter fields
375/// below). They are different kinds of full on purpose:
376///
377/// `MAX_EPOCH_STROKES` caps the *live* canvas — the strokes since the last
378/// clear. Hitting it is recoverable: the creator clears, the epoch counter
379/// resets to zero and drawing resumes. Nothing is deleted by that clear.
380///
381/// `MAX_BOARD_STROKES` caps the board's total *storage*, and never resets,
382/// because a clear keeps its history for playback. Hitting it stamps
383/// `closed_at`: the board turns permanently read-only, but stays fully
384/// readable and replayable — a closed board loses no stroke it ever carried.
385pub const MAX_EPOCH_STROKES: i64 = 5_000;
386pub const MAX_BOARD_STROKES: i64 = 50_000;
387
388/// How many boards one creator may hold. Without it the two caps above cost an
389/// attacker nothing — a full board is answered by opening the next one — so
390/// this is the counter that actually bounds a single account's storage. Kept on
391/// the user row, the same shape as `CHATBOT_THREAD_COUNT_FIELD`.
392pub const MAX_BOARDS_PER_CREATOR: i64 = 200;
393
394/// The only accepted stroke kinds. `stroke`: a drawn path, carrying its
395/// payload. `clear`: the marker row that ends an epoch — it deletes nothing,
396/// it is the epoch index, so replaying across it reconstructs the whole
397/// session.
398pub const BOARD_STROKE_KINDS: [&str; 2] = ["stroke", "clear"];
399
400/// Ceiling on a `board_id` arriving on the board WebSocket, for the same reason
401/// as [`MAX_QUESTION_ID_LEN`]: the field is a record key — a 26-char ULID in
402/// every real payload — and the error frame *echoes* it back, so an unbounded
403/// id lets a client make its own room reflect a 64 MiB frame at it. Checked
404/// before any database work.
405pub const MAX_BOARD_ID_LEN: usize = 64;
406
407/// Inclusive bounds for an exam's per-attempt duration, milliseconds
408/// (1 minute to 24 hours). Required for `async`, optional for `open`.
409pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;
410pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000;
411
412/// Upper bound for an exam's attempt limit; `UNLIMITED_EXAM_ATTEMPTS` (zero)
413/// is the wire-and-storage spelling of "no limit". A limit of 1 — the
414/// default — is the classic single sitting.
415pub const MAX_EXAM_ATTEMPTS: i64 = 100;
416pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0;
417
418/// Cadence of the background keepalive query on the database WebSocket. The
419/// traffic keeps the connection from being dropped as idle; when it does drop,
420/// the ping also makes the SDK notice and reconnect long before the next real
421/// request would. Doubles as the liveness probe behind
422/// [`crate::state::DbHealth`], so this is also the widest window in which a
423/// request can reach a socket already known-dead — keep it short.
424pub const DB_KEEPALIVE_INTERVAL_SECS: u64 = 5;
425
426/// How long a keepalive ping may hang before the socket counts as down. The
427/// SDK parks queries indefinitely while it reconnects (its retry loop stops
428/// draining the request channel), so the ping needs its own deadline or the
429/// probe hangs with everything else and never reports.
430pub const DB_PING_TIMEOUT_SECS: u64 = 2;
431
432/// Ceiling on a single HTTP request. Backstop for requests that reached the
433/// database in the window between the socket dying and the keepalive noticing:
434/// without it they park until the database returns, which can be hours.
435/// Generous enough not to clip a legitimate slow upload at `max_file_bytes`.
436pub const REQUEST_TIMEOUT_SECS: u64 = 30;
437
438/// The longest caller-supplied `x-request-id` header the server will carry.
439///
440/// The id lands on `http.request.id` of every span, so anything a client puts
441/// there it can export: free text and unbounded cardinality both. A header
442/// longer than this (or one carrying anything outside `[A-Za-z0-9._-]`) is
443/// dropped and a UUID minted in its place — the request still succeeds, it
444/// just stops being correlatable by the caller's own id, which is exactly why
445/// a client needs to know the bound.
446pub const MAX_REQUEST_ID_LEN: usize = 64;
447
448/// Backoff ceiling for the boot connection retry. The database is usually a
449/// sibling container coming up in parallel, so the first attempts fail; the
450/// process retries forever rather than exiting, because exiting turns a
451/// few-second wait into a container restart loop that outruns its budget and
452/// stays down.
453pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5;
454
455/// Cadence of the `state` ticks on the student exam-room WebSocket
456/// (`GET /exams/{id}/attempt/ws`).
457pub const EXAM_WS_TICK_SECS: u64 = 2;
458
459/// Cadence of the keepalive ticks on the whiteboard-room WebSocket. Slower than
460/// the exam room's, because a board room carries no countdown a client renders
461/// against — the tick only keeps an idle socket from being reaped.
462pub const BOARD_WS_TICK_SECS: u64 = 15;
463
464/// How many strokes one replay message carries when a socket joins. The join
465/// replays the current epoch, which is `MAX_EPOCH_STROKES` at worst, so it is
466/// sent in batches rather than as one frame that could reach the WebSocket
467/// frame limit on a busy board.
468pub const BOARD_REPLAY_CHUNK: usize = 200;
469
470/// Depth of one board room's fan-out channel: how far a slow socket may lag the
471/// strokes being drawn before it is dropped and has to rejoin (which replays
472/// the epoch from storage anyway, so nothing is lost by the drop).
473pub const BOARD_HUB_CAPACITY: usize = 256;
474
475/// Ceiling on a `question_id` arriving on the exam-room WebSocket. The field is
476/// a record key — a 26-char ULID in every real payload — not free text, so this
477/// is generous by a factor of two and change. The cap exists because the
478/// per-question error frame *echoes* the id back: axum's default WebSocket
479/// frame limit is 64 MiB, so without it a client can make its own room reflect
480/// that whole payload. Rejected before any database work, and unattributed — an
481/// unusable id names no question, so nothing of it is sent back.
482pub const MAX_QUESTION_ID_LEN: usize = 64;
483
484/// The only accepted question kinds. `choice`: pick one of the listed
485/// choices, auto-scorable. `text`: free text, judged by the grader.
486pub const QUESTION_KINDS: [&str; 2] = ["choice", "text"];
487
488pub const MAX_QUESTION_TEXT_LEN: usize = 2_000;
489
490/// Inclusive bounds for a question's points (its share of the auto-score).
491pub const MIN_QUESTION_POINTS: i64 = 1;
492pub const MAX_QUESTION_POINTS: i64 = 100;
493
494/// Bounds for a choice question's option list and each option's text.
495pub const MIN_QUESTION_CHOICES: usize = 2;
496pub const MAX_QUESTION_CHOICES: usize = 10;
497pub const MAX_CHOICE_TEXT_LEN: usize = 500;
498
499pub const MAX_ANSWER_TEXT_LEN: usize = 10_000;
500
501/// Inclusive bounds for an exam mark.
502pub const MIN_MARK: i64 = 0;
503pub const MAX_MARK: i64 = 100;
504
505/// Inclusive bounds for an exam kind's weight in the course average. The
506/// minimum of 1 keeps every graded exam counted and the average's denominator
507/// non-zero.
508pub const MIN_EXAM_KIND_WEIGHT: i64 = 1;
509pub const MAX_EXAM_KIND_WEIGHT: i64 = 100;
510
511pub const SESSION_DURATION_DAYS: i64 = 7;
512
513/// How far in the past a request-supplied schedule instant (exam window,
514/// lesson, event time) may lie before it is rejected as backdated. The grace
515/// absorbs request latency and modest client-clock skew — a "starts now"
516/// submission must survive its own round trip — while still refusing
517/// genuinely past deadlines.
518pub const SCHEDULE_PAST_GRACE_MS: i64 = 60 * 1000;
519
520/// Upper bound on a list endpoint's `limit` page-size parameter. Omitting
521/// `limit` returns every (remaining) row; when supplied it must be
522/// `1..=MAX_PAGE_LIMIT`. The `#[param(maximum = ...)]` and the "1 and 500"
523/// wording in `web::page` mirror this literal — keep them in step.
524pub const MAX_PAGE_LIMIT: i64 = 500;
525
526/// Wire-protocol identifier for the AI bridge, sent in [`crate::ai::protocol::Hello`]
527/// and used as the QUIC ALPN. Bump both together on a breaking frame change:
528/// ALPN mismatch rejects an old service at the TLS handshake, before it can
529/// send a frame we would misparse.
530pub const AI_PROTOCOL: &str = "hab/2";
531pub const AI_ALPN: &[u8] = b"hab/2";
532
533/// Hard ceiling on one AI-bridge frame. Checked against the length prefix
534/// before the body buffer is allocated. Generous because a payload may carry a
535/// base64 question image, but bounded so a bad length cannot exhaust memory.
536pub const AI_MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
537
538/// Default wait for one AI request before the stream is abandoned
539/// (`AI_REQUEST_TIMEOUT_SECS`). Model inference is slow, so this is far longer
540/// than [`REQUEST_TIMEOUT_SECS`] — AI calls must not sit on an HTTP request
541/// path that the outer timeout would kill first.
542pub const AI_DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 30;
543
544/// Upper bound on a worker's self-declared `max_concurrent`, and the value
545/// used when it declares none. A worker that claims a huge number would let
546/// the registry pile every request onto one service.
547pub const AI_MAX_CONCURRENT_PER_WORKER: usize = 64;
548pub const AI_DEFAULT_CONCURRENT_PER_WORKER: usize = 8;
549
550/// QUIC idle timeout and keepalive for a service connection. The keepalive is
551/// well under the idle timeout so an idle-but-healthy service is never dropped
552/// for being quiet; a service that actually died is deregistered within the
553/// idle window without any application-level heartbeat frame.
554pub const AI_IDLE_TIMEOUT_SECS: u64 = 30;
555pub const AI_KEEPALIVE_SECS: u64 = 10;
556
557/// How long a blob body may make *no* progress before its stream is reset.
558/// A STALL bound, not a transfer cap: the clock is per write, so a slow peer
559/// that keeps reading streams a whole `max_file_bytes` file for as long as it
560/// takes, while a service that opens a blob stream and never reads it stops
561/// pinning a task and an open file descriptor once the QUIC stream window
562/// fills. A wall-clock deadline on the transfer could not tell the two apart.
563pub const AI_BLOB_WRITE_STALL_SECS: u64 = 30;
564
565/// The capability an AI service declares to answer chatbot turns. The bridge
566/// routes a chat request to any worker carrying it; with none registered the
567/// chat endpoints report the service as unavailable.
568pub const AI_CHAT_CAPABILITY: &str = "chat.reply";
569
570/// The capability an AI service declares to index a course note for retrieval.
571/// The backend dispatches on it after a note (or one of its files) changes;
572/// with no worker carrying it the trigger is a silent no-op — indexing is a
573/// bonus on top of the note, never a condition of storing one.
574pub const AI_RAG_INDEX_CAPABILITY: &str = "rag.index";
575
576/// Deadline on one `rag.index` round trip. Longer than a chat turn
577/// ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`]): chunking and embedding a note with
578/// ten attachments is batch work, and nobody is waiting on it — the dispatch
579/// is fire-and-forget, off the HTTP request path.
580pub const AI_RAG_INDEX_TIMEOUT_SECS: u64 = 120;
581
582/// Hard ceiling on one chat message's characters — the newtype bound, above
583/// which no school setting can reach. Sized for a pasted question with its
584/// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.
585pub const MAX_CHATBOT_MESSAGE_LEN: usize = 8_000;
586
587/// The school-adjustable per-message character cap (`max_chatbot_message_len` in
588/// settings): its default and the inclusive range a manager may set. The
589/// ceiling is [`MAX_CHATBOT_MESSAGE_LEN`] — a longer prompt costs the AI service
590/// context it needs for the history.
591pub const DEFAULT_MAX_CHATBOT_MESSAGE_LEN: i64 = 4_000;
592pub const MIN_MAX_CHATBOT_MESSAGE_LEN: i64 = 100;
593pub const MAX_MAX_CHATBOT_MESSAGE_LEN: i64 = MAX_CHATBOT_MESSAGE_LEN as i64;
594
595/// Bound on a chat thread's display name. A thread is named by hand or not at
596/// all — nothing auto-titles one — so this only has to fit a line a user typed.
597pub const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200;
598
599/// How many prior user/assistant turns of a thread are replayed to the
600/// AI service as context (`chatbot_history_turns` in settings): its default and
601/// the inclusive range a manager may set. Every turn is re-sent on every
602/// request, so the ceiling bounds both the frame size and the inference cost.
603pub const DEFAULT_CHATBOT_HISTORY_TURNS: i64 = 10;
604pub const MIN_CHATBOT_HISTORY_TURNS: i64 = 1;
605pub const MAX_CHATBOT_HISTORY_TURNS: i64 = 50;
606
607/// How many threads one user may keep (`max_chatbot_threads` in
608/// settings): its default and the inclusive range a manager may set. Reached,
609/// the user deletes an old thread before starting a new one — the cap is
610/// storage protection, not a usage quota.
611pub const DEFAULT_MAX_CHATBOT_THREADS: i64 = 50;
612pub const MIN_MAX_CHATBOT_THREADS: i64 = 1;
613pub const MAX_MAX_CHATBOT_THREADS: i64 = 500;
614
615/// How often the chat stream re-reads a `pending` assistant message while it
616/// waits for the answer. The reply lands in the database from whichever task
617/// owns the bridge stream, so the reader polls rather than sharing state.
618pub const CHAT_STREAM_POLL_MS: u64 = 200;
619
620/// How long an assistant message may sit `pending` before a reader gives up on
621/// it and reports it failed. Comfortably past
622/// [`AI_DEFAULT_REQUEST_TIMEOUT_SECS`] (which `AI_REQUEST_TIMEOUT_SECS` may
623/// raise), because the answering task normally stamps the failure itself —
624/// this only catches the row whose task died with the process.
625pub const CHATBOT_PENDING_STALE_SECS: i64 = 300;
626
627/// The largest per-request AI deadline a deployment may configure
628/// (`AI_REQUEST_TIMEOUT_SECS`). Anything above it is clamped down to it at
629/// startup, loudly — see [`crate::config`].
630///
631/// A sanity ceiling, well under [`CHATBOT_PENDING_STALE_SECS`]: a reply that
632/// arrives after the staleness window is discarded by the read-time
633/// projection, so a deadline anywhere near it could never produce an answer a
634/// user sees — it would only hold a task and a worker slot open for nothing.
635/// A school that genuinely needs longer raises this and the staleness window
636/// together.
637pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = 60;
638
639/// How long a dialling AI service has to complete its `Hello`/`Welcome`
640/// exchange before the connection is dropped. Short: the handshake is one
641/// frame each way, and an unauthenticated connection must not be able to
642/// occupy the listener indefinitely.
643pub const AI_HANDSHAKE_TIMEOUT_SECS: u64 = 10;
644
645/// The only REST paths an AI service may read over the bridge — deny-by-default,
646/// matched segment-wise by [`crate::ai::api`] with `{x}` standing for exactly
647/// one segment. This list *is* the services' access scope, so it is a service
648/// contract documented in `README.md`, not a tunable published at `/limits`
649/// (string arrays are exempt from that completeness gate).
650///
651/// JSON-only, and only what a study-companion needs: who the user is, their
652/// notes, their course's notes, their homework, and their own progress reports.
653/// Byte-serving routes
654/// (note files, submission files, avatars, question images) are left out — the
655/// frames carry JSON, and a blob has no business crossing this seam yet.
656pub const AI_API_ALLOWLIST: &[&str] = &[
657 "/auth/me",
658 "/users/me/profile",
659 "/users/{id}/profile",
660 "/notes",
661 "/notes/{id}",
662 "/course-notes",
663 "/course-notes/{id}",
664 "/course-notes/{id}/files",
665 "/homework",
666 "/homework/{id}",
667 "/homework/{id}/result",
668 "/homework/{id}/submission",
669 "/homework/report/{user}",
670 "/marks/me",
671 "/marks/{user}",
672 "/attendance/me",
673 "/attendance/{user}",
674 "/pomodoro/me",
675 "/pomodoro/{user}",
676];
677
678// --- rate limiting -----------------------------------------------------
679
680/// Default requests-per-minute-per-IP for `/auth/login` + `/auth/register`.
681pub const DEFAULT_AUTH_RATE_LIMIT: u32 = 10;
682/// Default requests-per-minute-per-IP across the whole API.
683pub const DEFAULT_API_RATE_LIMIT: u32 = 300;
684/// Default chatbot messages per minute *per user*. Sits far above a human
685/// typing while still blunting a scripted fan-out at the AI service behind the
686/// bridge — which is the cost this tier rations, not this process.
687pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20;
688
689/// Once the bucket map holds this many distinct clients, a new key sweeps out
690/// the expired entries and, if that frees nothing, evicts the least-spent live
691/// buckets — **never an exhausted one** — down to three quarters of this.
692/// Evicting a bucket that had reached its limit would hand back the very
693/// refusal it was enforcing, so a flood cannot make the limiter fail open; the
694/// concession is that while the map is saturated with exhausted buckets a
695/// never-before-seen client gets no bucket of its own and is metered against
696/// the one shared [`RATE_LIMIT_OVERFLOW_MAX`] budget instead — so newcomers
697/// during a flood can be refused, while every client already in the map keeps
698/// its own counter untouched. Keeps memory bounded without a reaper task.
699pub const PURGE_AT: usize = 10_000;
700
701/// Requests per window every client that finds the bucket map saturated shares
702/// between them — one aggregate counter, no key, no map entry.
703///
704/// It is the bound on the fail-open path: without it a new key arriving at a
705/// full map is admitted unmetered, so an attacker who first fills the map with
706/// exhausted buckets buys unlimited throughput from fresh keys. With it that
707/// bypass is capped at this many requests a minute, fleet-wide, and a genuine
708/// newcomer gets in on whatever of it is left — an attacker who burns the lot
709/// does `429` the newcomers, which refusing them outright would have done for
710/// free. Clients already in the map are unaffected throughout. Sized for the
711/// genuine side: this is a *request* budget, not a client one (a keyless client
712/// spends it on every request, not just its first), so roughly 10 requests a
713/// second for all newcomers together — far under any single client's API tier,
714/// and only ever in force while 10k buckets sit exhausted at once, which is an
715/// attack and not a school day.
716pub const RATE_LIMIT_OVERFLOW_MAX: u32 = 600;
717
718/// The shared counter the limiter folds its local admits into, so a window's
719/// budget survives a restart (see [`crate::rate_limit`]).
720pub const RATE_LIMIT_TABLE: &str = "rate_limit";
721
722/// How often a limiter pushes its admits and reads the window's total back.
723/// The knob that decides the worst case: within one interval a just-started
724/// process can admit up to its full local budget before the total tightens it, so
725/// short enough to matter and long enough to stay one query per tier per tick.
726pub const RATE_SYNC_INTERVAL_SECS: u64 = 2;
727
728/// How long one sync round may wait on the database. The SDK *parks* a query
729/// while the socket is down instead of failing it, so the liveness flag alone
730/// cannot stop a round wedging the task forever — this is the backstop that
731/// keeps the limiter purely local through an outage instead of stalled.
732pub const RATE_SYNC_TIMEOUT_SECS: u64 = 5;
733
734/// How many client buckets one round syncs. A round is a single query holding
735/// one statement per bucket, so this bounds both its size and the write volume
736/// a burst of distinct clients can put on the database.
737pub const RATE_SYNC_MAX_KEYS: usize = 512;
738
739// --- time spans --------------------------------------------------------
740
741pub const MILLIS_PER_DAY: i64 = 24 * 60 * 60 * 1000;
742
743/// One week, the only recurrence step this backend expands.
744pub const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY;
745
746// --- enum value tables -------------------------------------------------
747
748/// Every *assignable* role, lowest privilege first. `Role::Ai` is deliberately
749/// absent: it is a service principal, so leaving it out of this table is what
750/// keeps `Role::try_from_str` (and every surface that lists roles) from ever
751/// handing it to a user.
752pub const ROLES: [Role; 5] = [
753 Role::Parent,
754 Role::Student,
755 Role::Teacher,
756 Role::Manager,
757 Role::Admin,
758];
759
760/// The record key `User::ai_principal` carries. A literal, not a ULID, so it
761/// can never collide with a minted user row — and the row is never written.
762pub const AI_PRINCIPAL_KEY: &str = "ai_service";
763
764pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark];
765
766pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En];
767
768/// A `palette_color` preference is `#` plus exactly six hex digits — the length
769/// of the whole string, `#` included.
770pub const PALETTE_COLOR_LEN: usize = 7;
771
772/// The shape a `palette_color` must match, as a regular expression. This
773/// describes what the server **accepts**, so it is case-insensitive — the value
774/// is normalized to lowercase on store, and a client that sent `#FEFAE0` reads
775/// `#fefae0` back. Publishing the lowercase-only form would have a client
776/// reject its own valid input.
777///
778/// Deliberately an open value set: any valid hex accent color, not a closed
779/// list of the frontend's palette, so a new palette entry needs no backend
780/// change.
781pub const PALETTE_COLOR_PATTERN: &str = "^#[0-9a-fA-F]{6}$";
782
783/// Folders a sender may file their side into (`Sent` is their home).
784pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash];
785/// Folders a recipient may file their side into (`Inbox` is their home).
786pub const RECIPIENT_FOLDERS: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash];
787
788/// The two lifecycle states of a pool question. `pending`: awaiting teacher+
789/// approval, visible only to the asker and to teacher+. `approved`: in the
790/// pool, school-wide. Rejection is not a state — a teacher+ simply deletes the
791/// question.
792pub const STATUS_PENDING: &str = "pending";
793pub const STATUS_APPROVED: &str = "approved";
794pub const POOL_QUESTION_STATUSES: [&str; 2] = [STATUS_PENDING, STATUS_APPROVED];
795
796/// The two reaches of a bank question template: the author's own drawer, or
797/// published to the whole school.
798pub const BANK_VISIBILITY_PRIVATE: &str = "private";
799pub const BANK_VISIBILITY_SCHOOL: &str = "school";
800
801// --- fixed keys and literals -------------------------------------------
802
803/// The settings singleton's fixed key: one school per deployment, one settings
804/// row.
805pub const SETTINGS_KEY: &str = "school";
806
807/// A fixed password whose hash is the login decoy (see
808/// [`crate::domain::user::PasswordHash::verify_decoy`]). Not a secret — it
809/// never matches a real account.
810pub const DECOY_PASSWORD: &str = "decoy-password-not-a-secret";
811
812/// The `error_code` a stale `pending` chatbot row presents as. Distinct from
813/// the boot sweep's `interrupted`: this one was never repaired, only projected.
814pub const STALE_ERROR_CODE: &str = "timed_out";
815
816/// Ceiling on a stored `error_code`. Codes are short slugs, but one arrives
817/// from an out-of-process AI service — a trust boundary — so it is trimmed
818/// rather than trusted.
819pub const MAX_ERROR_CODE_LEN: usize = 64;
820
821/// Replacements applied *after* lowercasing, in order. One table, two
822/// consumers ([`crate::domain::text_fold::search_fold`] and
823/// [`crate::domain::text_fold::search_fold_sql`]): the needle and the column
824/// are folded by the same rules by construction, which is the whole point.
825pub const TEXT_FOLD_REPLACEMENTS: &[(&str, &str)] = &[
826 ("\u{307}", ""), // combining dot above, left behind by İ → i̇
827 ("ı", "i"),
828 ("ş", "s"),
829 ("ğ", "g"),
830 ("ç", "c"),
831 ("ö", "o"),
832 ("ü", "u"),
833 ("â", "a"),
834 ("î", "i"),
835 ("û", "u"),
836];
837
838// --- response shaping --------------------------------------------------
839
840/// Bodies larger than this are streamed through without buffering — JSON pages
841/// sit far below it, so the cap only bounds worst-case memory. A response whose
842/// `Content-Length` exceeds it (or is absent, i.e. a stream) skips the ETag
843/// middleware.
844pub const MAX_ETAG_BODY_BYTES: u64 = 1 << 20; // 1 MiB
845
846/// How many `delta` events a completed chatbot answer is cut into, and the
847/// shortest chunk worth emitting.
848pub const REPLY_CHUNKS: usize = 8;
849pub const MIN_CHUNK_CHARS: usize = 24;
850
851// --- query text --------------------------------------------------------
852
853/// The whole of [`crate::domain::bank_question::BankQuestion::usage_counts`]:
854/// **one** statement (no `;`), so a page of templates costs one round trip no
855/// matter how long it is. Named so a test can assert that, since a per-row
856/// `count()` is exactly the N+1 this page was cleaned of once.
857pub const USAGE_COUNTS_SQL: &str =
858 "SELECT from_bank, count() AS n FROM exam_question WHERE from_bank IN $ids GROUP BY from_bank";
859
860// --- database tables ---------------------------------------------------
861
862pub const USER_TABLE: &str = "user";
863pub const SESSION_TABLE: &str = "session";
864pub const NOTE_TABLE: &str = "note";
865pub const MESSAGE_TABLE: &str = "message";
866pub const NOTE_FILE_TABLE: &str = "note_file";
867pub const COURSE_NOTE_TABLE: &str = "course_note";
868pub const COURSE_NOTE_FILE_TABLE: &str = "course_note_file";
869pub const RAG_OUTPUT_TABLE: &str = "rag_output";
870pub const EVENT_TABLE: &str = "event";
871pub const ATTENDANCE_TABLE: &str = "attendance";
872pub const REGISTRATION_TABLE: &str = "registration";
873pub const EXAM_TABLE: &str = "exam";
874pub const EXAM_RESULT_TABLE: &str = "exam_result";
875pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt";
876pub const EXAM_QUESTION_TABLE: &str = "exam_question";
877pub const QUESTION_IMAGE_TABLE: &str = "question_image";
878pub const EXAM_ANSWER_TABLE: &str = "exam_answer";
879pub const ANSWER_IMAGE_TABLE: &str = "answer_image";
880pub const BANK_QUESTION_TABLE: &str = "bank_question";
881pub const BANK_QUESTION_IMAGE_TABLE: &str = "bank_question_image";
882pub const COURSE_TABLE: &str = "course";
883pub const ENROLLMENT_TABLE: &str = "enrollment";
884pub const CLASS_GROUP_TABLE: &str = "class_group";
885pub const CLASS_MEMBER_TABLE: &str = "class_member";
886pub const CLASS_COURSE_TABLE: &str = "class_course";
887pub const CLASS_BLUEPRINT_TABLE: &str = "class_blueprint";
888pub const PARENT_LINK_TABLE: &str = "parent_link";
889pub const COURSE_SESSION_TABLE: &str = "course_session";
890pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance";
891pub const WORK_ENTRY_TABLE: &str = "work_entry";
892pub const POMODORO_SESSION_TABLE: &str = "pomodoro_session";
893pub const SETTINGS_TABLE: &str = "settings";
894pub const TERM_TABLE: &str = "term";
895pub const SUBJECT_TABLE: &str = "subject";
896pub const POOL_QUESTION_TABLE: &str = "pool_question";
897pub const SOLUTION_TABLE: &str = "solution";
898pub const HOMEWORK_TABLE: &str = "homework";
899pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission";
900pub const HOMEWORK_FILE_TABLE: &str = "homework_file";
901pub const HOMEWORK_RESULT_TABLE: &str = "homework_result";
902pub const CHATBOT_THREAD_TABLE: &str = "chatbot_thread";
903pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message";
904pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";
905pub const APPOINTMENT_TABLE: &str = "appointment";
906pub const MENU_TABLE: &str = "menu";
907pub const MENU_DISH_TABLE: &str = "menu_dish";
908pub const DIETARY_PROFILE_TABLE: &str = "dietary_profile";
909pub const MEAL_BOOKING_TABLE: &str = "meal_booking";
910pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";
911pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
912pub const FEE_PLAN_TABLE: &str = "fee_plan";
913pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";
914pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";
915pub const BOARD_TABLE: &str = "board";
916pub const BOARD_STROKE_TABLE: &str = "board_stroke";
917/// One row per badge a user has earned, keyed by the pair. A table of its own
918/// rather than an array column on the user row: an `array<…>` there breaks
919/// every `PATCH` of that row, and awards are append-only facts with their own
920/// timestamp (see [`crate::domain::badge`]).
921pub const BADGE_AWARD_TABLE: &str = "badge_award";
922/// One row per *name* the school's settings offer, keyed by the name itself:
923/// how many rows still reference it, and whether it has been retired out of the
924/// list (see the reference counters in [`crate::db::cap`]).
925pub const KIND_REF_TABLE: &str = "kind_ref";
926pub const SLOT_REF_TABLE: &str = "slot_ref";
927
928// --- stored cap counters -------------------------------------------------
929
930/// The counter columns behind the count caps (see [`crate::db::cap`]).
931/// Each one lives on the *parent* row, because a single-record conditional
932/// `UPDATE` is the only guard a concurrent writer cannot outrun (a lock is
933/// released around the round trip). Spelled here rather than at the call site
934/// so the field a claim
935/// increments and the field a delete decrements cannot drift apart; the
936/// definitions themselves are in `MIGRATION`, and a typo there is caught by
937/// SCHEMAFULL refusing the write.
938pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count";
939pub const REGISTRATION_COUNT_FIELD: &str = "registration_count";
940/// Not a cap — a refcount, and the whole of the term delete guard: how many
941/// courses link this term. A term may only be dropped at zero, and the count
942/// is claimed before a course's link is written, so the two decisions contend
943/// on the term row instead of on a cross-table `SELECT` no transaction orders.
944pub const COURSE_COUNT_FIELD: &str = "course_count";
945/// The two refcounts on a class row: how many students it holds and how many
946/// courses it is attached to. A class may only be dropped at zero on both.
947pub const CLASS_MEMBER_COUNT_FIELD: &str = "class_member_count";
948pub const CLASS_COURSE_COUNT_FIELD: &str = "class_course_count";
949/// Classes linking a term, the second half of the term delete guard. Deliberately
950/// *not* `COURSE_COUNT_FIELD`: boot recounts that one from the course rows alone,
951/// so a class claiming into it would be wiped on the next migration.
952pub const TERM_CLASS_COUNT_FIELD: &str = "class_count";
953/// A refcount too, and the whole of the fee-plan edit *and* delete guard: how
954/// many students are on this plan. A plan may only be edited or deleted at
955/// zero, and the count is claimed in the same transaction as the assignment
956/// row, so a manager's edit and a concurrent assign contend on the plan row
957/// rather than on a `SELECT` the edit had already outrun. Nothing ever
958/// releases it — an assignment is never unassigned, because the charges it
959/// raised are history.
960pub const FEE_PLAN_ASSIGNMENT_COUNT_FIELD: &str = "assignment_count";
961/// The condition itself, spelled once: a plan is editable and deletable
962/// exactly while nobody is on it. The `??` is parenthesized on purpose —
963/// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every*
964/// row and would license editing a plan a family is already being billed for.
965pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0";
966pub const NOTE_FILE_COUNT_FIELD: &str = "file_count";
967pub const COURSE_NOTE_FILE_COUNT_FIELD: &str = "file_count";
968pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
969pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
970/// The column a *grant* claim moves and puts back, so its transaction writes
971/// the holder's own `user` record — the one key
972/// [`crate::service::user::set_role`] writes (see
973/// [`crate::db::cap::role_claim`]). Any `option<int>` on the row would do:
974/// the claim nets zero and never reads it, so this is an alias rather than a
975/// column of its own — a new one would mean a migration on a SCHEMAFULL table
976/// for a value nothing ever observes.
977pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD;
978/// How many boards this user created, on the user row — the same per-user shape
979/// as `CHATBOT_THREAD_COUNT_FIELD`, capped at `MAX_BOARDS_PER_CREATOR`. It is
980/// what closes the "open another board" way around the two board counters
981/// below; released when a board is deleted.
982pub const USER_BOARD_COUNT_FIELD: &str = "board_count";
983/// The lifetime totals behind the badges, all on the user row. Not caps: each
984/// one counts something the person *did*. A counter comes down in exactly one
985/// shape, and the two cases that qualify share a reason: the account credited
986/// is the account that can delete what earned it, so a strictly monotonic
987/// counter is a farm. A student withdrawing their own submission gives the two
988/// homework counters back (else one homework becomes fifty by
989/// submit/delete/submit), and a teacher un-grading gives back
990/// `MARKS_GIVEN` — with `HIGH_MARK` on the exam side, credited to the student
991/// by the same act (else one exam becomes fifty by grade/ungrade/regrade).
992/// The exam and pomodoro totals never decrease at all, and each earns that by
993/// counting something a repeat cannot re-earn rather than by anyone's restraint:
994/// `EXAM_SAT_TOTAL` counts *exams sat*, moving only on a student's first sitting
995/// of an exam (`seq == 1`), because retakes are a loop the student drives alone —
996/// an open exam with unlimited attempts is start/finish/start, no teacher in it —
997/// and a stint is a span of time that has to be lived through to be finished.
998/// Nothing else decrements: the cascades (an exam, a homework or
999/// a course delete, which do take the attempt and result rows with them) leave
1000/// them alone, since history a teacher erased is still history the student
1001/// lived. A badge already earned is never taken back either, whatever a counter
1002/// does afterwards — [`crate::domain::badge`] only ever adds award rows. Floored
1003/// at zero, and absent means zero: an account older than the columns reads
1004/// exactly like a fresh one.
1005//
1006// corner-cut: that cascade ruling is also the farm's long way round — delete the
1007// *exam* instead of the mark and the credit stands, so the loop still climbs,
1008// at a couple of requests a point rather than two. Closing it means
1009// `Exam::delete`, `Homework::delete` and `Course::delete` refunding per swept
1010// row the way `ExamResult::remove` now does, which is a policy call (a course
1011// delete would then have to walk every mark it drops) rather than an oversight.
1012pub const HOMEWORK_SUBMITTED_TOTAL_FIELD: &str = "homework_submitted_total";
1013pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total";
1014pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total";
1015pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total";
1016pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total";
1017/// The bookkeeping behind the counted-stint rule below: which UTC day the
1018/// student last had a stint counted on, and how many counted that day. Internal
1019/// state like the two streak columns — no badge reads either, `/limits` names
1020/// neither, no profile key serves them. The day rolls the tally back to zero.
1021pub const POMODORO_COUNTED_DAY_FIELD: &str = "pomodoro_counted_day";
1022pub const POMODORO_COUNTED_TODAY_FIELD: &str = "pomodoro_counted_today";
1023/// What makes a finished stint *count* towards `pomodoro_finished_total` and
1024/// `pomodoro_focus_ms_total` (and towards the study streak): it must have run at
1025/// least this long, and it must be within the day's quota.
1026///
1027/// Without them the pair is the farm [`crate::domain::pool_question::PoolQuestion::approve`]
1028/// reasons about from the other end: `finish` is self-service, a stint costs two
1029/// requests and no second person, so a counter moved once per round-trip is
1030/// farmable — 200 pairs in a minute and a half bought `pomodoro_finished_200`,
1031/// permanently, since a badge is never revoked.
1032///
1033/// Five minutes is well under a conventional 25-minute pomodoro on purpose: a
1034/// student who breaks off early still focused, and the counter should not
1035/// punish that. It is four orders of magnitude above a scripted round-trip,
1036/// which is the whole distance that matters — the cheat now costs the wall
1037/// clock it claims. Sixteen a day is likewise above any honest school day
1038/// (sixteen full pomodoros is over six hours of pure focus) while capping the
1039/// minimum-length farm at eighty minutes of real waiting per day, so
1040/// `pomodoro_finished_200` takes at least thirteen calendar days to buy instead
1041/// of ninety seconds. Both are read `>=`/`<`, i.e. a stint of exactly the
1042/// minimum counts and the sixteenth of the day counts.
1043pub const MIN_COUNTED_POMODORO_MS: i64 = 300_000;
1044pub const MAX_COUNTED_POMODORO_PER_DAY: i64 = 16;
1045/// The staff-side and second student-side totals, same shape and same rules:
1046/// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and
1047/// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the
1048/// approvals a teacher hands out and `POOL_PUBLISHED` the questions whose
1049/// author got approved — credited at approval, which is why the name says
1050/// published rather than asked.
1051pub const MARKS_GIVEN_TOTAL_FIELD: &str = "marks_given_total";
1052pub const LESSONS_HELD_TOTAL_FIELD: &str = "lessons_held_total";
1053pub const POOL_APPROVED_TOTAL_FIELD: &str = "pool_approved_total";
1054pub const POOL_PUBLISHED_TOTAL_FIELD: &str = "pool_published_total";
1055pub const LESSONS_ATTENDED_TOTAL_FIELD: &str = "lessons_attended_total";
1056pub const HIGH_MARK_TOTAL_FIELD: &str = "high_mark_total";
1057/// The longest run of consecutive days the student has studied, and the two
1058/// bookkeeping columns the write site needs to compute it: the run in progress
1059/// and the last day counted (both plain day numbers, midnight UTC — the same
1060/// boundary every other day calculation here uses).
1061///
1062/// Only the longest is a badge counter: it never comes down, which is what
1063/// keeps it on the ordinary `>=` rule with no second catalog shape. The other
1064/// two are internal state — no badge reads them, `/limits` never names them,
1065/// and no profile key serves them.
1066pub const STUDY_STREAK_LONGEST_FIELD: &str = "study_streak_longest";
1067pub const STUDY_STREAK_CURRENT_FIELD: &str = "study_streak_current";
1068pub const STUDY_STREAK_LAST_DAY_FIELD: &str = "study_streak_last_day";
1069/// When a lesson was first counted towards its teacher's `lessons_held_total`,
1070/// stamped on the `course_session` row by the first roll call taken for it.
1071/// Bookkeeping like the two streak columns above: no badge reads it, `/limits`
1072/// never names it, no profile key serves it. Its only job is the once-per-
1073/// session guard — a lesson is credited when it is *taken*, and the thirtieth
1074/// student marked must credit nothing further.
1075pub const LESSON_COUNTED_AT_FIELD: &str = "held_counted_at";
1076/// What counts as a high mark, out of `MAX_MARK`. Hardcoded next to the badge
1077/// thresholds rather than read from the school's grade bands: those are
1078/// renameable display labels, and a badge id must never depend on a value a
1079/// school can change at runtime — `high_mark_10` has to mean the same thing in
1080/// every deployment, forever.
1081pub const HIGH_MARK_MIN: i64 = 90;
1082
1083/// The badge catalog: every badge the system can award, as
1084/// `(id, the counter it reads, the value that earns it)`. Hardcoded on
1085/// purpose — moving a threshold is a deploy, which is what keeps
1086/// [`crate::domain::badge::earned`] a pure function of the stats and makes the
1087/// rules reviewable in a diff instead of editable in a settings row.
1088///
1089/// The ids are the API: the frontend maps them to a label and an icon, and an
1090/// award row stores one forever. So an id is never reused for a different
1091/// meaning; retiring one is done by deleting the line, and the awards that
1092/// carry it simply stop being served (no data migration —
1093/// [`crate::db::badge::list_for`] filters to the live
1094/// catalog).
1095pub const BADGES: [(&str, BadgeStat, i64); 34] = [
1096 ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1),
1097 ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10),
1098 ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50),
1099 ("homework_on_time_10", BadgeStat::HomeworkOnTime, 10),
1100 ("homework_on_time_25", BadgeStat::HomeworkOnTime, 25),
1101 ("exam_sat_1", BadgeStat::ExamSat, 1),
1102 ("exam_sat_10", BadgeStat::ExamSat, 10),
1103 ("exam_sat_25", BadgeStat::ExamSat, 25),
1104 ("pomodoro_finished_10", BadgeStat::PomodoroFinished, 10),
1105 ("pomodoro_finished_50", BadgeStat::PomodoroFinished, 50),
1106 ("pomodoro_finished_200", BadgeStat::PomodoroFinished, 200),
1107 // Ten and fifty hours of focus, in the milliseconds the counter stores.
1108 (
1109 "pomodoro_focus_ms_36000000",
1110 BadgeStat::PomodoroFocusMs,
1111 36_000_000,
1112 ),
1113 (
1114 "pomodoro_focus_ms_180000000",
1115 BadgeStat::PomodoroFocusMs,
1116 180_000_000,
1117 ),
1118 ("marks_given_10", BadgeStat::MarksGiven, 10),
1119 ("marks_given_50", BadgeStat::MarksGiven, 50),
1120 ("marks_given_250", BadgeStat::MarksGiven, 250),
1121 ("lessons_held_10", BadgeStat::LessonsHeld, 10),
1122 ("lessons_held_50", BadgeStat::LessonsHeld, 50),
1123 ("lessons_held_200", BadgeStat::LessonsHeld, 200),
1124 ("pool_approved_5", BadgeStat::PoolApproved, 5),
1125 ("pool_approved_25", BadgeStat::PoolApproved, 25),
1126 ("pool_approved_100", BadgeStat::PoolApproved, 100),
1127 ("pool_published_1", BadgeStat::PoolPublished, 1),
1128 ("pool_published_10", BadgeStat::PoolPublished, 10),
1129 ("pool_published_50", BadgeStat::PoolPublished, 50),
1130 ("lessons_attended_10", BadgeStat::LessonsAttended, 10),
1131 ("lessons_attended_50", BadgeStat::LessonsAttended, 50),
1132 ("lessons_attended_200", BadgeStat::LessonsAttended, 200),
1133 // Exam marks at or above `HIGH_MARK_MIN`, counted per graded sitting.
1134 ("high_mark_1", BadgeStat::HighMark, 1),
1135 ("high_mark_10", BadgeStat::HighMark, 10),
1136 ("high_mark_25", BadgeStat::HighMark, 25),
1137 // Consecutive study days, read off the longest run ever held — so these
1138 // are earned once and never lost when the run breaks.
1139 ("study_streak_3", BadgeStat::StudyStreak, 3),
1140 ("study_streak_7", BadgeStat::StudyStreak, 7),
1141 ("study_streak_30", BadgeStat::StudyStreak, 30),
1142];
1143/// The two stroke counters on a board row. `epoch_stroke_count` is reset to
1144/// zero by a clear and capped at `MAX_EPOCH_STROKES` — a full epoch is
1145/// recoverable. `total_stroke_count` is never reset and capped at
1146/// `MAX_BOARD_STROKES`; reaching it stamps `closed_at`, and a closed board is
1147/// read-only for good. Both are claimed in the same conditional write as the
1148/// stroke row, so two people drawing at once contend on the board record rather
1149/// than on a `SELECT count()` either of them can outrun.
1150pub const BOARD_EPOCH_STROKE_COUNT_FIELD: &str = "epoch_stroke_count";
1151pub const BOARD_TOTAL_STROKE_COUNT_FIELD: &str = "total_stroke_count";
1152/// Cap 1, not N: an appointment slot holds at most one live booking, so this
1153/// counter is really an "is it taken" flag kept in the shape every other cap
1154/// uses (`claim`/`release`), which is what makes rejecting or cancelling a
1155/// booking give the slot back.
1156pub const SLOT_OCCUPIED_FIELD: &str = "occupied";
1157/// Not caps either, and uncapped by design: how many exam questions and how
1158/// many homework still point at a subject. A subject may be deleted exactly
1159/// while both read zero, so the delete's own `WHERE` decides it — the
1160/// cross-table "does anything reference this?" count it replaces was already
1161/// stale when the delete landed.
1162pub const SUBJECT_QUESTION_COUNT_FIELD: &str = "exam_question_count";
1163pub const SUBJECT_HOMEWORK_COUNT_FIELD: &str = "homework_count";
1164/// How many marks an exam carries. Uncapped too, and the only counter its
1165/// entity carries as a field: the exam's save is a whole-row `CONTENT` write,
1166/// which would wipe a column the struct did not know about. That save pins it,
1167/// which is what makes "this exam has no marks" — the gate a kind change is
1168/// refused on — decided at write time rather than at read time.
1169pub const EXAM_RESULT_COUNT_FIELD: &str = "result_count";
1170/// The two columns of a reference-counter row (`kind_ref`, `slot_ref`): how
1171/// many rows still point at the name, and whether it has left the school's
1172/// list. Both `option<…>`, absent meaning zero references and in service.
1173pub const REF_COUNT_FIELD: &str = "count";
1174pub const REF_RETIRED_FIELD: &str = "retired";
1175/// Seats held on one menu — the meal capacity cap.
1176pub const MENU_SEAT_COUNT_FIELD: &str = "seats_booked";
1177/// Not a cap: the menu's revision, bumped by every write that can change what
1178/// a seat costs (a dish added, re-priced or removed, the capacity moved). A
1179/// booking claims its seat only at the revision it read the price at, so the
1180/// price frozen onto the row is one the menu really carried at that instant.
1181pub const MENU_VERSION_FIELD: &str = "version";
1182
1183/// Not a cap either: the grade that froze a homework submission, absent while
1184/// the submission is still open. Every student-side write to a submission (its
1185/// text, its files) carries `graded_by_result = NONE` as a condition, so the
1186/// "not graded yet" decision and the write it licenses are one conditional
1187/// single-record write rather than a cross-table read a concurrent grade can
1188/// outrun. Set by grading, cleared by un-grading, never by the student.
1189pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";
1190/// The condition itself, spelled once: a submission is writable exactly while
1191/// its grade stamp is absent.
1192pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE";
1193/// The same idea for a whiteboard, spelled once: a board accepts strokes
1194/// exactly while the creator has not locked it and it has not closed itself on
1195/// `MAX_BOARD_STROKES`. Every stroke write carries it, so "is this board still
1196/// open" and the write it licenses are one conditional single-record write —
1197/// a lock landing mid-draw beats the stroke instead of racing it.
1198pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE";
1199/// A signup list has **frozen**: the event takes registrations at all *and* it
1200/// started, or — for an ends_at-only event (a pure signup deadline) — that end
1201/// passed. A timeless event never freezes. Matched against `$now` in millis, on
1202/// an `event` row.
1203///
1204/// This is `Event::registration_capacity`'s `Conflict` arm re-spelled in
1205/// SurrealQL, because the role cascade (`service::user::set_role`) frees a demoted
1206/// parent's seats *inside* its transaction and cannot call Rust from there. The
1207/// audience conjunct is what keeps it that arm and only that arm: an event that
1208/// takes no registrations is refused earlier, by the `Validation` arm, so a
1209/// stray row on one is deleted rather than frozen — which is what the pre-fold
1210/// sweep did, and dropping the conjunct would silently change it. Two spellings
1211/// of one rule is a drift risk, so it is spelled once here and
1212/// `event::tests::the_sql_freeze_guard_matches_the_rust_one` fails the suite the
1213/// day the two disagree.
1214pub const REGISTRATION_FROZEN_GUARD: &str = "audience.kind = 'registration' \
1215 AND (starts_at ?? ends_at) != NONE AND (starts_at ?? ends_at) <= $now";
1216
1217/// How hard a counter write tries before giving up, and the first backoff step
1218/// it sleeps between attempts (doubling, plus jitter). Contention on one record
1219/// is the guard working as designed, and SurrealDB answers it by aborting the
1220/// loser's transaction — so these two numbers are what turn "retry the
1221/// transaction" into a queue. Sized for one HTTP burst of racers on a single
1222/// parent: seven doublings from 2ms is a quarter of a second of patience.
1223pub const CAP_WRITE_TRIES: usize = 8;
1224pub const CAP_WRITE_BACKOFF_MS: u64 = 2;