forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

pomodoro.rs364 lines, 14.6 KiBHistoryRawDownload
1use crate::web::tenant_state::State;
2use axum::Json;
3use axum::extract::{Path, Query};
4use axum::http::StatusCode;
5use serde::{Deserialize, Serialize};
6use utoipa::{IntoParams, ToSchema};
7use utoipa_axum::router::OpenApiRouter;
8use utoipa_axum::routes;
9
10use crate::constant::MAX_POMODORO_LABEL_LEN;
11use crate::domain::pomodoro::PomodoroSession;
12use crate::domain::role::Role;
13use crate::domain::user::{User, UserId};
14use crate::error::{AppError, ErrorResponse, ValidationError};
15use crate::service::parent_link::ensure_can_observe;
16use crate::service::pomodoro;
17use crate::state::AppState;
18use crate::validate::validate_optional;
19
20use super::{CurrentUser, PageParams};
21
22pub fn routes() -> OpenApiRouter<AppState> {
23 OpenApiRouter::new()
24 .routes(routes!(start))
25 .routes(routes!(finish))
26 .routes(routes!(my_pomodoro))
27 .routes(routes!(user_pomodoro))
28}
29
30/// A 403 unless `user` is a student — the pomodoro timer is the students'
31/// study tool (staff time-keeping is the work log). Only `start` is gated:
32/// finishing merely closes a session that only a student could have opened,
33/// so a mid-session promotion still gets its last stint on the record.
34fn ensure_student(user: &User) -> Result<(), AppError> {
35 if user.get_role() != Role::Student {
36 return Err(AppError::Forbidden("only students run pomodoro sessions"));
37 }
38 Ok(())
39}
40
41#[derive(Serialize, ToSchema)]
42struct PomodoroResponse {
43 id: String,
44 /// The student this session belongs to.
45 user: String,
46 /// Session start, UTC unix-milliseconds (server-stamped).
47 started_at: i64,
48 /// Session end, UTC unix-milliseconds; `null` while still running.
49 finished_at: Option<i64>,
50 /// `finished_at - started_at`; `null` while still running.
51 duration_ms: Option<i64>,
52 /// Whether this stint moved the lifetime pomodoro counters (and so the
53 /// badges and the study streak): it did when it ran at least
54 /// `pomodoro.min_counted_ms` and was within that UTC day's
55 /// `pomodoro.max_counted_per_day` (both on `GET /limits`). `null` while
56 /// still running, and on stints closed before the rule existed. An
57 /// uncounted stint is kept and listed exactly like any other.
58 counted: Option<bool>,
59 /// What the student called this stint when they started it — their own
60 /// name for what it was for. `null` on an unnamed stint and on rows
61 /// from before the field existed.
62 label: Option<String>,
63}
64
65impl PomodoroResponse {
66 fn new(session: &PomodoroSession) -> Self {
67 let started_at = session.get_started_at().as_millis();
68 let finished_at = session.get_finished_at().map(|t| t.as_millis());
69 Self {
70 id: session.get_id().key().to_string(),
71 user: session.get_user().key().to_string(),
72 started_at,
73 finished_at,
74 duration_ms: finished_at.map(|done| done.saturating_sub(started_at)),
75 counted: session.get_counted(),
76 label: session.get_label().map(str::to_string),
77 }
78 }
79}
80
81/// The standard `{items, total, limit, offset}` page envelope over the
82/// sessions, plus the unpaged focus total — spelled out (not `Page<T>`) so the
83/// extra field rides inside the same flat object.
84#[derive(Serialize, ToSchema)]
85struct PomodoroLog {
86 items: Vec<PomodoroResponse>,
87 /// Total sessions in the log the filter selects, before `limit`/`offset`
88 /// are applied.
89 #[schema(example = 256)]
90 total: i64,
91 /// Echo of the applied `limit`; `null` when the response is unbounded.
92 #[schema(example = 100)]
93 limit: Option<i64>,
94 /// Echo of the applied `offset`.
95 #[schema(example = 0)]
96 offset: i64,
97 /// Sum of `duration_ms` over every *finished* session the filter selects —
98 /// the whole log, not just this page. A running session counts nothing
99 /// until finished.
100 total_focus_ms: i64,
101}
102
103impl PomodoroLog {
104 fn new(page: pomodoro::PomodoroLogPage, limit: Option<i64>, offset: i64) -> Self {
105 Self {
106 items: page.items.iter().map(PomodoroResponse::new).collect(),
107 total: page.total,
108 limit,
109 offset,
110 total_focus_ms: page.total_focus_ms,
111 }
112 }
113}
114
115/// The optional body names the stint: `{"label": "math"}` stores what the
116/// student called it, trimmed, and the label then rides every response that
117/// carries the session. A blank label starts an unnamed stint and an
118/// over-long one is `400`; no body at all is exactly the old no-label start.
119#[derive(Deserialize, ToSchema)]
120struct StartPomodoro {
121 /// The student's own name for what this stint is for — free text, not a
122 /// subject reference, bounded by `pomodoro.max_label_len` on `GET
123 /// /limits`.
124 label: Option<String>,
125}
126
127/// Start a pomodoro focus session. Students only. The instant is stamped by
128/// the server clock — clients never supply it. Always succeeds for a student:
129/// a dangling unfinished session (the browser died mid-timer) is discarded
130/// and replaced, so there is no way to lock yourself out of starting. The
131/// frontend runs the visible countdown and the break rhythm; the backend
132/// records only the focus stint. The body is optional and names the stint:
133/// a `label` rides the response and every log it lists in — a blank or
134/// absent body starts an unnamed stint, an over-long label is `400`.
135#[utoipa::path(
136 post,
137 path = "/start",
138 tag = "pomodoro",
139 security(("session_cookie" = [])),
140 request_body(content = StartPomodoro, description = "Optional; names the stint"),
141 responses(
142 (status = 201, description = "Session started — the running session", body = PomodoroResponse),
143 (status = 400, description = "Label is over-long", body = ErrorResponse),
144 (status = 401, description = "Not authenticated", body = ErrorResponse),
145 (status = 403, description = "Requires the student role", body = ErrorResponse),
146 (status = 422, description = "The body does not fit this request: a field has the wrong type", body = ErrorResponse),
147 ),
148)]
149async fn start(
150 State(st): State<AppState>,
151 CurrentUser(user): CurrentUser,
152 body: Option<Json<StartPomodoro>>,
153) -> Result<(StatusCode, Json<PomodoroResponse>), AppError> {
154 ensure_student(&user)?;
155 // A blank or absent label records none; a present one is validated (400
156 // if over-long) and trimmed before it reaches the row.
157 let label = match body.and_then(|Json(req)| req.label) {
158 Some(label) if !label.trim().is_empty() => {
159 let trimmed = label.trim();
160 validate_optional("label", trimmed, MAX_POMODORO_LABEL_LEN)?;
161 Some(trimmed.to_string())
162 }
163 _ => None,
164 };
165 let session = pomodoro::start(&st.db, user.get_id(), label).await?;
166 Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session))))
167}
168
169/// Finish the running pomodoro session, closing it with a server-stamped
170/// instant (`409` when nothing is running); answers `counted` — whether it
171/// moved the badge counters (ran at least `pomodoro.min_counted_ms`, within
172/// that UTC day's `pomodoro.max_counted_per_day`).
173///
174/// The counters `counted` speaks for are the lifetime pomodoro ones — the
175/// badges and the study streak read those. Both bounds are published on
176/// `GET /limits`; the day bucket rolls at midnight UTC. A stint that counts
177/// for nothing is still
178/// recorded, still listed, and still sums into `total_focus_ms` — only the
179/// badge counters are held to the rule, because finishing is self-service and a
180/// counter moved once per round-trip is farmable.
181#[utoipa::path(
182 post,
183 path = "/finish",
184 tag = "pomodoro",
185 security(("session_cookie" = [])),
186 responses(
187 (status = 200, description = "Session finished — the closed session", body = PomodoroResponse),
188 (status = 401, description = "Not authenticated", body = ErrorResponse),
189 (status = 409, description = "No pomodoro session running", body = ErrorResponse),
190 ),
191)]
192async fn finish(
193 State(st): State<AppState>,
194 CurrentUser(user): CurrentUser,
195) -> Result<Json<PomodoroResponse>, AppError> {
196 let session = pomodoro::finish(&st.db, user.get_id()).await?;
197 Ok(Json(PomodoroResponse::new(&session)))
198}
199
200/// The optional `?from=&to=` window over the log. Both bounds are UTC unix
201/// milliseconds and half-open — `from` inclusive, `to` exclusive, so
202/// adjacent windows tile without overlap — and independent: each present
203/// bound narrows from its own end. Absent, the log is untouched.
204#[derive(Debug, Deserialize, IntoParams)]
205struct HistoryFilter {
206 /// Keep sessions that started at or after this instant.
207 #[param(example = 1_760_000_000_000i64)]
208 from: Option<i64>,
209 /// Keep sessions that started before this instant.
210 #[param(example = 1_760_008_640_000i64)]
211 to: Option<i64>,
212}
213
214impl HistoryFilter {
215 /// The validated bounds, or `(None, None)` for the whole log. A negative
216 /// bound is a `400` naming the field: the server stamps every instant
217 /// itself, so nothing predates the epoch and a negative value is a
218 /// malformed request, not an era to page through.
219 fn resolve(&self) -> Result<(Option<i64>, Option<i64>), AppError> {
220 let bound = |value: Option<i64>, field: &'static str| match value {
221 Some(ms) if ms < 0 => Err(AppError::Validation(ValidationError::Invalid {
222 field,
223 reason: "must not be negative",
224 })),
225 other => Ok(other),
226 };
227 Ok((bound(self.from, "from")?, bound(self.to, "to")?))
228 }
229}
230
231/// The caller's own pomodoro log, newest first — the running session (if any)
232/// included (`finished_at: null`) — plus `total_focus_ms`, the unpaged sum of
233/// finished-session durations. Paged via `?limit=&offset=` (omit `limit` for
234/// the whole log).
235///
236/// `from`/`to` (unix milliseconds) narrow the log to sessions that started in
237/// the half-open window `[from, to)` — both optional, AND-ed when both are
238/// given, negative values a `400`. The window bounds the page, `total` and
239/// `total_focus_ms` alike: the focus total is the sum over the same filtered
240/// set the page reads, and with neither bound the response is the
241/// whole-history log, unchanged.
242#[utoipa::path(
243 get,
244 path = "/me",
245 tag = "pomodoro",
246 security(("session_cookie" = [])),
247 params(PageParams, HistoryFilter),
248 responses(
249 (status = 200, description = "A page of the caller's pomodoro log with the unpaged focus total", body = PomodoroLog),
250 (status = 400, description = "Invalid limit, offset, from, or to", body = ErrorResponse),
251 (status = 401, description = "Not authenticated", body = ErrorResponse),
252 ),
253)]
254async fn my_pomodoro(
255 State(st): State<AppState>,
256 CurrentUser(user): CurrentUser,
257 Query(page): Query<PageParams>,
258 Query(filter): Query<HistoryFilter>,
259) -> Result<Json<PomodoroLog>, AppError> {
260 let (limit, offset) = page.resolve()?;
261 let (from, to) = filter.resolve()?;
262 let log = pomodoro::page_for_user(&st.db, user.get_id(), from, to, limit, offset).await?;
263 Ok(Json(PomodoroLog::new(log, limit, offset)))
264}
265
266/// A student's pomodoro log, newest first, with `total_focus_ms` — the same
267/// shape as `/me`. Requires teacher+ (study oversight), or a parent tied to
268/// the target student. Paged via `?limit=&offset=`.
269///
270/// Like `/me`, the optional `from`/`to` window (unix milliseconds, the
271/// half-open `[from, to)`) narrows the log — page, `total` and
272/// `total_focus_ms` together — and leaves the observation rules untouched: a
273/// caller who may not read the log cannot read a window of it either.
274#[utoipa::path(
275 get,
276 path = "/{user}",
277 tag = "pomodoro",
278 security(("session_cookie" = [])),
279 params(("user" = String, Path, description = "User id"), PageParams, HistoryFilter),
280 responses(
281 (status = 200, description = "A page of the user's pomodoro log with the unpaged focus total", body = PomodoroLog),
282 (status = 400, description = "Invalid limit, offset, from, or to", body = ErrorResponse),
283 (status = 401, description = "Not authenticated", body = ErrorResponse),
284 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
285 (status = 404, description = "User not found", body = ErrorResponse),
286 ),
287)]
288async fn user_pomodoro(
289 State(st): State<AppState>,
290 CurrentUser(caller): CurrentUser,
291 Path(user): Path<String>,
292 Query(page): Query<PageParams>,
293 Query(filter): Query<HistoryFilter>,
294) -> Result<Json<PomodoroLog>, AppError> {
295 let (limit, offset) = page.resolve()?;
296 let (from, to) = filter.resolve()?;
297 let target = UserId::from_key(&user);
298 ensure_can_observe(&caller, &target, &st.db).await?;
299 // User must exist — a missing user is a 404, not an empty log.
300 crate::service::user::read(&st.db, &target)
301 .await?
302 .ok_or(AppError::NotFound)?;
303 let log = pomodoro::page_for_user(&st.db, &target, from, to, limit, offset).await?;
304 Ok(Json(PomodoroLog::new(log, limit, offset)))
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use axum::http::Uri;
311
312 #[test]
313 fn an_absent_window_leaves_the_log_untouched() {
314 let filter = HistoryFilter {
315 from: None,
316 to: None,
317 };
318 assert_eq!(filter.resolve().unwrap(), (None, None));
319 }
320
321 #[test]
322 fn a_negative_bound_is_a_400_naming_the_field() {
323 let filter = HistoryFilter {
324 from: Some(-1),
325 to: None,
326 };
327 let AppError::Validation(ValidationError::Invalid { field, .. }) =
328 filter.resolve().unwrap_err()
329 else {
330 panic!("a negative `from` must be a validation error");
331 };
332 assert_eq!(field, "from");
333
334 let filter = HistoryFilter {
335 from: None,
336 to: Some(-1),
337 };
338 let AppError::Validation(ValidationError::Invalid { field, .. }) =
339 filter.resolve().unwrap_err()
340 else {
341 panic!("a negative `to` must be a validation error");
342 };
343 assert_eq!(field, "to");
344 }
345
346 #[test]
347 fn zero_is_a_legal_bound() {
348 let filter = HistoryFilter {
349 from: Some(0),
350 to: Some(0),
351 };
352 assert_eq!(filter.resolve().unwrap(), (Some(0), Some(0)));
353 }
354
355 #[test]
356 fn a_present_but_empty_bound_is_a_400_naming_the_field() {
357 // `?from=` carries no i64: the query extractor itself refuses, the
358 // same 400 `?limit=` has always given for an empty value.
359 let err = Query::<HistoryFilter>::try_from_uri(&Uri::from_static("/?from=&to=5"))
360 .unwrap_err();
361 assert_eq!(err.status(), StatusCode::BAD_REQUEST);
362 assert!(err.body_text().contains("from"), "{}", err.body_text());
363 }
364}