forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBebffd41Ahmet Kaan Gümüş2 months ago509 commits

limits.rs763 lines, 33.2 KiBHistoryRawDownload
1//! `GET /limits` — every compile-time validation bound, served as data.
2//!
3//! The frontend has to enforce the same rules the newtypes do (a `maxlength`
4//! on an input, a client-side check before a doomed request). Hard-coding them
5//! there means two copies that silently drift apart the day one moves. This
6//! endpoint is the single source: every field below reads a `crate::constant`
7//! item directly, so a changed constant changes the response in the same
8//! commit.
9//!
10//! School-adjustable policy (exam kinds, attendance statuses, grade bands, the
11//! live `max_file_bytes`) lives in `GET /settings` — this route carries only
12//! the fixed bounds those settings must themselves stay inside.
13
14use axum::Json;
15use axum::extract::State;
16use serde::Serialize;
17use utoipa::ToSchema;
18use utoipa_axum::router::OpenApiRouter;
19use utoipa_axum::routes;
20
21use crate::constant::*;
22use crate::domain::badge::BADGES;
23use crate::domain::preferences::{LANGUAGES, THEMES};
24use crate::domain::role::ROLES;
25use crate::state::AppState;
26
27pub fn routes() -> OpenApiRouter<AppState> {
28 OpenApiRouter::new().routes(routes!(get_limits))
29}
30
31/// Account fields: credentials, profile, and the closed role set.
32#[derive(Serialize, ToSchema)]
33struct UserLimits {
34 /// The school slug the login and registration forms ask for, in front of
35 /// the dot in the session cookie. Lowercase `a-z`, `0-9` and `-`, starting
36 /// with a letter or digit.
37 min_slug_len: usize,
38 max_slug_len: usize,
39 /// Slugs no school may take — they name the builder cookie prefix and the
40 /// control database.
41 reserved_slugs: Vec<&'static str>,
42 /// A school's display name, set by the vendor when the school is created.
43 max_school_name_len: usize,
44 min_username_len: usize,
45 max_username_len: usize,
46 /// Separators allowed inside a username — never at the edges, never doubled.
47 #[schema(example = json!([".", "_", "-"]))]
48 username_separators: Vec<String>,
49 /// Names `POST /auth/register` refuses (they read as staff).
50 reserved_usernames: Vec<&'static str>,
51 min_password_len: usize,
52 max_password_len: usize,
53 max_name_len: usize,
54 /// The self-chosen name a user's profile is shown under.
55 max_display_name_len: usize,
56 /// Free text under a profile's name.
57 max_bio_len: usize,
58 /// How many course references a profile read embeds — a cap on the
59 /// response, not on membership. The full list stays at `/courses/me`.
60 max_profile_courses: usize,
61 /// Same, for classes; the full list stays at `/classes/me`.
62 max_profile_classes: usize,
63 max_email_len: usize,
64 /// Digit count, ignoring spaces and punctuation.
65 min_phone_digits: usize,
66 max_phone_digits: usize,
67 /// Every role, lowest privilege first.
68 #[schema(example = json!(["parent", "student", "teacher", "manager", "admin"]))]
69 roles: Vec<&'static str>,
70 /// Accepted `theme` preference values (`null` clears it).
71 #[schema(example = json!(["light", "dark"]))]
72 themes: Vec<&'static str>,
73 /// Accepted `language` preference values (`null` clears it).
74 #[schema(example = json!(["tr", "en"]))]
75 languages: Vec<&'static str>,
76 /// Shape a `palette_color` preference must match, as a regular expression
77 /// (`null` clears it). Open on purpose — any hex accent color, not a fixed
78 /// palette — so this is a pattern, not a value list like `themes`. Matches
79 /// either case: the server normalizes the value to lowercase on store, so a
80 /// response may differ in case from what was sent.
81 #[schema(example = "^#[0-9a-fA-F]{6}$")]
82 palette_color_pattern: &'static str,
83 /// Length of a `palette_color`, `#` included.
84 palette_color_len: usize,
85 /// How long a login session stays valid, days.
86 session_duration_days: i64,
87}
88
89/// The auto-earned badge catalog. A group like every other key here, so a
90/// client can walk this response uniformly; the catalog itself is the one
91/// field inside.
92#[derive(Serialize, ToSchema)]
93struct BadgeLimits {
94 /// Every badge the system can auto-award, in catalog order. Hardcoded, so
95 /// like everything else here it moves only with a deploy.
96 catalog: Vec<BadgeLimit>,
97 /// The exam mark that counts as a high one, out of `mark.max_mark`, behind
98 /// the `high_mark` ladder. Published because the id alone does not say it:
99 /// deliberately not the school's grade bands, which are renameable labels.
100 #[schema(example = 90)]
101 high_mark_min: i64,
102}
103
104/// One badge in the auto-earned catalog. The id is the whole contract: a
105/// profile hands back ids and nothing else, and the label and icon behind one
106/// live in the client, exactly as they do for a role or a course kind.
107#[derive(Serialize, ToSchema)]
108struct BadgeLimit {
109 /// Stable id, never reused for another meaning. A retired badge simply
110 /// stops appearing here.
111 #[schema(example = "homework_submitted_10")]
112 id: &'static str,
113 /// The lifetime counter it reads — badges sharing one form a ladder. An
114 /// API-side name, not the column it is stored in, so storage can be
115 /// renamed without moving this contract.
116 #[schema(example = "homework_submitted")]
117 stat: &'static str,
118 /// Counter value that earns it. Awards are permanent: a counter that later
119 /// falls back below this does not take the badge away.
120 #[schema(example = 10)]
121 threshold: i64,
122}
123
124/// Note bodies and their attachments.
125#[derive(Serialize, ToSchema)]
126struct NoteLimits {
127 max_title_len: usize,
128 max_content_len: usize,
129 /// How many files one note may carry.
130 max_files: usize,
131 /// How many files one course note may carry.
132 max_course_note_files: usize,
133}
134
135/// Uploaded-file metadata, shared by every upload route.
136#[derive(Serialize, ToSchema)]
137struct FileLimits {
138 max_name_len: usize,
139 max_content_type_len: usize,
140 /// Inclusive range a manager may set `max_file_bytes` to in `/settings`;
141 /// the live value is on `GET /settings`, this is the hard ceiling above it.
142 min_max_file_bytes: i64,
143 max_max_file_bytes: i64,
144 default_max_file_bytes: i64,
145 /// Content types an inline image (question illustrations, option pictures,
146 /// pool photos, answer drawings) may declare. Raster only — no SVG.
147 #[schema(example = json!(["image/png", "image/jpeg", "image/webp", "image/gif"]))]
148 image_content_types: Vec<&'static str>,
149}
150
151/// One-to-one messages.
152#[derive(Serialize, ToSchema)]
153struct MessageLimits {
154 max_subject_len: usize,
155 max_body_len: usize,
156 /// The sender's optional free-text badge.
157 max_label_len: usize,
158}
159
160/// Events and their registration lists.
161#[derive(Serialize, ToSchema)]
162struct EventLimits {
163 max_title_len: usize,
164 max_description_len: usize,
165}
166
167/// Courses, their curriculum subjects, lesson sessions, and the classes that
168/// bulk-enroll into them.
169#[derive(Serialize, ToSchema)]
170struct CourseLimits {
171 max_title_len: usize,
172 max_description_len: usize,
173 /// The only accepted `kind` values. Only `course` is taught through class
174 /// instances (exams, sessions, homework); `study` (etüt) and `club` are
175 /// joined school-wide.
176 #[schema(example = json!(["course", "study", "club"]))]
177 kinds: Vec<&'static str>,
178 max_subject_name_len: usize,
179 max_subject_description_len: usize,
180 max_session_topic_len: usize,
181 max_term_name_len: usize,
182 max_class_name_len: usize,
183 /// A class's optional free-text grade label ("9", "10-A").
184 max_class_grade_len: usize,
185 /// Students one class may hold. Removing one frees a place.
186 max_class_members: i64,
187 /// Instances one class may carry. Detaching one frees a place.
188 max_class_courses: i64,
189 /// Inclusive bounds for an instance's weekly lesson hours (`ders_saati`).
190 min_ders_saati: i64,
191 max_ders_saati: i64,
192 /// An academic year's name (`POST /academic-years`).
193 max_academic_year_name_len: usize,
194}
195
196/// Exams, their questions, answers, and marks.
197#[derive(Serialize, ToSchema)]
198struct ExamLimits {
199 max_title_len: usize,
200 max_description_len: usize,
201 /// The only accepted `mode` values; an exam with no mode is offline-graded.
202 #[schema(example = json!(["sync", "async", "open"]))]
203 modes: Vec<&'static str>,
204 /// Inclusive bounds for `duration_ms` (1 minute – 24 hours).
205 min_duration_ms: i64,
206 max_duration_ms: i64,
207 /// Upper bound for `max_attempts`; `unlimited_attempts` (0) means no limit.
208 max_attempts: i64,
209 unlimited_attempts: i64,
210 /// The only accepted question `kind` values.
211 #[schema(example = json!(["choice", "text"]))]
212 question_kinds: Vec<&'static str>,
213 max_question_text_len: usize,
214 min_question_points: i64,
215 max_question_points: i64,
216 min_question_choices: usize,
217 max_question_choices: usize,
218 max_choice_text_len: usize,
219 max_answer_text_len: usize,
220 min_mark: i64,
221 max_mark: i64,
222 /// Cadence of the exam-room WebSocket's `state` frames, seconds.
223 ws_tick_secs: u64,
224 /// Ceiling on a `question_id` sent over the exam-room WebSocket.
225 ws_max_question_id_len: usize,
226}
227
228/// Homework assignments and submissions.
229#[derive(Serialize, ToSchema)]
230struct HomeworkLimits {
231 max_title_len: usize,
232 max_description_len: usize,
233 /// A submission's optional free-text note.
234 max_text_len: usize,
235 max_files_per_submission: usize,
236 /// How many students an explicit `assigned` subset may name.
237 max_assigned: usize,
238 /// The only accepted teacher-set `status` values.
239 #[schema(example = json!(["done", "incomplete", "missing"]))]
240 statuses: Vec<&'static str>,
241}
242
243/// The school question pool and its solutions.
244#[derive(Serialize, ToSchema)]
245struct QuestionPoolLimits {
246 max_title_len: usize,
247 max_body_len: usize,
248 max_solution_body_len: usize,
249}
250
251/// Teacher availability slots and the bookings on them.
252#[derive(Serialize, ToSchema)]
253struct AppointmentLimits {
254 /// A published slot's optional note.
255 max_note_len: usize,
256 /// The requester's required reason.
257 max_reason_len: usize,
258 /// How many slots one weekly-repeating publish may expand into.
259 max_slot_occurrences: usize,
260}
261
262/// The food program: menus and their dishes, dietary profiles, bookings and
263/// the meal ledger. The school's own lists (`meal_slots`, `dietary_tags`) and
264/// its booking cutoff are on `GET /settings`; what stands here is the fixed
265/// range those must stay inside.
266#[derive(Serialize, ToSchema)]
267struct MealLimits {
268 max_dish_name_len: usize,
269 max_dish_description_len: usize,
270 /// How many dishes one menu may list.
271 max_dishes_per_menu: usize,
272 /// Dietary tags one dish may carry.
273 max_dish_tags: usize,
274 /// Upper bound for a menu's optional `capacity`; absent = uncapped.
275 max_menu_capacity: i64,
276 /// How many times one student's seat on one menu may be taken — the first
277 /// booking plus the re-bookings after a cancel. Past it, `POST
278 /// /meals/menus/{id}/bookings` is a `409`: every cycle writes two
279 /// permanent ledger lines, so this bounds the statement, not the mind
280 /// changing. Only the canteen can free such a seat afterwards.
281 max_booking_attempts: i64,
282 /// Dietary tags one student's profile may carry, and its kitchen note.
283 max_dietary_tags: usize,
284 max_dietary_note_len: usize,
285 /// Money is **minor units** (kuruş) as an integer everywhere — never a
286 /// decimal, never a float. These cap one dish and one ledger line.
287 max_dish_price_minor: i64,
288 max_ledger_amount_minor: i64,
289 /// How the money moved, and why.
290 max_ledger_method_len: usize,
291 max_ledger_note_len: usize,
292 /// Ceiling on the `/settings` knob that closes booking (and cancelling)
293 /// ahead of a meal, minutes; the live value is on `GET /settings`.
294 max_cancel_cutoff_minutes: i64,
295 /// Ceiling on a meal slot's `serving_minute` — minutes past midnight
296 /// **UTC** on the menu's date, which is what the cutoff counts back from.
297 /// `1439` = 23:59 UTC. There is no school timezone: staff enter UTC.
298 max_serving_minute: i64,
299 /// The only accepted booking `status` values.
300 #[schema(example = json!(["booked", "cancelled"]))]
301 booking_statuses: Vec<&'static str>,
302 /// The only accepted meal-attendance `status` values — deliberately not
303 /// the school's lesson attendance statuses.
304 #[schema(example = json!(["served", "missed"]))]
305 attendance_statuses: Vec<&'static str>,
306 /// The only accepted ledger `kind` values.
307 #[schema(example = json!(["charge", "credit", "reversal"]))]
308 ledger_kinds: Vec<&'static str>,
309}
310
311/// School payments: fee plans, their assignment, and the payment ledger. Money
312/// is **minor units** (kuruş) as an integer, and one ledger line is capped by
313/// the same `max_ledger_amount_minor` the meal ledger publishes.
314#[derive(Serialize, ToSchema)]
315struct PaymentLimits {
316 max_plan_name_len: usize,
317 /// How many installments one fee plan may schedule.
318 max_plan_installments: usize,
319 /// How many students one bulk assignment may name.
320 max_assign_students: usize,
321 /// How many charge lines one bulk assignment may append — the students it
322 /// names times the plan's installments. A request past this is a `400`
323 /// telling the caller to split the batch; nothing is written.
324 max_assign_writes: usize,
325 /// How many lines may be applied to one ledger line: the payments under a
326 /// charge, the refunds under a payment, and the reversals among them. Past
327 /// it, a further payment or refund against that line is a `409`.
328 max_applied_lines: usize,
329 /// Ceiling on the optional `request_key` that makes a credit or a refund
330 /// retry-safe; charset `[A-Za-z0-9-]` (no `_`), at least one character.
331 max_request_key_len: usize,
332 /// The only accepted payment-ledger `kind` values.
333 #[schema(example = json!(["charge", "credit", "reversal", "refund"]))]
334 ledger_kinds: Vec<&'static str>,
335}
336
337/// The AI chatbot. Each range bounds the matching `/settings` knob; the live
338/// values are on `GET /settings`.
339#[derive(Serialize, ToSchema)]
340struct ChatbotLimits {
341 /// Hard ceiling on a message, above which no school setting can reach.
342 max_message_len: usize,
343 /// A thread's display name. Threads are named by hand or left untitled —
344 /// nothing auto-titles one.
345 max_thread_title_len: usize,
346 min_max_message_len: i64,
347 max_max_message_len: i64,
348 default_max_message_len: i64,
349 min_history_turns: i64,
350 max_history_turns: i64,
351 default_history_turns: i64,
352 min_max_threads: i64,
353 max_max_threads: i64,
354 default_max_threads: i64,
355}
356
357/// The RAG nest: a tier of its own — every message spends a retrieval over the
358/// whole course-note corpus before it generates anything — plus the school
359/// knobs it reuses from the chatbot. One `rag.chat` message is a chat message
360/// in every way the newtypes check, so message length, thread titles, history
361/// depth and the thread cap come from the same `/settings` fields; their fixed
362/// ranges are published here a second time so a RAG client need not read the
363/// chatbot group to bound its input.
364#[derive(Serialize, ToSchema)]
365struct RagLimits {
366 /// Hard ceiling on the `(sınıf, ders)` scope pairs one ask may carry. The
367 /// corpus is routed by the pair, so this bounds what one question can ask
368 /// a retrieval to sweep.
369 max_scope_pairs: usize,
370 /// Hard ceiling on the citations one answer may store in its message row.
371 max_citations: usize,
372 /// Pages one citation may span. A citation names a page range, and an
373 /// answer that could name every page of every document would be a copy of
374 /// the corpus, not a citation.
375 max_citation_pages: usize,
376 /// The chatbot's message bound, reused.
377 max_message_len: usize,
378 /// The chatbot's thread-title bound, reused.
379 max_thread_title_len: usize,
380 /// The school-owned message-length setting's fixed range, reused.
381 min_max_message_len: i64,
382 max_max_message_len: i64,
383 default_max_message_len: i64,
384 /// The school-owned history-depth setting's fixed range, reused.
385 min_history_turns: i64,
386 max_history_turns: i64,
387 default_history_turns: i64,
388 /// The school-owned thread-cap setting's fixed range, reused.
389 min_max_threads: i64,
390 max_max_threads: i64,
391 default_max_threads: i64,
392}
393
394/// What a finished pomodoro stint must be to *count* — to move the lifetime
395/// counters the badges and the study streak read. Not a validation bound:
396/// `POST /pomodoro/finish` never refuses a stint over these, it records it and
397/// answers `counted: false`. Published so a client can say what a stint is
398/// worth (and what is left of today's quota) instead of guessing why a badge
399/// did not arrive.
400#[derive(Serialize, ToSchema)]
401struct PomodoroLimits {
402 /// Shortest stint that counts, milliseconds — a stint of exactly this long
403 /// counts. Well under a conventional 25-minute pomodoro: breaking off early
404 /// is still studying. Its job is only to price a scripted round-trip out.
405 #[schema(example = 300000)]
406 min_counted_ms: i64,
407 /// How many stints count per UTC day. Every further one that day is
408 /// recorded and listed as usual, and counts nothing.
409 #[schema(example = 16)]
410 max_counted_per_day: i64,
411 /// How long a stint's optional student-given label may be — the student's
412 /// own name for what the stint is for, given at `POST /pomodoro/start`.
413 max_label_len: usize,
414}
415
416/// A collaborative whiteboard: its title, its roster, and the two growth caps
417/// that decide when a canvas must be cleared and when a board is finished.
418#[derive(Serialize, ToSchema)]
419struct BoardLimits {
420 max_title_len: usize,
421 /// People the creator may name onto one board. Every participant draws, so
422 /// this also bounds a room's writer count.
423 max_participants: usize,
424 /// Ceiling on one stroke's serialized payload, bytes.
425 max_stroke_payload_len: usize,
426 /// The *live* canvas cap: strokes since the last clear. Hitting it is
427 /// recoverable — the creator clears, the canvas empties, the history is
428 /// kept, and drawing resumes.
429 max_epoch_strokes: i64,
430 /// The *lifetime* storage cap, which never resets because a clear keeps its
431 /// history. Hitting it makes the board permanently read-only: it stays
432 /// fully readable and replayable, and a new board must be opened.
433 max_board_strokes: i64,
434 /// Boards one creating user may hold. Deleting a board frees a seat.
435 max_boards_per_creator: i64,
436 /// The accepted stroke kinds. `clear` is a marker that ends an epoch, not a
437 /// deletion.
438 #[schema(example = json!(["stroke", "clear"]))]
439 stroke_kinds: Vec<&'static str>,
440 /// Cadence of the board-room WebSocket's keepalive ticks, seconds.
441 ws_tick_secs: u64,
442 /// Ceiling on a `board_id` sent over the board-room WebSocket.
443 ws_max_board_id_len: usize,
444}
445
446/// Bounds on the school-editable lists in `PATCH /settings`.
447#[derive(Serialize, ToSchema)]
448struct SettingsLimits {
449 /// Entry count for the exam-kind and attendance-status lists.
450 max_list_len: usize,
451 /// Per-entry characters in those lists.
452 max_item_len: usize,
453 min_exam_kind_weight: i64,
454 max_exam_kind_weight: i64,
455 max_grade_bands: usize,
456 max_grade_label_len: usize,
457 /// Attendance statuses no school may remove.
458 #[schema(example = json!(["present", "absent", "late", "excused"]))]
459 required_attendance_statuses: Vec<&'static str>,
460}
461
462/// The request budgets a caller is held to before it starts getting `429`s
463/// with a `Retry-After`. Unlike everything else here these are **deployment**
464/// configuration, not compile-time constants — they come from environment
465/// variables, so the numbers are this server's live values rather than fixed
466/// ones. `0` means the tier is switched off.
467#[derive(Serialize, ToSchema)]
468struct RateLimits {
469 /// Fixed window every tier is counted over, seconds.
470 window_secs: u64,
471 /// Per-IP budget for `/auth/login` and `/auth/register`.
472 #[schema(example = 10)]
473 auth_per_minute: u32,
474 /// Per-IP budget across the whole API, this endpoint included.
475 #[schema(example = 300)]
476 api_per_minute: u32,
477 /// Per-*user* budget for sending chatbot messages (keyed by account, not
478 /// address, so it survives a changing IP).
479 #[schema(example = 20)]
480 chatbot_per_minute: u32,
481 /// Per-*user* budget for sending RAG messages, keyed the same way.
482 #[schema(example = 6)]
483 rag_per_minute: u32,
484}
485
486/// Rules that hold across every endpoint.
487#[derive(Serialize, ToSchema)]
488struct RequestLimits {
489 /// Upper bound on a list endpoint's `?limit=`. Omitting it returns
490 /// everything remaining.
491 max_page_limit: i64,
492 /// How far in the past a submitted schedule instant may lie before it is
493 /// refused as backdated — the grace that absorbs clock skew.
494 schedule_past_grace_ms: i64,
495 /// Ceiling on how long one request may take before it is aborted.
496 request_timeout_secs: u64,
497 /// Longest `x-request-id` header the server keeps. A longer one — or one
498 /// carrying anything outside `[A-Za-z0-9._-]` — is replaced by a
499 /// server-minted UUID, so the caller loses correlation on its own id.
500 max_request_id_len: usize,
501}
502
503/// Every fixed limit the API enforces, grouped by the resource it applies to.
504#[derive(Serialize, ToSchema)]
505struct LimitsResponse {
506 user: UserLimits,
507 badges: BadgeLimits,
508 note: NoteLimits,
509 file: FileLimits,
510 message: MessageLimits,
511 event: EventLimits,
512 course: CourseLimits,
513 exam: ExamLimits,
514 homework: HomeworkLimits,
515 question_pool: QuestionPoolLimits,
516 appointment: AppointmentLimits,
517 meal: MealLimits,
518 payment: PaymentLimits,
519 chatbot: ChatbotLimits,
520 rag: RagLimits,
521 pomodoro: PomodoroLimits,
522 board: BoardLimits,
523 settings: SettingsLimits,
524 request: RequestLimits,
525 rate: RateLimits,
526}
527
528impl LimitsResponse {
529 fn new(st: &AppState) -> Self {
530 Self {
531 user: UserLimits {
532 min_slug_len: MIN_SLUG_LEN,
533 max_slug_len: MAX_SLUG_LEN,
534 reserved_slugs: crate::tenant::RESERVED_SLUGS.to_vec(),
535 max_school_name_len: MAX_SCHOOL_NAME_LEN,
536 min_username_len: MIN_USERNAME_LEN,
537 max_username_len: MAX_USERNAME_LEN,
538 username_separators: USERNAME_SEPARATORS.iter().map(char::to_string).collect(),
539 reserved_usernames: RESERVED_USERNAMES.to_vec(),
540 min_password_len: MIN_PASSWORD_LEN,
541 max_password_len: MAX_PASSWORD_LEN,
542 max_name_len: MAX_NAME_LEN,
543 max_display_name_len: MAX_DISPLAY_NAME_LEN,
544 max_bio_len: MAX_BIO_LEN,
545 max_profile_courses: MAX_PROFILE_COURSES,
546 max_profile_classes: MAX_PROFILE_CLASSES,
547 max_email_len: MAX_EMAIL_LEN,
548 min_phone_digits: MIN_PHONE_DIGITS,
549 max_phone_digits: MAX_PHONE_DIGITS,
550 roles: ROLES.iter().map(|role| role.as_str()).collect(),
551 themes: THEMES.iter().map(|theme| theme.as_str()).collect(),
552 languages: LANGUAGES.iter().map(|language| language.as_str()).collect(),
553 palette_color_pattern: PALETTE_COLOR_PATTERN,
554 palette_color_len: PALETTE_COLOR_LEN,
555 session_duration_days: SESSION_DURATION_DAYS,
556 },
557 badges: BadgeLimits {
558 catalog: BADGES
559 .iter()
560 .map(|(id, stat, threshold)| BadgeLimit {
561 id,
562 stat: stat.as_str(),
563 threshold: *threshold,
564 })
565 .collect(),
566 high_mark_min: HIGH_MARK_MIN,
567 },
568 note: NoteLimits {
569 max_title_len: MAX_NOTE_TITLE_LEN,
570 max_content_len: MAX_NOTE_CONTENT_LEN,
571 max_files: MAX_NOTE_FILES,
572 max_course_note_files: MAX_COURSE_NOTE_FILES,
573 },
574 file: FileLimits {
575 max_name_len: MAX_FILE_NAME_LEN,
576 max_content_type_len: MAX_FILE_CONTENT_TYPE_LEN,
577 min_max_file_bytes: MIN_MAX_FILE_BYTES,
578 max_max_file_bytes: MAX_MAX_FILE_BYTES,
579 default_max_file_bytes: DEFAULT_MAX_FILE_BYTES,
580 image_content_types: QUESTION_IMAGE_CONTENT_TYPES.to_vec(),
581 },
582 message: MessageLimits {
583 max_subject_len: MAX_MESSAGE_SUBJECT_LEN,
584 max_body_len: MAX_MESSAGE_BODY_LEN,
585 max_label_len: MAX_MESSAGE_LABEL_LEN,
586 },
587 event: EventLimits {
588 max_title_len: MAX_EVENT_TITLE_LEN,
589 max_description_len: MAX_EVENT_DESCRIPTION_LEN,
590 },
591 course: CourseLimits {
592 max_title_len: MAX_COURSE_TITLE_LEN,
593 max_description_len: MAX_COURSE_DESCRIPTION_LEN,
594 kinds: COURSE_KINDS.to_vec(),
595 max_subject_name_len: MAX_SUBJECT_NAME_LEN,
596 max_subject_description_len: MAX_SUBJECT_DESCRIPTION_LEN,
597 max_session_topic_len: MAX_SESSION_TOPIC_LEN,
598 max_term_name_len: MAX_TERM_NAME_LEN,
599 max_class_name_len: MAX_CLASS_NAME_LEN,
600 max_class_grade_len: MAX_CLASS_GRADE_LEN,
601 max_class_members: MAX_CLASS_MEMBERS,
602 max_class_courses: MAX_CLASS_COURSES,
603 min_ders_saati: MIN_DERS_SAATI,
604 max_ders_saati: MAX_DERS_SAATI,
605 max_academic_year_name_len: MAX_ACADEMIC_YEAR_NAME_LEN,
606 },
607 exam: ExamLimits {
608 max_title_len: MAX_EXAM_TITLE_LEN,
609 max_description_len: MAX_EXAM_DESCRIPTION_LEN,
610 modes: EXAM_MODES.to_vec(),
611 min_duration_ms: MIN_EXAM_DURATION_MS,
612 max_duration_ms: MAX_EXAM_DURATION_MS,
613 max_attempts: MAX_EXAM_ATTEMPTS,
614 unlimited_attempts: UNLIMITED_EXAM_ATTEMPTS,
615 question_kinds: QUESTION_KINDS.to_vec(),
616 max_question_text_len: MAX_QUESTION_TEXT_LEN,
617 min_question_points: MIN_QUESTION_POINTS,
618 max_question_points: MAX_QUESTION_POINTS,
619 min_question_choices: MIN_QUESTION_CHOICES,
620 max_question_choices: MAX_QUESTION_CHOICES,
621 max_choice_text_len: MAX_CHOICE_TEXT_LEN,
622 max_answer_text_len: MAX_ANSWER_TEXT_LEN,
623 min_mark: MIN_MARK,
624 max_mark: MAX_MARK,
625 ws_tick_secs: EXAM_WS_TICK_SECS,
626 ws_max_question_id_len: MAX_QUESTION_ID_LEN,
627 },
628 homework: HomeworkLimits {
629 max_title_len: MAX_HOMEWORK_TITLE_LEN,
630 max_description_len: MAX_HOMEWORK_DESCRIPTION_LEN,
631 max_text_len: MAX_HOMEWORK_TEXT_LEN,
632 max_files_per_submission: MAX_HOMEWORK_FILES_PER_SUBMISSION,
633 max_assigned: MAX_HOMEWORK_ASSIGNED,
634 statuses: HOMEWORK_STATUSES.to_vec(),
635 },
636 question_pool: QuestionPoolLimits {
637 max_title_len: MAX_POOL_QUESTION_TITLE_LEN,
638 max_body_len: MAX_POOL_QUESTION_BODY_LEN,
639 max_solution_body_len: MAX_SOLUTION_BODY_LEN,
640 },
641 appointment: AppointmentLimits {
642 max_note_len: MAX_APPOINTMENT_NOTE_LEN,
643 max_reason_len: MAX_APPOINTMENT_REASON_LEN,
644 max_slot_occurrences: MAX_SLOT_OCCURRENCES,
645 },
646 meal: MealLimits {
647 max_dish_name_len: MAX_DISH_NAME_LEN,
648 max_dish_description_len: MAX_DISH_DESCRIPTION_LEN,
649 max_dishes_per_menu: MAX_DISHES_PER_MENU,
650 max_dish_tags: MAX_DISH_TAGS,
651 max_menu_capacity: MAX_MENU_CAPACITY,
652 max_booking_attempts: MAX_MEAL_BOOKING_ATTEMPTS,
653 max_dietary_tags: MAX_DIETARY_TAGS,
654 max_dietary_note_len: MAX_DIETARY_NOTE_LEN,
655 max_dish_price_minor: MAX_DISH_PRICE_MINOR,
656 max_ledger_amount_minor: MAX_LEDGER_AMOUNT_MINOR,
657 max_ledger_method_len: MAX_LEDGER_METHOD_LEN,
658 max_ledger_note_len: MAX_LEDGER_NOTE_LEN,
659 max_cancel_cutoff_minutes: MAX_MEAL_CANCEL_CUTOFF_MINUTES,
660 max_serving_minute: MAX_MEAL_SERVING_MINUTE,
661 booking_statuses: MEAL_BOOKING_STATUSES.to_vec(),
662 attendance_statuses: MEAL_ATTENDANCE_STATUSES.to_vec(),
663 ledger_kinds: MEAL_LEDGER_KINDS.to_vec(),
664 },
665 payment: PaymentLimits {
666 max_plan_name_len: MAX_FEE_PLAN_NAME_LEN,
667 max_plan_installments: MAX_FEE_PLAN_INSTALLMENTS,
668 max_assign_students: MAX_FEE_PLAN_ASSIGN_STUDENTS,
669 max_assign_writes: MAX_FEE_PLAN_ASSIGN_WRITES,
670 max_applied_lines: MAX_LEDGER_APPLIED_LINES,
671 max_request_key_len: MAX_PAYMENT_REQUEST_KEY_LEN,
672 ledger_kinds: PAYMENT_LEDGER_KINDS.to_vec(),
673 },
674 chatbot: ChatbotLimits {
675 max_message_len: MAX_CHATBOT_MESSAGE_LEN,
676 max_thread_title_len: MAX_CHATBOT_THREAD_TITLE_LEN,
677 min_max_message_len: MIN_MAX_CHATBOT_MESSAGE_LEN,
678 max_max_message_len: MAX_MAX_CHATBOT_MESSAGE_LEN,
679 default_max_message_len: DEFAULT_MAX_CHATBOT_MESSAGE_LEN,
680 min_history_turns: MIN_CHATBOT_HISTORY_TURNS,
681 max_history_turns: MAX_CHATBOT_HISTORY_TURNS,
682 default_history_turns: DEFAULT_CHATBOT_HISTORY_TURNS,
683 min_max_threads: MIN_MAX_CHATBOT_THREADS,
684 max_max_threads: MAX_MAX_CHATBOT_THREADS,
685 default_max_threads: DEFAULT_MAX_CHATBOT_THREADS,
686 },
687 rag: RagLimits {
688 max_scope_pairs: MAX_RAG_SCOPE_PAIRS,
689 max_citations: MAX_RAG_CITATIONS,
690 max_citation_pages: MAX_RAG_CITATION_PAGES,
691 max_message_len: MAX_CHATBOT_MESSAGE_LEN,
692 max_thread_title_len: MAX_CHATBOT_THREAD_TITLE_LEN,
693 min_max_message_len: MIN_MAX_CHATBOT_MESSAGE_LEN,
694 max_max_message_len: MAX_MAX_CHATBOT_MESSAGE_LEN,
695 default_max_message_len: DEFAULT_MAX_CHATBOT_MESSAGE_LEN,
696 min_history_turns: MIN_CHATBOT_HISTORY_TURNS,
697 max_history_turns: MAX_CHATBOT_HISTORY_TURNS,
698 default_history_turns: DEFAULT_CHATBOT_HISTORY_TURNS,
699 min_max_threads: MIN_MAX_CHATBOT_THREADS,
700 max_max_threads: MAX_MAX_CHATBOT_THREADS,
701 default_max_threads: DEFAULT_MAX_CHATBOT_THREADS,
702 },
703 pomodoro: PomodoroLimits {
704 min_counted_ms: MIN_COUNTED_POMODORO_MS,
705 max_counted_per_day: MAX_COUNTED_POMODORO_PER_DAY,
706 max_label_len: MAX_POMODORO_LABEL_LEN,
707 },
708 board: BoardLimits {
709 max_title_len: MAX_BOARD_TITLE_LEN,
710 max_participants: MAX_BOARD_PARTICIPANTS,
711 max_stroke_payload_len: MAX_STROKE_PAYLOAD_LEN,
712 max_epoch_strokes: MAX_EPOCH_STROKES,
713 max_board_strokes: MAX_BOARD_STROKES,
714 max_boards_per_creator: MAX_BOARDS_PER_CREATOR,
715 stroke_kinds: BOARD_STROKE_KINDS.to_vec(),
716 ws_tick_secs: BOARD_WS_TICK_SECS,
717 ws_max_board_id_len: MAX_BOARD_ID_LEN,
718 },
719 settings: SettingsLimits {
720 max_list_len: MAX_SETTINGS_LIST_LEN,
721 max_item_len: MAX_SETTINGS_ITEM_LEN,
722 min_exam_kind_weight: MIN_EXAM_KIND_WEIGHT,
723 max_exam_kind_weight: MAX_EXAM_KIND_WEIGHT,
724 max_grade_bands: MAX_GRADE_BANDS,
725 max_grade_label_len: MAX_GRADE_LABEL_LEN,
726 required_attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.to_vec(),
727 },
728 rate: RateLimits {
729 window_secs: 60,
730 auth_per_minute: st.rate_limit.auth_per_minute,
731 api_per_minute: st.rate_limit.api_per_minute,
732 chatbot_per_minute: st.chatbot_limit.max_per_window(),
733 rag_per_minute: st.rag_limit.max_per_window(),
734 },
735 request: RequestLimits {
736 max_page_limit: MAX_PAGE_LIMIT,
737 schedule_past_grace_ms: SCHEDULE_PAST_GRACE_MS,
738 request_timeout_secs: REQUEST_TIMEOUT_SECS,
739 max_request_id_len: MAX_REQUEST_ID_LEN,
740 },
741 }
742 }
743}
744
745/// Every fixed validation bound the API enforces. Unauthenticated: the
746/// registration and login forms need the username and password bounds before a
747/// session exists, and none of these values are secrets — they are the same
748/// rules a 400 would spell out.
749///
750/// The values are compile-time constants, so the response only ever changes
751/// with a deploy — cache it for the session rather than re-fetching per form.
752/// School-adjustable policy (exam kinds, attendance statuses, grade bands, the
753/// live `max_file_bytes` and chatbot knobs) is on `GET /settings` instead; what
754/// appears here for those is the fixed range a manager may set them within.
755#[utoipa::path(
756 get,
757 path = "/limits",
758 tag = "meta",
759 responses((status = 200, description = "Every fixed validation bound", body = LimitsResponse)),
760)]
761async fn get_limits(State(st): State<AppState>) -> Json<LimitsResponse> {
762 Json(LimitsResponse::new(&st))
763}