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

exam.rs389 lines, 12.8 KiBHistoryRawDownload
1use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS};
2use crate::domain::class_course::ClassCourseId;
3use crate::domain::monotonic_id::next_uuid;
4use crate::domain::settings::ExamKindDef;
5use crate::domain::term::TermId;
6use crate::domain::timestamp::Timestamp;
7use crate::domain::user::UserId;
8use crate::error::{AppError, ValidationError};
9
10/// The one spelling of the re-draft refusal, shared by the update workflow's
11/// pre-flight gate ([`crate::service::exam::update`]) and the in-transaction
12/// guard that re-makes it at write time — a client cannot tell which of the
13/// two refused.
14pub(crate) fn redraft_error() -> AppError {
15 AppError::Conflict(
16 "cannot turn a published exam back into a draft after attempts or results exist",
17 )
18}
19use crate::validate::{
20 validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional,
21 validate_required,
22};
23
24#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
25#[sqlx(transparent)]
26pub struct ExamId(uuid::Uuid);
27
28impl ExamId {
29 /// Minted from the process-wide monotonic generator, not a plain random
30 /// UUID: exams list `id DESC` (newest first,
31 /// [`crate::db::exam::list_windowed`]),
32 /// and a random low half scrambles rows minted in the same millisecond.
33 pub fn generate() -> Self {
34 Self(next_uuid())
35 }
36
37 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
38 /// cannot take the newtype. Static `query!` binds take `self` directly.
39 pub fn uuid(&self) -> uuid::Uuid {
40 self.0
41 }
42
43 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
44 /// which matches no row.
45 pub fn from_key(key: &str) -> Self {
46 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
47 }
48
49 pub fn key(&self) -> String {
50 self.0.to_string()
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
55#[sqlx(transparent)]
56pub struct ExamTitle(String);
57
58impl ExamTitle {
59 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
60 validate_required("title", value, MAX_EXAM_TITLE_LEN)?;
61 Ok(Self(value.to_string()))
62 }
63
64 pub fn as_str(&self) -> &str {
65 &self.0
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
70#[sqlx(transparent)]
71pub struct ExamDescription(String);
72
73impl ExamDescription {
74 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
75 validate_optional("description", value, MAX_EXAM_DESCRIPTION_LEN)?;
76 Ok(Self(value.to_string()))
77 }
78
79 pub fn as_str(&self) -> &str {
80 &self.0
81 }
82}
83
84/// A validated exam kind — one of the school's configured kinds
85/// ([`crate::domain::settings::Settings::get_exam_kinds`]). The kind carries
86/// the exam's weight in the course average (set per kind in settings, not per
87/// exam). Stored exams keep their kind even if the school later edits the
88/// list; only new writes are held to the current one.
89#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
90#[sqlx(transparent)]
91pub struct ExamKind(String);
92
93impl ExamKind {
94 pub fn try_new(value: &str, allowed: &[ExamKindDef]) -> Result<Self, ValidationError> {
95 if !allowed.iter().any(|kind| kind.get_name() == value) {
96 return Err(ValidationError::Invalid {
97 field: "kind",
98 reason: "is not one of this school's exam kinds (see GET /settings)",
99 });
100 }
101 Ok(Self(value.to_string()))
102 }
103
104 pub fn as_str(&self) -> &str {
105 &self.0
106 }
107}
108
109/// A validated exam mode: `sync` (everyone sits inside one fixed window),
110/// `async` (each student starts inside the window and gets `duration_ms`), or
111/// `open` (no window — sit anytime, with an optional per-attempt duration).
112#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
113#[sqlx(transparent)]
114pub struct ExamMode(String);
115
116impl ExamMode {
117 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
118 validate_exam_mode(value)?;
119 Ok(Self(value.to_string()))
120 }
121
122 pub fn as_str(&self) -> &str {
123 &self.0
124 }
125}
126
127/// A validated per-attempt time budget, milliseconds. Required for an `async`
128/// exam, optional for an `open` one (absent = unlimited time).
129#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
130#[sqlx(transparent)]
131pub struct ExamDuration(i64);
132
133impl ExamDuration {
134 pub fn try_new(value: i64) -> Result<Self, ValidationError> {
135 validate_exam_duration(value)?;
136 Ok(Self(value))
137 }
138
139 pub fn as_millis(&self) -> i64 {
140 self.0
141 }
142}
143
144/// How many attempts a student gets at an exam. `0` means unlimited — the
145/// same spelling on the wire and in storage; `1` (the default) is the classic
146/// single sitting. Editable live: raising it mid-exam grants retakes, and
147/// lowering it only blocks *future* starts (existing attempts stand).
148#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
149#[sqlx(transparent)]
150pub struct ExamAttemptLimit(i64);
151
152impl ExamAttemptLimit {
153 pub fn try_new(value: i64) -> Result<Self, ValidationError> {
154 validate_attempt_limit(value)?;
155 Ok(Self(value))
156 }
157
158 /// The single-sitting default for exams created without a limit.
159 pub fn single() -> Self {
160 Self(1)
161 }
162
163 pub fn as_i64(&self) -> i64 {
164 self.0
165 }
166
167 pub fn is_unlimited(&self) -> bool {
168 self.0 == UNLIMITED_EXAM_ATTEMPTS
169 }
170
171 /// Whether a student who already used `used` attempts may start another.
172 pub fn allows_another(&self, used: usize) -> bool {
173 self.is_unlimited() || (used as i64) < self.0
174 }
175}
176
177/// The scheduling fields of an exam, validated as a unit — they only make
178/// sense together. `try_new` is the sole constructor, so an `ExamSchedule` in
179/// hand always satisfies:
180///
181/// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an offline-graded
182/// exam; attempts are rejected),
183/// - `sync` → `starts_at` + `ends_at`, no duration (everyone's deadline is
184/// `ends_at`),
185/// - `async` → `starts_at` + `ends_at` + `duration_ms`, with `duration_ms` no
186/// greater than the window (a student who starts at `t` gets until
187/// `min(t + duration_ms, ends_at)`),
188/// - `open` → no window; `duration_ms` optional (a student who starts at `t`
189/// gets until `t + duration_ms`, or forever when absent),
190/// - `ends_at` strictly after `starts_at` whenever the window exists.
191#[derive(Debug, Clone, Default)]
192pub struct ExamSchedule {
193 pub(crate) mode: Option<ExamMode>,
194 pub(crate) starts_at: Option<Timestamp>,
195 pub(crate) ends_at: Option<Timestamp>,
196 pub(crate) duration_ms: Option<ExamDuration>,
197}
198
199impl ExamSchedule {
200 pub fn try_new(
201 mode: Option<ExamMode>,
202 starts_at: Option<Timestamp>,
203 ends_at: Option<Timestamp>,
204 duration_ms: Option<ExamDuration>,
205 ) -> Result<Self, ValidationError> {
206 let invalid = |field, reason| ValidationError::Invalid { field, reason };
207 match &mode {
208 None => {
209 if starts_at.is_some() || ends_at.is_some() || duration_ms.is_some() {
210 return Err(invalid(
211 "mode",
212 "starts_at, ends_at, and duration_ms require a mode (sync, async, or open)",
213 ));
214 }
215 }
216 Some(m) if m.as_str() == "open" => {
217 if starts_at.is_some() || ends_at.is_some() {
218 return Err(invalid(
219 "starts_at",
220 "an open exam has no window — drop starts_at/ends_at or pick sync/async",
221 ));
222 }
223 // `duration_ms` stays optional: limited time per attempt when
224 // set, unlimited when absent.
225 }
226 Some(m) => {
227 if starts_at.is_none() {
228 return Err(invalid("starts_at", "required for a scheduled exam"));
229 }
230 if ends_at.is_none() {
231 return Err(invalid("ends_at", "required for a scheduled exam"));
232 }
233 if ends_at <= starts_at {
234 return Err(invalid("ends_at", "must be after starts_at"));
235 }
236 match (m.as_str(), duration_ms.is_some()) {
237 ("async", false) => {
238 return Err(invalid("duration_ms", "required for an async exam"));
239 }
240 ("sync", true) => {
241 return Err(invalid(
242 "duration_ms",
243 "only async and open exams take a duration",
244 ));
245 }
246 _ => {}
247 }
248 // Below the match on purpose: a `sync` exam carrying a
249 // duration is answered by the match's root cause (it takes no
250 // duration at all), not by how the duration compares to the
251 // window. Only `async` reaches here with one to compare.
252 if let (Some(duration), Some(starts), Some(ends)) =
253 (duration_ms, starts_at, ends_at)
254 {
255 let window_ms = ends.as_millis().saturating_sub(starts.as_millis());
256 if duration.as_millis() > window_ms {
257 return Err(invalid(
258 "duration_ms",
259 "must fit within the starts_at..ends_at window",
260 ));
261 }
262 }
263 }
264 }
265 Ok(Self {
266 mode,
267 starts_at,
268 ends_at,
269 duration_ms,
270 })
271 }
272
273 pub fn get_mode(&self) -> Option<&ExamMode> {
274 self.mode.as_ref()
275 }
276}
277
278/// One exam. The schedule is flattened into columns, always written through
279/// an [`ExamSchedule`], so the invariants above hold for every stored row.
280///
281/// The `result_count` counter deliberately does NOT live on the struct: it is
282/// a plain `BIGINT NOT NULL DEFAULT 0` column that only the mark-write and
283/// mark-delete paths touch with conditional single statements, and every read
284/// of it is its own `SELECT` — no whole-row rewrite can clobber it, and no
285/// stale snapshot can pin it.
286#[derive(Debug, Clone, sqlx::FromRow)]
287pub struct Exam {
288 pub(crate) id: ExamId,
289 pub(crate) creator: UserId,
290 pub(crate) class_course: ClassCourseId,
291 pub(crate) term: TermId,
292 pub(crate) title: ExamTitle,
293 pub(crate) description: ExamDescription,
294 pub(crate) kind: ExamKind,
295 pub(crate) mode: Option<ExamMode>,
296 pub(crate) starts_at: Option<Timestamp>,
297 pub(crate) ends_at: Option<Timestamp>,
298 pub(crate) duration_ms: Option<ExamDuration>,
299 pub(crate) max_attempts: ExamAttemptLimit,
300 pub(crate) allow_rejoin: bool,
301 pub(crate) allow_review: bool,
302 // Work-in-progress marker: a draft is visible only to its course's
303 // managers, cannot be sat, and cannot be graded.
304 pub(crate) draft: bool,
305}
306
307impl Exam {
308 pub fn get_id(&self) -> &ExamId {
309 &self.id
310 }
311
312 pub fn get_creator(&self) -> &UserId {
313 &self.creator
314 }
315
316 pub fn get_class_course(&self) -> &ClassCourseId {
317 &self.class_course
318 }
319
320 pub fn get_term(&self) -> &TermId {
321 &self.term
322 }
323
324 pub fn get_title(&self) -> &ExamTitle {
325 &self.title
326 }
327
328 pub fn get_description(&self) -> &ExamDescription {
329 &self.description
330 }
331
332 pub fn get_kind(&self) -> &ExamKind {
333 &self.kind
334 }
335
336 pub fn get_mode(&self) -> Option<&ExamMode> {
337 self.mode.as_ref()
338 }
339
340 pub fn get_starts_at(&self) -> Option<Timestamp> {
341 self.starts_at
342 }
343
344 pub fn get_ends_at(&self) -> Option<Timestamp> {
345 self.ends_at
346 }
347
348 pub fn get_duration_ms(&self) -> Option<ExamDuration> {
349 self.duration_ms
350 }
351
352 pub fn get_max_attempts(&self) -> ExamAttemptLimit {
353 self.max_attempts
354 }
355
356 /// Whether a student who left the exam room may come back into it (and
357 /// keep saving answers). The teacher can flip this live.
358 pub fn get_allow_rejoin(&self) -> bool {
359 self.allow_rejoin
360 }
361
362 /// Whether students may review their graded attempt once results are out.
363 /// The teacher can flip this live.
364 pub fn get_allow_review(&self) -> bool {
365 self.allow_review
366 }
367
368 /// Whether the exam is still being prepared — hidden from students, not
369 /// sittable, not gradable, until published.
370 pub fn is_draft(&self) -> bool {
371 self.draft
372 }
373
374 /// The stored schedule as the validated bundle (for merge-on-update).
375 /// Bypasses `try_new`: the fields were written through an `ExamSchedule`,
376 /// so the invariants already hold.
377 pub fn schedule(&self) -> ExamSchedule {
378 ExamSchedule {
379 mode: self.mode.clone(),
380 starts_at: self.starts_at,
381 ends_at: self.ends_at,
382 duration_ms: self.duration_ms,
383 }
384 }
385
386 pub fn is_creator(&self, user: &UserId) -> bool {
387 &self.creator == user
388 }
389}