forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

constant.rs1190 lines, 61.4 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/// Ceiling on a single HTTP request. Backstop for requests that reached the
418/// database in the window between the socket dying and the keepalive noticing:
419/// without it they park until the database returns, which can be hours.
420/// Generous enough not to clip a legitimate slow upload at `max_file_bytes`.
421pub const REQUEST_TIMEOUT_SECS: u64 = 30;
422
423/// The longest caller-supplied `x-request-id` header the server will carry.
424///
425/// The id lands on `http.request.id` of every span, so anything a client puts
426/// there it can export: free text and unbounded cardinality both. A header
427/// longer than this (or one carrying anything outside `[A-Za-z0-9._-]`) is
428/// dropped and a UUID minted in its place — the request still succeeds, it
429/// just stops being correlatable by the caller's own id, which is exactly why
430/// a client needs to know the bound.
431pub const MAX_REQUEST_ID_LEN: usize = 64;
432
433/// Backoff ceiling for the boot connection retry. The database is usually a
434/// sibling container coming up in parallel, so the first attempts fail; the
435/// process retries forever rather than exiting, because exiting turns a
436/// few-second wait into a container restart loop that outruns its budget and
437/// stays down.
438pub const DB_CONNECT_BACKOFF_MAX_SECS: u64 = 5;
439
440/// Cadence of the `state` ticks on the student exam-room WebSocket
441/// (`GET /exams/{id}/attempt/ws`).
442pub const EXAM_WS_TICK_SECS: u64 = 2;
443
444/// Cadence of the keepalive ticks on the whiteboard-room WebSocket. Slower than
445/// the exam room's, because a board room carries no countdown a client renders
446/// against — the tick only keeps an idle socket from being reaped.
447pub const BOARD_WS_TICK_SECS: u64 = 15;
448
449/// How many strokes one replay message carries when a socket joins. The join
450/// replays the current epoch, which is `MAX_EPOCH_STROKES` at worst, so it is
451/// sent in batches rather than as one frame that could reach the WebSocket
452/// frame limit on a busy board.
453pub const BOARD_REPLAY_CHUNK: usize = 200;
454
455/// Depth of one board room's fan-out channel: how far a slow socket may lag the
456/// strokes being drawn before it is dropped and has to rejoin (which replays
457/// the epoch from storage anyway, so nothing is lost by the drop).
458pub const BOARD_HUB_CAPACITY: usize = 256;
459
460/// Ceiling on a `question_id` arriving on the exam-room WebSocket. The field is
461/// a record key — a 26-char ULID in every real payload — not free text, so this
462/// is generous by a factor of two and change. The cap exists because the
463/// per-question error frame *echoes* the id back: axum's default WebSocket
464/// frame limit is 64 MiB, so without it a client can make its own room reflect
465/// that whole payload. Rejected before any database work, and unattributed — an
466/// unusable id names no question, so nothing of it is sent back.
467pub const MAX_QUESTION_ID_LEN: usize = 64;
468
469/// The only accepted question kinds. `choice`: pick one of the listed
470/// choices, auto-scorable. `text`: free text, judged by the grader.
471pub const QUESTION_KINDS: [&str; 2] = ["choice", "text"];
472
473pub const MAX_QUESTION_TEXT_LEN: usize = 2_000;
474
475/// Inclusive bounds for a question's points (its share of the auto-score).
476pub const MIN_QUESTION_POINTS: i64 = 1;
477pub const MAX_QUESTION_POINTS: i64 = 100;
478
479/// Bounds for a choice question's option list and each option's text.
480pub const MIN_QUESTION_CHOICES: usize = 2;
481pub const MAX_QUESTION_CHOICES: usize = 10;
482pub const MAX_CHOICE_TEXT_LEN: usize = 500;
483
484pub const MAX_ANSWER_TEXT_LEN: usize = 10_000;
485
486/// Inclusive bounds for an exam mark.
487pub const MIN_MARK: i64 = 0;
488pub const MAX_MARK: i64 = 100;
489
490/// Inclusive bounds for an exam kind's weight in the course average. The
491/// minimum of 1 keeps every graded exam counted and the average's denominator
492/// non-zero.
493pub const MIN_EXAM_KIND_WEIGHT: i64 = 1;
494pub const MAX_EXAM_KIND_WEIGHT: i64 = 100;
495
496pub const SESSION_DURATION_DAYS: i64 = 7;
497
498/// How far in the past a request-supplied schedule instant (exam window,
499/// lesson, event time) may lie before it is rejected as backdated. The grace
500/// absorbs request latency and modest client-clock skew — a "starts now"
501/// submission must survive its own round trip — while still refusing
502/// genuinely past deadlines.
503pub const SCHEDULE_PAST_GRACE_MS: i64 = 60 * 1000;
504
505/// Upper bound on a list endpoint's `limit` page-size parameter. Omitting
506/// `limit` returns every (remaining) row; when supplied it must be
507/// `1..=MAX_PAGE_LIMIT`. The `#[param(maximum = ...)]` and the "1 and 500"
508/// wording in `web::page` mirror this literal — keep them in step.
509pub const MAX_PAGE_LIMIT: i64 = 500;
510
511/// Wire-protocol identifier for the AI bridge, sent in [`crate::ai::protocol::Hello`]
512/// and used as the QUIC ALPN. Bump both together on a breaking frame change:
513/// ALPN mismatch rejects an old service at the TLS handshake, before it can
514/// send a frame we would misparse.
515pub const AI_PROTOCOL: &str = "hab/2";
516pub const AI_ALPN: &[u8] = b"hab/2";
517
518/// Hard ceiling on one AI-bridge frame. Checked against the length prefix
519/// before the body buffer is allocated. Generous because a payload may carry a
520/// base64 question image, but bounded so a bad length cannot exhaust memory.
521pub const AI_MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
522
523/// Default wait for one AI request before the stream is abandoned
524/// (`AI_REQUEST_TIMEOUT_SECS`). Model inference is slow, so this is far longer
525/// than [`REQUEST_TIMEOUT_SECS`] — AI calls must not sit on an HTTP request
526/// path that the outer timeout would kill first.
527pub const AI_DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 30;
528
529/// Upper bound on a worker's self-declared `max_concurrent`, and the value
530/// used when it declares none. A worker that claims a huge number would let
531/// the registry pile every request onto one service.
532pub const AI_MAX_CONCURRENT_PER_WORKER: usize = 64;
533pub const AI_DEFAULT_CONCURRENT_PER_WORKER: usize = 8;
534
535/// QUIC idle timeout and keepalive for a service connection. The keepalive is
536/// well under the idle timeout so an idle-but-healthy service is never dropped
537/// for being quiet; a service that actually died is deregistered within the
538/// idle window without any application-level heartbeat frame.
539pub const AI_IDLE_TIMEOUT_SECS: u64 = 30;
540pub const AI_KEEPALIVE_SECS: u64 = 10;
541
542/// How long a blob body may make *no* progress before its stream is reset.
543/// A STALL bound, not a transfer cap: the clock is per write, so a slow peer
544/// that keeps reading streams a whole `max_file_bytes` file for as long as it
545/// takes, while a service that opens a blob stream and never reads it stops
546/// pinning a task and an open file descriptor once the QUIC stream window
547/// fills. A wall-clock deadline on the transfer could not tell the two apart.
548pub const AI_BLOB_WRITE_STALL_SECS: u64 = 30;
549
550/// The capability an AI service declares to answer chatbot turns. The bridge
551/// routes a chat request to any worker carrying it; with none registered the
552/// chat endpoints report the service as unavailable.
553pub const AI_CHAT_CAPABILITY: &str = "chat.reply";
554
555/// The capability an AI service declares to index a course note for retrieval.
556/// The backend dispatches on it after a note (or one of its files) changes;
557/// with no worker carrying it the trigger is a silent no-op — indexing is a
558/// bonus on top of the note, never a condition of storing one.
559pub const AI_RAG_INDEX_CAPABILITY: &str = "rag.index";
560
561/// Deadline on one `rag.index` round trip. Longer than a chat turn
562/// ([`AI_DEFAULT_REQUEST_TIMEOUT_SECS`]): chunking and embedding a note with
563/// ten attachments is batch work, and nobody is waiting on it — the dispatch
564/// is fire-and-forget, off the HTTP request path.
565pub const AI_RAG_INDEX_TIMEOUT_SECS: u64 = 120;
566
567/// Hard ceiling on one chat message's characters — the newtype bound, above
568/// which no school setting can reach. Sized for a pasted question with its
569/// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.
570pub const MAX_CHATBOT_MESSAGE_LEN: usize = 8_000;
571
572/// The school-adjustable per-message character cap (`max_chatbot_message_len` in
573/// settings): its default and the inclusive range a manager may set. The
574/// ceiling is [`MAX_CHATBOT_MESSAGE_LEN`] — a longer prompt costs the AI service
575/// context it needs for the history.
576pub const DEFAULT_MAX_CHATBOT_MESSAGE_LEN: i64 = 4_000;
577pub const MIN_MAX_CHATBOT_MESSAGE_LEN: i64 = 100;
578pub const MAX_MAX_CHATBOT_MESSAGE_LEN: i64 = MAX_CHATBOT_MESSAGE_LEN as i64;
579
580/// Bound on a chat thread's display name. A thread is named by hand or not at
581/// all — nothing auto-titles one — so this only has to fit a line a user typed.
582pub const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200;
583
584/// How many prior user/assistant turns of a thread are replayed to the
585/// AI service as context (`chatbot_history_turns` in settings): its default and
586/// the inclusive range a manager may set. Every turn is re-sent on every
587/// request, so the ceiling bounds both the frame size and the inference cost.
588pub const DEFAULT_CHATBOT_HISTORY_TURNS: i64 = 10;
589pub const MIN_CHATBOT_HISTORY_TURNS: i64 = 1;
590pub const MAX_CHATBOT_HISTORY_TURNS: i64 = 50;
591
592/// How many threads one user may keep (`max_chatbot_threads` in
593/// settings): its default and the inclusive range a manager may set. Reached,
594/// the user deletes an old thread before starting a new one — the cap is
595/// storage protection, not a usage quota.
596pub const DEFAULT_MAX_CHATBOT_THREADS: i64 = 50;
597pub const MIN_MAX_CHATBOT_THREADS: i64 = 1;
598pub const MAX_MAX_CHATBOT_THREADS: i64 = 500;
599
600/// How often the chat stream re-reads a `pending` assistant message while it
601/// waits for the answer. The reply lands in the database from whichever task
602/// owns the bridge stream, so the reader polls rather than sharing state.
603pub const CHAT_STREAM_POLL_MS: u64 = 200;
604
605/// How long an assistant message may sit `pending` before a reader gives up on
606/// it and reports it failed. Comfortably past
607/// [`AI_DEFAULT_REQUEST_TIMEOUT_SECS`] (which `AI_REQUEST_TIMEOUT_SECS` may
608/// raise), because the answering task normally stamps the failure itself —
609/// this only catches the row whose task died with the process.
610pub const CHATBOT_PENDING_STALE_SECS: i64 = 300;
611
612/// The largest per-request AI deadline a deployment may configure
613/// (`AI_REQUEST_TIMEOUT_SECS`). Anything above it is clamped down to it at
614/// startup, loudly — see [`crate::config`].
615///
616/// A sanity ceiling, well under [`CHATBOT_PENDING_STALE_SECS`]: a reply that
617/// arrives after the staleness window is discarded by the read-time
618/// projection, so a deadline anywhere near it could never produce an answer a
619/// user sees — it would only hold a task and a worker slot open for nothing.
620/// A school that genuinely needs longer raises this and the staleness window
621/// together.
622pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = 60;
623
624/// How long a dialling AI service has to complete its `Hello`/`Welcome`
625/// exchange before the connection is dropped. Short: the handshake is one
626/// frame each way, and an unauthenticated connection must not be able to
627/// occupy the listener indefinitely.
628pub const AI_HANDSHAKE_TIMEOUT_SECS: u64 = 10;
629
630/// The only REST paths an AI service may read over the bridge — deny-by-default,
631/// matched segment-wise by [`crate::ai::api`] with `{x}` standing for exactly
632/// one segment. This list *is* the services' access scope, so it is a service
633/// contract documented in `README.md`, not a tunable published at `/limits`
634/// (string arrays are exempt from that completeness gate).
635///
636/// JSON-only, and only what a study-companion needs: who the user is, their
637/// notes, their course's notes, their homework, and their own progress reports.
638/// Byte-serving routes
639/// (note files, submission files, avatars, question images) are left out — the
640/// frames carry JSON, and a blob has no business crossing this seam yet.
641pub const AI_API_ALLOWLIST: &[&str] = &[
642 "/auth/me",
643 "/users/me/profile",
644 "/users/{id}/profile",
645 "/notes",
646 "/notes/{id}",
647 "/course-notes",
648 "/course-notes/{id}",
649 "/course-notes/{id}/files",
650 "/homework",
651 "/homework/{id}",
652 "/homework/{id}/result",
653 "/homework/{id}/submission",
654 "/homework/report/{user}",
655 "/marks/me",
656 "/marks/{user}",
657 "/attendance/me",
658 "/attendance/{user}",
659 "/pomodoro/me",
660 "/pomodoro/{user}",
661];
662
663// --- rate limiting -----------------------------------------------------
664
665/// Default requests-per-minute-per-IP for `/auth/login` + `/auth/register`.
666pub const DEFAULT_AUTH_RATE_LIMIT: u32 = 10;
667/// Default requests-per-minute-per-IP across the whole API.
668pub const DEFAULT_API_RATE_LIMIT: u32 = 300;
669/// Default chatbot messages per minute *per user*. Sits far above a human
670/// typing while still blunting a scripted fan-out at the AI service behind the
671/// bridge — which is the cost this tier rations, not this process.
672pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20;
673
674/// Once the bucket map holds this many distinct clients, a new key sweeps out
675/// the expired entries and, if that frees nothing, evicts the least-spent live
676/// buckets — **never an exhausted one** — down to three quarters of this.
677/// Evicting a bucket that had reached its limit would hand back the very
678/// refusal it was enforcing, so a flood cannot make the limiter fail open; the
679/// concession is that while the map is saturated with exhausted buckets a
680/// never-before-seen client gets no bucket of its own and is metered against
681/// the one shared [`RATE_LIMIT_OVERFLOW_MAX`] budget instead — so newcomers
682/// during a flood can be refused, while every client already in the map keeps
683/// its own counter untouched. Keeps memory bounded without a reaper task.
684pub const PURGE_AT: usize = 10_000;
685
686/// Requests per window every client that finds the bucket map saturated shares
687/// between them — one aggregate counter, no key, no map entry.
688///
689/// It is the bound on the fail-open path: without it a new key arriving at a
690/// full map is admitted unmetered, so an attacker who first fills the map with
691/// exhausted buckets buys unlimited throughput from fresh keys. With it that
692/// bypass is capped at this many requests a minute, fleet-wide, and a genuine
693/// newcomer gets in on whatever of it is left — an attacker who burns the lot
694/// does `429` the newcomers, which refusing them outright would have done for
695/// free. Clients already in the map are unaffected throughout. Sized for the
696/// genuine side: this is a *request* budget, not a client one (a keyless client
697/// spends it on every request, not just its first), so roughly 10 requests a
698/// second for all newcomers together — far under any single client's API tier,
699/// and only ever in force while 10k buckets sit exhausted at once, which is an
700/// attack and not a school day.
701pub const RATE_LIMIT_OVERFLOW_MAX: u32 = 600;
702
703/// The shared counter the limiter folds its local admits into, so a window's
704/// budget survives a restart (see [`crate::rate_limit`]).
705pub const RATE_LIMIT_TABLE: &str = "rate_limit";
706
707/// How often a limiter pushes its admits and reads the window's total back.
708/// The knob that decides the worst case: within one interval a just-started
709/// process can admit up to its full local budget before the total tightens it, so
710/// short enough to matter and long enough to stay one query per tier per tick.
711pub const RATE_SYNC_INTERVAL_SECS: u64 = 2;
712
713/// How long one sync round may wait on the database. The SDK *parks* a query
714/// while the socket is down instead of failing it, so the liveness flag alone
715/// cannot stop a round wedging the task forever — this is the backstop that
716/// keeps the limiter purely local through an outage instead of stalled.
717pub const RATE_SYNC_TIMEOUT_SECS: u64 = 5;
718
719/// How many client buckets one round syncs. A round is a single query holding
720/// one statement per bucket, so this bounds both its size and the write volume
721/// a burst of distinct clients can put on the database.
722pub const RATE_SYNC_MAX_KEYS: usize = 512;
723
724// --- time spans --------------------------------------------------------
725
726pub const MILLIS_PER_DAY: i64 = 24 * 60 * 60 * 1000;
727
728/// One week, the only recurrence step this backend expands.
729pub const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY;
730
731// --- enum value tables -------------------------------------------------
732
733/// Every *assignable* role, lowest privilege first. `Role::Ai` is deliberately
734/// absent: it is a service principal, so leaving it out of this table is what
735/// keeps `Role::try_from_str` (and every surface that lists roles) from ever
736/// handing it to a user.
737pub const ROLES: [Role; 5] = [
738 Role::Parent,
739 Role::Student,
740 Role::Teacher,
741 Role::Manager,
742 Role::Admin,
743];
744
745/// The record key `User::ai_principal` carries. A literal, not a ULID, so it
746/// can never collide with a minted user row — and the row is never written.
747pub const AI_PRINCIPAL_KEY: &str = "ai_service";
748
749pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark];
750
751pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En];
752
753/// A `palette_color` preference is `#` plus exactly six hex digits — the length
754/// of the whole string, `#` included.
755pub const PALETTE_COLOR_LEN: usize = 7;
756
757/// The shape a `palette_color` must match, as a regular expression. This
758/// describes what the server **accepts**, so it is case-insensitive — the value
759/// is normalized to lowercase on store, and a client that sent `#FEFAE0` reads
760/// `#fefae0` back. Publishing the lowercase-only form would have a client
761/// reject its own valid input.
762///
763/// Deliberately an open value set: any valid hex accent color, not a closed
764/// list of the frontend's palette, so a new palette entry needs no backend
765/// change.
766pub const PALETTE_COLOR_PATTERN: &str = "^#[0-9a-fA-F]{6}$";
767
768/// Folders a sender may file their side into (`Sent` is their home).
769pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash];
770/// Folders a recipient may file their side into (`Inbox` is their home).
771pub const RECIPIENT_FOLDERS: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash];
772
773/// The two lifecycle states of a pool question. `pending`: awaiting teacher+
774/// approval, visible only to the asker and to teacher+. `approved`: in the
775/// pool, school-wide. Rejection is not a state — a teacher+ simply deletes the
776/// question.
777pub const STATUS_PENDING: &str = "pending";
778pub const STATUS_APPROVED: &str = "approved";
779pub const POOL_QUESTION_STATUSES: [&str; 2] = [STATUS_PENDING, STATUS_APPROVED];
780
781/// The two reaches of a bank question template: the author's own drawer, or
782/// published to the whole school.
783pub const BANK_VISIBILITY_PRIVATE: &str = "private";
784pub const BANK_VISIBILITY_SCHOOL: &str = "school";
785
786// --- fixed keys and literals -------------------------------------------
787
788/// The settings singleton's fixed key: one school per deployment, one settings
789/// row.
790pub const SETTINGS_KEY: &str = "school";
791
792/// A fixed password whose hash is the login decoy (see
793/// [`crate::domain::user::PasswordHash::verify_decoy`]). Not a secret — it
794/// never matches a real account.
795pub const DECOY_PASSWORD: &str = "decoy-password-not-a-secret";
796
797/// The `error_code` a stale `pending` chatbot row presents as. Distinct from
798/// the boot sweep's `interrupted`: this one was never repaired, only projected.
799pub const STALE_ERROR_CODE: &str = "timed_out";
800
801/// Ceiling on a stored `error_code`. Codes are short slugs, but one arrives
802/// from an out-of-process AI service — a trust boundary — so it is trimmed
803/// rather than trusted.
804pub const MAX_ERROR_CODE_LEN: usize = 64;
805
806/// Replacements applied *after* lowercasing, in order. One table, two
807/// consumers ([`crate::domain::text_fold::search_fold`] and
808/// [`crate::domain::text_fold::search_fold_sql`]): the needle and the column
809/// are folded by the same rules by construction, which is the whole point.
810pub const TEXT_FOLD_REPLACEMENTS: &[(&str, &str)] = &[
811 ("\u{307}", ""), // combining dot above, left behind by İ → i̇
812 ("ı", "i"),
813 ("ş", "s"),
814 ("ğ", "g"),
815 ("ç", "c"),
816 ("ö", "o"),
817 ("ü", "u"),
818 ("â", "a"),
819 ("î", "i"),
820 ("û", "u"),
821];
822
823// --- response shaping --------------------------------------------------
824
825/// Bodies larger than this are streamed through without buffering — JSON pages
826/// sit far below it, so the cap only bounds worst-case memory. A response whose
827/// `Content-Length` exceeds it (or is absent, i.e. a stream) skips the ETag
828/// middleware.
829pub const MAX_ETAG_BODY_BYTES: u64 = 1 << 20; // 1 MiB
830
831/// How many `delta` events a completed chatbot answer is cut into, and the
832/// shortest chunk worth emitting.
833pub const REPLY_CHUNKS: usize = 8;
834pub const MIN_CHUNK_CHARS: usize = 24;
835
836// --- query text --------------------------------------------------------
837
838/// The whole of [`crate::db::bank_question::usage_counts`]:
839/// **one** statement (no `;`), so a page of templates costs one round trip no
840/// matter how long it is. Named so a test can assert that, since a per-row
841/// `count()` is exactly the N+1 this page was cleaned of once.
842pub const USAGE_COUNTS_SQL: &str =
843 "SELECT from_bank, count() AS n FROM exam_question WHERE from_bank IN $ids GROUP BY from_bank";
844
845// --- database tables ---------------------------------------------------
846
847pub const USER_TABLE: &str = "user";
848pub const SESSION_TABLE: &str = "session";
849pub const NOTE_TABLE: &str = "note";
850pub const MESSAGE_TABLE: &str = "message";
851pub const NOTE_FILE_TABLE: &str = "note_file";
852pub const COURSE_NOTE_TABLE: &str = "course_note";
853pub const COURSE_NOTE_FILE_TABLE: &str = "course_note_file";
854pub const RAG_OUTPUT_TABLE: &str = "rag_output";
855pub const EVENT_TABLE: &str = "event";
856pub const ATTENDANCE_TABLE: &str = "attendance";
857pub const REGISTRATION_TABLE: &str = "registration";
858pub const EXAM_TABLE: &str = "exam";
859pub const EXAM_RESULT_TABLE: &str = "exam_result";
860pub const EXAM_ATTEMPT_TABLE: &str = "exam_attempt";
861pub const EXAM_QUESTION_TABLE: &str = "exam_question";
862pub const QUESTION_IMAGE_TABLE: &str = "question_image";
863pub const EXAM_ANSWER_TABLE: &str = "exam_answer";
864pub const ANSWER_IMAGE_TABLE: &str = "answer_image";
865pub const BANK_QUESTION_TABLE: &str = "bank_question";
866pub const BANK_QUESTION_IMAGE_TABLE: &str = "bank_question_image";
867pub const COURSE_TABLE: &str = "course";
868pub const ENROLLMENT_TABLE: &str = "enrollment";
869pub const CLASS_GROUP_TABLE: &str = "class_group";
870pub const CLASS_MEMBER_TABLE: &str = "class_member";
871pub const CLASS_COURSE_TABLE: &str = "class_course";
872pub const CLASS_BLUEPRINT_TABLE: &str = "class_blueprint";
873pub const PARENT_LINK_TABLE: &str = "parent_link";
874pub const COURSE_SESSION_TABLE: &str = "course_session";
875pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance";
876pub const WORK_ENTRY_TABLE: &str = "work_entry";
877pub const POMODORO_SESSION_TABLE: &str = "pomodoro_session";
878pub const SETTINGS_TABLE: &str = "settings";
879pub const TERM_TABLE: &str = "term";
880pub const SUBJECT_TABLE: &str = "subject";
881pub const POOL_QUESTION_TABLE: &str = "pool_question";
882pub const SOLUTION_TABLE: &str = "solution";
883pub const HOMEWORK_TABLE: &str = "homework";
884pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission";
885pub const HOMEWORK_FILE_TABLE: &str = "homework_file";
886pub const HOMEWORK_RESULT_TABLE: &str = "homework_result";
887pub const CHATBOT_THREAD_TABLE: &str = "chatbot_thread";
888pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message";
889pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";
890pub const APPOINTMENT_TABLE: &str = "appointment";
891pub const MENU_TABLE: &str = "menu";
892pub const MENU_DISH_TABLE: &str = "menu_dish";
893pub const DIETARY_PROFILE_TABLE: &str = "dietary_profile";
894pub const MEAL_BOOKING_TABLE: &str = "meal_booking";
895pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";
896pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
897pub const FEE_PLAN_TABLE: &str = "fee_plan";
898pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";
899pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";
900pub const BOARD_TABLE: &str = "board";
901/// One row per badge a user has earned, keyed by the pair. A table of its own
902/// rather than an array column on the user row: an `array<…>` there breaks
903/// every `PATCH` of that row, and awards are append-only facts with their own
904/// timestamp (see [`crate::domain::badge`]).
905pub const BADGE_AWARD_TABLE: &str = "badge_award";
906/// One row per *name* the school's settings offer, keyed by the name itself:
907/// how many rows still reference it, and whether it has been retired out of the
908/// list (see the reference counters in [`crate::db::cap`]).
909pub const KIND_REF_TABLE: &str = "kind_ref";
910pub const SLOT_REF_TABLE: &str = "slot_ref";
911
912// --- stored cap counters -------------------------------------------------
913
914/// The counter columns behind the count caps (see [`crate::db::cap`]).
915/// Each one lives on the *parent* row, because a single-record conditional
916/// `UPDATE` is the only guard a concurrent writer cannot outrun (a lock is
917/// released around the round trip). Spelled here rather than at the call site
918/// so the field a claim
919/// increments and the field a delete decrements cannot drift apart; the
920/// definitions themselves are in `MIGRATION`, and a typo there is caught by
921/// SCHEMAFULL refusing the write.
922pub const ENROLLMENT_COUNT_FIELD: &str = "enrollment_count";
923pub const REGISTRATION_COUNT_FIELD: &str = "registration_count";
924/// Not a cap — a refcount, and the whole of the term delete guard: how many
925/// courses link this term. A term may only be dropped at zero, and the count
926/// is claimed before a course's link is written, so the two decisions contend
927/// on the term row instead of on a cross-table `SELECT` no transaction orders.
928pub const COURSE_COUNT_FIELD: &str = "course_count";
929/// The two refcounts on a class row: how many students it holds and how many
930/// courses it is attached to. A class may only be dropped at zero on both.
931pub const CLASS_MEMBER_COUNT_FIELD: &str = "class_member_count";
932pub const CLASS_COURSE_COUNT_FIELD: &str = "class_course_count";
933/// Classes linking a term, the second half of the term delete guard. Deliberately
934/// *not* `COURSE_COUNT_FIELD`: boot recounts that one from the course rows alone,
935/// so a class claiming into it would be wiped on the next migration.
936pub const TERM_CLASS_COUNT_FIELD: &str = "class_count";
937/// A refcount too, and the whole of the fee-plan edit *and* delete guard: how
938/// many students are on this plan. A plan may only be edited or deleted at
939/// zero, and the count is claimed in the same transaction as the assignment
940/// row, so a manager's edit and a concurrent assign contend on the plan row
941/// rather than on a `SELECT` the edit had already outrun. Nothing ever
942/// releases it — an assignment is never unassigned, because the charges it
943/// raised are history.
944pub const FEE_PLAN_ASSIGNMENT_COUNT_FIELD: &str = "assignment_count";
945/// The condition itself, spelled once: a plan is editable and deletable
946/// exactly while nobody is on it. The `??` is parenthesized on purpose —
947/// `count ?? 0 = 0` parses as `count ?? (0 = 0)`, which is truthy for *every*
948/// row and would license editing a plan a family is already being billed for.
949pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0";
950pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count";
951pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
952/// The column a *grant* claim moves and puts back, so its transaction writes
953/// the holder's own `user` record — the one key
954/// [`crate::service::user::set_role`] writes (see
955/// [`crate::db::cap::role_claim`]). Any `option<int>` on the row would do:
956/// the claim nets zero and never reads it, so this is an alias rather than a
957/// column of its own — a new one would mean a migration on a SCHEMAFULL table
958/// for a value nothing ever observes.
959pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD;
960/// The lifetime totals behind the badges, all on the user row. Not caps: each
961/// one counts something the person *did*. A counter comes down in exactly one
962/// shape, and the two cases that qualify share a reason: the account credited
963/// is the account that can delete what earned it, so a strictly monotonic
964/// counter is a farm. A student withdrawing their own submission gives the two
965/// homework counters back (else one homework becomes fifty by
966/// submit/delete/submit), and a teacher un-grading gives back
967/// `MARKS_GIVEN` — with `HIGH_MARK` on the exam side, credited to the student
968/// by the same act (else one exam becomes fifty by grade/ungrade/regrade).
969/// The exam and pomodoro totals never decrease at all, and each earns that by
970/// counting something a repeat cannot re-earn rather than by anyone's restraint:
971/// `EXAM_SAT_TOTAL` counts *exams sat*, moving only on a student's first sitting
972/// of an exam (`seq == 1`), because retakes are a loop the student drives alone —
973/// an open exam with unlimited attempts is start/finish/start, no teacher in it —
974/// and a stint is a span of time that has to be lived through to be finished.
975/// Nothing else decrements: the cascades (an exam, a homework or
976/// a course delete, which do take the attempt and result rows with them) leave
977/// them alone, since history a teacher erased is still history the student
978/// lived. A badge already earned is never taken back either, whatever a counter
979/// does afterwards — [`crate::domain::badge`] only ever adds award rows. Floored
980/// at zero, and absent means zero: an account older than the columns reads
981/// exactly like a fresh one.
982//
983// corner-cut: that cascade ruling is also the farm's long way round — delete the
984// *exam* instead of the mark and the credit stands, so the loop still climbs,
985// at a couple of requests a point rather than two. Closing it means
986// `Exam::delete`, `Homework::delete` and `Course::delete` refunding per swept
987// row the way `ExamResult::remove` now does, which is a policy call (a course
988// delete would then have to walk every mark it drops) rather than an oversight.
989pub const HOMEWORK_SUBMITTED_TOTAL_FIELD: &str = "homework_submitted_total";
990pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total";
991pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total";
992pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total";
993pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total";
994/// The bookkeeping behind the counted-stint rule below: which UTC day the
995/// student last had a stint counted on, and how many counted that day. Internal
996/// state like the two streak columns — no badge reads either, `/limits` names
997/// neither, no profile key serves them. The day rolls the tally back to zero.
998pub const POMODORO_COUNTED_DAY_FIELD: &str = "pomodoro_counted_day";
999pub const POMODORO_COUNTED_TODAY_FIELD: &str = "pomodoro_counted_today";
1000/// What makes a finished stint *count* towards `pomodoro_finished_total` and
1001/// `pomodoro_focus_ms_total` (and towards the study streak): it must have run at
1002/// least this long, and it must be within the day's quota.
1003///
1004/// Without them the pair is the farm [`crate::db::pool_question::approve`]
1005/// reasons about from the other end: `finish` is self-service, a stint costs two
1006/// requests and no second person, so a counter moved once per round-trip is
1007/// farmable — 200 pairs in a minute and a half bought `pomodoro_finished_200`,
1008/// permanently, since a badge is never revoked.
1009///
1010/// Five minutes is well under a conventional 25-minute pomodoro on purpose: a
1011/// student who breaks off early still focused, and the counter should not
1012/// punish that. It is four orders of magnitude above a scripted round-trip,
1013/// which is the whole distance that matters — the cheat now costs the wall
1014/// clock it claims. Sixteen a day is likewise above any honest school day
1015/// (sixteen full pomodoros is over six hours of pure focus) while capping the
1016/// minimum-length farm at eighty minutes of real waiting per day, so
1017/// `pomodoro_finished_200` takes at least thirteen calendar days to buy instead
1018/// of ninety seconds. Both are read `>=`/`<`, i.e. a stint of exactly the
1019/// minimum counts and the sixteenth of the day counts.
1020pub const MIN_COUNTED_POMODORO_MS: i64 = 300_000;
1021pub const MAX_COUNTED_POMODORO_PER_DAY: i64 = 16;
1022/// A stint's optional student-given label — the student's own name for what
1023/// the stint is for ("math", "TYT denemesi"), free text rather than a subject
1024/// link, bounded like the other short labels.
1025pub const MAX_POMODORO_LABEL_LEN: usize = 100;
1026/// The staff-side and second student-side totals, same shape and same rules:
1027/// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and
1028/// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the
1029/// approvals a teacher hands out and `POOL_PUBLISHED` the questions whose
1030/// author got approved — credited at approval, which is why the name says
1031/// published rather than asked.
1032pub const MARKS_GIVEN_TOTAL_FIELD: &str = "marks_given_total";
1033pub const LESSONS_HELD_TOTAL_FIELD: &str = "lessons_held_total";
1034pub const POOL_APPROVED_TOTAL_FIELD: &str = "pool_approved_total";
1035pub const POOL_PUBLISHED_TOTAL_FIELD: &str = "pool_published_total";
1036pub const LESSONS_ATTENDED_TOTAL_FIELD: &str = "lessons_attended_total";
1037pub const HIGH_MARK_TOTAL_FIELD: &str = "high_mark_total";
1038/// The longest run of consecutive days the student has studied, and the two
1039/// bookkeeping columns the write site needs to compute it: the run in progress
1040/// and the last day counted (both plain day numbers, midnight UTC — the same
1041/// boundary every other day calculation here uses).
1042///
1043/// Only the longest is a badge counter: it never comes down, which is what
1044/// keeps it on the ordinary `>=` rule with no second catalog shape. The other
1045/// two are internal state — no badge reads them, `/limits` never names them,
1046/// and no profile key serves them.
1047pub const STUDY_STREAK_LONGEST_FIELD: &str = "study_streak_longest";
1048pub const STUDY_STREAK_CURRENT_FIELD: &str = "study_streak_current";
1049pub const STUDY_STREAK_LAST_DAY_FIELD: &str = "study_streak_last_day";
1050/// When a lesson was first counted towards its teacher's `lessons_held_total`,
1051/// stamped on the `course_session` row by the first roll call taken for it.
1052/// Bookkeeping like the two streak columns above: no badge reads it, `/limits`
1053/// never names it, no profile key serves it. Its only job is the once-per-
1054/// session guard — a lesson is credited when it is *taken*, and the thirtieth
1055/// student marked must credit nothing further.
1056pub const LESSON_COUNTED_AT_FIELD: &str = "held_counted_at";
1057/// What counts as a high mark, out of `MAX_MARK`. Hardcoded next to the badge
1058/// thresholds rather than read from the school's grade bands: those are
1059/// renameable display labels, and a badge id must never depend on a value a
1060/// school can change at runtime — `high_mark_10` has to mean the same thing in
1061/// every deployment, forever.
1062pub const HIGH_MARK_MIN: i64 = 90;
1063
1064/// The badge catalog: every badge the system can award, as
1065/// `(id, the counter it reads, the value that earns it)`. Hardcoded on
1066/// purpose — moving a threshold is a deploy, which is what keeps
1067/// [`crate::domain::badge::earned`] a pure function of the stats and makes the
1068/// rules reviewable in a diff instead of editable in a settings row.
1069///
1070/// The ids are the API: the frontend maps them to a label and an icon, and an
1071/// award row stores one forever. So an id is never reused for a different
1072/// meaning; retiring one is done by deleting the line, and the awards that
1073/// carry it simply stop being served (no data migration —
1074/// [`crate::db::badge::list_for`] filters to the live
1075/// catalog).
1076pub const BADGES: [(&str, BadgeStat, i64); 34] = [
1077 ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1),
1078 ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10),
1079 ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50),
1080 ("homework_on_time_10", BadgeStat::HomeworkOnTime, 10),
1081 ("homework_on_time_25", BadgeStat::HomeworkOnTime, 25),
1082 ("exam_sat_1", BadgeStat::ExamSat, 1),
1083 ("exam_sat_10", BadgeStat::ExamSat, 10),
1084 ("exam_sat_25", BadgeStat::ExamSat, 25),
1085 ("pomodoro_finished_10", BadgeStat::PomodoroFinished, 10),
1086 ("pomodoro_finished_50", BadgeStat::PomodoroFinished, 50),
1087 ("pomodoro_finished_200", BadgeStat::PomodoroFinished, 200),
1088 // Ten and fifty hours of focus, in the milliseconds the counter stores.
1089 (
1090 "pomodoro_focus_ms_36000000",
1091 BadgeStat::PomodoroFocusMs,
1092 36_000_000,
1093 ),
1094 (
1095 "pomodoro_focus_ms_180000000",
1096 BadgeStat::PomodoroFocusMs,
1097 180_000_000,
1098 ),
1099 ("marks_given_10", BadgeStat::MarksGiven, 10),
1100 ("marks_given_50", BadgeStat::MarksGiven, 50),
1101 ("marks_given_250", BadgeStat::MarksGiven, 250),
1102 ("lessons_held_10", BadgeStat::LessonsHeld, 10),
1103 ("lessons_held_50", BadgeStat::LessonsHeld, 50),
1104 ("lessons_held_200", BadgeStat::LessonsHeld, 200),
1105 ("pool_approved_5", BadgeStat::PoolApproved, 5),
1106 ("pool_approved_25", BadgeStat::PoolApproved, 25),
1107 ("pool_approved_100", BadgeStat::PoolApproved, 100),
1108 ("pool_published_1", BadgeStat::PoolPublished, 1),
1109 ("pool_published_10", BadgeStat::PoolPublished, 10),
1110 ("pool_published_50", BadgeStat::PoolPublished, 50),
1111 ("lessons_attended_10", BadgeStat::LessonsAttended, 10),
1112 ("lessons_attended_50", BadgeStat::LessonsAttended, 50),
1113 ("lessons_attended_200", BadgeStat::LessonsAttended, 200),
1114 // Exam marks at or above `HIGH_MARK_MIN`, counted per graded sitting.
1115 ("high_mark_1", BadgeStat::HighMark, 1),
1116 ("high_mark_10", BadgeStat::HighMark, 10),
1117 ("high_mark_25", BadgeStat::HighMark, 25),
1118 // Consecutive study days, read off the longest run ever held — so these
1119 // are earned once and never lost when the run breaks.
1120 ("study_streak_3", BadgeStat::StudyStreak, 3),
1121 ("study_streak_7", BadgeStat::StudyStreak, 7),
1122 ("study_streak_30", BadgeStat::StudyStreak, 30),
1123];
1124/// Cap 1, not N: an appointment slot holds at most one live booking, so this
1125/// counter is really an "is it taken" flag kept in the shape every other cap
1126/// uses (`claim`/`release`), which is what makes rejecting or cancelling a
1127/// booking give the slot back.
1128pub const SLOT_OCCUPIED_FIELD: &str = "occupied";
1129/// Not caps either, and uncapped by design: how many exam questions and how
1130/// many homework still point at a subject. A subject may be deleted exactly
1131/// while both read zero, so the delete's own `WHERE` decides it — the
1132/// cross-table "does anything reference this?" count it replaces was already
1133/// stale when the delete landed.
1134pub const SUBJECT_QUESTION_COUNT_FIELD: &str = "exam_question_count";
1135pub const SUBJECT_HOMEWORK_COUNT_FIELD: &str = "homework_count";
1136/// How many marks an exam carries. Uncapped too, and the only counter its
1137/// entity carries as a field: the exam's save is a whole-row `CONTENT` write,
1138/// which would wipe a column the struct did not know about. That save pins it,
1139/// which is what makes "this exam has no marks" — the gate a kind change is
1140/// refused on — decided at write time rather than at read time.
1141pub const EXAM_RESULT_COUNT_FIELD: &str = "result_count";
1142/// The two columns of a reference-counter row (`kind_ref`, `slot_ref`): how
1143/// many rows still point at the name, and whether it has left the school's
1144/// list. Both `option<…>`, absent meaning zero references and in service.
1145pub const REF_COUNT_FIELD: &str = "count";
1146pub const REF_RETIRED_FIELD: &str = "retired";
1147/// Seats held on one menu — the meal capacity cap.
1148pub const MENU_SEAT_COUNT_FIELD: &str = "seats_booked";
1149/// Not a cap: the menu's revision, bumped by every write that can change what
1150/// a seat costs (a dish added, re-priced or removed, the capacity moved). A
1151/// booking claims its seat only at the revision it read the price at, so the
1152/// price frozen onto the row is one the menu really carried at that instant.
1153pub const MENU_VERSION_FIELD: &str = "version";
1154
1155/// Not a cap either: the grade that froze a homework submission, absent while
1156/// the submission is still open. Every student-side write to a submission (its
1157/// text, its files) carries `graded_by_result = NONE` as a condition, so the
1158/// "not graded yet" decision and the write it licenses are one conditional
1159/// single-record write rather than a cross-table read a concurrent grade can
1160/// outrun. Set by grading, cleared by un-grading, never by the student.
1161pub const SUBMISSION_GRADED_FIELD: &str = "graded_by_result";
1162/// The condition itself, spelled once: a submission is writable exactly while
1163/// its grade stamp is absent.
1164pub const SUBMISSION_OPEN_GUARD: &str = "graded_by_result = NONE";
1165/// A signup list has **frozen**: the event takes registrations at all *and* it
1166/// started, or — for an ends_at-only event (a pure signup deadline) — that end
1167/// passed. A timeless event never freezes. Matched against `$now` in millis, on
1168/// an `event` row.
1169///
1170/// This is `Event::registration_capacity`'s `Conflict` arm re-spelled in
1171/// SurrealQL, because the role cascade (`service::user::set_role`) frees a demoted
1172/// parent's seats *inside* its transaction and cannot call Rust from there. The
1173/// audience conjunct is what keeps it that arm and only that arm: an event that
1174/// takes no registrations is refused earlier, by the `Validation` arm, so a
1175/// stray row on one is deleted rather than frozen — which is what the pre-fold
1176/// sweep did, and dropping the conjunct would silently change it. Two spellings
1177/// of one rule is a drift risk, so it is spelled once here and
1178/// `event::tests::the_sql_freeze_guard_matches_the_rust_one` fails the suite the
1179/// day the two disagree.
1180pub const REGISTRATION_FROZEN_GUARD: &str = "audience.kind = 'registration' \
1181 AND (starts_at ?? ends_at) != NONE AND (starts_at ?? ends_at) <= $now";
1182
1183/// How hard a counter write tries before giving up, and the first backoff step
1184/// it sleeps between attempts (doubling, plus jitter). Contention on one record
1185/// is the guard working as designed, and SurrealDB answers it by aborting the
1186/// loser's transaction — so these two numbers are what turn "retry the
1187/// transaction" into a queue. Sized for one HTTP burst of racers on a single
1188/// parent: seven doublings from 2ms is a quarter of a second of patience.
1189pub const CAP_WRITE_TRIES: usize = 8;
1190pub const CAP_WRITE_BACKOFF_MS: u64 = 2;