forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBc44f362Ahmet Kaan Gümüş2 months ago520 commits

module.rs429 lines, 14.2 KiBHistoryRawDownload
1//! Per-school **module entitlements**: which parts of the product a school has
2//! bought. A module is exactly one router nest (`/meals`, `/exams`, …), so the
3//! unit a school is sold and the unit the router refuses are the same thing —
4//! there is no per-route entitlement to keep in sync with a per-route guard.
5//!
6//! A disabled module answers `403 {"error":"module disabled","module":"<name>"}`
7//! on every route in its nest ([`crate::web::module_gate`]), while an unmatched
8//! path inside it still `404`s, because the gate is a `route_layer`.
9//!
10//! Stored on the school registry row as bare lowercase strings, like
11//! [`crate::tenant::SchoolStatus`] — see [`crate::tenant::School::modules`].
12
13use std::collections::BTreeSet;
14
15use serde::Serialize;
16
17use crate::error::{AppError, ValidationError};
18
19/// One router nest a school may have switched on or off.
20///
21/// `Ord` is the declaration order and is only ever used to key the
22/// [`ModuleSet`] — every user-visible ordering goes through
23/// [`ModuleSet::names`], which sorts the strings.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
25#[serde(rename_all = "snake_case")]
26pub enum Module {
27 /// The `ai` package's module — and the switch on **every outbound AI
28 /// dispatch**, not just the `/chatbot` nest: a school without it sends no
29 /// data to an AI service at all (rag indexing is a silent no-op, the blob
30 /// stream refuses `module_disabled`).
31 Chatbot,
32 Notes,
33 Messages,
34 Events,
35 Appointments,
36 Courses,
37 CourseNotes,
38 Classes,
39 Sessions,
40 Exams,
41 Marks,
42 Meals,
43 Payments,
44 Work,
45 Pomodoro,
46 Questions,
47 BankQuestions,
48 Attendance,
49 Subjects,
50 Homework,
51 Boards,
52}
53
54/// The commercial bundle a module is sold in. A package is a name for a set of
55/// modules and nothing more — entitlement is always stored per module, so a
56/// re-packaging never has to migrate a school's row.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
58#[serde(rename_all = "snake_case")]
59pub enum Package {
60 Academics,
61 Communication,
62 Operations,
63 Ai,
64}
65
66impl Module {
67 pub const ALL: [Module; 21] = [
68 Module::Chatbot,
69 Module::Notes,
70 Module::Messages,
71 Module::Events,
72 Module::Appointments,
73 Module::Courses,
74 Module::CourseNotes,
75 Module::Classes,
76 Module::Sessions,
77 Module::Exams,
78 Module::Marks,
79 Module::Meals,
80 Module::Payments,
81 Module::Work,
82 Module::Pomodoro,
83 Module::Questions,
84 Module::BankQuestions,
85 Module::Attendance,
86 Module::Subjects,
87 Module::Homework,
88 Module::Boards,
89 ];
90
91 pub fn as_str(self) -> &'static str {
92 match self {
93 Module::Chatbot => "chatbot",
94 Module::Notes => "notes",
95 Module::Messages => "messages",
96 Module::Events => "events",
97 Module::Appointments => "appointments",
98 Module::Courses => "courses",
99 Module::CourseNotes => "course_notes",
100 Module::Classes => "classes",
101 Module::Sessions => "sessions",
102 Module::Exams => "exams",
103 Module::Marks => "marks",
104 Module::Meals => "meals",
105 Module::Payments => "payments",
106 Module::Work => "work",
107 Module::Pomodoro => "pomodoro",
108 Module::Questions => "questions",
109 Module::BankQuestions => "bank_questions",
110 Module::Attendance => "attendance",
111 Module::Subjects => "subjects",
112 Module::Homework => "homework",
113 Module::Boards => "boards",
114 }
115 }
116
117 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
118 Module::ALL
119 .into_iter()
120 .find(|m| m.as_str() == value)
121 .ok_or_else(|| ValidationError::Unknown {
122 field: "module",
123 value: value.to_string(),
124 })
125 }
126
127 /// The modules this one cannot work without. Every edge is a hard
128 /// structural reference — a `record<…>` field in
129 /// [`crate::migration_sql`] or a handler that reads the other module's row
130 /// — never a merely-nicer-together pairing; the evidence is on each line.
131 pub fn requires(self) -> &'static [Module] {
132 match self {
133 // `DEFINE FIELD course ON subject TYPE record<course>`
134 Module::Subjects => &[Module::Courses],
135 // `DEFINE FIELD course ON course_note TYPE record<course>`
136 Module::CourseNotes => &[Module::Courses],
137 // `DEFINE FIELD course ON course_session TYPE record<course>`
138 Module::Sessions => &[Module::Courses],
139 // `DEFINE FIELD course ON exam TYPE record<course>` +
140 // `DEFINE FIELD subject ON exam_question TYPE record<subject>`
141 Module::Exams => &[Module::Courses, Module::Subjects],
142 // `DEFINE FIELD course ON homework TYPE record<course>` +
143 // `DEFINE FIELD subject ON homework TYPE record<subject>`
144 Module::Homework => &[Module::Courses, Module::Subjects],
145 // `DEFINE FIELD course ON class_course TYPE record<course>` — a
146 // class is bulk enrollment into courses.
147 Module::Classes => &[Module::Courses],
148 // `DEFINE FIELD exam ON exam_result TYPE record<exam>`; the marks
149 // report is a weighted read of exam results.
150 Module::Marks => &[Module::Exams],
151 // The report tallies both halves: `attendance.event
152 // record<event>` and `session_attendance.session
153 // record<course_session>`.
154 Module::Attendance => &[Module::Events, Module::Sessions],
155 // No edge: `bank_question.subject` is `option<record<subject>>`,
156 // so a bank question stands on its own.
157 _ => &[],
158 }
159 }
160
161 pub fn package(self) -> Package {
162 match self {
163 Module::Courses
164 | Module::Subjects
165 | Module::Sessions
166 | Module::Exams
167 | Module::Marks
168 | Module::Homework
169 | Module::Classes
170 | Module::CourseNotes
171 | Module::Attendance
172 | Module::BankQuestions => Package::Academics,
173 Module::Notes
174 | Module::Messages
175 | Module::Events
176 | Module::Appointments
177 | Module::Questions
178 | Module::Boards => Package::Communication,
179 Module::Meals | Module::Payments | Module::Work | Module::Pomodoro => {
180 Package::Operations
181 }
182 Module::Chatbot => Package::Ai,
183 }
184 }
185
186 /// The modules that require this one — the reverse of [`Module::requires`],
187 /// derived rather than written down, so the two can never disagree.
188 pub fn dependents(self) -> Vec<Module> {
189 Module::ALL
190 .into_iter()
191 .filter(|other| other.requires().contains(&self))
192 .collect()
193 }
194}
195
196impl std::fmt::Display for Module {
197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198 f.write_str(self.as_str())
199 }
200}
201
202impl Package {
203 pub const ALL: [Package; 4] = [
204 Package::Academics,
205 Package::Communication,
206 Package::Operations,
207 Package::Ai,
208 ];
209
210 pub fn as_str(self) -> &'static str {
211 match self {
212 Package::Academics => "academics",
213 Package::Communication => "communication",
214 Package::Operations => "operations",
215 Package::Ai => "ai",
216 }
217 }
218
219 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
220 Package::ALL
221 .into_iter()
222 .find(|p| p.as_str() == value)
223 .ok_or_else(|| ValidationError::Unknown {
224 field: "package",
225 value: value.to_string(),
226 })
227 }
228
229 /// The modules this package sells, derived from [`Module::package`].
230 pub fn modules(self) -> Vec<Module> {
231 Module::ALL
232 .into_iter()
233 .filter(|m| m.package() == self)
234 .collect()
235 }
236}
237
238/// What one school has switched on. Ordered, so a set has exactly one
239/// serialization and a diff between two schools reads the same every time.
240#[derive(Debug, Clone, PartialEq, Eq, Default)]
241pub struct ModuleSet(BTreeSet<Module>);
242
243impl ModuleSet {
244 pub fn all() -> Self {
245 ModuleSet(Module::ALL.into_iter().collect())
246 }
247
248 pub fn empty() -> Self {
249 ModuleSet(BTreeSet::new())
250 }
251
252 pub fn contains(&self, module: Module) -> bool {
253 self.0.contains(&module)
254 }
255
256 pub fn insert(&mut self, module: Module) {
257 self.0.insert(module);
258 }
259
260 pub fn remove(&mut self, module: Module) {
261 self.0.remove(&module);
262 }
263
264 pub fn iter(&self) -> impl Iterator<Item = Module> + '_ {
265 self.0.iter().copied()
266 }
267
268 pub fn is_empty(&self) -> bool {
269 self.0.is_empty()
270 }
271
272 /// Parse a client-supplied list. An unknown name is refused by name rather
273 /// than dropped: silently ignoring it would sell a school a module that
274 /// does not exist and report success.
275 pub fn from_names(names: &[String]) -> Result<Self, ValidationError> {
276 let mut set = BTreeSet::new();
277 for name in names {
278 set.insert(Module::try_from_str(name)?);
279 }
280 Ok(ModuleSet(set))
281 }
282
283 /// The stored form: sorted, so the row is byte-stable.
284 pub fn names(&self) -> Vec<String> {
285 let mut names: Vec<String> = self.iter().map(|m| m.as_str().to_string()).collect();
286 names.sort();
287 names
288 }
289
290 /// Every `(module, missing requirement)` pair this set holds, in a stable
291 /// order.
292 pub fn missing_requirements(&self) -> Vec<(Module, Module)> {
293 self.iter()
294 .flat_map(|module| {
295 module
296 .requires()
297 .iter()
298 .filter(|needed| !self.contains(**needed))
299 .map(move |needed| (module, *needed))
300 })
301 .collect()
302 }
303
304 /// Refuse a set that switches a module on without what it structurally
305 /// needs. One `409` naming **every** violation, so a caller fixing a set
306 /// does not discover them one round trip at a time.
307 pub fn validate(&self) -> Result<(), AppError> {
308 let missing = self.missing_requirements();
309 if missing.is_empty() {
310 return Ok(());
311 }
312 let message = missing
313 .into_iter()
314 .map(|(module, needed)| format!("{module} requires {needed}, which is not enabled"))
315 .collect::<Vec<_>>()
316 .join("; ");
317 Err(AppError::ConflictOwned(message))
318 }
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 #[test]
326 fn every_module_names_itself_and_round_trips() {
327 assert_eq!(Module::ALL.len(), 21);
328 let mut seen = BTreeSet::new();
329 for module in Module::ALL {
330 assert!(seen.insert(module.as_str()), "duplicate {module}");
331 assert_eq!(Module::try_from_str(module.as_str()).unwrap(), module);
332 }
333 assert!(Module::try_from_str("course-notes").is_err(), "snake_case");
334 assert!(Module::try_from_str("").is_err());
335 }
336
337 /// A cycle would make some set of modules unsatisfiable — every member
338 /// would need another member that needs it back.
339 #[test]
340 fn the_dependency_graph_is_acyclic() {
341 fn depth(module: Module, seen: &mut Vec<Module>) {
342 assert!(!seen.contains(&module), "cycle through {module}: {seen:?}");
343 seen.push(module);
344 for needed in module.requires() {
345 depth(*needed, seen);
346 }
347 seen.pop();
348 }
349 for module in Module::ALL {
350 depth(module, &mut Vec::new());
351 }
352 }
353
354 #[test]
355 fn every_module_is_sold_in_exactly_one_package() {
356 let packaged: Vec<Module> = Package::ALL
357 .into_iter()
358 .flat_map(Package::modules)
359 .collect();
360 assert_eq!(packaged.len(), Module::ALL.len());
361 for module in Module::ALL {
362 assert_eq!(
363 packaged.iter().filter(|m| **m == module).count(),
364 1,
365 "{module} is not in exactly one package"
366 );
367 }
368 }
369
370 #[test]
371 fn dependents_is_the_exact_reverse_of_requires() {
372 for module in Module::ALL {
373 for dependent in module.dependents() {
374 assert!(dependent.requires().contains(&module));
375 }
376 for needed in module.requires() {
377 assert!(needed.dependents().contains(&module));
378 }
379 }
380 // The phrasing a caller builds from the reverse edges.
381 assert_eq!(Module::Exams.dependents(), vec![Module::Marks]);
382 assert_eq!(
383 Module::Courses.dependents(),
384 vec![
385 Module::CourseNotes,
386 Module::Classes,
387 Module::Sessions,
388 Module::Exams,
389 Module::Subjects,
390 Module::Homework,
391 ]
392 );
393 }
394
395 #[test]
396 fn a_full_set_is_valid_and_a_lone_module_names_all_it_misses() {
397 assert!(ModuleSet::all().validate().is_ok());
398 assert!(ModuleSet::empty().validate().is_ok());
399
400 let mut lone = ModuleSet::empty();
401 lone.insert(Module::Exams);
402 let err = lone.validate().expect_err("exams alone is unsatisfiable");
403 let message = err.to_string();
404 assert!(
405 message.contains("exams requires courses, which is not enabled"),
406 "{message}"
407 );
408 assert!(
409 message.contains("exams requires subjects, which is not enabled"),
410 "both misses in one message: {message}"
411 );
412 assert!(matches!(err, AppError::ConflictOwned(_)));
413 }
414
415 #[test]
416 fn names_round_trip_and_an_unknown_name_is_refused() {
417 let all = ModuleSet::all();
418 let names = all.names();
419 assert_eq!(names.len(), 21);
420 assert!(names.windows(2).all(|w| w[0] < w[1]), "sorted: {names:?}");
421 assert_eq!(ModuleSet::from_names(&names).unwrap(), all);
422
423 let err = ModuleSet::from_names(&["meals".into(), "kantin".into()]).unwrap_err();
424 assert!(
425 err.to_string().contains("`kantin`"),
426 "names the offender: {err}"
427 );
428 }
429}