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

page.rs362 lines, 14.0 KiBHistoryRawDownload
1//! Shared pagination: the `?limit=&offset=` query every list endpoint accepts,
2//! and the `{items, total, limit, offset}` envelope they return.
3//!
4//! Paging is opt-in. Omit `limit` and the response still carries every
5//! (remaining) row — so a client that ignores the parameters keeps seeing full
6//! lists, and callers that genuinely need the whole set are never silently
7//! truncated. `total` is always the full, unpaged row count, so a frontend can
8//! render "showing 100 of 256" and drive a pager without a second request.
9//!
10//! The windowing is a slice over the already-ordered domain list (the domain
11//! layer still returns the full, sorted `Vec`): endpoints that join people onto
12//! their rows do that join over the page alone, so the expensive lookup shrinks
13//! with the page even though the base scan does not.
14
15use serde::{Deserialize, Serialize};
16use utoipa::{IntoParams, ToSchema};
17
18use crate::constant::MAX_PAGE_LIMIT;
19use crate::error::{AppError, ValidationError};
20
21/// The `?limit=&offset=` pair on a list endpoint. Both optional: omit `limit`
22/// for every remaining row, omit `offset` to start at the top.
23#[derive(Debug, Deserialize, IntoParams)]
24pub struct PageParams {
25 /// Maximum rows to return. Omit for every remaining row; when supplied it
26 /// must be between `1` and `500`.
27 #[param(minimum = 1, maximum = 500, example = 100)]
28 pub limit: Option<i64>,
29 /// Rows to skip from the start of the list. Defaults to `0`; an offset past
30 /// the end simply yields an empty page.
31 #[param(minimum = 0, example = 0)]
32 pub offset: Option<i64>,
33}
34
35impl PageParams {
36 /// Validate and normalize into `(limit, offset)`. A `limit` outside
37 /// `1..=MAX_PAGE_LIMIT` or a negative `offset` is a `400` naming the field.
38 pub fn resolve(&self) -> Result<(Option<i64>, i64), AppError> {
39 if let Some(limit) = self.limit
40 && !(1..=MAX_PAGE_LIMIT).contains(&limit)
41 {
42 return Err(AppError::Validation(ValidationError::Invalid {
43 field: "limit",
44 reason: "must be between 1 and 500",
45 }));
46 }
47 let offset = self.offset.unwrap_or(0);
48 if offset < 0 {
49 return Err(AppError::Validation(ValidationError::Invalid {
50 field: "offset",
51 reason: "must not be negative",
52 }));
53 }
54 Ok((self.limit, offset))
55 }
56}
57
58/// A row that carries a schedule window, so [`WindowParams`] can filter and
59/// order it. Both ends are optional unix milliseconds; `order_key` is the row
60/// id key, used only to break ties so paging stays stable.
61pub trait Scheduled {
62 fn starts_at_ms(&self) -> Option<i64>;
63 fn ends_at_ms(&self) -> Option<i64>;
64 fn order_key(&self) -> String;
65}
66
67/// The optional `?starts_after=&ends_after=&starts_before=&ends_before=`
68/// schedule window on a list of scheduled rows. All four are unix milliseconds
69/// and independent (AND-ed when several are given). Omit all four and the list
70/// is untouched — same order, same total as an unfiltered call.
71#[derive(Debug, Deserialize, IntoParams)]
72pub struct WindowParams {
73 /// Keep only rows starting strictly after this unix-millisecond instant.
74 /// Rows without a `starts_at` are dropped.
75 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
76 #[serde(default)]
77 pub starts_after: Option<i64>,
78 /// Keep only rows whose window has not finished by this unix-millisecond
79 /// instant: `ends_at > value`, falling back to `starts_at > value` when
80 /// `ends_at` is null. Rows with no schedule at all are dropped.
81 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
82 #[serde(default)]
83 pub ends_after: Option<i64>,
84 /// Keep only rows starting strictly before this unix-millisecond instant.
85 /// Rows without a `starts_at` are dropped.
86 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
87 #[serde(default)]
88 pub starts_before: Option<i64>,
89 /// Keep only rows whose window has already finished by this
90 /// unix-millisecond instant: `ends_at < value`, falling back to
91 /// `starts_at < value` when `ends_at` is null. Rows with no schedule at
92 /// all are dropped.
93 #[param(minimum = 0, example = 1_760_000_000_000_i64)]
94 #[serde(default)]
95 pub ends_before: Option<i64>,
96}
97
98impl WindowParams {
99 /// The `400` half of the window: a negative bound is refused naming its
100 /// field. Endpoints that push the window into SQL call this before the
101 /// read; [`Self::apply`] calls it before filtering.
102 pub fn validate(&self) -> Result<(), AppError> {
103 for (field, value) in [
104 ("starts_after", self.starts_after),
105 ("ends_after", self.ends_after),
106 ("starts_before", self.starts_before),
107 ("ends_before", self.ends_before),
108 ] {
109 if value.is_some_and(|value| value < 0) {
110 return Err(AppError::Validation(ValidationError::Invalid {
111 field,
112 reason: "must not be negative",
113 }));
114 }
115 }
116 Ok(())
117 }
118
119 /// Apply the window to an already-visibility-filtered list. With no
120 /// parameter the list is returned untouched; with any, schedule-less
121 /// rows are dropped and the survivors are sorted ascending by `starts_at`
122 /// (falling back to `ends_at`), ties broken by id. A negative value is a
123 /// `400` naming the field.
124 pub fn apply<T: Scheduled>(&self, mut items: Vec<T>) -> Result<Vec<T>, AppError> {
125 self.validate()?;
126 if self.starts_after.is_none()
127 && self.ends_after.is_none()
128 && self.starts_before.is_none()
129 && self.ends_before.is_none()
130 {
131 return Ok(items);
132 }
133 items.retain(|item| {
134 let starts = item.starts_at_ms();
135 let ends = item.ends_at_ms();
136 // The `*_after` bounds drop a `None` on their own (`None > Some`
137 // is false), but `None < Some(_)` is *true* — `Option` orders
138 // `None` first — so the `*_before` bounds must refuse a missing
139 // end explicitly, the way SQL's `NULL < x` does.
140 self.starts_after.is_none_or(|after| starts > Some(after))
141 && self
142 .starts_before
143 .is_none_or(|before| starts.is_some_and(|start| start < before))
144 && self
145 .ends_after
146 .is_none_or(|after| ends.or(starts) > Some(after))
147 && self
148 .ends_before
149 .is_none_or(|before| ends.or(starts).is_some_and(|end| end < before))
150 });
151 // Every survivor has at least one end, so the fallback never yields
152 // `None` — but sort defensively rather than unwrapping.
153 items.sort_by(|a, b| {
154 let key = |item: &T| item.starts_at_ms().or_else(|| item.ends_at_ms());
155 key(a)
156 .cmp(&key(b))
157 .then_with(|| a.order_key().cmp(&b.order_key()))
158 });
159 Ok(items)
160 }
161}
162
163/// One page of a list: the `items`, the full `total` (row count before the
164/// window), and the `limit`/`offset` that produced it. `limit` is `null` when
165/// the caller asked for every row.
166#[derive(Debug, Serialize, ToSchema)]
167pub struct Page<T> {
168 pub items: Vec<T>,
169 /// Total rows in the full list, before `limit`/`offset` are applied.
170 #[schema(example = 256)]
171 pub total: i64,
172 /// Echo of the applied `limit`; `null` when the response is unbounded.
173 #[schema(example = 100)]
174 pub limit: Option<i64>,
175 /// Echo of the applied `offset`.
176 #[schema(example = 0)]
177 pub offset: i64,
178}
179
180impl<T> Page<T> {
181 pub fn new(items: Vec<T>, total: i64, limit: Option<i64>, offset: i64) -> Self {
182 Self {
183 items,
184 total,
185 limit,
186 offset,
187 }
188 }
189}
190
191/// The window `[offset, offset + limit)` of `items`, clamped to the ends. An
192/// offset at or past the end yields an empty slice — a client paging off the
193/// tail gets `[]`, not an error — and a `None` limit runs to the end. `total`
194/// stays the caller's job: take `items.len()` before slicing.
195pub fn paginate<T>(items: &[T], limit: Option<i64>, offset: i64) -> &[T] {
196 let start = (offset.max(0) as usize).min(items.len());
197 let end = match limit {
198 Some(limit) => start.saturating_add(limit.max(0) as usize).min(items.len()),
199 None => items.len(),
200 };
201 &items[start..end]
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 fn params(limit: Option<i64>, offset: Option<i64>) -> PageParams {
209 PageParams { limit, offset }
210 }
211
212 #[test]
213 fn resolve_accepts_bounds_and_defaults_offset() {
214 assert_eq!(params(None, None).resolve().unwrap(), (None, 0));
215 assert_eq!(params(Some(1), None).resolve().unwrap(), (Some(1), 0));
216 assert_eq!(
217 params(Some(MAX_PAGE_LIMIT), Some(40)).resolve().unwrap(),
218 (Some(MAX_PAGE_LIMIT), 40)
219 );
220 }
221
222 #[test]
223 fn resolve_rejects_out_of_range_limit_and_negative_offset() {
224 assert!(params(Some(0), None).resolve().is_err());
225 assert!(params(Some(MAX_PAGE_LIMIT + 1), None).resolve().is_err());
226 assert!(params(Some(-5), None).resolve().is_err());
227 assert!(params(None, Some(-1)).resolve().is_err());
228 }
229
230 struct Row(&'static str, Option<i64>, Option<i64>);
231
232 impl Scheduled for Row {
233 fn starts_at_ms(&self) -> Option<i64> {
234 self.1
235 }
236 fn ends_at_ms(&self) -> Option<i64> {
237 self.2
238 }
239 fn order_key(&self) -> String {
240 self.0.to_owned()
241 }
242 }
243
244 fn rows() -> Vec<Row> {
245 vec![
246 Row("none", None, None),
247 Row("running", Some(10), Some(40)),
248 Row("later", Some(30), None),
249 Row("ending", None, Some(20)),
250 Row("tie", Some(30), Some(50)),
251 ]
252 }
253
254 fn keys(window: WindowParams) -> Vec<&'static str> {
255 window
256 .apply(rows())
257 .unwrap()
258 .iter()
259 .map(|row| row.0)
260 .collect()
261 }
262
263 fn window(
264 starts_after: Option<i64>,
265 ends_after: Option<i64>,
266 starts_before: Option<i64>,
267 ends_before: Option<i64>,
268 ) -> WindowParams {
269 WindowParams {
270 starts_after,
271 ends_after,
272 starts_before,
273 ends_before,
274 }
275 }
276
277 #[test]
278 fn window_absent_leaves_the_list_untouched() {
279 assert_eq!(
280 keys(window(None, None, None, None)),
281 ["none", "running", "later", "ending", "tie"]
282 );
283 }
284
285 #[test]
286 fn ends_after_keeps_unfinished_rows_and_falls_back_to_starts_at() {
287 // `ending` has no start (kept on ends_at), `later` no end (kept on the
288 // starts_at fallback), `none` has neither and always drops. Ascending
289 // by starts_at ?? ends_at, ties broken by key.
290 assert_eq!(
291 keys(window(None, Some(15), None, None)),
292 ["running", "ending", "later", "tie"]
293 );
294 // At 25, `ending` (ends 20) is over; `running` (ends 40) is not.
295 assert_eq!(
296 keys(window(None, Some(25), None, None)),
297 ["running", "later", "tie"]
298 );
299 }
300
301 #[test]
302 fn starts_after_excludes_started_and_start_less_rows() {
303 assert_eq!(keys(window(Some(25), None, None, None)), ["later", "tie"]);
304 // AND-ed with ends_after: `tie` ends at 50, while `later` has no end
305 // and its starts_at fallback (30) is already behind 45.
306 assert_eq!(
307 keys(window(Some(25), Some(45), None, None)),
308 ["tie"]
309 );
310 assert!(keys(window(Some(60), None, None, None)).is_empty());
311 }
312
313 #[test]
314 fn starts_before_excludes_not_yet_started_and_start_less_rows() {
315 // Strictly before: a row starting exactly at the instant is out.
316 assert_eq!(keys(window(None, None, Some(30), None)), ["running"]);
317 // AND-ed with ends_after: `running` (ends 40) survives 35; `tie`
318 // starts exactly at 30 and a `starts_before` is strict.
319 assert_eq!(keys(window(None, Some(35), Some(30), None)), ["running"]);
320 }
321
322 #[test]
323 fn ends_before_keeps_only_finished_rows_dropping_the_unscheduled() {
324 // At 45: `ending` (ends 20) is over, `later` on its starts_at
325 // fallback (30) is over, `running` (ends 40) is over; `tie` (ends 50)
326 // is not; `none` has no schedule and always drops.
327 assert_eq!(keys(window(None, None, None, Some(45))), ["running", "ending", "later"]);
328 // Exactly at the end is not before it.
329 assert_eq!(keys(window(None, None, None, Some(40))), ["ending", "later"]);
330 }
331
332 #[test]
333 fn window_rejects_negative_values() {
334 assert!(window(Some(-1), None, None, None).apply(rows()).is_err());
335 assert!(window(None, Some(-1), None, None).apply(rows()).is_err());
336 assert!(window(None, None, Some(-1), None).apply(rows()).is_err());
337 assert!(window(None, None, None, Some(-1)).apply(rows()).is_err());
338 // The shared validate reports the field it refuses.
339 let Err(AppError::Validation(ValidationError::Invalid { field, .. })) =
340 window(None, None, Some(-1), None).apply(rows())
341 else {
342 panic!("expected a validation error");
343 };
344 assert_eq!(field, "starts_before");
345 }
346
347 #[test]
348 fn paginate_windows_and_clamps() {
349 let items: Vec<i64> = (0..10).collect();
350 // A bounded window in the middle.
351 assert_eq!(paginate(&items, Some(3), 2), &[2, 3, 4]);
352 // No limit → everything from the offset to the end.
353 assert_eq!(paginate(&items, None, 7), &[7, 8, 9]);
354 // Limit overruns the end → clamped, not padded.
355 assert_eq!(paginate(&items, Some(100), 8), &[8, 9]);
356 // Offset at or past the end → empty page, not a panic.
357 assert!(paginate(&items, Some(5), 10).is_empty());
358 assert!(paginate(&items, Some(5), 999).is_empty());
359 // No limit, zero offset → the whole list.
360 assert_eq!(paginate(&items, None, 0), items.as_slice());
361 }
362}