forge
Explore
Log in

Don't you dare go Hollow

Paginate every list endpoint

Browse files at this commit

f3d2b0a1708fbae8957932638a577ed4b1f4f95cAhmet Kaan GümüşParent: 9aca0b4
  • feat
    • paginate every list endpoint
Show full message
✨ feat(web)!: paginate every list endpoint

Every array-returning GET now accepts `?limit=&offset=` and returns a
`{ items, total, limit, offset }` envelope instead of a bare array.
Paging is opt-in: omitting `limit` returns the full list (limit echoes
null), so callers that need the whole set — an exam's questions during a
sitting, roster/grade pickers — are never silently truncated. `total`
always carries the unpaged count, so a frontend can render "100 of 256"
and drive a pager without a second request.

Windowing is a slice over the already-ordered domain list (the domain
layer is untouched); endpoints that embed people run that join over the
page alone. `limit` must be 1..=500 and `offset` >= 0 (else 400); an
offset past the end yields an empty page, not an error.

Covers all 17 list GETs, including /courses/me, /work/me, /work/{user},
and /users/search — whose hard 10-row cap is dropped in favour of the
same paging. Not paged: /exams/{id}/attempt/{questions,answers}, the
marks & attendance report objects, /exams/{id}/live, and /settings.

Shared machinery lives in web::page (Page<T>, PageParams, paginate).
Docs updated across the OpenAPI spec (utoipa query params + Page_*
response schemas), the Swagger UI it feeds, and the README (a Paging
section plus a `· paged` tag on every list row).

BREAKING CHANGE: list endpoints return a pagination envelope, not a bare
JSON array — clients must read `.items`. /users/search no longer caps at
10 results.
README.mdmodified+30 -17
@@ -228,6 +228,19 @@ monitor) additionally need **course-management rights** (creator or manager+):
228 one teacher cannot look into another teacher's course, and the per-user228 one teacher cannot look into another teacher's course, and the per-user
229 marks/attendance reports narrow to the courses the caller manages.229 marks/attendance reports narrow to the courses the caller manages.
230 230
231+**Paging.** Every list endpoint below (the rows tagged **· paged**) accepts
232+`?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope
233+rather than a bare array. `total` is the full row count *before* the window, so
234+a frontend can show "100 of 256" and page with `offset`. Paging is **opt-in**:
235+omit `limit` and you get every remaining row (the echoed `limit` is then
236+`null`), so a caller that sends no parameters still receives the whole list —
237+nothing silently truncates. `limit` must be `1`–`500`, `offset` defaults to `0`
238+and must be ≥ 0 (bad values are `400`), and an `offset` at or past the end
239+returns an empty `items` (not an error). Deliberately **not** paged — these keep
240+their existing shapes: the student exam-room reads
241+`/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and
242+`/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`.
243+
231 | Method | Path | Auth | Description |244 | Method | Path | Auth | Description |
232 |--------|----------------------------------|---------|---------------------------------|245 |--------|----------------------------------|---------|---------------------------------|
233 | GET | `/health` | no | Liveness check |246 | GET | `/health` | no | Liveness check |
@@ -240,49 +253,49 @@ marks/attendance reports narrow to the courses the caller manages.
240 | POST | `/auth/logout` | no | Clear session (no-op if none) |253 | POST | `/auth/logout` | no | Clear session (no-op if none) |
241 | GET | `/auth/me` | student | Current user (incl. `role` and personal info) |254 | GET | `/auth/me` | student | Current user (incl. `role` and personal info) |
242 | PATCH | `/users/me` | student | Update own personal info (see below) |255 | PATCH | `/users/me` | student | Update own personal info (see below) |
243-| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); ≤10 refs, no contact info |256+| GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); refs only, no contact info · paged |
244-| GET | `/users` | admin | List all users |257+| GET | `/users` | admin | List all users · paged |
245 | GET | `/users/{id}` | admin | Get one user |258 | GET | `/users/{id}` | admin | Get one user |
246 | PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role |259 | PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role |
247 | PATCH | `/users/{id}/profile` | admin | Update any user's personal info |260 | PATCH | `/users/{id}/profile` | admin | Update any user's personal info |
248 | POST | `/notes` | student | `{title, content?}` |261 | POST | `/notes` | student | `{title, content?}` |
249-| GET | `/notes` | student | List own notes |262+| GET | `/notes` | student | List own notes · paged |
250 | GET | `/notes/{id}` | student | Get own note |263 | GET | `/notes/{id}` | student | Get own note |
251 | PATCH | `/notes/{id}` | student | `{title?, content?}` |264 | PATCH | `/notes/{id}` | student | `{title?, content?}` |
252 | DELETE | `/notes/{id}` | student | Delete own note |265 | DELETE | `/notes/{id}` | student | Delete own note |
253 | POST | `/events` | teacher | `{title, description?, starts_at?, ends_at?}` |266 | POST | `/events` | teacher | `{title, description?, starts_at?, ends_at?}` |
254-| GET | `/events` | student | List all events |267+| GET | `/events` | student | List all events · paged |
255 | GET | `/events/{id}` | student | Get event |268 | GET | `/events/{id}` | student | Get event |
256 | PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any) |269 | PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any) |
257 | DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |270 | DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) |
258 | POST | `/events/{id}/attendance` | student | `{status, user_id?}` — self if `user_id` omitted; marking others needs teacher+ |271 | POST | `/events/{id}/attendance` | student | `{status, user_id?}` — self if `user_id` omitted; marking others needs teacher+ |
259-| GET | `/events/{id}/attendance` | teacher | List attendance for event (students read their own tallies via `/attendance/me`) |272+| GET | `/events/{id}/attendance` | teacher | List attendance for event (students read their own tallies via `/attendance/me`) · paged |
260 | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |273 | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance |
261 | POST | `/courses` | teacher | `{title, description?}` (creator manages it) |274 | POST | `/courses` | teacher | `{title, description?}` (creator manages it) |
262-| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) |275+| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged |
263-| GET | `/courses/me` | student | The caller's **enrolled** courses |276+| GET | `/courses/me` | student | The caller's **enrolled** courses · paged |
264 | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) |277 | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) |
265 | PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) |278 | PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) |
266 | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments (creator, or manager+) |279 | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments (creator, or manager+) |
267 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a user (idempotent upsert; course manager) |280 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a user (idempotent upsert; course manager) |
268-| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) |281+| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged |
269 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |282 | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) |
270 | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) |283 | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) |
271-| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, or manager+) |284+| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, or manager+) · paged |
272 | GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |285 | GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) |
273 | PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |286 | PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) |
274 | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |287 | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) |
275 | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled** students; the teacher's own row needs manager+ |288 | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled** students; the teacher's own row needs manager+ |
276-| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) |289+| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged |
277 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |290 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |
278 | POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?}` — add an exam (course manager); its weight comes from the kind |291 | POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?}` — add an exam (course manager); its weight comes from the kind |
279-| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) |292+| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) · paged |
280-| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) |293+| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) · paged |
281 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) |294 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) |
282 | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) |295 | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) |
283 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) |296 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) |
284 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) |297 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) |
285-| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) |298+| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |
286 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |299 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |
287 | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |300 | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |
288 | GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |301 | GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) |
@@ -290,7 +303,7 @@ marks/attendance reports narrow to the courses the caller manages.
290 | GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |303 | GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` |
291 | POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |304 | POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room |
292 | POST | `/exams/{id}/questions` | teacher | `{text, kind, points, choices?, correct?}` — add a question (course manager; frozen once attempted) |305 | POST | `/exams/{id}/questions` | teacher | `{text, kind, points, choices?, correct?}` — add a question (course manager; frozen once attempted) |
293-| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) |306+| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged |
294 | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) |307 | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) |
295 | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |308 | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) |
296 | GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires enrollment + an attempt) |309 | GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires enrollment + an attempt) |
@@ -303,8 +316,8 @@ marks/attendance reports narrow to the courses the caller manages.
303 | GET | `/marks/{user}` | teacher | A user's mark report, narrowed to the caller's courses (manager+: full) |316 | GET | `/marks/{user}` | teacher | A user's mark report, narrowed to the caller's courses (manager+: full) |
304 | POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |317 | POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |
305 | POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |318 | POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |
306-| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) |319+| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) · paged |
307-| GET | `/work/{user}` | manager | A staff member's work log |320+| GET | `/work/{user}` | manager | A staff member's work log · paged |
308 | PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` — correct a **closed** stint (`409` on open) |321 | PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` — correct a **closed** stint (`409` on open) |
309 | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |322 | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |
310 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |323 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
@@ -312,7 +325,7 @@ marks/attendance reports narrow to the courses the caller manages.
312 | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands` |325 | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands` |
313 | PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") |326 | PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") |
314 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |327 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |
315-| GET | `/terms` | student | List terms, newest first |328+| GET | `/terms` | student | List terms, newest first · paged |
316 | GET | `/terms/{id}` | student | Get one term |329 | GET | `/terms/{id}` | student | Get one term |
317 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |330 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |
318 | DELETE | `/terms/{id}` | manager | Delete a term — linked courses are unlinked, never deleted |331 | DELETE | `/terms/{id}` | manager | Delete a term — linked courses are unlinked, never deleted |
src/constant.rsmodified+6 -0
@@ -139,3 +139,9 @@ pub const SESSION_DURATION_DAYS: i64 = 7;
139 /// submission must survive its own round trip — while still refusing139 /// submission must survive its own round trip — while still refusing
140 /// genuinely past deadlines.140 /// genuinely past deadlines.
141 pub const SCHEDULE_PAST_GRACE_MS: i64 = 60 * 1000;141 pub const SCHEDULE_PAST_GRACE_MS: i64 = 60 * 1000;
142+
143+/// Upper bound on a list endpoint's `limit` page-size parameter. Omitting
144+/// `limit` returns every (remaining) row; when supplied it must be
145+/// `1..=MAX_PAGE_LIMIT`. The `#[param(maximum = ...)]` and the "1 and 500"
146+/// wording in `web::page` mirror this literal — keep them in step.
147+pub const MAX_PAGE_LIMIT: i64 = 500;
src/domain/user.rsmodified+4 -4
@@ -276,9 +276,9 @@ impl User {
276 276
277 /// Case-insensitive fragment search over username, name, and surname —277 /// Case-insensitive fragment search over username, name, and surname —
278 /// backs the user pickers. `role` narrows to one role (e.g. only students278 /// backs the user pickers. `role` narrows to one role (e.g. only students
279- /// for an enroll picker); `None` searches everyone. Capped at 10 rows:279+ /// for an enroll picker); `None` searches everyone. Returns every match,
280- /// pickers show a short list, and the cap keeps an over-broad fragment280+ /// ordered by username; the HTTP layer pages the result like any other list
281- /// from hauling the whole table.281+ /// (no built-in cap — an over-broad fragment is windowed by `?limit`).
282 pub async fn search(282 pub async fn search(
283 query: &str,283 query: &str,
284 role: Option<Role>,284 role: Option<Role>,
@@ -297,7 +297,7 @@ impl User {
297 OR string::lowercase(name ?? '') CONTAINS $q \297 OR string::lowercase(name ?? '') CONTAINS $q \
298 OR string::lowercase(surname ?? '') CONTAINS $q) \298 OR string::lowercase(surname ?? '') CONTAINS $q) \
299 {role_clause} \299 {role_clause} \
300- ORDER BY username LIMIT 10"300+ ORDER BY username"
301 ))301 ))
302 .bind(("q", needle));302 .bind(("q", needle));
303 if let Some(role) = role {303 if let Some(role) = role {
src/lib.rsmodified+1 -1
@@ -32,7 +32,7 @@ use crate::state::AppState;
32 info(32 info(
33 title = "Hezarfen Backend API",33 title = "Hezarfen Backend API",
34 version = env!("CARGO_PKG_VERSION"),34 version = env!("CARGO_PKG_VERSION"),
35- description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands) lives in an editable settings singleton, and courses may link to academic terms.",35+ description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands) lives in an editable settings singleton, and courses may link to academic terms. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
36 ),36 ),
37 modifiers(&SecurityAddon),37 modifiers(&SecurityAddon),
38 tags(38 tags(
src/web/courses.rsmodified+86 -42
@@ -1,7 +1,7 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2 2
3 use axum::Json;3 use axum::Json;
4-use axum::extract::{Path, State};4+use axum::extract::{Path, Query, State};
5 use axum::http::StatusCode;5 use axum::http::StatusCode;
6 use serde::{Deserialize, Serialize};6 use serde::{Deserialize, Serialize};
7 use utoipa::ToSchema;7 use utoipa::ToSchema;
@@ -26,8 +26,8 @@ use crate::state::AppState;
26 use super::sessions::resolve_session_teacher;26 use super::sessions::resolve_session_teacher;
27 use super::terms::resolve_term;27 use super::terms::resolve_term;
28 use super::{28 use super::{
29- CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, SessionResponse,29+ CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher,
30- check_not_past, check_time_range, person_map, set_or_clear,30+ SessionResponse, check_not_past, check_time_range, paginate, person_map, set_or_clear,
31 };31 };
32 32
33 pub fn routes() -> OpenApiRouter<AppState> {33 pub fn routes() -> OpenApiRouter<AppState> {
@@ -199,42 +199,64 @@ async fn create_course(
199 }199 }
200 200
201 /// List the courses visible to the caller: every course for manager+,201 /// List the courses visible to the caller: every course for manager+,
202-/// otherwise the courses they created plus the ones they're enrolled in.202+/// otherwise the courses they created plus the ones they're enrolled in. Paged
203+/// via `?limit=&offset=` (omit `limit` for the full list); returns a
204+/// `{items, total, limit, offset}` envelope.
203 #[utoipa::path(205 #[utoipa::path(
204 get,206 get,
205 path = "/",207 path = "/",
206 tag = "courses",208 tag = "courses",
207 security(("session_cookie" = [])),209 security(("session_cookie" = [])),
210+ params(PageParams),
208 responses(211 responses(
209- (status = 200, description = "The caller's visible courses", body = [CourseResponse]),212+ (status = 200, description = "A page of the caller's visible courses (all of them when unpaged)", body = Page<CourseResponse>),
213+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
210 (status = 401, description = "Not authenticated", body = ErrorResponse),214 (status = 401, description = "Not authenticated", body = ErrorResponse),
211 ),215 ),
212 )]216 )]
213 async fn list_courses(217 async fn list_courses(
214 State(st): State<AppState>,218 State(st): State<AppState>,
215 CurrentUser(user): CurrentUser,219 CurrentUser(user): CurrentUser,
216-) -> Result<Json<Vec<CourseResponse>>, AppError> {220+ Query(page): Query<PageParams>,
221+) -> Result<Json<Page<CourseResponse>>, AppError> {
222+ let (limit, offset) = page.resolve()?;
217 let courses = visible_courses(&user, &st.db).await?;223 let courses = visible_courses(&user, &st.db).await?;
218- Ok(Json(courses.iter().map(CourseResponse::new).collect()))224+ let total = courses.len() as i64;
225+ let items = paginate(&courses, limit, offset)
226+ .iter()
227+ .map(CourseResponse::new)
228+ .collect();
229+ Ok(Json(Page::new(items, total, limit, offset)))
219 }230 }
220 231
221-/// The courses the current user is enrolled in.232+/// The courses the current user is enrolled in, paged via `?limit=&offset=`
233+/// (omit `limit` for all of them); returns a `{items, total, limit, offset}`
234+/// envelope.
222 #[utoipa::path(235 #[utoipa::path(
223 get,236 get,
224 path = "/me",237 path = "/me",
225 tag = "courses",238 tag = "courses",
226 security(("session_cookie" = [])),239 security(("session_cookie" = [])),
240+ params(PageParams),
227 responses(241 responses(
228- (status = 200, description = "The caller's enrolled courses", body = [CourseResponse]),242+ (status = 200, description = "A page of the caller's enrolled courses (all of them when unpaged)", body = Page<CourseResponse>),
243+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
229 (status = 401, description = "Not authenticated", body = ErrorResponse),244 (status = 401, description = "Not authenticated", body = ErrorResponse),
230 ),245 ),
231 )]246 )]
232 async fn my_courses(247 async fn my_courses(
233 State(st): State<AppState>,248 State(st): State<AppState>,
234 CurrentUser(user): CurrentUser,249 CurrentUser(user): CurrentUser,
235-) -> Result<Json<Vec<CourseResponse>>, AppError> {250+ Query(page): Query<PageParams>,
251+) -> Result<Json<Page<CourseResponse>>, AppError> {
252+ let (limit, offset) = page.resolve()?;
236 let courses = Course::list_enrolled(user.get_id(), &st.db).await?;253 let courses = Course::list_enrolled(user.get_id(), &st.db).await?;
237- Ok(Json(courses.iter().map(CourseResponse::new).collect()))254+ let total = courses.len() as i64;
255+ let items = paginate(&courses, limit, offset)
256+ .iter()
257+ .map(CourseResponse::new)
258+ .collect();
259+ Ok(Json(Page::new(items, total, limit, offset)))
238 }260 }
239 261
240 /// Fetch a single course by id. Visible to its enrolled users, its creator,262 /// Fetch a single course by id. Visible to its enrolled users, its creator,
@@ -398,16 +420,19 @@ async fn enroll(
398 Ok(Json(EnrollmentResponse::new(&enrollment, &people)))420 Ok(Json(EnrollmentResponse::new(&enrollment, &people)))
399 }421 }
400 422
401-/// List a course's roster. Requires teacher+ and course management rights —423+/// List a course's roster, paged via `?limit=&offset=` (omit `limit` for the
402-/// students see their own courses via `GET /courses/me`.424+/// whole roster). Requires teacher+ and course management rights — students see
425+/// their own courses via `GET /courses/me`. Returns a
426+/// `{items, total, limit, offset}` envelope.
403 #[utoipa::path(427 #[utoipa::path(
404 get,428 get,
405 path = "/{id}/enrollments",429 path = "/{id}/enrollments",
406 tag = "courses",430 tag = "courses",
407 security(("session_cookie" = [])),431 security(("session_cookie" = [])),
408- params(("id" = String, Path, description = "Course id")),432+ params(("id" = String, Path, description = "Course id"), PageParams),
409 responses(433 responses(
410- (status = 200, description = "All enrollments", body = [EnrollmentResponse]),434+ (status = 200, description = "A page of enrollments (the whole roster when unpaged)", body = Page<EnrollmentResponse>),
435+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
411 (status = 401, description = "Not authenticated", body = ErrorResponse),436 (status = 401, description = "Not authenticated", body = ErrorResponse),
412 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),437 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
413 (status = 404, description = "Course not found", body = ErrorResponse),438 (status = 404, description = "Course not found", body = ErrorResponse),
@@ -417,7 +442,9 @@ async fn list_roster(
417 State(st): State<AppState>,442 State(st): State<AppState>,
418 RequireTeacher(user): RequireTeacher,443 RequireTeacher(user): RequireTeacher,
419 Path(id): Path<String>,444 Path(id): Path<String>,
420-) -> Result<Json<Vec<EnrollmentResponse>>, AppError> {445+ Query(page): Query<PageParams>,
446+) -> Result<Json<Page<EnrollmentResponse>>, AppError> {
447+ let (limit, offset) = page.resolve()?;
421 // Course must exist — a missing course is a 404, not an empty roster.448 // Course must exist — a missing course is a 404, not an empty roster.
422 let course = Course::read(&CourseId::from_key(&id), &st.db)449 let course = Course::read(&CourseId::from_key(&id), &st.db)
423 .await?450 .await?
@@ -428,19 +455,20 @@ async fn list_roster(
428 ));455 ));
429 }456 }
430 let enrollments = Enrollment::list_for_course(course.get_id(), &st.db).await?;457 let enrollments = Enrollment::list_for_course(course.get_id(), &st.db).await?;
458+ let total = enrollments.len() as i64;
459+ // Join people onto the page alone — the lookup shrinks with the window.
460+ let rows = paginate(&enrollments, limit, offset);
431 let people = person_map(461 let people = person_map(
432- enrollments462+ rows.iter()
433- .iter()
434 .flat_map(|e| [e.get_user().clone(), e.get_enrolled_by().clone()]),463 .flat_map(|e| [e.get_user().clone(), e.get_enrolled_by().clone()]),
435 &st.db,464 &st.db,
436 )465 )
437 .await?;466 .await?;
438- Ok(Json(467+ let items = rows
439- enrollments468+ .iter()
440- .iter()469+ .map(|e| EnrollmentResponse::new(e, &people))
441- .map(|e| EnrollmentResponse::new(e, &people))470+ .collect();
442- .collect(),471+ Ok(Json(Page::new(items, total, limit, offset)))
443- ))
444 }472 }
445 473
446 /// Unenroll a user from a course. Requires teacher+ and course management474 /// Unenroll a user from a course. Requires teacher+ and course management
@@ -555,16 +583,18 @@ async fn create_exam_in_course(
555 Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam))))583 Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam))))
556 }584 }
557 585
558-/// List a course's exams. Visible to the course's enrolled users, its586+/// List a course's exams, paged via `?limit=&offset=` (omit `limit` for all of
559-/// creator, and managers/admins.587+/// them). Visible to the course's enrolled users, its creator, and
588+/// managers/admins. Returns a `{items, total, limit, offset}` envelope.
560 #[utoipa::path(589 #[utoipa::path(
561 get,590 get,
562 path = "/{id}/exams",591 path = "/{id}/exams",
563 tag = "courses",592 tag = "courses",
564 security(("session_cookie" = [])),593 security(("session_cookie" = [])),
565- params(("id" = String, Path, description = "Course id")),594+ params(("id" = String, Path, description = "Course id"), PageParams),
566 responses(595 responses(
567- (status = 200, description = "The course's exams", body = [ExamResponse]),596+ (status = 200, description = "A page of the course's exams (all of them when unpaged)", body = Page<ExamResponse>),
597+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
568 (status = 401, description = "Not authenticated", body = ErrorResponse),598 (status = 401, description = "Not authenticated", body = ErrorResponse),
569 (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse),599 (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse),
570 (status = 404, description = "Course not found", body = ErrorResponse),600 (status = 404, description = "Course not found", body = ErrorResponse),
@@ -574,7 +604,9 @@ async fn list_course_exams(
574 State(st): State<AppState>,604 State(st): State<AppState>,
575 CurrentUser(user): CurrentUser,605 CurrentUser(user): CurrentUser,
576 Path(id): Path<String>,606 Path(id): Path<String>,
577-) -> Result<Json<Vec<ExamResponse>>, AppError> {607+ Query(page): Query<PageParams>,
608+) -> Result<Json<Page<ExamResponse>>, AppError> {
609+ let (limit, offset) = page.resolve()?;
578 // Course must exist — a missing course is a 404, not an empty exam list.610 // Course must exist — a missing course is a 404, not an empty exam list.
579 let course = Course::read(&CourseId::from_key(&id), &st.db)611 let course = Course::read(&CourseId::from_key(&id), &st.db)
580 .await?612 .await?
@@ -585,7 +617,12 @@ async fn list_course_exams(
585 ));617 ));
586 }618 }
587 let exams = Exam::list_for_course(course.get_id(), &st.db).await?;619 let exams = Exam::list_for_course(course.get_id(), &st.db).await?;
588- Ok(Json(exams.iter().map(ExamResponse::new).collect()))620+ let total = exams.len() as i64;
621+ let items = paginate(&exams, limit, offset)
622+ .iter()
623+ .map(ExamResponse::new)
624+ .collect();
625+ Ok(Json(Page::new(items, total, limit, offset)))
589 }626 }
590 627
591 // ---- sessions in a course --------------------------------------------------628 // ---- sessions in a course --------------------------------------------------
@@ -662,16 +699,19 @@ async fn create_session_in_course(
662 ))699 ))
663 }700 }
664 701
665-/// List a course's lesson sessions, most recent first. Visible to the702+/// List a course's lesson sessions, most recent first, paged via
666-/// course's enrolled users, its creator, and managers/admins.703+/// `?limit=&offset=` (omit `limit` for all of them). Visible to the course's
704+/// enrolled users, its creator, and managers/admins. Returns a
705+/// `{items, total, limit, offset}` envelope.
667 #[utoipa::path(706 #[utoipa::path(
668 get,707 get,
669 path = "/{id}/sessions",708 path = "/{id}/sessions",
670 tag = "courses",709 tag = "courses",
671 security(("session_cookie" = [])),710 security(("session_cookie" = [])),
672- params(("id" = String, Path, description = "Course id")),711+ params(("id" = String, Path, description = "Course id"), PageParams),
673 responses(712 responses(
674- (status = 200, description = "The course's sessions", body = [SessionResponse]),713+ (status = 200, description = "A page of the course's sessions (all of them when unpaged)", body = Page<SessionResponse>),
714+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
675 (status = 401, description = "Not authenticated", body = ErrorResponse),715 (status = 401, description = "Not authenticated", body = ErrorResponse),
676 (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse),716 (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse),
677 (status = 404, description = "Course not found", body = ErrorResponse),717 (status = 404, description = "Course not found", body = ErrorResponse),
@@ -681,7 +721,9 @@ async fn list_course_sessions(
681 State(st): State<AppState>,721 State(st): State<AppState>,
682 CurrentUser(user): CurrentUser,722 CurrentUser(user): CurrentUser,
683 Path(id): Path<String>,723 Path(id): Path<String>,
684-) -> Result<Json<Vec<SessionResponse>>, AppError> {724+ Query(page): Query<PageParams>,
725+) -> Result<Json<Page<SessionResponse>>, AppError> {
726+ let (limit, offset) = page.resolve()?;
685 // Course must exist — a missing course is a 404, not an empty list.727 // Course must exist — a missing course is a 404, not an empty list.
686 let course = Course::read(&CourseId::from_key(&id), &st.db)728 let course = Course::read(&CourseId::from_key(&id), &st.db)
687 .await?729 .await?
@@ -692,11 +734,13 @@ async fn list_course_sessions(
692 ));734 ));
693 }735 }
694 let sessions = CourseSession::list_for_course(course.get_id(), &st.db).await?;736 let sessions = CourseSession::list_for_course(course.get_id(), &st.db).await?;
695- let people = person_map(sessions.iter().map(|s| s.get_teacher().clone()), &st.db).await?;737+ let total = sessions.len() as i64;
696- Ok(Json(738+ // Join teachers onto the page alone — the lookup shrinks with the window.
697- sessions739+ let rows = paginate(&sessions, limit, offset);
698- .iter()740+ let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?;
699- .map(|s| SessionResponse::new(s, &people))741+ let items = rows
700- .collect(),742+ .iter()
701- ))743+ .map(|s| SessionResponse::new(s, &people))
744+ .collect();
745+ Ok(Json(Page::new(items, total, limit, offset)))
702 }746 }
src/web/events.rsmodified+36 -20
@@ -1,7 +1,7 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2 2
3 use axum::Json;3 use axum::Json;
4-use axum::extract::{Path, State};4+use axum::extract::{Path, Query, State};
5 use axum::http::StatusCode;5 use axum::http::StatusCode;
6 use serde::{Deserialize, Serialize};6 use serde::{Deserialize, Serialize};
7 use utoipa::ToSchema;7 use utoipa::ToSchema;
@@ -18,8 +18,8 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
18 use crate::state::AppState;18 use crate::state::AppState;
19 19
20 use super::{20 use super::{
21- CurrentUser, PersonRef, RequireTeacher, check_not_past, check_time_range, person_map,21+ CurrentUser, Page, PageParams, PersonRef, RequireTeacher, check_not_past, check_time_range,
22- set_or_clear,22+ paginate, person_map, set_or_clear,
23 };23 };
24 24
25 pub fn routes() -> OpenApiRouter<AppState> {25 pub fn routes() -> OpenApiRouter<AppState> {
@@ -160,23 +160,33 @@ async fn create_event(
160 Ok((StatusCode::CREATED, Json(EventResponse::new(&event))))160 Ok((StatusCode::CREATED, Json(EventResponse::new(&event))))
161 }161 }
162 162
163-/// List all events.163+/// List all events, newest first. Paged via `?limit=&offset=` (omit `limit`
164+/// for every event); returns a `{items, total, limit, offset}` envelope.
164 #[utoipa::path(165 #[utoipa::path(
165 get,166 get,
166 path = "/",167 path = "/",
167 tag = "events",168 tag = "events",
168 security(("session_cookie" = [])),169 security(("session_cookie" = [])),
170+ params(PageParams),
169 responses(171 responses(
170- (status = 200, description = "All events", body = [EventResponse]),172+ (status = 200, description = "A page of events (all of them when unpaged)", body = Page<EventResponse>),
173+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
171 (status = 401, description = "Not authenticated", body = ErrorResponse),174 (status = 401, description = "Not authenticated", body = ErrorResponse),
172 ),175 ),
173 )]176 )]
174 async fn list_events(177 async fn list_events(
175 State(st): State<AppState>,178 State(st): State<AppState>,
176 _user: CurrentUser,179 _user: CurrentUser,
177-) -> Result<Json<Vec<EventResponse>>, AppError> {180+ Query(page): Query<PageParams>,
181+) -> Result<Json<Page<EventResponse>>, AppError> {
182+ let (limit, offset) = page.resolve()?;
178 let events = Event::list_all(&st.db).await?;183 let events = Event::list_all(&st.db).await?;
179- Ok(Json(events.iter().map(EventResponse::new).collect()))184+ let total = events.len() as i64;
185+ let items = paginate(&events, limit, offset)
186+ .iter()
187+ .map(EventResponse::new)
188+ .collect();
189+ Ok(Json(Page::new(items, total, limit, offset)))
180 }190 }
181 191
182 /// Fetch a single event by id.192 /// Fetch a single event by id.
@@ -362,16 +372,19 @@ async fn mark(
362 Ok(Json(AttendanceResponse::new(&attendance, &people)))372 Ok(Json(AttendanceResponse::new(&attendance, &people)))
363 }373 }
364 374
365-/// List the attendance roster for an event. Requires teacher+ — students see375+/// List the attendance roster for an event, paged via `?limit=&offset=` (omit
366-/// their own tallies via `GET /attendance/me`.376+/// `limit` for the whole roster). Requires teacher+ — students see their own
377+/// tallies via `GET /attendance/me`. Returns a `{items, total, limit, offset}`
378+/// envelope.
367 #[utoipa::path(379 #[utoipa::path(
368 get,380 get,
369 path = "/{id}/attendance",381 path = "/{id}/attendance",
370 tag = "events",382 tag = "events",
371 security(("session_cookie" = [])),383 security(("session_cookie" = [])),
372- params(("id" = String, Path, description = "Event id")),384+ params(("id" = String, Path, description = "Event id"), PageParams),
373 responses(385 responses(
374- (status = 200, description = "Attendance roster", body = [AttendanceResponse]),386+ (status = 200, description = "A page of the attendance roster (all of it when unpaged)", body = Page<AttendanceResponse>),
387+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
375 (status = 401, description = "Not authenticated", body = ErrorResponse),388 (status = 401, description = "Not authenticated", body = ErrorResponse),
376 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),389 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
377 (status = 404, description = "Event not found", body = ErrorResponse),390 (status = 404, description = "Event not found", body = ErrorResponse),
@@ -381,26 +394,29 @@ async fn list_attendance(
381 State(st): State<AppState>,394 State(st): State<AppState>,
382 _teacher: RequireTeacher,395 _teacher: RequireTeacher,
383 Path(id): Path<String>,396 Path(id): Path<String>,
384-) -> Result<Json<Vec<AttendanceResponse>>, AppError> {397+ Query(page): Query<PageParams>,
398+) -> Result<Json<Page<AttendanceResponse>>, AppError> {
399+ let (limit, offset) = page.resolve()?;
385 let event_id = EventId::from_key(&id);400 let event_id = EventId::from_key(&id);
386 // Event must exist — a missing event is a 404, not an empty roster.401 // Event must exist — a missing event is a 404, not an empty roster.
387 Event::read(&event_id, &st.db)402 Event::read(&event_id, &st.db)
388 .await?403 .await?
389 .ok_or(AppError::NotFound)?;404 .ok_or(AppError::NotFound)?;
390 let roster = Attendance::list_for_event(&event_id, &st.db).await?;405 let roster = Attendance::list_for_event(&event_id, &st.db).await?;
406+ let total = roster.len() as i64;
407+ // Join people onto the page alone — the lookup shrinks with the window.
408+ let rows = paginate(&roster, limit, offset);
391 let people = person_map(409 let people = person_map(
392- roster410+ rows.iter()
393- .iter()
394 .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),411 .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),
395 &st.db,412 &st.db,
396 )413 )
397 .await?;414 .await?;
398- Ok(Json(415+ let items = rows
399- roster416+ .iter()
400- .iter()417+ .map(|a| AttendanceResponse::new(a, &people))
401- .map(|a| AttendanceResponse::new(a, &people))418+ .collect();
402- .collect(),419+ Ok(Json(Page::new(items, total, limit, offset)))
403- ))
404 }420 }
405 421
406 /// Remove a user's attendance record from an event. Requires teacher+.422 /// Remove a user's attendance record from an event. Requires teacher+.
src/web/exams.rsmodified+54 -27
@@ -2,7 +2,7 @@ use std::collections::HashMap;
2 use std::time::Duration;2 use std::time::Duration;
3 3
4 use axum::Json;4 use axum::Json;
5-use axum::extract::{Path, State};5+use axum::extract::{Path, Query, State};
6 use axum::http::StatusCode;6 use axum::http::StatusCode;
7 use axum::response::sse::{Event, KeepAlive, Sse};7 use axum::response::sse::{Event, KeepAlive, Sse};
8 use serde::{Deserialize, Serialize};8 use serde::{Deserialize, Serialize};
@@ -35,7 +35,8 @@ use crate::state::AppState;
35 35
36 use super::courses::{can_manage_course, can_view_course, visible_courses};36 use super::courses::{can_manage_course, can_view_course, visible_courses};
37 use super::{37 use super::{
38- CurrentUser, ExamResponse, PersonRef, RequireTeacher, check_not_past, person_map, set_or_clear,38+ CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, check_not_past,
39+ paginate, person_map, set_or_clear,
39 };40 };
40 41
41 pub fn routes() -> OpenApiRouter<AppState> {42 pub fn routes() -> OpenApiRouter<AppState> {
@@ -161,21 +162,27 @@ async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> {
161 // Exams are created inside a course: `POST /courses/{id}/exams`.162 // Exams are created inside a course: `POST /courses/{id}/exams`.
162 163
163 /// List the exams visible to the caller: every exam for manager+, otherwise164 /// List the exams visible to the caller: every exam for manager+, otherwise
164-/// the exams of the courses they created or are enrolled in.165+/// the exams of the courses they created or are enrolled in. Paged via
166+/// `?limit=&offset=` (omit `limit` for the full list); returns a
167+/// `{items, total, limit, offset}` envelope.
165 #[utoipa::path(168 #[utoipa::path(
166 get,169 get,
167 path = "/",170 path = "/",
168 tag = "exams",171 tag = "exams",
169 security(("session_cookie" = [])),172 security(("session_cookie" = [])),
173+ params(PageParams),
170 responses(174 responses(
171- (status = 200, description = "The caller's visible exams", body = [ExamResponse]),175+ (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page<ExamResponse>),
176+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
172 (status = 401, description = "Not authenticated", body = ErrorResponse),177 (status = 401, description = "Not authenticated", body = ErrorResponse),
173 ),178 ),
174 )]179 )]
175 async fn list_exams(180 async fn list_exams(
176 State(st): State<AppState>,181 State(st): State<AppState>,
177 CurrentUser(user): CurrentUser,182 CurrentUser(user): CurrentUser,
178-) -> Result<Json<Vec<ExamResponse>>, AppError> {183+ Query(page): Query<PageParams>,
184+) -> Result<Json<Page<ExamResponse>>, AppError> {
185+ let (limit, offset) = page.resolve()?;
179 let exams = if user.get_role().at_least(Role::Manager) {186 let exams = if user.get_role().at_least(Role::Manager) {
180 Exam::list_all(&st.db).await?187 Exam::list_all(&st.db).await?
181 } else {188 } else {
@@ -183,7 +190,12 @@ async fn list_exams(
183 let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();190 let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();
184 Exam::list_for_courses(&ids, &st.db).await?191 Exam::list_for_courses(&ids, &st.db).await?
185 };192 };
186- Ok(Json(exams.iter().map(ExamResponse::new).collect()))193+ let total = exams.len() as i64;
194+ let items = paginate(&exams, limit, offset)
195+ .iter()
196+ .map(ExamResponse::new)
197+ .collect();
198+ Ok(Json(Page::new(items, total, limit, offset)))
187 }199 }
188 200
189 /// Fetch a single exam by id. Visible to its course's enrolled users, the201 /// Fetch a single exam by id. Visible to its course's enrolled users, the
@@ -443,17 +455,19 @@ async fn grade(
443 Ok(Json(ExamResultResponse::new(&result, &people)))455 Ok(Json(ExamResultResponse::new(&result, &people)))
444 }456 }
445 457
446-/// List every result for an exam. Requires teacher+ and management rights458+/// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all
447-/// over the exam's course — students read only their own via459+/// of them). Requires teacher+ and management rights over the exam's course —
448-/// `GET /exams/{id}/result`.460+/// students read only their own via `GET /exams/{id}/result`. Returns a
461+/// `{items, total, limit, offset}` envelope.
449 #[utoipa::path(462 #[utoipa::path(
450 get,463 get,
451 path = "/{id}/results",464 path = "/{id}/results",
452 tag = "exams",465 tag = "exams",
453 security(("session_cookie" = [])),466 security(("session_cookie" = [])),
454- params(("id" = String, Path, description = "Exam id")),467+ params(("id" = String, Path, description = "Exam id"), PageParams),
455 responses(468 responses(
456- (status = 200, description = "All results", body = [ExamResultResponse]),469+ (status = 200, description = "A page of results (all of them when unpaged)", body = Page<ExamResultResponse>),
470+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
457 (status = 401, description = "Not authenticated", body = ErrorResponse),471 (status = 401, description = "Not authenticated", body = ErrorResponse),
458 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),472 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
459 (status = 404, description = "Exam not found", body = ErrorResponse),473 (status = 404, description = "Exam not found", body = ErrorResponse),
@@ -463,7 +477,9 @@ async fn list_results(
463 State(st): State<AppState>,477 State(st): State<AppState>,
464 RequireTeacher(user): RequireTeacher,478 RequireTeacher(user): RequireTeacher,
465 Path(id): Path<String>,479 Path(id): Path<String>,
466-) -> Result<Json<Vec<ExamResultResponse>>, AppError> {480+ Query(page): Query<PageParams>,
481+) -> Result<Json<Page<ExamResultResponse>>, AppError> {
482+ let (limit, offset) = page.resolve()?;
467 // Exam must exist — a missing exam is a 404, not an empty result list.483 // Exam must exist — a missing exam is a 404, not an empty result list.
468 let exam = Exam::read(&ExamId::from_key(&id), &st.db)484 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
469 .await?485 .await?
@@ -475,19 +491,20 @@ async fn list_results(
475 ));491 ));
476 }492 }
477 let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?;493 let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?;
494+ let total = results.len() as i64;
495+ // Join people onto the page alone — the lookup shrinks with the window.
496+ let rows = paginate(&results, limit, offset);
478 let people = person_map(497 let people = person_map(
479- results498+ rows.iter()
480- .iter()
481 .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]),499 .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]),
482 &st.db,500 &st.db,
483 )501 )
484 .await?;502 .await?;
485- Ok(Json(503+ let items = rows
486- results504+ .iter()
487- .iter()505+ .map(|r| ExamResultResponse::new(r, &people))
488- .map(|r| ExamResultResponse::new(r, &people))506+ .collect();
489- .collect(),507+ Ok(Json(Page::new(items, total, limit, offset)))
490- ))
491 }508 }
492 509
493 /// The current user's own result for an exam. Any authenticated user may read510 /// The current user's own result for an exam. Any authenticated user may read
@@ -1308,17 +1325,20 @@ async fn create_question(
1308 Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question))))1325 Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question))))
1309 }1326 }
1310 1327
1311-/// The exam's full question list, `correct` indexes included — the answer1328+/// The exam's question list, `correct` indexes included — the answer key,
1312-/// key. Requires teacher+ and management rights over the exam's course.1329+/// paged via `?limit=&offset=` (omit `limit` for the whole list). Requires
1313-/// Students read questions through `GET /exams/{id}/attempt/questions`.1330+/// teacher+ and management rights over the exam's course. Students read
1331+/// questions through `GET /exams/{id}/attempt/questions`. Returns a
1332+/// `{items, total, limit, offset}` envelope.
1314 #[utoipa::path(1333 #[utoipa::path(
1315 get,1334 get,
1316 path = "/{id}/questions",1335 path = "/{id}/questions",
1317 tag = "exams",1336 tag = "exams",
1318 security(("session_cookie" = [])),1337 security(("session_cookie" = [])),
1319- params(("id" = String, Path, description = "Exam id")),1338+ params(("id" = String, Path, description = "Exam id"), PageParams),
1320 responses(1339 responses(
1321- (status = 200, description = "The exam's questions", body = [QuestionResponse]),1340+ (status = 200, description = "A page of the exam's questions (all of them when unpaged)", body = Page<QuestionResponse>),
1341+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1322 (status = 401, description = "Not authenticated", body = ErrorResponse),1342 (status = 401, description = "Not authenticated", body = ErrorResponse),
1323 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),1343 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
1324 (status = 404, description = "Exam not found", body = ErrorResponse),1344 (status = 404, description = "Exam not found", body = ErrorResponse),
@@ -1328,7 +1348,9 @@ async fn list_questions(
1328 State(st): State<AppState>,1348 State(st): State<AppState>,
1329 RequireTeacher(user): RequireTeacher,1349 RequireTeacher(user): RequireTeacher,
1330 Path(id): Path<String>,1350 Path(id): Path<String>,
1331-) -> Result<Json<Vec<QuestionResponse>>, AppError> {1351+ Query(page): Query<PageParams>,
1352+) -> Result<Json<Page<QuestionResponse>>, AppError> {
1353+ let (limit, offset) = page.resolve()?;
1332 let exam = Exam::read(&ExamId::from_key(&id), &st.db)1354 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1333 .await?1355 .await?
1334 .ok_or(AppError::NotFound)?;1356 .ok_or(AppError::NotFound)?;
@@ -1339,7 +1361,12 @@ async fn list_questions(
1339 ));1361 ));
1340 }1362 }
1341 let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;1363 let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?;
1342- Ok(Json(questions.iter().map(QuestionResponse::new).collect()))1364+ let total = questions.len() as i64;
1365+ let items = paginate(&questions, limit, offset)
1366+ .iter()
1367+ .map(QuestionResponse::new)
1368+ .collect();
1369+ Ok(Json(Page::new(items, total, limit, offset)))
1343 }1370 }
1344 1371
1345 /// Edit a question. Requires teacher+ and management rights over the exam's1372 /// Edit a question. Requires teacher+ and management rights over the exam's
src/web/mod.rsmodified+2 -0
@@ -19,9 +19,11 @@ pub mod work;
19 19
20 mod dto;20 mod dto;
21 mod extractor;21 mod extractor;
22+mod page;
22 23
23 pub use dto::{CourseResponse, ExamResponse, PersonRef, SessionResponse, UserResponse, person_map};24 pub use dto::{CourseResponse, ExamResponse, PersonRef, SessionResponse, UserResponse, person_map};
24 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher};25 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher};
26+pub use page::{Page, PageParams, paginate};
25 27
26 use serde::{Deserialize, Deserializer};28 use serde::{Deserialize, Deserializer};
27 29
src/web/notes.rsmodified+17 -6
@@ -1,5 +1,5 @@
1 use axum::Json;1 use axum::Json;
2-use axum::extract::{Path, State};2+use axum::extract::{Path, Query, State};
3 use axum::http::StatusCode;3 use axum::http::StatusCode;
4 use serde::{Deserialize, Serialize};4 use serde::{Deserialize, Serialize};
5 use utoipa::ToSchema;5 use utoipa::ToSchema;
@@ -10,7 +10,7 @@ use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
10 use crate::error::{AppError, ErrorResponse};10 use crate::error::{AppError, ErrorResponse};
11 use crate::state::AppState;11 use crate::state::AppState;
12 12
13-use super::CurrentUser;13+use super::{CurrentUser, Page, PageParams, paginate};
14 14
15 pub fn routes() -> OpenApiRouter<AppState> {15 pub fn routes() -> OpenApiRouter<AppState> {
16 OpenApiRouter::new()16 OpenApiRouter::new()
@@ -73,23 +73,34 @@ async fn create(
73 Ok((StatusCode::CREATED, Json(NoteResponse::new(&note))))73 Ok((StatusCode::CREATED, Json(NoteResponse::new(&note))))
74 }74 }
75 75
76-/// List all notes owned by the current user.76+/// List the notes owned by the current user, newest first. Paged via
77+/// `?limit=&offset=` (omit `limit` for all of them); returns a
78+/// `{items, total, limit, offset}` envelope.
77 #[utoipa::path(79 #[utoipa::path(
78 get,80 get,
79 path = "/",81 path = "/",
80 tag = "notes",82 tag = "notes",
81 security(("session_cookie" = [])),83 security(("session_cookie" = [])),
84+ params(PageParams),
82 responses(85 responses(
83- (status = 200, description = "The user's notes", body = [NoteResponse]),86+ (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page<NoteResponse>),
87+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
84 (status = 401, description = "Not authenticated", body = ErrorResponse),88 (status = 401, description = "Not authenticated", body = ErrorResponse),
85 ),89 ),
86 )]90 )]
87 async fn list(91 async fn list(
88 State(st): State<AppState>,92 State(st): State<AppState>,
89 CurrentUser(user): CurrentUser,93 CurrentUser(user): CurrentUser,
90-) -> Result<Json<Vec<NoteResponse>>, AppError> {94+ Query(page): Query<PageParams>,
95+) -> Result<Json<Page<NoteResponse>>, AppError> {
96+ let (limit, offset) = page.resolve()?;
91 let notes = Note::list_for(user.get_id(), &st.db).await?;97 let notes = Note::list_for(user.get_id(), &st.db).await?;
92- Ok(Json(notes.iter().map(NoteResponse::new).collect()))98+ let total = notes.len() as i64;
99+ let items = paginate(&notes, limit, offset)
100+ .iter()
101+ .map(NoteResponse::new)
102+ .collect();
103+ Ok(Json(Page::new(items, total, limit, offset)))
93 }104 }
94 105
95 /// Fetch a single note by id (must be owned by the current user).106 /// Fetch a single note by id (must be owned by the current user).
src/web/page.rsadded+140 -0
@@ -0,0 +1,140 @@
1+//! Shared pagination: the `?limit=&offset=` query every list endpoint accepts,
2+//! and the `{items, total, limit, offset}` envelope they return.
3+//!
4+//! Paging is opt-in. Omit `limit` and the response still carries every
5+//! (remaining) row — so a client that ignores the parameters keeps seeing full
6+//! lists, and callers that genuinely need the whole set are never silently
7+//! truncated. `total` is always the full, unpaged row count, so a frontend can
8+//! render "showing 100 of 256" and drive a pager without a second request.
9+//!
10+//! The windowing is a slice over the already-ordered domain list (the domain
11+//! layer still returns the full, sorted `Vec`): endpoints that join people onto
12+//! their rows do that join over the page alone, so the expensive lookup shrinks
13+//! with the page even though the base scan does not.
14+
15+use serde::{Deserialize, Serialize};
16+use utoipa::{IntoParams, ToSchema};
17+
18+use crate::constant::MAX_PAGE_LIMIT;
19+use crate::error::{AppError, ValidationError};
20+
21+/// The `?limit=&offset=` pair on a list endpoint. Both optional: omit `limit`
22+/// for every remaining row, omit `offset` to start at the top.
23+#[derive(Debug, Deserialize, IntoParams)]
24+pub struct PageParams {
25+ /// Maximum rows to return. Omit for every remaining row; when supplied it
26+ /// must be between `1` and `500`.
27+ #[param(minimum = 1, maximum = 500, example = 100)]
28+ pub limit: Option<i64>,
29+ /// Rows to skip from the start of the list. Defaults to `0`; an offset past
30+ /// the end simply yields an empty page.
31+ #[param(minimum = 0, example = 0)]
32+ pub offset: Option<i64>,
33+}
34+
35+impl PageParams {
36+ /// Validate and normalize into `(limit, offset)`. A `limit` outside
37+ /// `1..=MAX_PAGE_LIMIT` or a negative `offset` is a `400` naming the field.
38+ pub fn resolve(&self) -> Result<(Option<i64>, i64), AppError> {
39+ if let Some(limit) = self.limit
40+ && !(1..=MAX_PAGE_LIMIT).contains(&limit)
41+ {
42+ return Err(AppError::Validation(ValidationError::Invalid {
43+ field: "limit",
44+ reason: "must be between 1 and 500",
45+ }));
46+ }
47+ let offset = self.offset.unwrap_or(0);
48+ if offset < 0 {
49+ return Err(AppError::Validation(ValidationError::Invalid {
50+ field: "offset",
51+ reason: "must not be negative",
52+ }));
53+ }
54+ Ok((self.limit, offset))
55+ }
56+}
57+
58+/// One page of a list: the `items`, the full `total` (row count before the
59+/// window), and the `limit`/`offset` that produced it. `limit` is `null` when
60+/// the caller asked for every row.
61+#[derive(Debug, Serialize, ToSchema)]
62+pub struct Page<T> {
63+ pub items: Vec<T>,
64+ /// Total rows in the full list, before `limit`/`offset` are applied.
65+ #[schema(example = 256)]
66+ pub total: i64,
67+ /// Echo of the applied `limit`; `null` when the response is unbounded.
68+ #[schema(example = 100)]
69+ pub limit: Option<i64>,
70+ /// Echo of the applied `offset`.
71+ #[schema(example = 0)]
72+ pub offset: i64,
73+}
74+
75+impl<T> Page<T> {
76+ pub fn new(items: Vec<T>, total: i64, limit: Option<i64>, offset: i64) -> Self {
77+ Self {
78+ items,
79+ total,
80+ limit,
81+ offset,
82+ }
83+ }
84+}
85+
86+/// The window `[offset, offset + limit)` of `items`, clamped to the ends. An
87+/// offset at or past the end yields an empty slice — a client paging off the
88+/// tail gets `[]`, not an error — and a `None` limit runs to the end. `total`
89+/// stays the caller's job: take `items.len()` before slicing.
90+pub fn paginate<T>(items: &[T], limit: Option<i64>, offset: i64) -> &[T] {
91+ let start = (offset.max(0) as usize).min(items.len());
92+ let end = match limit {
93+ Some(limit) => start.saturating_add(limit.max(0) as usize).min(items.len()),
94+ None => items.len(),
95+ };
96+ &items[start..end]
97+}
98+
99+#[cfg(test)]
100+mod tests {
101+ use super::*;
102+
103+ fn params(limit: Option<i64>, offset: Option<i64>) -> PageParams {
104+ PageParams { limit, offset }
105+ }
106+
107+ #[test]
108+ fn resolve_accepts_bounds_and_defaults_offset() {
109+ assert_eq!(params(None, None).resolve().unwrap(), (None, 0));
110+ assert_eq!(params(Some(1), None).resolve().unwrap(), (Some(1), 0));
111+ assert_eq!(
112+ params(Some(MAX_PAGE_LIMIT), Some(40)).resolve().unwrap(),
113+ (Some(MAX_PAGE_LIMIT), 40)
114+ );
115+ }
116+
117+ #[test]
118+ fn resolve_rejects_out_of_range_limit_and_negative_offset() {
119+ assert!(params(Some(0), None).resolve().is_err());
120+ assert!(params(Some(MAX_PAGE_LIMIT + 1), None).resolve().is_err());
121+ assert!(params(Some(-5), None).resolve().is_err());
122+ assert!(params(None, Some(-1)).resolve().is_err());
123+ }
124+
125+ #[test]
126+ fn paginate_windows_and_clamps() {
127+ let items: Vec<i64> = (0..10).collect();
128+ // A bounded window in the middle.
129+ assert_eq!(paginate(&items, Some(3), 2), &[2, 3, 4]);
130+ // No limit → everything from the offset to the end.
131+ assert_eq!(paginate(&items, None, 7), &[7, 8, 9]);
132+ // Limit overruns the end → clamped, not padded.
133+ assert_eq!(paginate(&items, Some(100), 8), &[8, 9]);
134+ // Offset at or past the end → empty page, not a panic.
135+ assert!(paginate(&items, Some(5), 10).is_empty());
136+ assert!(paginate(&items, Some(5), 999).is_empty());
137+ // No limit, zero offset → the whole list.
138+ assert_eq!(paginate(&items, None, 0), items.as_slice());
139+ }
140+}
src/web/sessions.rsmodified+22 -17
@@ -1,7 +1,7 @@
1 use std::collections::HashMap;1 use std::collections::HashMap;
2 2
3 use axum::Json;3 use axum::Json;
4-use axum::extract::{Path, State};4+use axum::extract::{Path, Query, State};
5 use axum::http::StatusCode;5 use axum::http::StatusCode;
6 use serde::{Deserialize, Serialize};6 use serde::{Deserialize, Serialize};
7 use utoipa::ToSchema;7 use utoipa::ToSchema;
@@ -23,8 +23,8 @@ use crate::state::AppState;
23 23
24 use super::courses::{can_manage_course, can_view_course};24 use super::courses::{can_manage_course, can_view_course};
25 use super::{25 use super::{
26- CurrentUser, PersonRef, RequireTeacher, SessionResponse, check_not_past, check_time_range,26+ CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past,
27- person_map, set_or_clear,27+ check_time_range, paginate, person_map, set_or_clear,
28 };28 };
29 29
30 pub fn routes() -> OpenApiRouter<AppState> {30 pub fn routes() -> OpenApiRouter<AppState> {
@@ -333,17 +333,19 @@ async fn mark_roll_call(
333 Ok(Json(SessionAttendanceResponse::new(&attendance, &people)))333 Ok(Json(SessionAttendanceResponse::new(&attendance, &people)))
334 }334 }
335 335
336-/// List a session's roll call. Same rights as taking it: the session's336+/// List a session's roll call, paged via `?limit=&offset=` (omit `limit` for
337-/// teacher or a course manager — students see their own tallies via337+/// the whole roster). Same rights as taking it: the session's teacher or a
338-/// `GET /attendance/me`.338+/// course manager — students see their own tallies via `GET /attendance/me`.
339+/// Returns a `{items, total, limit, offset}` envelope.
339 #[utoipa::path(340 #[utoipa::path(
340 get,341 get,
341 path = "/{id}/attendance",342 path = "/{id}/attendance",
342 tag = "sessions",343 tag = "sessions",
343 security(("session_cookie" = [])),344 security(("session_cookie" = [])),
344- params(("id" = String, Path, description = "Session id")),345+ params(("id" = String, Path, description = "Session id"), PageParams),
345 responses(346 responses(
346- (status = 200, description = "Roll-call roster", body = [SessionAttendanceResponse]),347+ (status = 200, description = "A page of the roll-call roster (all of it when unpaged)", body = Page<SessionAttendanceResponse>),
348+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
347 (status = 401, description = "Not authenticated", body = ErrorResponse),349 (status = 401, description = "Not authenticated", body = ErrorResponse),
348 (status = 403, description = "Not the session teacher or a course manager", body = ErrorResponse),350 (status = 403, description = "Not the session teacher or a course manager", body = ErrorResponse),
349 (status = 404, description = "Session not found", body = ErrorResponse),351 (status = 404, description = "Session not found", body = ErrorResponse),
@@ -353,7 +355,9 @@ async fn list_roll_call(
353 State(st): State<AppState>,355 State(st): State<AppState>,
354 RequireTeacher(user): RequireTeacher,356 RequireTeacher(user): RequireTeacher,
355 Path(id): Path<String>,357 Path(id): Path<String>,
356-) -> Result<Json<Vec<SessionAttendanceResponse>>, AppError> {358+ Query(page): Query<PageParams>,
359+) -> Result<Json<Page<SessionAttendanceResponse>>, AppError> {
360+ let (limit, offset) = page.resolve()?;
357 let (session, course) = session_with_course(&id, &st.db).await?;361 let (session, course) = session_with_course(&id, &st.db).await?;
358 if !can_roll_call(&session, &course, &user) {362 if !can_roll_call(&session, &course, &user) {
359 return Err(AppError::Forbidden(363 return Err(AppError::Forbidden(
@@ -361,19 +365,20 @@ async fn list_roll_call(
361 ));365 ));
362 }366 }
363 let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?;367 let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?;
368+ let total = roster.len() as i64;
369+ // Join people onto the page alone — the lookup shrinks with the window.
370+ let rows = paginate(&roster, limit, offset);
364 let people = person_map(371 let people = person_map(
365- roster372+ rows.iter()
366- .iter()
367 .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),373 .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]),
368 &st.db,374 &st.db,
369 )375 )
370 .await?;376 .await?;
371- Ok(Json(377+ let items = rows
372- roster378+ .iter()
373- .iter()379+ .map(|a| SessionAttendanceResponse::new(a, &people))
374- .map(|a| SessionAttendanceResponse::new(a, &people))380+ .collect();
375- .collect(),381+ Ok(Json(Page::new(items, total, limit, offset)))
376- ))
377 }382 }
378 383
379 /// Remove a user's roll-call row from a session. Same rights as marking:384 /// Remove a user's roll-call row from a session. Same rights as marking:
src/web/terms.rsmodified+17 -6
@@ -1,5 +1,5 @@
1 use axum::Json;1 use axum::Json;
2-use axum::extract::{Path, State};2+use axum::extract::{Path, Query, State};
3 use axum::http::StatusCode;3 use axum::http::StatusCode;
4 use serde::{Deserialize, Serialize};4 use serde::{Deserialize, Serialize};
5 use utoipa::ToSchema;5 use utoipa::ToSchema;
@@ -12,7 +12,7 @@ use crate::domain::timestamp::Timestamp;
12 use crate::error::{AppError, ErrorResponse, ValidationError};12 use crate::error::{AppError, ErrorResponse, ValidationError};
13 use crate::state::AppState;13 use crate::state::AppState;
14 14
15-use super::{CurrentUser, RequireManager, check_time_range};15+use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range, paginate};
16 16
17 pub fn routes() -> OpenApiRouter<AppState> {17 pub fn routes() -> OpenApiRouter<AppState> {
18 OpenApiRouter::new()18 OpenApiRouter::new()
@@ -110,23 +110,34 @@ async fn create_term(
110 }110 }
111 111
112 /// List every term, newest first. Any authenticated user — students need the112 /// List every term, newest first. Any authenticated user — students need the
113-/// calendar to make sense of their courses.113+/// calendar to make sense of their courses. Paged via `?limit=&offset=` (omit
114+/// `limit` for the full list); returns a `{items, total, limit, offset}`
115+/// envelope.
114 #[utoipa::path(116 #[utoipa::path(
115 get,117 get,
116 path = "/",118 path = "/",
117 tag = "terms",119 tag = "terms",
118 security(("session_cookie" = [])),120 security(("session_cookie" = [])),
121+ params(PageParams),
119 responses(122 responses(
120- (status = 200, description = "All terms", body = [TermResponse]),123+ (status = 200, description = "A page of terms (the full list when unpaged)", body = Page<TermResponse>),
124+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
121 (status = 401, description = "Not authenticated", body = ErrorResponse),125 (status = 401, description = "Not authenticated", body = ErrorResponse),
122 ),126 ),
123 )]127 )]
124 async fn list_terms(128 async fn list_terms(
125 State(st): State<AppState>,129 State(st): State<AppState>,
126 CurrentUser(_user): CurrentUser,130 CurrentUser(_user): CurrentUser,
127-) -> Result<Json<Vec<TermResponse>>, AppError> {131+ Query(page): Query<PageParams>,
132+) -> Result<Json<Page<TermResponse>>, AppError> {
133+ let (limit, offset) = page.resolve()?;
128 let terms = Term::list_all(&st.db).await?;134 let terms = Term::list_all(&st.db).await?;
129- Ok(Json(terms.iter().map(TermResponse::new).collect()))135+ let total = terms.len() as i64;
136+ let items = paginate(&terms, limit, offset)
137+ .iter()
138+ .map(TermResponse::new)
139+ .collect();
140+ Ok(Json(Page::new(items, total, limit, offset)))
130 }141 }
131 142
132 /// Fetch a single term by id.143 /// Fetch a single term by id.
src/web/users.rsmodified+43 -11
@@ -13,7 +13,9 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
13 use crate::state::AppState;13 use crate::state::AppState;
14 14
15 use super::dto::Role as RoleSchema;15 use super::dto::Role as RoleSchema;
16-use super::{CurrentUser, PersonRef, RequireAdmin, RequireTeacher, UserResponse};16+use super::{
17+ CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UserResponse, paginate,
18+};
17 19
18 pub fn routes() -> OpenApiRouter<AppState> {20 pub fn routes() -> OpenApiRouter<AppState> {
19 OpenApiRouter::new()21 OpenApiRouter::new()
@@ -98,12 +100,20 @@ struct SearchUsers {
98 /// Restrict matches to one role: `student`, `teacher`, `manager`, or100 /// Restrict matches to one role: `student`, `teacher`, `manager`, or
99 /// `admin`. Omit to search every role.101 /// `admin`. Omit to search every role.
100 role: Option<String>,102 role: Option<String>,
103+ /// Max matches to return. Omit for every match; when given, `1`–`500`.
104+ #[param(minimum = 1, maximum = 500, example = 100)]
105+ limit: Option<i64>,
106+ /// Matches to skip from the start. Defaults to `0`.
107+ #[param(minimum = 0, example = 0)]
108+ offset: Option<i64>,
101 }109 }
102 110
103 /// Find users by username or name — backs the pickers (enroll, grade, mark111 /// Find users by username or name — backs the pickers (enroll, grade, mark
104 /// attendance). Requires teacher+. `role` narrows to one role (e.g.112 /// attendance). Requires teacher+. `role` narrows to one role (e.g.
105-/// `role=student` for an enroll picker). Returns at most 10 matches, and only113+/// `role=student` for an enroll picker). Paged via `?limit=&offset=` like the
106-/// id/username/display name — no contact details.114+/// other lists (omit `limit` for every match); returns a
115+/// `{items, total, limit, offset}` envelope carrying only id/username/display
116+/// name — no contact details.
107 #[utoipa::path(117 #[utoipa::path(
108 get,118 get,
109 path = "/search",119 path = "/search",
@@ -111,8 +121,8 @@ struct SearchUsers {
111 security(("session_cookie" = [])),121 security(("session_cookie" = [])),
112 params(SearchUsers),122 params(SearchUsers),
113 responses(123 responses(
114- (status = 200, description = "Matching users, at most 10", body = [PersonRef]),124+ (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),
115- (status = 400, description = "Empty query or unknown role", body = ErrorResponse),125+ (status = 400, description = "Empty query, unknown role, or invalid limit/offset", body = ErrorResponse),
116 (status = 401, description = "Not authenticated", body = ErrorResponse),126 (status = 401, description = "Not authenticated", body = ErrorResponse),
117 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),127 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
118 ),128 ),
@@ -121,26 +131,41 @@ async fn search_users(
121 State(st): State<AppState>,131 State(st): State<AppState>,
122 _teacher: RequireTeacher,132 _teacher: RequireTeacher,
123 Query(req): Query<SearchUsers>,133 Query(req): Query<SearchUsers>,
124-) -> Result<Json<Vec<PersonRef>>, AppError> {134+) -> Result<Json<Page<PersonRef>>, AppError> {
125 if req.q.trim().is_empty() {135 if req.q.trim().is_empty() {
126 return Err(AppError::Validation(ValidationError::Invalid {136 return Err(AppError::Validation(ValidationError::Invalid {
127 field: "q",137 field: "q",
128 reason: "must not be empty",138 reason: "must not be empty",
129 }));139 }));
130 }140 }
141+ let (limit, offset) = PageParams {
142+ limit: req.limit,
143+ offset: req.offset,
144+ }
145+ .resolve()?;
131 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;146 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;
132 let users = User::search(&req.q, role, &st.db).await?;147 let users = User::search(&req.q, role, &st.db).await?;
133- Ok(Json(users.iter().map(PersonRef::new).collect()))148+ let total = users.len() as i64;
149+ let items = paginate(&users, limit, offset)
150+ .iter()
151+ .map(PersonRef::new)
152+ .collect();
153+ Ok(Json(Page::new(items, total, limit, offset)))
134 }154 }
135 155
136-/// List every user with their role. Admin only.156+/// List every user with their role, newest first. Admin only. Paged: pass
157+/// `?limit=&offset=` to take a window (omit `limit` for the whole list); the
158+/// response is a `{items, total, limit, offset}` envelope where `total` counts
159+/// every user.
137 #[utoipa::path(160 #[utoipa::path(
138 get,161 get,
139 path = "/",162 path = "/",
140 tag = "users",163 tag = "users",
141 security(("session_cookie" = [])),164 security(("session_cookie" = [])),
165+ params(PageParams),
142 responses(166 responses(
143- (status = 200, description = "All users", body = [UserResponse]),167+ (status = 200, description = "A page of users (the full list when unpaged)", body = Page<UserResponse>),
168+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
144 (status = 401, description = "Not authenticated", body = ErrorResponse),169 (status = 401, description = "Not authenticated", body = ErrorResponse),
145 (status = 403, description = "Requires admin role", body = ErrorResponse),170 (status = 403, description = "Requires admin role", body = ErrorResponse),
146 ),171 ),
@@ -148,9 +173,16 @@ async fn search_users(
148 async fn list_users(173 async fn list_users(
149 State(st): State<AppState>,174 State(st): State<AppState>,
150 _admin: RequireAdmin,175 _admin: RequireAdmin,
151-) -> Result<Json<Vec<UserResponse>>, AppError> {176+ Query(page): Query<PageParams>,
177+) -> Result<Json<Page<UserResponse>>, AppError> {
178+ let (limit, offset) = page.resolve()?;
152 let users = User::list_all(&st.db).await?;179 let users = User::list_all(&st.db).await?;
153- Ok(Json(users.iter().map(UserResponse::new).collect()))180+ let total = users.len() as i64;
181+ let items = paginate(&users, limit, offset)
182+ .iter()
183+ .map(UserResponse::new)
184+ .collect();
185+ Ok(Json(Page::new(items, total, limit, offset)))
154 }186 }
155 187
156 /// Update the caller's own personal info: name, surname, email, phone, birth188 /// Update the caller's own personal info: name, surname, email, phone, birth
src/web/work.rsmodified+32 -11
@@ -1,5 +1,5 @@
1 use axum::Json;1 use axum::Json;
2-use axum::extract::{Path, State};2+use axum::extract::{Path, Query, State};
3 use axum::http::StatusCode;3 use axum::http::StatusCode;
4 use serde::{Deserialize, Serialize};4 use serde::{Deserialize, Serialize};
5 use utoipa::ToSchema;5 use utoipa::ToSchema;
@@ -12,7 +12,7 @@ use crate::domain::work_entry::{WorkEntry, WorkEntryId};
12 use crate::error::{AppError, ErrorResponse, ValidationError};12 use crate::error::{AppError, ErrorResponse, ValidationError};
13 use crate::state::AppState;13 use crate::state::AppState;
14 14
15-use super::{RequireManager, RequireTeacher};15+use super::{Page, PageParams, RequireManager, RequireTeacher, paginate};
16 16
17 pub fn routes() -> OpenApiRouter<AppState> {17 pub fn routes() -> OpenApiRouter<AppState> {
18 OpenApiRouter::new()18 OpenApiRouter::new()
@@ -105,14 +105,18 @@ async fn check_out(
105 }105 }
106 106
107 /// The caller's own work log, newest first — the open stint (if any) included107 /// The caller's own work log, newest first — the open stint (if any) included
108-/// (`check_out: null`). Requires teacher+ (staff).108+/// (`check_out: null`). Paged via `?limit=&offset=` (omit `limit` for the whole
109+/// log). Requires teacher+ (staff). Returns a `{items, total, limit, offset}`
110+/// envelope.
109 #[utoipa::path(111 #[utoipa::path(
110 get,112 get,
111 path = "/me",113 path = "/me",
112 tag = "work",114 tag = "work",
113 security(("session_cookie" = [])),115 security(("session_cookie" = [])),
116+ params(PageParams),
114 responses(117 responses(
115- (status = 200, description = "The caller's work log", body = [WorkEntryResponse]),118+ (status = 200, description = "A page of the caller's work log (the whole log when unpaged)", body = Page<WorkEntryResponse>),
119+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
116 (status = 401, description = "Not authenticated", body = ErrorResponse),120 (status = 401, description = "Not authenticated", body = ErrorResponse),
117 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),121 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
118 ),122 ),
@@ -120,20 +124,30 @@ async fn check_out(
120 async fn my_work(124 async fn my_work(
121 State(st): State<AppState>,125 State(st): State<AppState>,
122 RequireTeacher(user): RequireTeacher,126 RequireTeacher(user): RequireTeacher,
123-) -> Result<Json<Vec<WorkEntryResponse>>, AppError> {127+ Query(page): Query<PageParams>,
128+) -> Result<Json<Page<WorkEntryResponse>>, AppError> {
129+ let (limit, offset) = page.resolve()?;
124 let entries = WorkEntry::list_for_user(user.get_id(), &st.db).await?;130 let entries = WorkEntry::list_for_user(user.get_id(), &st.db).await?;
125- Ok(Json(entries.iter().map(WorkEntryResponse::new).collect()))131+ let total = entries.len() as i64;
132+ let items = paginate(&entries, limit, offset)
133+ .iter()
134+ .map(WorkEntryResponse::new)
135+ .collect();
136+ Ok(Json(Page::new(items, total, limit, offset)))
126 }137 }
127 138
128-/// A staff member's work log. Requires manager+.139+/// A staff member's work log, newest first, paged via `?limit=&offset=` (omit
140+/// `limit` for the whole log). Requires manager+. Returns a
141+/// `{items, total, limit, offset}` envelope.
129 #[utoipa::path(142 #[utoipa::path(
130 get,143 get,
131 path = "/{user}",144 path = "/{user}",
132 tag = "work",145 tag = "work",
133 security(("session_cookie" = [])),146 security(("session_cookie" = [])),
134- params(("user" = String, Path, description = "User id")),147+ params(("user" = String, Path, description = "User id"), PageParams),
135 responses(148 responses(
136- (status = 200, description = "The user's work log", body = [WorkEntryResponse]),149+ (status = 200, description = "A page of the user's work log (the whole log when unpaged)", body = Page<WorkEntryResponse>),
150+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
137 (status = 401, description = "Not authenticated", body = ErrorResponse),151 (status = 401, description = "Not authenticated", body = ErrorResponse),
138 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),152 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
139 (status = 404, description = "User not found", body = ErrorResponse),153 (status = 404, description = "User not found", body = ErrorResponse),
@@ -143,14 +157,21 @@ async fn user_work(
143 State(st): State<AppState>,157 State(st): State<AppState>,
144 _manager: RequireManager,158 _manager: RequireManager,
145 Path(user): Path<String>,159 Path(user): Path<String>,
146-) -> Result<Json<Vec<WorkEntryResponse>>, AppError> {160+ Query(page): Query<PageParams>,
161+) -> Result<Json<Page<WorkEntryResponse>>, AppError> {
162+ let (limit, offset) = page.resolve()?;
147 let target = UserId::from_key(&user);163 let target = UserId::from_key(&user);
148 // User must exist — a missing user is a 404, not an empty log.164 // User must exist — a missing user is a 404, not an empty log.
149 User::read(&target, &st.db)165 User::read(&target, &st.db)
150 .await?166 .await?
151 .ok_or(AppError::NotFound)?;167 .ok_or(AppError::NotFound)?;
152 let entries = WorkEntry::list_for_user(&target, &st.db).await?;168 let entries = WorkEntry::list_for_user(&target, &st.db).await?;
153- Ok(Json(entries.iter().map(WorkEntryResponse::new).collect()))169+ let total = entries.len() as i64;
170+ let items = paginate(&entries, limit, offset)
171+ .iter()
172+ .map(WorkEntryResponse::new)
173+ .collect();
174+ Ok(Json(Page::new(items, total, limit, offset)))
154 }175 }
155 176
156 /// Correct a closed stint's instants. Requires manager+. An open stint can't177 /// Correct a closed stint's instants. Requires manager+. An open stint can't
tests/common/mod.rsmodified+15 -0
@@ -121,6 +121,21 @@ pub fn id_of(v: &Value) -> String {
121 v["id"].as_str().expect("id field").to_string()121 v["id"].as_str().expect("id field").to_string()
122 }122 }
123 123
124+/// The `items` array of a paginated list envelope (`{items, total, limit,
125+/// offset}`) — the shape every `GET` list endpoint returns. Panics if `v`
126+/// isn't such an envelope, so a test that points it at the wrong body fails
127+/// loudly.
128+pub fn items(v: &Value) -> &Vec<Value> {
129+ v["items"]
130+ .as_array()
131+ .unwrap_or_else(|| panic!("expected a paginated list envelope with items[], got {v}"))
132+}
133+
134+/// The `total` count from a paginated list envelope.
135+pub fn total(v: &Value) -> i64 {
136+ v["total"].as_i64().expect("paginated envelope total")
137+}
138+
124 /// The caller's own user id via `GET /auth/me`.139 /// The caller's own user id via `GET /auth/me`.
125 pub async fn me_id(app: &Router, cookie: &str) -> String {140 pub async fn me_id(app: &Router, cookie: &str) -> String {
126 let res = send(app, "GET", "/auth/me", Some(cookie), None).await;141 let res = send(app, "GET", "/auth/me", Some(cookie), None).await;
tests/e2e.rsmodified+17 -17
@@ -177,12 +177,12 @@ async fn full_user_journey() {
177 .json()177 .json()
178 .await178 .await
179 .unwrap();179 .unwrap();
180- assert_eq!(roster.as_array().unwrap().len(), 1);180+ assert_eq!(roster["items"].as_array().unwrap().len(), 1);
181 // People come back as refs — id plus something a human can read.181 // People come back as refs — id plus something a human can read.
182- assert_eq!(roster[0]["user"]["id"], veli_id);182+ assert_eq!(roster["items"][0]["user"]["id"], veli_id);
183- assert_eq!(roster[0]["user"]["username"], "veli");183+ assert_eq!(roster["items"][0]["user"]["username"], "veli");
184- assert_eq!(roster[0]["marked_by"]["username"], "ali");184+ assert_eq!(roster["items"][0]["marked_by"]["username"], "ali");
185- assert_eq!(roster[0]["status"], "present");185+ assert_eq!(roster["items"][0]["status"], "present");
186 186
187 // --- user search (for the pickers) -----------------------------------187 // --- user search (for the pickers) -----------------------------------
188 // Teacher+ finds people by fragment; the refs carry no contact details.188 // Teacher+ finds people by fragment; the refs carry no contact details.
@@ -194,8 +194,8 @@ async fn full_user_journey() {
194 .json()194 .json()
195 .await195 .await
196 .unwrap();196 .unwrap();
197- assert_eq!(found[0]["username"], "veli");197+ assert_eq!(found["items"][0]["username"], "veli");
198- assert!(found[0].get("email").is_none());198+ assert!(found["items"][0].get("email").is_none());
199 199
200 // Role filter narrows: veli is a student, so she matches `role=student`200 // Role filter narrows: veli is a student, so she matches `role=student`
201 // but vanishes under `role=teacher`. An unknown role is a 400.201 // but vanishes under `role=teacher`. An unknown role is a 400.
@@ -207,8 +207,8 @@ async fn full_user_journey() {
207 .json()207 .json()
208 .await208 .await
209 .unwrap();209 .unwrap();
210- assert_eq!(found.as_array().unwrap().len(), 1);210+ assert_eq!(found["items"].as_array().unwrap().len(), 1);
211- assert_eq!(found[0]["username"], "veli");211+ assert_eq!(found["items"][0]["username"], "veli");
212 212
213 let found: Value = ali213 let found: Value = ali
214 .get(format!("{base}/users/search?q=vel&role=teacher"))214 .get(format!("{base}/users/search?q=vel&role=teacher"))
@@ -218,7 +218,7 @@ async fn full_user_journey() {
218 .json()218 .json()
219 .await219 .await
220 .unwrap();220 .unwrap();
221- assert!(found.as_array().unwrap().is_empty());221+ assert!(found["items"].as_array().unwrap().is_empty());
222 222
223 let res = ali223 let res = ali
224 .get(format!("{base}/users/search?q=vel&role=wizard"))224 .get(format!("{base}/users/search?q=vel&role=wizard"))
@@ -236,8 +236,8 @@ async fn full_user_journey() {
236 .json()236 .json()
237 .await237 .await
238 .unwrap();238 .unwrap();
239- assert_eq!(found.as_array().unwrap().len(), 1);239+ assert_eq!(found["items"].as_array().unwrap().len(), 1);
240- assert_eq!(found[0]["username"], "ali");240+ assert_eq!(found["items"][0]["username"], "ali");
241 241
242 // Search matches profile names too, and the role filter applies to those242 // Search matches profile names too, and the role filter applies to those
243 // hits as well: "lic" only exists in ali's freshly set name, not in any243 // hits as well: "lic" only exists in ali's freshly set name, not in any
@@ -258,9 +258,9 @@ async fn full_user_journey() {
258 .json()258 .json()
259 .await259 .await
260 .unwrap();260 .unwrap();
261- assert_eq!(found.as_array().unwrap().len(), 1);261+ assert_eq!(found["items"].as_array().unwrap().len(), 1);
262- assert_eq!(found[0]["username"], "ali");262+ assert_eq!(found["items"][0]["username"], "ali");
263- assert_eq!(found[0]["display_name"], "Alice");263+ assert_eq!(found["items"][0]["display_name"], "Alice");
264 264
265 let found: Value = ali265 let found: Value = ali
266 .get(format!("{base}/users/search?q=lic&role=student"))266 .get(format!("{base}/users/search?q=lic&role=student"))
@@ -270,7 +270,7 @@ async fn full_user_journey() {
270 .json()270 .json()
271 .await271 .await
272 .unwrap();272 .unwrap();
273- assert!(found.as_array().unwrap().is_empty());273+ assert!(found["items"].as_array().unwrap().is_empty());
274 274
275 let res = veli275 let res = veli
276 .get(format!("{base}/users/search?q=ali"))276 .get(format!("{base}/users/search?q=ali"))
@@ -381,7 +381,7 @@ async fn attendance_rollup_across_users() {
381 .json()381 .json()
382 .await382 .await
383 .unwrap();383 .unwrap();
384- assert_eq!(roster.as_array().unwrap().len(), 3);384+ assert_eq!(roster["items"].as_array().unwrap().len(), 3);
385 385
386 // Unauthenticated client is refused.386 // Unauthenticated client is refused.
387 let res = client()387 let res = client()
tests/integration.rsmodified+62 -120
@@ -301,12 +301,7 @@ async fn notes_crud_is_scoped_to_owner() {
301 301
302 // Owner sees exactly one; other user sees none and gets 404 on direct access.302 // Owner sees exactly one; other user sees none and gets 404 on direct access.
303 assert_eq!(303 assert_eq!(
304- send(&app, "GET", "/notes", Some(&ali), None)304+ common::items(&send(&app, "GET", "/notes", Some(&ali), None).await.body).len(),
305- .await
306- .body
307- .as_array()
308- .unwrap()
309- .len(),
310 1305 1
311 );306 );
312 assert_eq!(307 assert_eq!(
@@ -316,12 +311,7 @@ async fn notes_crud_is_scoped_to_owner() {
316 StatusCode::NOT_FOUND311 StatusCode::NOT_FOUND
317 );312 );
318 assert_eq!(313 assert_eq!(
319- send(&app, "GET", "/notes", Some(&veli), None)314+ common::items(&send(&app, "GET", "/notes", Some(&veli), None).await.body).len(),
320- .await
321- .body
322- .as_array()
323- .unwrap()
324- .len(),
325 0315 0
326 );316 );
327 317
@@ -471,12 +461,7 @@ async fn events_are_shared_but_creator_guarded() {
471 StatusCode::OK461 StatusCode::OK
472 );462 );
473 assert_eq!(463 assert_eq!(
474- send(&app, "GET", "/events", Some(&veli), None)464+ common::items(&send(&app, "GET", "/events", Some(&veli), None).await.body).len(),
475- .await
476- .body
477- .as_array()
478- .unwrap()
479- .len(),
480 1465 1
481 );466 );
482 467
@@ -597,7 +582,7 @@ async fn attendance_marking_and_upsert() {
597 582
598 // Two rows total.583 // Two rows total.
599 assert_eq!(584 assert_eq!(
600- send(585+ common::items(&send(
601 &app,586 &app,
602 "GET",587 "GET",
603 &format!("/events/{event_id}/attendance"),588 &format!("/events/{event_id}/attendance"),
@@ -605,9 +590,7 @@ async fn attendance_marking_and_upsert() {
605 None590 None
606 )591 )
607 .await592 .await
608- .body593+ .body)
609- .as_array()
610- .unwrap()
611 .len(),594 .len(),
612 2595 2
613 );596 );
@@ -626,7 +609,7 @@ async fn attendance_marking_and_upsert() {
626 StatusCode::NO_CONTENT609 StatusCode::NO_CONTENT
627 );610 );
628 assert_eq!(611 assert_eq!(
629- send(612+ common::items(&send(
630 &app,613 &app,
631 "GET",614 "GET",
632 &format!("/events/{event_id}/attendance"),615 &format!("/events/{event_id}/attendance"),
@@ -634,9 +617,7 @@ async fn attendance_marking_and_upsert() {
634 None617 None
635 )618 )
636 .await619 .await
637- .body620+ .body)
638- .as_array()
639- .unwrap()
640 .len(),621 .len(),
641 1622 1
642 );623 );
@@ -893,12 +874,7 @@ async fn exams_are_course_scoped_and_course_guarded() {
893 StatusCode::FORBIDDEN874 StatusCode::FORBIDDEN
894 );875 );
895 assert_eq!(876 assert_eq!(
896- send(&app, "GET", "/exams", Some(&veli), None)877+ common::items(&send(&app, "GET", "/exams", Some(&veli), None).await.body).len(),
897- .await
898- .body
899- .as_array()
900- .unwrap()
901- .len(),
902 0878 0
903 );879 );
904 assert_eq!(880 assert_eq!(
@@ -922,16 +898,11 @@ async fn exams_are_course_scoped_and_course_guarded() {
922 StatusCode::OK898 StatusCode::OK
923 );899 );
924 assert_eq!(900 assert_eq!(
925- send(&app, "GET", "/exams", Some(&ali), None)901+ common::items(&send(&app, "GET", "/exams", Some(&ali), None).await.body).len(),
926- .await
927- .body
928- .as_array()
929- .unwrap()
930- .len(),
931 1902 1
932 );903 );
933 assert_eq!(904 assert_eq!(
934- send(905+ common::items(&send(
935 &app,906 &app,
936 "GET",907 "GET",
937 &format!("/courses/{course_id}/exams"),908 &format!("/courses/{course_id}/exams"),
@@ -939,9 +910,7 @@ async fn exams_are_course_scoped_and_course_guarded() {
939 None910 None
940 )911 )
941 .await912 .await
942- .body913+ .body)
943- .as_array()
944- .unwrap()
945 .len(),914 .len(),
946 1915 1
947 );916 );
@@ -1117,7 +1086,7 @@ async fn grading_upsert_and_own_result() {
1117 1086
1118 // Teacher sees the full list (one row).1087 // Teacher sees the full list (one row).
1119 assert_eq!(1088 assert_eq!(
1120- send(1089+ common::items(&send(
1121 &app,1090 &app,
1122 "GET",1091 "GET",
1123 &format!("/exams/{exam_id}/results"),1092 &format!("/exams/{exam_id}/results"),
@@ -1125,9 +1094,7 @@ async fn grading_upsert_and_own_result() {
1125 None1094 None
1126 )1095 )
1127 .await1096 .await
1128- .body1097+ .body)
1129- .as_array()
1130- .unwrap()
1131 .len(),1098 .len(),
1132 11099 1
1133 );1100 );
@@ -1382,12 +1349,7 @@ async fn courses_are_owner_scoped_and_creator_guarded() {
1382 StatusCode::FORBIDDEN1349 StatusCode::FORBIDDEN
1383 );1350 );
1384 assert_eq!(1351 assert_eq!(
1385- send(&app, "GET", "/courses", Some(&veli), None)1352+ common::items(&send(&app, "GET", "/courses", Some(&veli), None).await.body).len(),
1386- .await
1387- .body
1388- .as_array()
1389- .unwrap()
1390- .len(),
1391 01353 0
1392 );1354 );
1393 1355
@@ -1406,12 +1368,7 @@ async fn courses_are_owner_scoped_and_creator_guarded() {
1406 StatusCode::OK1368 StatusCode::OK
1407 );1369 );
1408 assert_eq!(1370 assert_eq!(
1409- send(&app, "GET", "/courses", Some(caller), None)1371+ common::items(&send(&app, "GET", "/courses", Some(caller), None).await.body).len(),
1410- .await
1411- .body
1412- .as_array()
1413- .unwrap()
1414- .len(),
1415 11372 1
1416 );1373 );
1417 }1374 }
@@ -1535,7 +1492,7 @@ async fn enrollment_upsert_roster_and_my_courses() {
1535 None,1492 None,
1536 )1493 )
1537 .await;1494 .await;
1538- assert_eq!(roster.body.as_array().unwrap().len(), 1);1495+ assert_eq!(common::items(&roster.body).len(), 1);
1539 assert_eq!(1496 assert_eq!(
1540 send(1497 send(
1541 &app,1498 &app,
@@ -1551,21 +1508,21 @@ async fn enrollment_upsert_roster_and_my_courses() {
1551 1508
1552 // /courses/me shows the course for alice, stays empty for bob.1509 // /courses/me shows the course for alice, stays empty for bob.
1553 assert_eq!(1510 assert_eq!(
1554- send(&app, "GET", "/courses/me", Some(&alice), None)1511+ common::items(
1555- .await1512+ &send(&app, "GET", "/courses/me", Some(&alice), None)
1556- .body1513+ .await
1557- .as_array()1514+ .body,
1558- .unwrap()1515+ )
1559- .len(),1516+ .len(),
1560 11517 1
1561 );1518 );
1562 assert_eq!(1519 assert_eq!(
1563- send(&app, "GET", "/courses/me", Some(&bob), None)1520+ common::items(
1564- .await1521+ &send(&app, "GET", "/courses/me", Some(&bob), None)
1565- .body1522+ .await
1566- .as_array()1523+ .body,
1567- .unwrap()1524+ )
1568- .len(),1525+ .len(),
1569 01526 0
1570 );1527 );
1571 1528
@@ -1736,7 +1693,7 @@ async fn exam_creation_lives_under_courses() {
1736 StatusCode::OK1693 StatusCode::OK
1737 );1694 );
1738 assert_eq!(1695 assert_eq!(
1739- send(1696+ common::items(&send(
1740 &app,1697 &app,
1741 "GET",1698 "GET",
1742 &format!("/courses/{course_id}/exams"),1699 &format!("/courses/{course_id}/exams"),
@@ -1744,9 +1701,7 @@ async fn exam_creation_lives_under_courses() {
1744 None1701 None
1745 )1702 )
1746 .await1703 .await
1747- .body1704+ .body)
1748- .as_array()
1749- .unwrap()
1750 .len(),1705 .len(),
1751 11706 1
1752 );1707 );
@@ -1814,12 +1769,7 @@ async fn grading_requires_enrollment() {
1814 StatusCode::BAD_REQUEST1769 StatusCode::BAD_REQUEST
1815 );1770 );
1816 assert_eq!(1771 assert_eq!(
1817- send(&app, "GET", &grade_uri, Some(&teacher), None)1772+ common::items(&send(&app, "GET", &grade_uri, Some(&teacher), None).await.body).len(),
1818- .await
1819- .body
1820- .as_array()
1821- .unwrap()
1822- .len(),
1823 11773 1
1824 );1774 );
1825 assert_eq!(1775 assert_eq!(
@@ -2227,7 +2177,7 @@ async fn course_data_is_walled_off_from_other_teachers() {
2227 for uri in ["/courses", "/exams"] {2177 for uri in ["/courses", "/exams"] {
2228 let res = send(&app, "GET", uri, Some(caller), None).await;2178 let res = send(&app, "GET", uri, Some(caller), None).await;
2229 assert_eq!(2179 assert_eq!(
2230- res.body.as_array().unwrap().len(),2180+ common::items(&res.body).len(),
2231 visible,2181 visible,
2232 "{uri} as seen by caller"2182 "{uri} as seen by caller"
2233 );2183 );
@@ -2305,12 +2255,12 @@ async fn deleting_course_cascades_enrollments_exams_and_results() {
2305 StatusCode::NOT_FOUND2255 StatusCode::NOT_FOUND
2306 );2256 );
2307 assert_eq!(2257 assert_eq!(
2308- send(&app, "GET", "/courses/me", Some(&alice), None)2258+ common::items(
2309- .await2259+ &send(&app, "GET", "/courses/me", Some(&alice), None)
2310- .body2260+ .await
2311- .as_array()2261+ .body,
2312- .unwrap()2262+ )
2313- .len(),2263+ .len(),
2314 02264 0
2315 );2265 );
2316 assert_eq!(2266 assert_eq!(
@@ -2363,7 +2313,7 @@ async fn concurrent_enrollments_never_collide() {
2363 )2313 )
2364 .await;2314 .await;
2365 assert_eq!(2315 assert_eq!(
2366- roster.body.as_array().unwrap().len(),2316+ common::items(&roster.body).len(),
2367 1,2317 1,
2368 "upsert keeps a single row"2318 "upsert keeps a single row"
2369 );2319 );
@@ -2527,7 +2477,7 @@ async fn admin_manages_roles_with_guards() {
2527 // Admin lists users (at least admin + alice).2477 // Admin lists users (at least admin + alice).
2528 let list = send(&app, "GET", "/users", Some(&admin), None).await;2478 let list = send(&app, "GET", "/users", Some(&admin), None).await;
2529 assert_eq!(list.status, StatusCode::OK);2479 assert_eq!(list.status, StatusCode::OK);
2530- assert!(list.body.as_array().unwrap().len() >= 2);2480+ assert!(common::items(&list.body).len() >= 2);
2531 2481
2532 // Admin promotes alice to teacher; the change is reflected in the response...2482 // Admin promotes alice to teacher; the change is reflected in the response...
2533 let promoted = send(2483 let promoted = send(
@@ -2767,10 +2717,7 @@ async fn admin_reads_and_edits_any_profile_with_guards() {
2767 2717
2768 // The admin listing now carries the info columns too.2718 // The admin listing now carries the info columns too.
2769 let list = send(&app, "GET", "/users", Some(&admin), None).await;2719 let list = send(&app, "GET", "/users", Some(&admin), None).await;
2770- let listed = list2720+ let listed = common::items(&list.body)
2771- .body
2772- .as_array()
2773- .unwrap()
2774 .iter()2721 .iter()
2775 .find(|u| u["username"] == "alice")2722 .find(|u| u["username"] == "alice")
2776 .expect("alice listed")2723 .expect("alice listed")
@@ -2855,7 +2802,7 @@ async fn concurrent_attendance_marks_never_collide() {
2855 )2802 )
2856 .await;2803 .await;
2857 assert_eq!(2804 assert_eq!(
2858- roster.body.as_array().unwrap().len(),2805+ common::items(&roster.body).len(),
2859 1,2806 1,
2860 "upsert keeps a single row"2807 "upsert keeps a single row"
2861 );2808 );
@@ -2901,7 +2848,7 @@ async fn concurrent_exam_grades_never_collide() {
2901 )2848 )
2902 .await;2849 .await;
2903 assert_eq!(2850 assert_eq!(
2904- results.body.as_array().unwrap().len(),2851+ common::items(&results.body).len(),
2905 1,2852 1,
2906 "upsert keeps a single row"2853 "upsert keeps a single row"
2907 );2854 );
@@ -3076,7 +3023,7 @@ async fn graders_cannot_grade_themselves() {
3076 3023
3077 // And the rejected attempts wrote nothing.3024 // And the rejected attempts wrote nothing.
3078 assert_eq!(3025 assert_eq!(
3079- send(3026+ common::items(&send(
3080 &app,3027 &app,
3081 "GET",3028 "GET",
3082 &format!("/exams/{exam_id}/results"),3029 &format!("/exams/{exam_id}/results"),
@@ -3084,9 +3031,7 @@ async fn graders_cannot_grade_themselves() {
3084 None3031 None
3085 )3032 )
3086 .await3033 .await
3087- .body3034+ .body)
3088- .as_array()
3089- .unwrap()
3090 .len(),3035 .len(),
3091 03036 0
3092 );3037 );
@@ -3416,7 +3361,7 @@ async fn admin_seed_is_idempotent() {
3416 res.cookie.expect("session cookie")3361 res.cookie.expect("session cookie")
3417 };3362 };
3418 let res = send(&app, "GET", "/users", Some(&cookie), None).await;3363 let res = send(&app, "GET", "/users", Some(&cookie), None).await;
3419- let listed = res.body.as_array().expect("user list");3364+ let listed = common::items(&res.body);
3420 assert_eq!(listed.len(), 1, "seed must not duplicate the account");3365 assert_eq!(listed.len(), 1, "seed must not duplicate the account");
3421 assert_eq!(listed[0]["role"], "admin");3366 assert_eq!(listed[0]["role"], "admin");
3422 }3367 }
@@ -4893,7 +4838,7 @@ async fn question_crud_validation_and_rbac() {
4893 )4838 )
4894 .await;4839 .await;
4895 assert_eq!(res.status, StatusCode::OK);4840 assert_eq!(res.status, StatusCode::OK);
4896- let questions = res.body.as_array().expect("questions");4841+ let questions = common::items(&res.body);
4897 assert_eq!(questions.len(), 2);4842 assert_eq!(questions.len(), 2);
4898 assert_eq!(id_of(&questions[0]), choice_q);4843 assert_eq!(id_of(&questions[0]), choice_q);
4899 assert_eq!(id_of(&questions[1]), text_q);4844 assert_eq!(id_of(&questions[1]), text_q);
@@ -5109,7 +5054,7 @@ async fn question_crud_validation_and_rbac() {
5109 None,5054 None,
5110 )5055 )
5111 .await;5056 .await;
5112- assert_eq!(res.body.as_array().unwrap().len(), 1);5057+ assert_eq!(common::items(&res.body).len(), 1);
5113 }5058 }
5114 5059
5115 #[tokio::test]5060 #[tokio::test]
@@ -6044,8 +5989,8 @@ async fn question_patch_revalidates_the_stale_kind_bundle() {
6044 None,5989 None,
6045 )5990 )
6046 .await;5991 .await;
6047- assert_eq!(res.body[0]["choices"].as_array().unwrap().len(), 2);5992+ assert_eq!(common::items(&res.body)[0]["choices"].as_array().unwrap().len(), 2);
6048- assert_eq!(res.body[0]["correct"], 1);5993+ assert_eq!(common::items(&res.body)[0]["correct"], 1);
6049 }5994 }
6050 5995
6051 #[tokio::test]5996 #[tokio::test]
@@ -6317,8 +6262,8 @@ async fn session_crud_follows_course_management() {
6317 assert_eq!(res.status, StatusCode::OK);6262 assert_eq!(res.status, StatusCode::OK);
6318 // owner's, the manager's, and the one taught by `rival` — newest starts_at6263 // owner's, the manager's, and the one taught by `rival` — newest starts_at
6319 // first, so the two `start` lessons precede the earlier `rival` one.6264 // first, so the two `start` lessons precede the earlier `rival` one.
6320- assert_eq!(res.body.as_array().unwrap().len(), 3);6265+ assert_eq!(common::items(&res.body).len(), 3);
6321- assert_eq!(res.body[2]["starts_at"], now + 120_000);6266+ assert_eq!(common::items(&res.body)[2]["starts_at"], now + 120_000);
6322 let res = send(&app, "GET", "/courses/nope/sessions", Some(&student), None).await;6267 let res = send(&app, "GET", "/courses/nope/sessions", Some(&student), None).await;
6323 assert_eq!(res.status, StatusCode::NOT_FOUND);6268 assert_eq!(res.status, StatusCode::NOT_FOUND);
6324 let res = send(6269 let res = send(
@@ -6532,7 +6477,7 @@ async fn roll_call_rbac_and_upsert() {
6532 // get their own tallies via `/attendance/me`.6477 // get their own tallies via `/attendance/me`.
6533 let res = send(&app, "GET", &mark_uri, Some(&hoca), None).await;6478 let res = send(&app, "GET", &mark_uri, Some(&hoca), None).await;
6534 assert_eq!(res.status, StatusCode::OK);6479 assert_eq!(res.status, StatusCode::OK);
6535- let roster = res.body.as_array().unwrap();6480+ let roster = common::items(&res.body);
6536 assert_eq!(roster.len(), 1);6481 assert_eq!(roster.len(), 1);
6537 assert_eq!(roster[0]["status"], "absent");6482 assert_eq!(roster[0]["status"], "absent");
6538 let res = send(&app, "GET", &mark_uri, Some(&ali), None).await;6483 let res = send(&app, "GET", &mark_uri, Some(&ali), None).await;
@@ -6771,7 +6716,7 @@ async fn work_log_lifecycle_is_server_stamped_and_exclusive() {
6771 let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await;6716 let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await;
6772 assert_eq!(res.status, StatusCode::CONFLICT);6717 assert_eq!(res.status, StatusCode::CONFLICT);
6773 let res = send(&app, "GET", "/work/me", Some(&hoca), None).await;6718 let res = send(&app, "GET", "/work/me", Some(&hoca), None).await;
6774- let log = res.body.as_array().unwrap();6719+ let log = common::items(&res.body);
6775 assert_eq!(log.len(), 1);6720 assert_eq!(log.len(), 1);
6776 assert_eq!(log[0]["check_in"].as_i64().unwrap(), first_in);6721 assert_eq!(log[0]["check_in"].as_i64().unwrap(), first_in);
6777 6722
@@ -6787,7 +6732,7 @@ async fn work_log_lifecycle_is_server_stamped_and_exclusive() {
6787 let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await;6732 let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await;
6788 assert_eq!(res.status, StatusCode::CREATED);6733 assert_eq!(res.status, StatusCode::CREATED);
6789 let res = send(&app, "GET", "/work/me", Some(&hoca), None).await;6734 let res = send(&app, "GET", "/work/me", Some(&hoca), None).await;
6790- let log = res.body.as_array().unwrap();6735+ let log = common::items(&res.body);
6791 assert_eq!(log.len(), 2);6736 assert_eq!(log.len(), 2);
6792 assert!(log[0]["check_out"].is_null(), "open stint sorts newest");6737 assert!(log[0]["check_out"].is_null(), "open stint sorts newest");
6793 assert!(!log[1]["check_out"].is_null());6738 assert!(!log[1]["check_out"].is_null());
@@ -6813,7 +6758,7 @@ async fn work_log_manager_reads_and_corrections() {
6813 assert_eq!(res.status, StatusCode::FORBIDDEN);6758 assert_eq!(res.status, StatusCode::FORBIDDEN);
6814 let res = send(&app, "GET", &format!("/work/{hoca_id}"), Some(&boss), None).await;6759 let res = send(&app, "GET", &format!("/work/{hoca_id}"), Some(&boss), None).await;
6815 assert_eq!(res.status, StatusCode::OK);6760 assert_eq!(res.status, StatusCode::OK);
6816- assert_eq!(res.body.as_array().unwrap().len(), 2);6761+ assert_eq!(common::items(&res.body).len(), 2);
6817 let res = send(&app, "GET", "/work/01UNKNOWN", Some(&boss), None).await;6762 let res = send(&app, "GET", "/work/01UNKNOWN", Some(&boss), None).await;
6818 assert_eq!(res.status, StatusCode::NOT_FOUND);6763 assert_eq!(res.status, StatusCode::NOT_FOUND);
6819 6764
@@ -7182,7 +7127,7 @@ async fn search_matches_are_literal_not_like_wildcards() {
7182 // Under LIKE semantics it would match every user with a name.7127 // Under LIKE semantics it would match every user with a name.
7183 let res = send(&app, "GET", "/users/search?q=%25", Some(&teacher), None).await;7128 let res = send(&app, "GET", "/users/search?q=%25", Some(&teacher), None).await;
7184 assert_eq!(res.status, StatusCode::OK);7129 assert_eq!(res.status, StatusCode::OK);
7185- let hits = res.body.as_array().unwrap();7130+ let hits = common::items(&res.body);
7186 assert_eq!(hits.len(), 1, "`%` must match literally: {hits:?}");7131 assert_eq!(hits.len(), 1, "`%` must match literally: {hits:?}");
7187 assert_eq!(hits[0]["username"], "percy");7132 assert_eq!(hits[0]["username"], "percy");
7188 7133
@@ -7190,7 +7135,7 @@ async fn search_matches_are_literal_not_like_wildcards() {
7190 // semantics `_` is any-single-character and would match everyone.7135 // semantics `_` is any-single-character and would match everyone.
7191 let res = send(&app, "GET", "/users/search?q=_", Some(&teacher), None).await;7136 let res = send(&app, "GET", "/users/search?q=_", Some(&teacher), None).await;
7192 assert_eq!(res.status, StatusCode::OK);7137 assert_eq!(res.status, StatusCode::OK);
7193- let hits = res.body.as_array().unwrap();7138+ let hits = common::items(&res.body);
7194 assert_eq!(hits.len(), 1, "`_` must match literally: {hits:?}");7139 assert_eq!(hits.len(), 1, "`_` must match literally: {hits:?}");
7195 assert_eq!(hits[0]["username"], "under_score");7140 assert_eq!(hits[0]["username"], "under_score");
7196 }7141 }
@@ -7226,7 +7171,7 @@ async fn course_catalog_lists_a_creator_enrolled_course_once() {
7226 7171
7227 let res = send(&app, "GET", "/courses", Some(&teacher), None).await;7172 let res = send(&app, "GET", "/courses", Some(&teacher), None).await;
7228 assert_eq!(res.status, StatusCode::OK);7173 assert_eq!(res.status, StatusCode::OK);
7229- let courses = res.body.as_array().unwrap();7174+ let courses = common::items(&res.body);
7230 assert_eq!(courses.len(), 1, "created+enrolled must dedup: {courses:?}");7175 assert_eq!(courses.len(), 1, "created+enrolled must dedup: {courses:?}");
7231 assert_eq!(courses[0]["id"], json!(course));7176 assert_eq!(courses[0]["id"], json!(course));
7232 7177
@@ -7234,7 +7179,7 @@ async fn course_catalog_lists_a_creator_enrolled_course_once() {
7234 // the course's exams either.7179 // the course's exams either.
7235 let exam = create_exam(&app, &teacher, &course, "mt", "quiz").await;7180 let exam = create_exam(&app, &teacher, &course, "mt", "quiz").await;
7236 let res = send(&app, "GET", "/exams", Some(&teacher), None).await;7181 let res = send(&app, "GET", "/exams", Some(&teacher), None).await;
7237- let exams = res.body.as_array().unwrap();7182+ let exams = common::items(&res.body);
7238 assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}");7183 assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}");
7239 assert_eq!(exams[0]["id"], json!(exam));7184 assert_eq!(exams[0]["id"], json!(exam));
7240 }7185 }
@@ -7640,7 +7585,7 @@ async fn terms_crud_gates_and_links_to_courses() {
7640 // Any authenticated user reads the calendar.7585 // Any authenticated user reads the calendar.
7641 let res = send(&app, "GET", "/terms", Some(&student), None).await;7586 let res = send(&app, "GET", "/terms", Some(&student), None).await;
7642 assert_eq!(res.status, StatusCode::OK);7587 assert_eq!(res.status, StatusCode::OK);
7643- assert_eq!(res.body.as_array().unwrap().len(), 1);7588+ assert_eq!(common::items(&res.body).len(), 1);
7644 7589
7645 // Courses link to a term at creation; a bogus id is a 400, not a silent null.7590 // Courses link to a term at creation; a bogus id is a 400, not a silent null.
7646 let res = send(7591 let res = send(
@@ -7809,10 +7754,7 @@ async fn terms_list_newest_first_require_auth_and_unlink_in_bulk() {
7809 7754
7810 // Newest (by starts_at) first.7755 // Newest (by starts_at) first.
7811 let res = send(&app, "GET", "/terms", Some(&teacher), None).await;7756 let res = send(&app, "GET", "/terms", Some(&teacher), None).await;
7812- let names: Vec<&str> = res7757+ let names: Vec<&str> = common::items(&res.body)
7813- .body
7814- .as_array()
7815- .unwrap()
7816 .iter()7758 .iter()
7817 .map(|t| t["name"].as_str().unwrap())7759 .map(|t| t["name"].as_str().unwrap())
7818 .collect();7760 .collect();
tests/pagination.rsadded+163 -0
@@ -0,0 +1,163 @@
1+//! Pagination behavior common to every list endpoint: the `{items, total,
2+//! limit, offset}` envelope, opt-in windowing, join-on-the-page, and the `400`s
3+//! for out-of-range parameters. One representative endpoint per shape — the
4+//! machinery (`web::page`) is shared, so this pins the contract without
5+//! re-testing all 16 lists.
6+
7+mod common;
8+
9+use axum::http::StatusCode;
10+use common::{app_and_db, create_course, enroll, items, login, login_as, me_id, send, total};
11+use serde_json::json;
12+
13+/// Register `user00..user{n-1}` as plain students.
14+async fn seed_students(app: &axum::Router, n: usize) {
15+ for i in 0..n {
16+ let name = format!("user{i:02}");
17+ let creds = json!({ "username": name, "password": "secret1" });
18+ let res = send(app, "POST", "/auth/register", None, Some(creds)).await;
19+ assert_eq!(res.status, StatusCode::CREATED, "register {name}");
20+ }
21+}
22+
23+#[tokio::test]
24+async fn envelope_windows_and_total_is_stable() {
25+ let (app, db) = app_and_db().await;
26+ // 1 admin (to read /users) + 24 students = 25 accounts.
27+ let admin = login_as(&app, &db, "boss", "admin").await;
28+ seed_students(&app, 24).await;
29+
30+ // Unpaged: the whole list, `limit` echoes null, `total` counts everyone.
31+ let res = send(&app, "GET", "/users", Some(&admin), None).await;
32+ assert_eq!(res.status, StatusCode::OK);
33+ assert_eq!(total(&res.body), 25);
34+ assert_eq!(items(&res.body).len(), 25);
35+ assert!(res.body["limit"].is_null(), "omitted limit echoes null");
36+ assert_eq!(res.body["offset"], 0);
37+
38+ // First window of 10.
39+ let res = send(&app, "GET", "/users?limit=10&offset=0", Some(&admin), None).await;
40+ assert_eq!(total(&res.body), 25);
41+ assert_eq!(items(&res.body).len(), 10);
42+ assert_eq!(res.body["limit"], 10);
43+ assert_eq!(res.body["offset"], 0);
44+ let page1: Vec<_> = items(&res.body).iter().map(|u| u["id"].clone()).collect();
45+
46+ // Second window — disjoint from the first, identical total.
47+ let res = send(&app, "GET", "/users?limit=10&offset=10", Some(&admin), None).await;
48+ assert_eq!(total(&res.body), 25);
49+ assert_eq!(items(&res.body).len(), 10);
50+ assert_eq!(res.body["offset"], 10);
51+ let page2: Vec<_> = items(&res.body).iter().map(|u| u["id"].clone()).collect();
52+ assert!(
53+ page2.iter().all(|id| !page1.contains(id)),
54+ "consecutive pages must not overlap"
55+ );
56+
57+ // Tail — the remaining 5, even though a full window of 10 was asked for.
58+ let res = send(&app, "GET", "/users?limit=10&offset=20", Some(&admin), None).await;
59+ assert_eq!(items(&res.body).len(), 5, "tail returns only the remainder");
60+ assert_eq!(total(&res.body), 25);
61+
62+ // Past the end — an empty page, not an error, and `total` stays honest.
63+ let res = send(&app, "GET", "/users?limit=10&offset=999", Some(&admin), None).await;
64+ assert_eq!(res.status, StatusCode::OK);
65+ assert!(items(&res.body).is_empty(), "offset past the end is empty");
66+ assert_eq!(total(&res.body), 25);
67+}
68+
69+#[tokio::test]
70+async fn bad_paging_params_are_rejected() {
71+ let (app, db) = app_and_db().await;
72+ let admin = login_as(&app, &db, "boss", "admin").await;
73+
74+ for bad in [
75+ "limit=0", // below the floor
76+ "limit=501", // above the 500 cap
77+ "limit=-1", // negative
78+ "offset=-1", // negative offset
79+ "limit=abc", // not an integer
80+ ] {
81+ let res = send(&app, "GET", &format!("/users?{bad}"), Some(&admin), None).await;
82+ assert_eq!(
83+ res.status,
84+ StatusCode::BAD_REQUEST,
85+ "GET /users?{bad} should be 400"
86+ );
87+ }
88+
89+ // The inclusive bounds and a bare offset are accepted.
90+ for ok in ["limit=1", "limit=500", "offset=0", "limit=50&offset=0"] {
91+ let res = send(&app, "GET", &format!("/users?{ok}"), Some(&admin), None).await;
92+ assert_eq!(res.status, StatusCode::OK, "GET /users?{ok} should be 200");
93+ }
94+}
95+
96+#[tokio::test]
97+async fn paged_roster_still_embeds_people_on_the_page() {
98+ // A list that joins person refs must run that join over the returned page,
99+ // not the whole table — the page rows still carry their embedded people.
100+ let (app, db) = app_and_db().await;
101+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
102+ let course = create_course(&app, &teacher, "Algebra").await;
103+
104+ for i in 0..5 {
105+ let student = login(&app, &format!("stud{i}")).await;
106+ let sid = me_id(&app, &student).await;
107+ enroll(&app, &teacher, &course, &sid).await;
108+ }
109+
110+ let uri = format!("/courses/{course}/enrollments?limit=2&offset=0");
111+ let res = send(&app, "GET", &uri, Some(&teacher), None).await;
112+ assert_eq!(res.status, StatusCode::OK);
113+ assert_eq!(total(&res.body), 5, "total counts the whole roster");
114+ let page = items(&res.body);
115+ assert_eq!(page.len(), 2, "only the requested window comes back");
116+ for row in page {
117+ assert!(
118+ row["user"]["username"].is_string(),
119+ "enrolled student ref present on the page: {row}"
120+ );
121+ assert!(
122+ row["enrolled_by"]["username"].is_string(),
123+ "enroller ref present on the page: {row}"
124+ );
125+ }
126+}
127+
128+#[tokio::test]
129+async fn user_search_is_paged_not_capped() {
130+ // `/users/search` used to hard-cap at 10 rows; it now pages like the rest.
131+ let (app, db) = app_and_db().await;
132+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
133+ // 12 accounts sharing the "grp" fragment — past the old cap.
134+ for i in 0..12 {
135+ let creds = json!({ "username": format!("grp{i:02}"), "password": "secret1" });
136+ let res = send(&app, "POST", "/auth/register", None, Some(creds)).await;
137+ assert_eq!(res.status, StatusCode::CREATED);
138+ }
139+
140+ // Unpaged: every match comes back — no 10-row ceiling.
141+ let res = send(&app, "GET", "/users/search?q=grp", Some(&teacher), None).await;
142+ assert_eq!(res.status, StatusCode::OK);
143+ assert_eq!(total(&res.body), 12, "all matches counted, not capped at 10");
144+ assert_eq!(items(&res.body).len(), 12);
145+
146+ // Windowed like any other list — the tail is the remainder.
147+ let res = send(
148+ &app,
149+ "GET",
150+ "/users/search?q=grp&limit=5&offset=10",
151+ Some(&teacher),
152+ None,
153+ )
154+ .await;
155+ assert_eq!(total(&res.body), 12);
156+ assert_eq!(items(&res.body).len(), 2, "offset 10 of 12 leaves 2");
157+
158+ // Paging bounds are enforced, and a blank query is still refused.
159+ let res = send(&app, "GET", "/users/search?q=grp&limit=0", Some(&teacher), None).await;
160+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "limit=0 is a 400");
161+ let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await;
162+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "blank q is still a 400");
163+}
tests/persistence.rsmodified+9 -9
@@ -83,12 +83,12 @@ async fn file_engine_runs_full_flow() {
83 .await;83 .await;
84 assert_eq!(note.status, StatusCode::CREATED);84 assert_eq!(note.status, StatusCode::CREATED);
85 assert_eq!(85 assert_eq!(
86- send(&app, "GET", "/notes", Some(&cookie), None)86+ common::items(
87- .await87+ &send(&app, "GET", "/notes", Some(&cookie), None)
88- .body88+ .await
89- .as_array()89+ .body,
90- .unwrap()90+ )
91- .len(),91+ .len(),
92 192 1
93 );93 );
94 }94 }
@@ -143,7 +143,7 @@ async fn data_survives_reopen() {
143 "notes list body: {}",143 "notes list body: {}",
144 notes.body144 notes.body
145 );145 );
146- let rows = notes.body.as_array().unwrap();146+ let rows = common::items(&notes.body);
147 assert_eq!(rows.len(), 1, "note survived reopen");147 assert_eq!(rows.len(), 1, "note survived reopen");
148 assert_eq!(rows[0]["title"], "persisted");148 assert_eq!(rows[0]["title"], "persisted");
149 }149 }
@@ -315,7 +315,7 @@ async fn course_marks_survive_reopen() {
315 None,315 None,
316 )316 )
317 .await;317 .await;
318- assert_eq!(roster.body.as_array().unwrap().len(), 1, "roster intact");318+ assert_eq!(common::items(&roster.body).len(), 1, "roster intact");
319 }319 }
320 }320 }
321 321
@@ -403,7 +403,7 @@ async fn settings_and_terms_survive_reopen() {
403 assert_eq!(res.body["name"], "2026 Fall");403 assert_eq!(res.body["name"], "2026 Fall");
404 404
405 let res = send(&app, "GET", "/courses", Some(&cookie), None).await;405 let res = send(&app, "GET", "/courses", Some(&cookie), None).await;
406- let courses = res.body.as_array().unwrap();406+ let courses = common::items(&res.body);
407 assert_eq!(courses.len(), 1);407 assert_eq!(courses.len(), 1);
408 assert_eq!(courses[0]["term"].as_str(), Some(term.as_str()));408 assert_eq!(courses[0]["term"].as_str(), Some(term.as_str()));
409 }409 }