forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

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