diff --git a/README.md b/README.md index f202b49..e6e66a3 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,19 @@ monitor) additionally need **course-management rights** (creator or manager+): one teacher cannot look into another teacher's course, and the per-user marks/attendance reports narrow to the courses the caller manages. +**Paging.** Every list endpoint below (the rows tagged **· paged**) accepts +`?limit=&offset=` and returns a `{ items, total, limit, offset }` envelope +rather than a bare array. `total` is the full row count *before* the window, so +a frontend can show "100 of 256" and page with `offset`. Paging is **opt-in**: +omit `limit` and you get every remaining row (the echoed `limit` is then +`null`), so a caller that sends no parameters still receives the whole list — +nothing silently truncates. `limit` must be `1`–`500`, `offset` defaults to `0` +and must be ≥ 0 (bad values are `400`), and an `offset` at or past the end +returns an empty `items` (not an error). Deliberately **not** paged — these keep +their existing shapes: the student exam-room reads +`/exams/{id}/attempt/questions` and `/attempt/answers`, the `/marks` and +`/attendance` report objects, the `/exams/{id}/live` monitor, and `/settings`. + | Method | Path | Auth | Description | |--------|----------------------------------|---------|---------------------------------| | GET | `/health` | no | Liveness check | @@ -240,49 +253,49 @@ marks/attendance reports narrow to the courses the caller manages. | POST | `/auth/logout` | no | Clear session (no-op if none) | | GET | `/auth/me` | student | Current user (incl. `role` and personal info) | | PATCH | `/users/me` | student | Update own personal info (see below) | -| GET | `/users/search` | teacher | `?q=&role=` — find users by username/name fragment (pickers); ≤10 refs, no contact info | -| GET | `/users` | admin | List all users | +| GET | `/users/search` | teacher | `?q=&role=` — find users by username/name fragment (pickers); refs only, no contact info · paged | +| GET | `/users` | admin | List all users · paged | | GET | `/users/{id}` | admin | Get one user | | PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role | | PATCH | `/users/{id}/profile` | admin | Update any user's personal info | | POST | `/notes` | student | `{title, content?}` | -| GET | `/notes` | student | List own notes | +| GET | `/notes` | student | List own notes · paged | | GET | `/notes/{id}` | student | Get own note | | PATCH | `/notes/{id}` | student | `{title?, content?}` | | DELETE | `/notes/{id}` | student | Delete own note | | POST | `/events` | teacher | `{title, description?, starts_at?, ends_at?}` | -| GET | `/events` | student | List all events | +| GET | `/events` | student | List all events · paged | | GET | `/events/{id}` | student | Get event | | PATCH | `/events/{id}` | teacher | Edit event (creator, or manager+ for any) | | DELETE | `/events/{id}` | teacher | Delete event (creator, or manager+ for any) | | POST | `/events/{id}/attendance` | student | `{status, user_id?}` — self if `user_id` omitted; marking others needs teacher+ | -| GET | `/events/{id}/attendance` | teacher | List attendance for event (students read their own tallies via `/attendance/me`) | +| GET | `/events/{id}/attendance` | teacher | List attendance for event (students read their own tallies via `/attendance/me`) · paged | | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance | | POST | `/courses` | teacher | `{title, description?}` (creator manages it) | -| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) | -| GET | `/courses/me` | student | The caller's **enrolled** courses | +| GET | `/courses` | student | The caller's visible courses: created + enrolled (manager+: all) · paged | +| GET | `/courses/me` | student | The caller's **enrolled** courses · paged | | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | | PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) | | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments (creator, or manager+) | | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a user (idempotent upsert; course manager) | -| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) | +| GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | -| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, or manager+) | +| GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, or manager+) · paged | | GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) | | PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) | | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) | | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled** students; the teacher's own row needs manager+ | -| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) | +| GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged | | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) | | 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 | -| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) | -| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) | +| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) · paged | +| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) · paged | | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) | | 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) | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) | | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) | -| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) | +| GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged | | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) | | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) | | 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. | 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` | | POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room | | POST | `/exams/{id}/questions` | teacher | `{text, kind, points, choices?, correct?}` — add a question (course manager; frozen once attempted) | -| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) | +| GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | | 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. | GET | `/marks/{user}` | teacher | A user's mark report, narrowed to the caller's courses (manager+: full) | | POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) | | POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) | -| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) | -| GET | `/work/{user}` | manager | A staff member's work log | +| GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) · paged | +| GET | `/work/{user}` | manager | A staff member's work log · paged | | PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` — correct a **closed** stint (`409` on open) | | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | | 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. | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands` | | PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | -| GET | `/terms` | student | List terms, newest first | +| GET | `/terms` | student | List terms, newest first · paged | | GET | `/terms/{id}` | student | Get one term | | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) | | DELETE | `/terms/{id}` | manager | Delete a term — linked courses are unlinked, never deleted | diff --git a/src/constant.rs b/src/constant.rs index c5aaf2d..87a323e 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -139,3 +139,9 @@ pub const SESSION_DURATION_DAYS: i64 = 7; /// submission must survive its own round trip — while still refusing /// genuinely past deadlines. pub const SCHEDULE_PAST_GRACE_MS: i64 = 60 * 1000; + +/// Upper bound on a list endpoint's `limit` page-size parameter. Omitting +/// `limit` returns every (remaining) row; when supplied it must be +/// `1..=MAX_PAGE_LIMIT`. The `#[param(maximum = ...)]` and the "1 and 500" +/// wording in `web::page` mirror this literal — keep them in step. +pub const MAX_PAGE_LIMIT: i64 = 500; diff --git a/src/domain/user.rs b/src/domain/user.rs index 0215a7d..a378583 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -276,9 +276,9 @@ impl User { /// Case-insensitive fragment search over username, name, and surname — /// backs the user pickers. `role` narrows to one role (e.g. only students - /// for an enroll picker); `None` searches everyone. Capped at 10 rows: - /// pickers show a short list, and the cap keeps an over-broad fragment - /// from hauling the whole table. + /// for an enroll picker); `None` searches everyone. Returns every match, + /// ordered by username; the HTTP layer pages the result like any other list + /// (no built-in cap — an over-broad fragment is windowed by `?limit`). pub async fn search( query: &str, role: Option, @@ -297,7 +297,7 @@ impl User { OR string::lowercase(name ?? '') CONTAINS $q \ OR string::lowercase(surname ?? '') CONTAINS $q) \ {role_clause} \ - ORDER BY username LIMIT 10" + ORDER BY username" )) .bind(("q", needle)); if let Some(role) = role { diff --git a/src/lib.rs b/src/lib.rs index 4f70ce2..843e3a7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - 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.", + 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.", ), modifiers(&SecurityAddon), tags( diff --git a/src/web/courses.rs b/src/web/courses.rs index 45364a8..cda8141 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -26,8 +26,8 @@ use crate::state::AppState; use super::sessions::resolve_session_teacher; use super::terms::resolve_term; use super::{ - CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, SessionResponse, - check_not_past, check_time_range, person_map, set_or_clear, + CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, + SessionResponse, check_not_past, check_time_range, paginate, person_map, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -199,42 +199,64 @@ async fn create_course( } /// List the courses visible to the caller: every course for manager+, -/// otherwise the courses they created plus the ones they're enrolled in. +/// otherwise the courses they created plus the ones they're enrolled in. Paged +/// via `?limit=&offset=` (omit `limit` for the full list); returns a +/// `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/", tag = "courses", security(("session_cookie" = [])), + params(PageParams), responses( - (status = 200, description = "The caller's visible courses", body = [CourseResponse]), + (status = 200, description = "A page of the caller's visible courses (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_courses( State(st): State, CurrentUser(user): CurrentUser, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let courses = visible_courses(&user, &st.db).await?; - Ok(Json(courses.iter().map(CourseResponse::new).collect())) + let total = courses.len() as i64; + let items = paginate(&courses, limit, offset) + .iter() + .map(CourseResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } -/// The courses the current user is enrolled in. +/// The courses the current user is enrolled in, paged via `?limit=&offset=` +/// (omit `limit` for all of them); returns a `{items, total, limit, offset}` +/// envelope. #[utoipa::path( get, path = "/me", tag = "courses", security(("session_cookie" = [])), + params(PageParams), responses( - (status = 200, description = "The caller's enrolled courses", body = [CourseResponse]), + (status = 200, description = "A page of the caller's enrolled courses (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn my_courses( State(st): State, CurrentUser(user): CurrentUser, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let courses = Course::list_enrolled(user.get_id(), &st.db).await?; - Ok(Json(courses.iter().map(CourseResponse::new).collect())) + let total = courses.len() as i64; + let items = paginate(&courses, limit, offset) + .iter() + .map(CourseResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Fetch a single course by id. Visible to its enrolled users, its creator, @@ -398,16 +420,19 @@ async fn enroll( Ok(Json(EnrollmentResponse::new(&enrollment, &people))) } -/// List a course's roster. Requires teacher+ and course management rights — -/// students see their own courses via `GET /courses/me`. +/// List a course's roster, paged via `?limit=&offset=` (omit `limit` for the +/// whole roster). Requires teacher+ and course management rights — students see +/// their own courses via `GET /courses/me`. Returns a +/// `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/{id}/enrollments", tag = "courses", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Course id")), + params(("id" = String, Path, description = "Course id"), PageParams), responses( - (status = 200, description = "All enrollments", body = [EnrollmentResponse]), + (status = 200, description = "A page of enrollments (the whole roster when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), @@ -417,7 +442,9 @@ async fn list_roster( State(st): State, RequireTeacher(user): RequireTeacher, Path(id): Path, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; // Course must exist — a missing course is a 404, not an empty roster. let course = Course::read(&CourseId::from_key(&id), &st.db) .await? @@ -428,19 +455,20 @@ async fn list_roster( )); } let enrollments = Enrollment::list_for_course(course.get_id(), &st.db).await?; + let total = enrollments.len() as i64; + // Join people onto the page alone — the lookup shrinks with the window. + let rows = paginate(&enrollments, limit, offset); let people = person_map( - enrollments - .iter() + rows.iter() .flat_map(|e| [e.get_user().clone(), e.get_enrolled_by().clone()]), &st.db, ) .await?; - Ok(Json( - enrollments - .iter() - .map(|e| EnrollmentResponse::new(e, &people)) - .collect(), - )) + let items = rows + .iter() + .map(|e| EnrollmentResponse::new(e, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Unenroll a user from a course. Requires teacher+ and course management @@ -555,16 +583,18 @@ async fn create_exam_in_course( Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) } -/// List a course's exams. Visible to the course's enrolled users, its -/// creator, and managers/admins. +/// List a course's exams, paged via `?limit=&offset=` (omit `limit` for all of +/// them). Visible to the course's enrolled users, its creator, and +/// managers/admins. Returns a `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/{id}/exams", tag = "courses", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Course id")), + params(("id" = String, Path, description = "Course id"), PageParams), responses( - (status = 200, description = "The course's exams", body = [ExamResponse]), + (status = 200, description = "A page of the course's exams (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), @@ -574,7 +604,9 @@ async fn list_course_exams( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; // Course must exist — a missing course is a 404, not an empty exam list. let course = Course::read(&CourseId::from_key(&id), &st.db) .await? @@ -585,7 +617,12 @@ async fn list_course_exams( )); } let exams = Exam::list_for_course(course.get_id(), &st.db).await?; - Ok(Json(exams.iter().map(ExamResponse::new).collect())) + let total = exams.len() as i64; + let items = paginate(&exams, limit, offset) + .iter() + .map(ExamResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } // ---- sessions in a course -------------------------------------------------- @@ -662,16 +699,19 @@ async fn create_session_in_course( )) } -/// List a course's lesson sessions, most recent first. Visible to the -/// course's enrolled users, its creator, and managers/admins. +/// List a course's lesson sessions, most recent first, paged via +/// `?limit=&offset=` (omit `limit` for all of them). Visible to the course's +/// enrolled users, its creator, and managers/admins. Returns a +/// `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/{id}/sessions", tag = "courses", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Course id")), + params(("id" = String, Path, description = "Course id"), PageParams), responses( - (status = 200, description = "The course's sessions", body = [SessionResponse]), + (status = 200, description = "A page of the course's sessions (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), @@ -681,7 +721,9 @@ async fn list_course_sessions( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; // Course must exist — a missing course is a 404, not an empty list. let course = Course::read(&CourseId::from_key(&id), &st.db) .await? @@ -692,11 +734,13 @@ async fn list_course_sessions( )); } let sessions = CourseSession::list_for_course(course.get_id(), &st.db).await?; - let people = person_map(sessions.iter().map(|s| s.get_teacher().clone()), &st.db).await?; - Ok(Json( - sessions - .iter() - .map(|s| SessionResponse::new(s, &people)) - .collect(), - )) + let total = sessions.len() as i64; + // Join teachers onto the page alone — the lookup shrinks with the window. + let rows = paginate(&sessions, limit, offset); + let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?; + let items = rows + .iter() + .map(|s| SessionResponse::new(s, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/src/web/events.rs b/src/web/events.rs index 504ff4e..5503e4e 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -18,8 +18,8 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::{ - CurrentUser, PersonRef, RequireTeacher, check_not_past, check_time_range, person_map, - set_or_clear, + CurrentUser, Page, PageParams, PersonRef, RequireTeacher, check_not_past, check_time_range, + paginate, person_map, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -160,23 +160,33 @@ async fn create_event( Ok((StatusCode::CREATED, Json(EventResponse::new(&event)))) } -/// List all events. +/// List all events, newest first. Paged via `?limit=&offset=` (omit `limit` +/// for every event); returns a `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/", tag = "events", security(("session_cookie" = [])), + params(PageParams), responses( - (status = 200, description = "All events", body = [EventResponse]), + (status = 200, description = "A page of events (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_events( State(st): State, _user: CurrentUser, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let events = Event::list_all(&st.db).await?; - Ok(Json(events.iter().map(EventResponse::new).collect())) + let total = events.len() as i64; + let items = paginate(&events, limit, offset) + .iter() + .map(EventResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Fetch a single event by id. @@ -362,16 +372,19 @@ async fn mark( Ok(Json(AttendanceResponse::new(&attendance, &people))) } -/// List the attendance roster for an event. Requires teacher+ — students see -/// their own tallies via `GET /attendance/me`. +/// List the attendance roster for an event, paged via `?limit=&offset=` (omit +/// `limit` for the whole roster). Requires teacher+ — students see their own +/// tallies via `GET /attendance/me`. Returns a `{items, total, limit, offset}` +/// envelope. #[utoipa::path( get, path = "/{id}/attendance", tag = "events", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Event id")), + params(("id" = String, Path, description = "Event id"), PageParams), responses( - (status = 200, description = "Attendance roster", body = [AttendanceResponse]), + (status = 200, description = "A page of the attendance roster (all of it when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), (status = 404, description = "Event not found", body = ErrorResponse), @@ -381,26 +394,29 @@ async fn list_attendance( State(st): State, _teacher: RequireTeacher, Path(id): Path, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let event_id = EventId::from_key(&id); // Event must exist — a missing event is a 404, not an empty roster. Event::read(&event_id, &st.db) .await? .ok_or(AppError::NotFound)?; let roster = Attendance::list_for_event(&event_id, &st.db).await?; + let total = roster.len() as i64; + // Join people onto the page alone — the lookup shrinks with the window. + let rows = paginate(&roster, limit, offset); let people = person_map( - roster - .iter() + rows.iter() .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]), &st.db, ) .await?; - Ok(Json( - roster - .iter() - .map(|a| AttendanceResponse::new(a, &people)) - .collect(), - )) + let items = rows + .iter() + .map(|a| AttendanceResponse::new(a, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Remove a user's attendance record from an event. Requires teacher+. diff --git a/src/web/exams.rs b/src/web/exams.rs index 241ac51..a7554fa 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use std::time::Duration; use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use axum::response::sse::{Event, KeepAlive, Sse}; use serde::{Deserialize, Serialize}; @@ -35,7 +35,8 @@ use crate::state::AppState; use super::courses::{can_manage_course, can_view_course, visible_courses}; use super::{ - CurrentUser, ExamResponse, PersonRef, RequireTeacher, check_not_past, person_map, set_or_clear, + CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, check_not_past, + paginate, person_map, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -161,21 +162,27 @@ async fn course_of(exam: &Exam, db: &Database) -> Result { // Exams are created inside a course: `POST /courses/{id}/exams`. /// List the exams visible to the caller: every exam for manager+, otherwise -/// the exams of the courses they created or are enrolled in. +/// the exams of the courses they created or are enrolled in. Paged via +/// `?limit=&offset=` (omit `limit` for the full list); returns a +/// `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/", tag = "exams", security(("session_cookie" = [])), + params(PageParams), responses( - (status = 200, description = "The caller's visible exams", body = [ExamResponse]), + (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_exams( State(st): State, CurrentUser(user): CurrentUser, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let exams = if user.get_role().at_least(Role::Manager) { Exam::list_all(&st.db).await? } else { @@ -183,7 +190,12 @@ async fn list_exams( let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); Exam::list_for_courses(&ids, &st.db).await? }; - Ok(Json(exams.iter().map(ExamResponse::new).collect())) + let total = exams.len() as i64; + let items = paginate(&exams, limit, offset) + .iter() + .map(ExamResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Fetch a single exam by id. Visible to its course's enrolled users, the @@ -443,17 +455,19 @@ async fn grade( Ok(Json(ExamResultResponse::new(&result, &people))) } -/// List every result for an exam. Requires teacher+ and management rights -/// over the exam's course — students read only their own via -/// `GET /exams/{id}/result`. +/// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all +/// of them). Requires teacher+ and management rights over the exam's course — +/// students read only their own via `GET /exams/{id}/result`. Returns a +/// `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/{id}/results", tag = "exams", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), + params(("id" = String, Path, description = "Exam id"), PageParams), responses( - (status = 200, description = "All results", body = [ExamResultResponse]), + (status = 200, description = "A page of results (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), @@ -463,7 +477,9 @@ async fn list_results( State(st): State, RequireTeacher(user): RequireTeacher, Path(id): Path, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; // Exam must exist — a missing exam is a 404, not an empty result list. let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? @@ -475,19 +491,20 @@ async fn list_results( )); } let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; + let total = results.len() as i64; + // Join people onto the page alone — the lookup shrinks with the window. + let rows = paginate(&results, limit, offset); let people = person_map( - results - .iter() + rows.iter() .flat_map(|r| [r.get_user().clone(), r.get_graded_by().clone()]), &st.db, ) .await?; - Ok(Json( - results - .iter() - .map(|r| ExamResultResponse::new(r, &people)) - .collect(), - )) + let items = rows + .iter() + .map(|r| ExamResultResponse::new(r, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// The current user's own result for an exam. Any authenticated user may read @@ -1308,17 +1325,20 @@ async fn create_question( Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) } -/// The exam's full question list, `correct` indexes included — the answer -/// key. Requires teacher+ and management rights over the exam's course. -/// Students read questions through `GET /exams/{id}/attempt/questions`. +/// The exam's question list, `correct` indexes included — the answer key, +/// paged via `?limit=&offset=` (omit `limit` for the whole list). Requires +/// teacher+ and management rights over the exam's course. Students read +/// questions through `GET /exams/{id}/attempt/questions`. Returns a +/// `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/{id}/questions", tag = "exams", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Exam id")), + params(("id" = String, Path, description = "Exam id"), PageParams), responses( - (status = 200, description = "The exam's questions", body = [QuestionResponse]), + (status = 200, description = "A page of the exam's questions (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), @@ -1328,7 +1348,9 @@ async fn list_questions( State(st): State, RequireTeacher(user): RequireTeacher, Path(id): Path, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; @@ -1339,7 +1361,12 @@ async fn list_questions( )); } let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; - Ok(Json(questions.iter().map(QuestionResponse::new).collect())) + let total = questions.len() as i64; + let items = paginate(&questions, limit, offset) + .iter() + .map(QuestionResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Edit a question. Requires teacher+ and management rights over the exam's diff --git a/src/web/mod.rs b/src/web/mod.rs index 3d780a6..66cc335 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -19,9 +19,11 @@ pub mod work; mod dto; mod extractor; +mod page; pub use dto::{CourseResponse, ExamResponse, PersonRef, SessionResponse, UserResponse, person_map}; pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; +pub use page::{Page, PageParams, paginate}; use serde::{Deserialize, Deserializer}; diff --git a/src/web/notes.rs b/src/web/notes.rs index df4b44a..3f6a8b1 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -1,5 +1,5 @@ use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -10,7 +10,7 @@ use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; -use super::CurrentUser; +use super::{CurrentUser, Page, PageParams, paginate}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -73,23 +73,34 @@ async fn create( Ok((StatusCode::CREATED, Json(NoteResponse::new(¬e)))) } -/// List all notes owned by the current user. +/// List the notes owned by the current user, newest first. Paged via +/// `?limit=&offset=` (omit `limit` for all of them); returns a +/// `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/", tag = "notes", security(("session_cookie" = [])), + params(PageParams), responses( - (status = 200, description = "The user's notes", body = [NoteResponse]), + (status = 200, description = "A page of the user's notes (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list( State(st): State, CurrentUser(user): CurrentUser, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let notes = Note::list_for(user.get_id(), &st.db).await?; - Ok(Json(notes.iter().map(NoteResponse::new).collect())) + let total = notes.len() as i64; + let items = paginate(¬es, limit, offset) + .iter() + .map(NoteResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Fetch a single note by id (must be owned by the current user). diff --git a/src/web/page.rs b/src/web/page.rs new file mode 100644 index 0000000..b786b25 --- /dev/null +++ b/src/web/page.rs @@ -0,0 +1,140 @@ +//! Shared pagination: the `?limit=&offset=` query every list endpoint accepts, +//! and the `{items, total, limit, offset}` envelope they return. +//! +//! Paging is opt-in. Omit `limit` and the response still carries every +//! (remaining) row — so a client that ignores the parameters keeps seeing full +//! lists, and callers that genuinely need the whole set are never silently +//! truncated. `total` is always the full, unpaged row count, so a frontend can +//! render "showing 100 of 256" and drive a pager without a second request. +//! +//! The windowing is a slice over the already-ordered domain list (the domain +//! layer still returns the full, sorted `Vec`): endpoints that join people onto +//! their rows do that join over the page alone, so the expensive lookup shrinks +//! with the page even though the base scan does not. + +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; + +use crate::constant::MAX_PAGE_LIMIT; +use crate::error::{AppError, ValidationError}; + +/// The `?limit=&offset=` pair on a list endpoint. Both optional: omit `limit` +/// for every remaining row, omit `offset` to start at the top. +#[derive(Debug, Deserialize, IntoParams)] +pub struct PageParams { + /// Maximum rows to return. Omit for every remaining row; when supplied it + /// must be between `1` and `500`. + #[param(minimum = 1, maximum = 500, example = 100)] + pub limit: Option, + /// Rows to skip from the start of the list. Defaults to `0`; an offset past + /// the end simply yields an empty page. + #[param(minimum = 0, example = 0)] + pub offset: Option, +} + +impl PageParams { + /// Validate and normalize into `(limit, offset)`. A `limit` outside + /// `1..=MAX_PAGE_LIMIT` or a negative `offset` is a `400` naming the field. + pub fn resolve(&self) -> Result<(Option, i64), AppError> { + if let Some(limit) = self.limit + && !(1..=MAX_PAGE_LIMIT).contains(&limit) + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "limit", + reason: "must be between 1 and 500", + })); + } + let offset = self.offset.unwrap_or(0); + if offset < 0 { + return Err(AppError::Validation(ValidationError::Invalid { + field: "offset", + reason: "must not be negative", + })); + } + Ok((self.limit, offset)) + } +} + +/// One page of a list: the `items`, the full `total` (row count before the +/// window), and the `limit`/`offset` that produced it. `limit` is `null` when +/// the caller asked for every row. +#[derive(Debug, Serialize, ToSchema)] +pub struct Page { + pub items: Vec, + /// Total rows in the full list, before `limit`/`offset` are applied. + #[schema(example = 256)] + pub total: i64, + /// Echo of the applied `limit`; `null` when the response is unbounded. + #[schema(example = 100)] + pub limit: Option, + /// Echo of the applied `offset`. + #[schema(example = 0)] + pub offset: i64, +} + +impl Page { + pub fn new(items: Vec, total: i64, limit: Option, offset: i64) -> Self { + Self { + items, + total, + limit, + offset, + } + } +} + +/// The window `[offset, offset + limit)` of `items`, clamped to the ends. An +/// offset at or past the end yields an empty slice — a client paging off the +/// tail gets `[]`, not an error — and a `None` limit runs to the end. `total` +/// stays the caller's job: take `items.len()` before slicing. +pub fn paginate(items: &[T], limit: Option, offset: i64) -> &[T] { + let start = (offset.max(0) as usize).min(items.len()); + let end = match limit { + Some(limit) => start.saturating_add(limit.max(0) as usize).min(items.len()), + None => items.len(), + }; + &items[start..end] +} + +#[cfg(test)] +mod tests { + use super::*; + + fn params(limit: Option, offset: Option) -> PageParams { + PageParams { limit, offset } + } + + #[test] + fn resolve_accepts_bounds_and_defaults_offset() { + assert_eq!(params(None, None).resolve().unwrap(), (None, 0)); + assert_eq!(params(Some(1), None).resolve().unwrap(), (Some(1), 0)); + assert_eq!( + params(Some(MAX_PAGE_LIMIT), Some(40)).resolve().unwrap(), + (Some(MAX_PAGE_LIMIT), 40) + ); + } + + #[test] + fn resolve_rejects_out_of_range_limit_and_negative_offset() { + assert!(params(Some(0), None).resolve().is_err()); + assert!(params(Some(MAX_PAGE_LIMIT + 1), None).resolve().is_err()); + assert!(params(Some(-5), None).resolve().is_err()); + assert!(params(None, Some(-1)).resolve().is_err()); + } + + #[test] + fn paginate_windows_and_clamps() { + let items: Vec = (0..10).collect(); + // A bounded window in the middle. + assert_eq!(paginate(&items, Some(3), 2), &[2, 3, 4]); + // No limit → everything from the offset to the end. + assert_eq!(paginate(&items, None, 7), &[7, 8, 9]); + // Limit overruns the end → clamped, not padded. + assert_eq!(paginate(&items, Some(100), 8), &[8, 9]); + // Offset at or past the end → empty page, not a panic. + assert!(paginate(&items, Some(5), 10).is_empty()); + assert!(paginate(&items, Some(5), 999).is_empty()); + // No limit, zero offset → the whole list. + assert_eq!(paginate(&items, None, 0), items.as_slice()); + } +} diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 11be8e4..8df7aa8 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -23,8 +23,8 @@ use crate::state::AppState; use super::courses::{can_manage_course, can_view_course}; use super::{ - CurrentUser, PersonRef, RequireTeacher, SessionResponse, check_not_past, check_time_range, - person_map, set_or_clear, + CurrentUser, Page, PageParams, PersonRef, RequireTeacher, SessionResponse, check_not_past, + check_time_range, paginate, person_map, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -333,17 +333,19 @@ async fn mark_roll_call( Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) } -/// List a session's roll call. Same rights as taking it: the session's -/// teacher or a course manager — students see their own tallies via -/// `GET /attendance/me`. +/// List a session's roll call, paged via `?limit=&offset=` (omit `limit` for +/// the whole roster). Same rights as taking it: the session's teacher or a +/// course manager — students see their own tallies via `GET /attendance/me`. +/// Returns a `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/{id}/attendance", tag = "sessions", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Session id")), + params(("id" = String, Path, description = "Session id"), PageParams), responses( - (status = 200, description = "Roll-call roster", body = [SessionAttendanceResponse]), + (status = 200, description = "A page of the roll-call roster (all of it when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the session teacher or a course manager", body = ErrorResponse), (status = 404, description = "Session not found", body = ErrorResponse), @@ -353,7 +355,9 @@ async fn list_roll_call( State(st): State, RequireTeacher(user): RequireTeacher, Path(id): Path, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let (session, course) = session_with_course(&id, &st.db).await?; if !can_roll_call(&session, &course, &user) { return Err(AppError::Forbidden( @@ -361,19 +365,20 @@ async fn list_roll_call( )); } let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?; + let total = roster.len() as i64; + // Join people onto the page alone — the lookup shrinks with the window. + let rows = paginate(&roster, limit, offset); let people = person_map( - roster - .iter() + rows.iter() .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]), &st.db, ) .await?; - Ok(Json( - roster - .iter() - .map(|a| SessionAttendanceResponse::new(a, &people)) - .collect(), - )) + let items = rows + .iter() + .map(|a| SessionAttendanceResponse::new(a, &people)) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Remove a user's roll-call row from a session. Same rights as marking: diff --git a/src/web/terms.rs b/src/web/terms.rs index df4d152..238e2af 100644 --- a/src/web/terms.rs +++ b/src/web/terms.rs @@ -1,5 +1,5 @@ use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -12,7 +12,7 @@ use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CurrentUser, RequireManager, check_time_range}; +use super::{CurrentUser, Page, PageParams, RequireManager, check_time_range, paginate}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -110,23 +110,34 @@ async fn create_term( } /// List every term, newest first. Any authenticated user — students need the -/// calendar to make sense of their courses. +/// calendar to make sense of their courses. Paged via `?limit=&offset=` (omit +/// `limit` for the full list); returns a `{items, total, limit, offset}` +/// envelope. #[utoipa::path( get, path = "/", tag = "terms", security(("session_cookie" = [])), + params(PageParams), responses( - (status = 200, description = "All terms", body = [TermResponse]), + (status = 200, description = "A page of terms (the full list when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_terms( State(st): State, CurrentUser(_user): CurrentUser, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let terms = Term::list_all(&st.db).await?; - Ok(Json(terms.iter().map(TermResponse::new).collect())) + let total = terms.len() as i64; + let items = paginate(&terms, limit, offset) + .iter() + .map(TermResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Fetch a single term by id. diff --git a/src/web/users.rs b/src/web/users.rs index 26b3d7c..2f8ba8a 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -13,7 +13,9 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::dto::Role as RoleSchema; -use super::{CurrentUser, PersonRef, RequireAdmin, RequireTeacher, UserResponse}; +use super::{ + CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UserResponse, paginate, +}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -98,12 +100,20 @@ struct SearchUsers { /// Restrict matches to one role: `student`, `teacher`, `manager`, or /// `admin`. Omit to search every role. role: Option, + /// Max matches to return. Omit for every match; when given, `1`–`500`. + #[param(minimum = 1, maximum = 500, example = 100)] + limit: Option, + /// Matches to skip from the start. Defaults to `0`. + #[param(minimum = 0, example = 0)] + offset: Option, } /// Find users by username or name — backs the pickers (enroll, grade, mark /// attendance). Requires teacher+. `role` narrows to one role (e.g. -/// `role=student` for an enroll picker). Returns at most 10 matches, and only -/// id/username/display name — no contact details. +/// `role=student` for an enroll picker). Paged via `?limit=&offset=` like the +/// other lists (omit `limit` for every match); returns a +/// `{items, total, limit, offset}` envelope carrying only id/username/display +/// name — no contact details. #[utoipa::path( get, path = "/search", @@ -111,8 +121,8 @@ struct SearchUsers { security(("session_cookie" = [])), params(SearchUsers), responses( - (status = 200, description = "Matching users, at most 10", body = [PersonRef]), - (status = 400, description = "Empty query or unknown role", body = ErrorResponse), + (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page), + (status = 400, description = "Empty query, unknown role, or invalid limit/offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), ), @@ -121,26 +131,41 @@ async fn search_users( State(st): State, _teacher: RequireTeacher, Query(req): Query, -) -> Result>, AppError> { +) -> Result>, AppError> { if req.q.trim().is_empty() { return Err(AppError::Validation(ValidationError::Invalid { field: "q", reason: "must not be empty", })); } + let (limit, offset) = PageParams { + limit: req.limit, + offset: req.offset, + } + .resolve()?; let role = req.role.as_deref().map(Role::try_from_str).transpose()?; let users = User::search(&req.q, role, &st.db).await?; - Ok(Json(users.iter().map(PersonRef::new).collect())) + let total = users.len() as i64; + let items = paginate(&users, limit, offset) + .iter() + .map(PersonRef::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } -/// List every user with their role. Admin only. +/// List every user with their role, newest first. Admin only. Paged: pass +/// `?limit=&offset=` to take a window (omit `limit` for the whole list); the +/// response is a `{items, total, limit, offset}` envelope where `total` counts +/// every user. #[utoipa::path( get, path = "/", tag = "users", security(("session_cookie" = [])), + params(PageParams), responses( - (status = 200, description = "All users", body = [UserResponse]), + (status = 200, description = "A page of users (the full list when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires admin role", body = ErrorResponse), ), @@ -148,9 +173,16 @@ async fn search_users( async fn list_users( State(st): State, _admin: RequireAdmin, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let users = User::list_all(&st.db).await?; - Ok(Json(users.iter().map(UserResponse::new).collect())) + let total = users.len() as i64; + let items = paginate(&users, limit, offset) + .iter() + .map(UserResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Update the caller's own personal info: name, surname, email, phone, birth diff --git a/src/web/work.rs b/src/web/work.rs index 008b55d..3d6aee1 100644 --- a/src/web/work.rs +++ b/src/web/work.rs @@ -1,5 +1,5 @@ use axum::Json; -use axum::extract::{Path, State}; +use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; @@ -12,7 +12,7 @@ use crate::domain::work_entry::{WorkEntry, WorkEntryId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{RequireManager, RequireTeacher}; +use super::{Page, PageParams, RequireManager, RequireTeacher, paginate}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -105,14 +105,18 @@ async fn check_out( } /// The caller's own work log, newest first — the open stint (if any) included -/// (`check_out: null`). Requires teacher+ (staff). +/// (`check_out: null`). Paged via `?limit=&offset=` (omit `limit` for the whole +/// log). Requires teacher+ (staff). Returns a `{items, total, limit, offset}` +/// envelope. #[utoipa::path( get, path = "/me", tag = "work", security(("session_cookie" = [])), + params(PageParams), responses( - (status = 200, description = "The caller's work log", body = [WorkEntryResponse]), + (status = 200, description = "A page of the caller's work log (the whole log when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), ), @@ -120,20 +124,30 @@ async fn check_out( async fn my_work( State(st): State, RequireTeacher(user): RequireTeacher, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let entries = WorkEntry::list_for_user(user.get_id(), &st.db).await?; - Ok(Json(entries.iter().map(WorkEntryResponse::new).collect())) + let total = entries.len() as i64; + let items = paginate(&entries, limit, offset) + .iter() + .map(WorkEntryResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } -/// A staff member's work log. Requires manager+. +/// A staff member's work log, newest first, paged via `?limit=&offset=` (omit +/// `limit` for the whole log). Requires manager+. Returns a +/// `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/{user}", tag = "work", security(("session_cookie" = [])), - params(("user" = String, Path, description = "User id")), + params(("user" = String, Path, description = "User id"), PageParams), responses( - (status = 200, description = "The user's work log", body = [WorkEntryResponse]), + (status = 200, description = "A page of the user's work log (the whole log when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "User not found", body = ErrorResponse), @@ -143,14 +157,21 @@ async fn user_work( State(st): State, _manager: RequireManager, Path(user): Path, -) -> Result>, AppError> { + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; let target = UserId::from_key(&user); // User must exist — a missing user is a 404, not an empty log. User::read(&target, &st.db) .await? .ok_or(AppError::NotFound)?; let entries = WorkEntry::list_for_user(&target, &st.db).await?; - Ok(Json(entries.iter().map(WorkEntryResponse::new).collect())) + let total = entries.len() as i64; + let items = paginate(&entries, limit, offset) + .iter() + .map(WorkEntryResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) } /// Correct a closed stint's instants. Requires manager+. An open stint can't diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 98641e8..a1f04ac 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -121,6 +121,21 @@ pub fn id_of(v: &Value) -> String { v["id"].as_str().expect("id field").to_string() } +/// The `items` array of a paginated list envelope (`{items, total, limit, +/// offset}`) — the shape every `GET` list endpoint returns. Panics if `v` +/// isn't such an envelope, so a test that points it at the wrong body fails +/// loudly. +pub fn items(v: &Value) -> &Vec { + v["items"] + .as_array() + .unwrap_or_else(|| panic!("expected a paginated list envelope with items[], got {v}")) +} + +/// The `total` count from a paginated list envelope. +pub fn total(v: &Value) -> i64 { + v["total"].as_i64().expect("paginated envelope total") +} + /// The caller's own user id via `GET /auth/me`. pub async fn me_id(app: &Router, cookie: &str) -> String { let res = send(app, "GET", "/auth/me", Some(cookie), None).await; diff --git a/tests/e2e.rs b/tests/e2e.rs index b1b2207..020d788 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -177,12 +177,12 @@ async fn full_user_journey() { .json() .await .unwrap(); - assert_eq!(roster.as_array().unwrap().len(), 1); + assert_eq!(roster["items"].as_array().unwrap().len(), 1); // People come back as refs — id plus something a human can read. - assert_eq!(roster[0]["user"]["id"], veli_id); - assert_eq!(roster[0]["user"]["username"], "veli"); - assert_eq!(roster[0]["marked_by"]["username"], "ali"); - assert_eq!(roster[0]["status"], "present"); + assert_eq!(roster["items"][0]["user"]["id"], veli_id); + assert_eq!(roster["items"][0]["user"]["username"], "veli"); + assert_eq!(roster["items"][0]["marked_by"]["username"], "ali"); + assert_eq!(roster["items"][0]["status"], "present"); // --- user search (for the pickers) ----------------------------------- // Teacher+ finds people by fragment; the refs carry no contact details. @@ -194,8 +194,8 @@ async fn full_user_journey() { .json() .await .unwrap(); - assert_eq!(found[0]["username"], "veli"); - assert!(found[0].get("email").is_none()); + assert_eq!(found["items"][0]["username"], "veli"); + assert!(found["items"][0].get("email").is_none()); // Role filter narrows: veli is a student, so she matches `role=student` // but vanishes under `role=teacher`. An unknown role is a 400. @@ -207,8 +207,8 @@ async fn full_user_journey() { .json() .await .unwrap(); - assert_eq!(found.as_array().unwrap().len(), 1); - assert_eq!(found[0]["username"], "veli"); + assert_eq!(found["items"].as_array().unwrap().len(), 1); + assert_eq!(found["items"][0]["username"], "veli"); let found: Value = ali .get(format!("{base}/users/search?q=vel&role=teacher")) @@ -218,7 +218,7 @@ async fn full_user_journey() { .json() .await .unwrap(); - assert!(found.as_array().unwrap().is_empty()); + assert!(found["items"].as_array().unwrap().is_empty()); let res = ali .get(format!("{base}/users/search?q=vel&role=wizard")) @@ -236,8 +236,8 @@ async fn full_user_journey() { .json() .await .unwrap(); - assert_eq!(found.as_array().unwrap().len(), 1); - assert_eq!(found[0]["username"], "ali"); + assert_eq!(found["items"].as_array().unwrap().len(), 1); + assert_eq!(found["items"][0]["username"], "ali"); // Search matches profile names too, and the role filter applies to those // hits as well: "lic" only exists in ali's freshly set name, not in any @@ -258,9 +258,9 @@ async fn full_user_journey() { .json() .await .unwrap(); - assert_eq!(found.as_array().unwrap().len(), 1); - assert_eq!(found[0]["username"], "ali"); - assert_eq!(found[0]["display_name"], "Alice"); + assert_eq!(found["items"].as_array().unwrap().len(), 1); + assert_eq!(found["items"][0]["username"], "ali"); + assert_eq!(found["items"][0]["display_name"], "Alice"); let found: Value = ali .get(format!("{base}/users/search?q=lic&role=student")) @@ -270,7 +270,7 @@ async fn full_user_journey() { .json() .await .unwrap(); - assert!(found.as_array().unwrap().is_empty()); + assert!(found["items"].as_array().unwrap().is_empty()); let res = veli .get(format!("{base}/users/search?q=ali")) @@ -381,7 +381,7 @@ async fn attendance_rollup_across_users() { .json() .await .unwrap(); - assert_eq!(roster.as_array().unwrap().len(), 3); + assert_eq!(roster["items"].as_array().unwrap().len(), 3); // Unauthenticated client is refused. let res = client() diff --git a/tests/integration.rs b/tests/integration.rs index bff5950..f4fca06 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -301,12 +301,7 @@ async fn notes_crud_is_scoped_to_owner() { // Owner sees exactly one; other user sees none and gets 404 on direct access. assert_eq!( - send(&app, "GET", "/notes", Some(&ali), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items(&send(&app, "GET", "/notes", Some(&ali), None).await.body).len(), 1 ); assert_eq!( @@ -316,12 +311,7 @@ async fn notes_crud_is_scoped_to_owner() { StatusCode::NOT_FOUND ); assert_eq!( - send(&app, "GET", "/notes", Some(&veli), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items(&send(&app, "GET", "/notes", Some(&veli), None).await.body).len(), 0 ); @@ -471,12 +461,7 @@ async fn events_are_shared_but_creator_guarded() { StatusCode::OK ); assert_eq!( - send(&app, "GET", "/events", Some(&veli), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items(&send(&app, "GET", "/events", Some(&veli), None).await.body).len(), 1 ); @@ -597,7 +582,7 @@ async fn attendance_marking_and_upsert() { // Two rows total. assert_eq!( - send( + common::items(&send( &app, "GET", &format!("/events/{event_id}/attendance"), @@ -605,9 +590,7 @@ async fn attendance_marking_and_upsert() { None ) .await - .body - .as_array() - .unwrap() + .body) .len(), 2 ); @@ -626,7 +609,7 @@ async fn attendance_marking_and_upsert() { StatusCode::NO_CONTENT ); assert_eq!( - send( + common::items(&send( &app, "GET", &format!("/events/{event_id}/attendance"), @@ -634,9 +617,7 @@ async fn attendance_marking_and_upsert() { None ) .await - .body - .as_array() - .unwrap() + .body) .len(), 1 ); @@ -893,12 +874,7 @@ async fn exams_are_course_scoped_and_course_guarded() { StatusCode::FORBIDDEN ); assert_eq!( - send(&app, "GET", "/exams", Some(&veli), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items(&send(&app, "GET", "/exams", Some(&veli), None).await.body).len(), 0 ); assert_eq!( @@ -922,16 +898,11 @@ async fn exams_are_course_scoped_and_course_guarded() { StatusCode::OK ); assert_eq!( - send(&app, "GET", "/exams", Some(&ali), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items(&send(&app, "GET", "/exams", Some(&ali), None).await.body).len(), 1 ); assert_eq!( - send( + common::items(&send( &app, "GET", &format!("/courses/{course_id}/exams"), @@ -939,9 +910,7 @@ async fn exams_are_course_scoped_and_course_guarded() { None ) .await - .body - .as_array() - .unwrap() + .body) .len(), 1 ); @@ -1117,7 +1086,7 @@ async fn grading_upsert_and_own_result() { // Teacher sees the full list (one row). assert_eq!( - send( + common::items(&send( &app, "GET", &format!("/exams/{exam_id}/results"), @@ -1125,9 +1094,7 @@ async fn grading_upsert_and_own_result() { None ) .await - .body - .as_array() - .unwrap() + .body) .len(), 1 ); @@ -1382,12 +1349,7 @@ async fn courses_are_owner_scoped_and_creator_guarded() { StatusCode::FORBIDDEN ); assert_eq!( - send(&app, "GET", "/courses", Some(&veli), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items(&send(&app, "GET", "/courses", Some(&veli), None).await.body).len(), 0 ); @@ -1406,12 +1368,7 @@ async fn courses_are_owner_scoped_and_creator_guarded() { StatusCode::OK ); assert_eq!( - send(&app, "GET", "/courses", Some(caller), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items(&send(&app, "GET", "/courses", Some(caller), None).await.body).len(), 1 ); } @@ -1535,7 +1492,7 @@ async fn enrollment_upsert_roster_and_my_courses() { None, ) .await; - assert_eq!(roster.body.as_array().unwrap().len(), 1); + assert_eq!(common::items(&roster.body).len(), 1); assert_eq!( send( &app, @@ -1551,21 +1508,21 @@ async fn enrollment_upsert_roster_and_my_courses() { // /courses/me shows the course for alice, stays empty for bob. assert_eq!( - send(&app, "GET", "/courses/me", Some(&alice), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items( + &send(&app, "GET", "/courses/me", Some(&alice), None) + .await + .body, + ) + .len(), 1 ); assert_eq!( - send(&app, "GET", "/courses/me", Some(&bob), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items( + &send(&app, "GET", "/courses/me", Some(&bob), None) + .await + .body, + ) + .len(), 0 ); @@ -1736,7 +1693,7 @@ async fn exam_creation_lives_under_courses() { StatusCode::OK ); assert_eq!( - send( + common::items(&send( &app, "GET", &format!("/courses/{course_id}/exams"), @@ -1744,9 +1701,7 @@ async fn exam_creation_lives_under_courses() { None ) .await - .body - .as_array() - .unwrap() + .body) .len(), 1 ); @@ -1814,12 +1769,7 @@ async fn grading_requires_enrollment() { StatusCode::BAD_REQUEST ); assert_eq!( - send(&app, "GET", &grade_uri, Some(&teacher), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items(&send(&app, "GET", &grade_uri, Some(&teacher), None).await.body).len(), 1 ); assert_eq!( @@ -2227,7 +2177,7 @@ async fn course_data_is_walled_off_from_other_teachers() { for uri in ["/courses", "/exams"] { let res = send(&app, "GET", uri, Some(caller), None).await; assert_eq!( - res.body.as_array().unwrap().len(), + common::items(&res.body).len(), visible, "{uri} as seen by caller" ); @@ -2305,12 +2255,12 @@ async fn deleting_course_cascades_enrollments_exams_and_results() { StatusCode::NOT_FOUND ); assert_eq!( - send(&app, "GET", "/courses/me", Some(&alice), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items( + &send(&app, "GET", "/courses/me", Some(&alice), None) + .await + .body, + ) + .len(), 0 ); assert_eq!( @@ -2363,7 +2313,7 @@ async fn concurrent_enrollments_never_collide() { ) .await; assert_eq!( - roster.body.as_array().unwrap().len(), + common::items(&roster.body).len(), 1, "upsert keeps a single row" ); @@ -2527,7 +2477,7 @@ async fn admin_manages_roles_with_guards() { // Admin lists users (at least admin + alice). let list = send(&app, "GET", "/users", Some(&admin), None).await; assert_eq!(list.status, StatusCode::OK); - assert!(list.body.as_array().unwrap().len() >= 2); + assert!(common::items(&list.body).len() >= 2); // Admin promotes alice to teacher; the change is reflected in the response... let promoted = send( @@ -2767,10 +2717,7 @@ async fn admin_reads_and_edits_any_profile_with_guards() { // The admin listing now carries the info columns too. let list = send(&app, "GET", "/users", Some(&admin), None).await; - let listed = list - .body - .as_array() - .unwrap() + let listed = common::items(&list.body) .iter() .find(|u| u["username"] == "alice") .expect("alice listed") @@ -2855,7 +2802,7 @@ async fn concurrent_attendance_marks_never_collide() { ) .await; assert_eq!( - roster.body.as_array().unwrap().len(), + common::items(&roster.body).len(), 1, "upsert keeps a single row" ); @@ -2901,7 +2848,7 @@ async fn concurrent_exam_grades_never_collide() { ) .await; assert_eq!( - results.body.as_array().unwrap().len(), + common::items(&results.body).len(), 1, "upsert keeps a single row" ); @@ -3076,7 +3023,7 @@ async fn graders_cannot_grade_themselves() { // And the rejected attempts wrote nothing. assert_eq!( - send( + common::items(&send( &app, "GET", &format!("/exams/{exam_id}/results"), @@ -3084,9 +3031,7 @@ async fn graders_cannot_grade_themselves() { None ) .await - .body - .as_array() - .unwrap() + .body) .len(), 0 ); @@ -3416,7 +3361,7 @@ async fn admin_seed_is_idempotent() { res.cookie.expect("session cookie") }; let res = send(&app, "GET", "/users", Some(&cookie), None).await; - let listed = res.body.as_array().expect("user list"); + let listed = common::items(&res.body); assert_eq!(listed.len(), 1, "seed must not duplicate the account"); assert_eq!(listed[0]["role"], "admin"); } @@ -4893,7 +4838,7 @@ async fn question_crud_validation_and_rbac() { ) .await; assert_eq!(res.status, StatusCode::OK); - let questions = res.body.as_array().expect("questions"); + let questions = common::items(&res.body); assert_eq!(questions.len(), 2); assert_eq!(id_of(&questions[0]), choice_q); assert_eq!(id_of(&questions[1]), text_q); @@ -5109,7 +5054,7 @@ async fn question_crud_validation_and_rbac() { None, ) .await; - assert_eq!(res.body.as_array().unwrap().len(), 1); + assert_eq!(common::items(&res.body).len(), 1); } #[tokio::test] @@ -6044,8 +5989,8 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { None, ) .await; - assert_eq!(res.body[0]["choices"].as_array().unwrap().len(), 2); - assert_eq!(res.body[0]["correct"], 1); + assert_eq!(common::items(&res.body)[0]["choices"].as_array().unwrap().len(), 2); + assert_eq!(common::items(&res.body)[0]["correct"], 1); } #[tokio::test] @@ -6317,8 +6262,8 @@ async fn session_crud_follows_course_management() { assert_eq!(res.status, StatusCode::OK); // owner's, the manager's, and the one taught by `rival` — newest starts_at // first, so the two `start` lessons precede the earlier `rival` one. - assert_eq!(res.body.as_array().unwrap().len(), 3); - assert_eq!(res.body[2]["starts_at"], now + 120_000); + assert_eq!(common::items(&res.body).len(), 3); + assert_eq!(common::items(&res.body)[2]["starts_at"], now + 120_000); let res = send(&app, "GET", "/courses/nope/sessions", Some(&student), None).await; assert_eq!(res.status, StatusCode::NOT_FOUND); let res = send( @@ -6532,7 +6477,7 @@ async fn roll_call_rbac_and_upsert() { // get their own tallies via `/attendance/me`. let res = send(&app, "GET", &mark_uri, Some(&hoca), None).await; assert_eq!(res.status, StatusCode::OK); - let roster = res.body.as_array().unwrap(); + let roster = common::items(&res.body); assert_eq!(roster.len(), 1); assert_eq!(roster[0]["status"], "absent"); 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() { let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await; assert_eq!(res.status, StatusCode::CONFLICT); let res = send(&app, "GET", "/work/me", Some(&hoca), None).await; - let log = res.body.as_array().unwrap(); + let log = common::items(&res.body); assert_eq!(log.len(), 1); assert_eq!(log[0]["check_in"].as_i64().unwrap(), first_in); @@ -6787,7 +6732,7 @@ async fn work_log_lifecycle_is_server_stamped_and_exclusive() { let res = send(&app, "POST", "/work/check-in", Some(&hoca), None).await; assert_eq!(res.status, StatusCode::CREATED); let res = send(&app, "GET", "/work/me", Some(&hoca), None).await; - let log = res.body.as_array().unwrap(); + let log = common::items(&res.body); assert_eq!(log.len(), 2); assert!(log[0]["check_out"].is_null(), "open stint sorts newest"); assert!(!log[1]["check_out"].is_null()); @@ -6813,7 +6758,7 @@ async fn work_log_manager_reads_and_corrections() { assert_eq!(res.status, StatusCode::FORBIDDEN); let res = send(&app, "GET", &format!("/work/{hoca_id}"), Some(&boss), None).await; assert_eq!(res.status, StatusCode::OK); - assert_eq!(res.body.as_array().unwrap().len(), 2); + assert_eq!(common::items(&res.body).len(), 2); let res = send(&app, "GET", "/work/01UNKNOWN", Some(&boss), None).await; assert_eq!(res.status, StatusCode::NOT_FOUND); @@ -7182,7 +7127,7 @@ async fn search_matches_are_literal_not_like_wildcards() { // Under LIKE semantics it would match every user with a name. let res = send(&app, "GET", "/users/search?q=%25", Some(&teacher), None).await; assert_eq!(res.status, StatusCode::OK); - let hits = res.body.as_array().unwrap(); + let hits = common::items(&res.body); assert_eq!(hits.len(), 1, "`%` must match literally: {hits:?}"); assert_eq!(hits[0]["username"], "percy"); @@ -7190,7 +7135,7 @@ async fn search_matches_are_literal_not_like_wildcards() { // semantics `_` is any-single-character and would match everyone. let res = send(&app, "GET", "/users/search?q=_", Some(&teacher), None).await; assert_eq!(res.status, StatusCode::OK); - let hits = res.body.as_array().unwrap(); + let hits = common::items(&res.body); assert_eq!(hits.len(), 1, "`_` must match literally: {hits:?}"); assert_eq!(hits[0]["username"], "under_score"); } @@ -7226,7 +7171,7 @@ async fn course_catalog_lists_a_creator_enrolled_course_once() { let res = send(&app, "GET", "/courses", Some(&teacher), None).await; assert_eq!(res.status, StatusCode::OK); - let courses = res.body.as_array().unwrap(); + let courses = common::items(&res.body); assert_eq!(courses.len(), 1, "created+enrolled must dedup: {courses:?}"); assert_eq!(courses[0]["id"], json!(course)); @@ -7234,7 +7179,7 @@ async fn course_catalog_lists_a_creator_enrolled_course_once() { // the course's exams either. let exam = create_exam(&app, &teacher, &course, "mt", "quiz").await; let res = send(&app, "GET", "/exams", Some(&teacher), None).await; - let exams = res.body.as_array().unwrap(); + let exams = common::items(&res.body); assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}"); assert_eq!(exams[0]["id"], json!(exam)); } @@ -7640,7 +7585,7 @@ async fn terms_crud_gates_and_links_to_courses() { // Any authenticated user reads the calendar. let res = send(&app, "GET", "/terms", Some(&student), None).await; assert_eq!(res.status, StatusCode::OK); - assert_eq!(res.body.as_array().unwrap().len(), 1); + assert_eq!(common::items(&res.body).len(), 1); // Courses link to a term at creation; a bogus id is a 400, not a silent null. let res = send( @@ -7809,10 +7754,7 @@ async fn terms_list_newest_first_require_auth_and_unlink_in_bulk() { // Newest (by starts_at) first. let res = send(&app, "GET", "/terms", Some(&teacher), None).await; - let names: Vec<&str> = res - .body - .as_array() - .unwrap() + let names: Vec<&str> = common::items(&res.body) .iter() .map(|t| t["name"].as_str().unwrap()) .collect(); diff --git a/tests/pagination.rs b/tests/pagination.rs new file mode 100644 index 0000000..3c07d31 --- /dev/null +++ b/tests/pagination.rs @@ -0,0 +1,163 @@ +//! Pagination behavior common to every list endpoint: the `{items, total, +//! limit, offset}` envelope, opt-in windowing, join-on-the-page, and the `400`s +//! for out-of-range parameters. One representative endpoint per shape — the +//! machinery (`web::page`) is shared, so this pins the contract without +//! re-testing all 16 lists. + +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, create_course, enroll, items, login, login_as, me_id, send, total}; +use serde_json::json; + +/// Register `user00..user{n-1}` as plain students. +async fn seed_students(app: &axum::Router, n: usize) { + for i in 0..n { + let name = format!("user{i:02}"); + let creds = json!({ "username": name, "password": "secret1" }); + let res = send(app, "POST", "/auth/register", None, Some(creds)).await; + assert_eq!(res.status, StatusCode::CREATED, "register {name}"); + } +} + +#[tokio::test] +async fn envelope_windows_and_total_is_stable() { + let (app, db) = app_and_db().await; + // 1 admin (to read /users) + 24 students = 25 accounts. + let admin = login_as(&app, &db, "boss", "admin").await; + seed_students(&app, 24).await; + + // Unpaged: the whole list, `limit` echoes null, `total` counts everyone. + let res = send(&app, "GET", "/users", Some(&admin), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(total(&res.body), 25); + assert_eq!(items(&res.body).len(), 25); + assert!(res.body["limit"].is_null(), "omitted limit echoes null"); + assert_eq!(res.body["offset"], 0); + + // First window of 10. + let res = send(&app, "GET", "/users?limit=10&offset=0", Some(&admin), None).await; + assert_eq!(total(&res.body), 25); + assert_eq!(items(&res.body).len(), 10); + assert_eq!(res.body["limit"], 10); + assert_eq!(res.body["offset"], 0); + let page1: Vec<_> = items(&res.body).iter().map(|u| u["id"].clone()).collect(); + + // Second window — disjoint from the first, identical total. + let res = send(&app, "GET", "/users?limit=10&offset=10", Some(&admin), None).await; + assert_eq!(total(&res.body), 25); + assert_eq!(items(&res.body).len(), 10); + assert_eq!(res.body["offset"], 10); + let page2: Vec<_> = items(&res.body).iter().map(|u| u["id"].clone()).collect(); + assert!( + page2.iter().all(|id| !page1.contains(id)), + "consecutive pages must not overlap" + ); + + // Tail — the remaining 5, even though a full window of 10 was asked for. + let res = send(&app, "GET", "/users?limit=10&offset=20", Some(&admin), None).await; + assert_eq!(items(&res.body).len(), 5, "tail returns only the remainder"); + assert_eq!(total(&res.body), 25); + + // Past the end — an empty page, not an error, and `total` stays honest. + let res = send(&app, "GET", "/users?limit=10&offset=999", Some(&admin), None).await; + assert_eq!(res.status, StatusCode::OK); + assert!(items(&res.body).is_empty(), "offset past the end is empty"); + assert_eq!(total(&res.body), 25); +} + +#[tokio::test] +async fn bad_paging_params_are_rejected() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + + for bad in [ + "limit=0", // below the floor + "limit=501", // above the 500 cap + "limit=-1", // negative + "offset=-1", // negative offset + "limit=abc", // not an integer + ] { + let res = send(&app, "GET", &format!("/users?{bad}"), Some(&admin), None).await; + assert_eq!( + res.status, + StatusCode::BAD_REQUEST, + "GET /users?{bad} should be 400" + ); + } + + // The inclusive bounds and a bare offset are accepted. + for ok in ["limit=1", "limit=500", "offset=0", "limit=50&offset=0"] { + let res = send(&app, "GET", &format!("/users?{ok}"), Some(&admin), None).await; + assert_eq!(res.status, StatusCode::OK, "GET /users?{ok} should be 200"); + } +} + +#[tokio::test] +async fn paged_roster_still_embeds_people_on_the_page() { + // A list that joins person refs must run that join over the returned page, + // not the whole table — the page rows still carry their embedded people. + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let course = create_course(&app, &teacher, "Algebra").await; + + for i in 0..5 { + let student = login(&app, &format!("stud{i}")).await; + let sid = me_id(&app, &student).await; + enroll(&app, &teacher, &course, &sid).await; + } + + let uri = format!("/courses/{course}/enrollments?limit=2&offset=0"); + let res = send(&app, "GET", &uri, Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(total(&res.body), 5, "total counts the whole roster"); + let page = items(&res.body); + assert_eq!(page.len(), 2, "only the requested window comes back"); + for row in page { + assert!( + row["user"]["username"].is_string(), + "enrolled student ref present on the page: {row}" + ); + assert!( + row["enrolled_by"]["username"].is_string(), + "enroller ref present on the page: {row}" + ); + } +} + +#[tokio::test] +async fn user_search_is_paged_not_capped() { + // `/users/search` used to hard-cap at 10 rows; it now pages like the rest. + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + // 12 accounts sharing the "grp" fragment — past the old cap. + for i in 0..12 { + let creds = json!({ "username": format!("grp{i:02}"), "password": "secret1" }); + let res = send(&app, "POST", "/auth/register", None, Some(creds)).await; + assert_eq!(res.status, StatusCode::CREATED); + } + + // Unpaged: every match comes back — no 10-row ceiling. + let res = send(&app, "GET", "/users/search?q=grp", Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(total(&res.body), 12, "all matches counted, not capped at 10"); + assert_eq!(items(&res.body).len(), 12); + + // Windowed like any other list — the tail is the remainder. + let res = send( + &app, + "GET", + "/users/search?q=grp&limit=5&offset=10", + Some(&teacher), + None, + ) + .await; + assert_eq!(total(&res.body), 12); + assert_eq!(items(&res.body).len(), 2, "offset 10 of 12 leaves 2"); + + // Paging bounds are enforced, and a blank query is still refused. + let res = send(&app, "GET", "/users/search?q=grp&limit=0", Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "limit=0 is a 400"); + let res = send(&app, "GET", "/users/search?q=", Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "blank q is still a 400"); +} diff --git a/tests/persistence.rs b/tests/persistence.rs index 8a06943..8beb7bc 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -83,12 +83,12 @@ async fn file_engine_runs_full_flow() { .await; assert_eq!(note.status, StatusCode::CREATED); assert_eq!( - send(&app, "GET", "/notes", Some(&cookie), None) - .await - .body - .as_array() - .unwrap() - .len(), + common::items( + &send(&app, "GET", "/notes", Some(&cookie), None) + .await + .body, + ) + .len(), 1 ); } @@ -143,7 +143,7 @@ async fn data_survives_reopen() { "notes list body: {}", notes.body ); - let rows = notes.body.as_array().unwrap(); + let rows = common::items(¬es.body); assert_eq!(rows.len(), 1, "note survived reopen"); assert_eq!(rows[0]["title"], "persisted"); } @@ -315,7 +315,7 @@ async fn course_marks_survive_reopen() { None, ) .await; - assert_eq!(roster.body.as_array().unwrap().len(), 1, "roster intact"); + assert_eq!(common::items(&roster.body).len(), 1, "roster intact"); } } @@ -403,7 +403,7 @@ async fn settings_and_terms_survive_reopen() { assert_eq!(res.body["name"], "2026 Fall"); let res = send(&app, "GET", "/courses", Some(&cookie), None).await; - let courses = res.body.as_array().unwrap(); + let courses = common::items(&res.body); assert_eq!(courses.len(), 1); assert_eq!(courses[0]["term"].as_str(), Some(term.as_str())); }