forge
Explore
Log in

Don't you dare go Hollow

Exam taking, WS protocol, endpoint and role tables

Browse files at this commit

52f608d477cc449fa7229b9182cae5831dc80acdAhmet Kaan GümüşParent: 4169291
  • docs
    • exam taking, WS protocol, endpoint and role tables
Show full message
📝 docs: exam taking, WS protocol, endpoint and role tables
README.mdmodified+168 -5
@@ -7,7 +7,11 @@ Session-cookie auth with four hierarchical roles (`student < teacher < manager
7 then mark users present / absent / late / excused. Marks are course-shaped7 then mark users present / absent / late / excused. Marks are course-shaped
8 (Google Classroom style): a teacher creates a course, enrolls students, adds8 (Google Classroom style): a teacher creates a course, enrolls students, adds
9 weighted exams inside it, and grades; students read a per-course weighted9 weighted exams inside it, and grades; students read a per-course weighted
10-average and an overall average from their mark report.10+average and an overall average from their mark report. Exams can be scheduled
11+**sync** (one fixed window) or **async** (start anytime inside the window, with
12+a personal time budget); students *sit* them via attempts, and teachers watch
13+attendance, per-student remaining time, submissions, and marks land live on a
14+monitor endpoint (snapshot or SSE stream).
11 15
12 Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)16 Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)
13 constructed only after its restrictions pass — invalid input can't be17 constructed only after its restrictions pass — invalid input can't be
@@ -134,6 +138,11 @@ effect on the user's very next call (no re-login).
134 | Create events; remove attendance rows | teacher | |138 | Create events; remove attendance rows | teacher | |
135 | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |139 | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event |
136 | View courses/exams; read **own** result, courses, mark report | student | |140 | View courses/exams; read **own** result, courses, mark report | student | |
141+| Sit a scheduled exam: start / read / submit **own** attempt | student | Must be enrolled; window enforced by the server clock |
142+| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | Attempt must be `in_progress`; deadline judged by the server clock |
143+| Author an exam's questions (add/edit/delete) | teacher | Course-management rights; frozen once anyone has an attempt |
144+| Read a question list (with `correct`) or a student's answer sheet | teacher | Staff-wide read, like result lists |
145+| Watch an exam's live monitor (snapshot or SSE stream) | teacher | Staff-wide read, like result lists |
137 | Create courses | teacher | The creator manages the course |146 | Create courses | teacher | The creator manages the course |
138 | Manage inside a course: edit/delete it, enroll/unenroll, add/edit/delete its exams, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course |147 | Manage inside a course: edit/delete it, enroll/unenroll, add/edit/delete its exams, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course |
139 | View rosters, full result lists, exam statistics, any user's mark report | teacher | Staff-wide reads |148 | View rosters, full result lists, exam statistics, any user's mark report | teacher | Staff-wide reads |
@@ -214,17 +223,30 @@ logged-in user.
214 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a user (idempotent upsert; course manager) |223 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a user (idempotent upsert; course manager) |
215 | GET | `/courses/{id}/enrollments` | teacher | List the course roster |224 | GET | `/courses/{id}/enrollments` | teacher | List the course roster |
216 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |225 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |
217-| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, weight}` — add an exam (course manager) |226+| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, weight, mode?, starts_at?, ends_at?, duration_ms?}` — add an exam (course manager) |
218 | GET | `/courses/{id}/exams` | student | List the course's exams |227 | GET | `/courses/{id}/exams` | student | List the course's exams |
219 | GET | `/exams` | student | List all exams |228 | GET | `/exams` | student | List all exams |
220 | GET | `/exams/{id}` | student | Get exam |229 | GET | `/exams/{id}` | student | Get exam |
221-| PATCH | `/exams/{id}` | teacher | Edit exam incl. `weight` (course manager; `course` immutable) |230+| PATCH | `/exams/{id}` | teacher | Edit exam incl. `weight` and schedule (course manager; `course` immutable, `mode` frozen once attempted) |
222-| DELETE | `/exams/{id}` | teacher | Delete exam + its results (course manager) |231+| DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) |
223 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) |232 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) |
224 | GET | `/exams/{id}/results` | teacher | List every result for the exam |233 | GET | `/exams/{id}/results` | teacher | List every result for the exam |
225 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |234 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |
226 | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |235 | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |
227 | GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results |236 | GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results |
237+| POST | `/exams/{id}/attempt` | student | Start (`201`) or resume (`200`) the caller's attempt — enrolled, window open |
238+| GET | `/exams/{id}/attempt` | student | Own attempt: status, deadline, `remaining_ms`, mark, progress (`answered`/`question_count`), server `now` |
239+| POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed) |
240+| POST | `/exams/{id}/questions` | teacher | `{text, kind, points, choices?, correct?}` — add a question (course manager; frozen once attempted) |
241+| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included |
242+| PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) |
243+| DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |
244+| GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires an attempt) |
245+| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while `in_progress` |
246+| GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` |
247+| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room: state ticks, autosave, finish (see "Taking an exam") |
248+| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × attempts × marks + per-student progress + counts |
249+| GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s |
228 | GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |250 | GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |
229 | GET | `/marks/{user}` | teacher | Any user's mark report |251 | GET | `/marks/{user}` | teacher | Any user's mark report |
230 252
@@ -257,6 +279,58 @@ is independent: omitted (or `null`) keeps the current value, an empty string
257 separators, `birth_date` is a real `YYYY-MM-DD` calendar date not in the279 separators, `birth_date` is a real `YYYY-MM-DD` calendar date not in the
258 future. Names allow unicode; usernames stay ASCII.280 future. Names allow unicode; usernames stay ASCII.
259 281
282+## Sync/async exams, attempts & live monitoring
283+
284+An exam is **unscheduled** by default (all schedule fields `null`) — graded
285+offline, exactly as before; attempts on it are a `409`. Scheduling means
286+setting, as one consistent unit (validated together on create and after every
287+`PATCH` merge):
288+
289+- `mode: "sync"` + `starts_at` + `ends_at` — everyone sits inside one window;
290+ every attempt's deadline is `ends_at`.
291+- `mode: "async"` + `starts_at` + `ends_at` + `duration_ms` — each student
292+ starts anywhere inside the window and gets
293+ `min(started_at + duration_ms, ends_at)` as their personal deadline.
294+ `duration_ms` is 1 minute to 24 hours.
295+- `ends_at` must be strictly after `starts_at`. All instants are the usual UTC
296+ unix-milliseconds, judged only by the server clock (`GET /time` for sync).
297+
298+A student **sits** a scheduled exam through their attempt (one per exam+user,
299+by construction — the row id is the composite key):
300+
301+- `POST /exams/{id}/attempt` starts it (enrolled + window open). Re-posting
302+ returns the existing attempt unchanged (`200`, not `201`): reconnecting
303+ never resets the clock. Starting is the live-attendance signal.
304+- `GET /exams/{id}/attempt` is the student's exam screen: `status`
305+ (`in_progress` | `submitted` | `expired`), `deadline`, `remaining_ms`, own
306+ `mark` once graded, and the server `now`.
307+- `POST /exams/{id}/attempt/finish` submits. After the deadline the attempt is
308+ `expired` — a valid terminal state (the student used their full time), and
309+ finishing answers `409`.
310+
311+Deadlines are **recomputed from the exam's current schedule on every read**,
312+never stored: a teacher who `PATCH`es `ends_at` (or an async `duration_ms`)
313+while the exam runs moves every running deadline instantly. What's frozen once
314+anyone has started is only `mode` (including unscheduling) — swapping the
315+deadline rules mid-sitting would be a different exam (`409`).
316+
317+Teachers watch it all live: `GET /exams/{id}/live` returns one snapshot —
318+the enrolled roster joined with attempts and marks (`not_started` |
319+`in_progress` | `submitted` | `expired`, per-student `deadline` /
320+`remaining_ms` / `mark`) plus summary counts, all judged at a single `now`.
321+`GET /exams/{id}/live/stream` is the same JSON as Server-Sent Events: a
322+`snapshot` event immediately on connect, then every ~2 s — attendance, ticking
323+clocks, submissions, and marks land without polling:
324+
325+```js
326+const es = new EventSource(`${BASE}/exams/${id}/live/stream`, { withCredentials: true });
327+es.addEventListener("snapshot", (e) => render(JSON.parse(e.data)));
328+```
329+
330+Deleting an exam (or its course) cascades attempts, questions, and answers
331+along with results; unenrolling mid-exam hides the student from the monitor
332+roster but keeps the attempt and mark rows, mirroring the marks report.
333+
260 > **Upgrading a pre-course database**: `exam` rows created before courses334 > **Upgrading a pre-course database**: `exam` rows created before courses
261 > existed lack the now-required `course` and `weight` fields and will fail to335 > existed lack the now-required `course` and `weight` fields and will fail to
262 > deserialize. For a dev database, delete `./data/hezarfen.db` and reboot; to336 > deserialize. For a dev database, delete `./data/hezarfen.db` and reboot; to
@@ -264,6 +338,88 @@ future. Names allow unicode; usernames stay ASCII.
264 > `UPDATE exam SET course = course:<id>, weight = 1 WHERE course = NONE;`338 > `UPDATE exam SET course = course:<id>, weight = 1 WHERE course = NONE;`
265 > after creating a course to attach them to.339 > after creating a course to attach them to.
266 340
341+## Taking an exam: questions, answers & the exam room
342+
343+Teachers author a question list per exam; students answer inside their
344+attempt, autosaved as they go; choice questions are machine-checked as a
345+**suggestion** — the final mark stays a human call through the existing
346+`POST /exams/{id}/results`.
347+
348+**Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`,
349+course-management rights): each has `text` (≤ 2000 chars), `points` `1`–`100`
350+(its share of the auto-score), and a `kind`:
351+
352+- `kind: "choice"` — carries `choices` (2–10 options, each ≤ 500 chars) and
353+ `correct`, the zero-based index of the right option. Auto-scorable.
354+- `kind: "text"` — free text, judged by the grader; carries neither.
355+
356+The kind bundle is validated as a unit (create and after every `PATCH` merge):
357+switching a question to `text` needs explicit `"choices": null, "correct":
358+null`, switching to `choice` must bring both along. Presentation order is
359+creation order. The whole list **freezes once anyone has started an attempt**
360+(`409` on create/edit/delete) — editing questions under a sitting student
361+would fork what "the exam" means. Deleting a question cascades its answers.
362+
363+**Answering** (student, attempt `in_progress`, deadline judged by the server
364+clock on every save):
365+
366+- `GET /exams/{id}/attempt/questions` — the sitting view. Requires an attempt
367+ (`404` before `POST /exams/{id}/attempt`; also the anti-peek gate), never
368+ contains `correct`, and embeds the caller's own saved answer per question
369+ (`{selected, text, updated_at}` or `null`). Still readable after
370+ submitting/expiry, for review.
371+- `POST /exams/{id}/attempt/answers` `{question_id, selected? | text?}` — an
372+ upsert: one row per question+user, re-answering overwrites. The payload must
373+ match the question's kind (`selected` indexing a choice, or `text`
374+ ≤ 10 000 chars — empty clears the draft); mismatches are `400`s. Once the
375+ attempt is submitted or past its deadline every save is a `409`; answers
376+ saved in time survive untouched for grading.
377+
378+**Grading view** (teacher+): `GET /exams/{id}/attempts/{user}/answers` returns
379+the student's sheet — every saved answer with `is_correct` (`true`/`false` for
380+choice, `null` for text: that's the grader's call) plus
381+`auto_score: {earned, possible}` summing the choice questions' points. It is a
382+suggestion to read while grading, never written anywhere.
383+
384+**The exam room (WebSocket)** — `GET /exams/{id}/attempt/ws`, cookie-authed
385+like everything else; REST above remains the full fallback. Gates run before
386+the upgrade: unknown exam `404`, unscheduled `409`, not enrolled `403`, no
387+attempt yet `404` (start it first), submitted/expired `409`. Then JSON text
388+frames:
389+
390+| direction | frame |
391+|-----------|-------|
392+| server → | `{"type":"state", status, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |
393+| client → | `{"type":"answer", "question_id":"…", "selected":1}` or `{"type":"answer", "question_id":"…", "text":"…"}` |
394+| server → | `{"type":"saved", question_id, updated_at}` — the autosave ack |
395+| client → | `{"type":"finish"}` — submit the attempt |
396+| server → | `{"type":"finished", finished_at}`, then Close |
397+| server → | `{"type":"expired"}`, then Close — a tick noticed the deadline |
398+| client → | `{"type":"ping"}` → server `{"type":"pong"}` |
399+| server → | `{"type":"error", message}` — bad JSON, wrong kind, deadline, … |
400+
401+Every tick and every save re-read the exam, so a mid-exam `ends_at` extension
402+moves the room's countdown on the next tick, and no stale socket can write
403+past its real deadline — the socket shares the exact REST write path.
404+Example client:
405+
406+```js
407+const ws = new WebSocket(`${BASE.replace("http", "ws")}/exams/${id}/attempt/ws`);
408+ws.onmessage = (e) => {
409+ const m = JSON.parse(e.data);
410+ if (m.type === "state") renderCountdown(m.remaining_ms, m.answered, m.question_count);
411+ if (m.type === "saved") markSaved(m.question_id);
412+};
413+const save = (question_id, selected) =>
414+ ws.send(JSON.stringify({ type: "answer", question_id, selected }));
415+```
416+
417+The live monitor rides along: each roster row now carries `answered` and
418+`last_activity` (latest save instant), and the snapshot a top-level
419+`question_count`, so "stuck at 3/10 for five minutes" is visible at a glance.
420+The student's own `GET /exams/{id}/attempt` echoes the same
421+`answered`/`question_count` pair.
422+
267 ## Quick tour (curl)423 ## Quick tour (curl)
268 424
269 ```sh425 ```sh
@@ -328,12 +484,19 @@ src/
328 attendance.rs AttendanceId · AttendanceStatus · Attendance484 attendance.rs AttendanceId · AttendanceStatus · Attendance
329 course.rs CourseId · CourseTitle · CourseDescription · Course485 course.rs CourseId · CourseTitle · CourseDescription · Course
330 enrollment.rs EnrollmentId · Enrollment (one row per course+user)486 enrollment.rs EnrollmentId · Enrollment (one row per course+user)
331- exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · ExamWeight · Exam (belongs to a course)487+ exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · ExamWeight ·
488+ ExamMode · ExamDuration · ExamSchedule · Exam (belongs to a course)
489+ exam_attempt.rs ExamAttemptId · AttemptStatus · ExamAttempt (one sitting per exam+user)
490+ exam_question.rs ExamQuestionId · QuestionText · QuestionKind · QuestionPoints ·
491+ ChoiceText · QuestionSpec · ExamQuestion (choice|text, per exam)
492+ exam_answer.rs ExamAnswerId · AnswerText · ExamAnswer (one row per question+user) ·
493+ auto_score (choice-question suggestion)
332 exam_result.rs ExamResultId · Mark · ExamResult (one row per exam+user)494 exam_result.rs ExamResultId · Mark · ExamResult (one row per exam+user)
333 web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +495 web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +
334 auth extractors496 auth extractors
335 extractor.rs CurrentUser · RequireTeacher · RequireAdmin497 extractor.rs CurrentUser · RequireTeacher · RequireAdmin
336 dto.rs shared UserResponse · CourseResponse · ExamResponse schemas498 dto.rs shared UserResponse · CourseResponse · ExamResponse schemas
499+ exam_ws.rs the student exam-room WebSocket (state ticks, autosave, finish)
337 auth.rs users.rs notes.rs events.rs courses.rs exams.rs marks.rs500 auth.rs users.rs notes.rs events.rs courses.rs exams.rs marks.rs
338 ```501 ```
339 502