Skip to main content

ash_jsonapi/
query.rs

1//! `?page[…]` and `?sort=` — parsed, checked, and handed to storage.
2//!
3//! A collection request carries its paging and ordering in the query string.
4//! This module turns that string into typed values, rejecting what is
5//! malformed before storage is touched, so a `List` implementation receives
6//! something it can use rather than raw strings it has to re-parse.
7//!
8//! Every failure here is a `400` carrying `source.parameter`, which is what
9//! JSON:API names for a bad query parameter — the counterpart to the
10//! `source.pointer` a bad document member gets.
11
12use std::collections::BTreeMap;
13
14use crate::context::Context;
15use crate::error::{ErrorCode, JsonApiError};
16
17/// How many resources a page holds when the client does not say.
18pub const DEFAULT_PAGE_SIZE: usize = 25;
19
20/// The largest page a client may ask for.
21///
22/// A cap is required: without one, `page[limit]=1000000` is a denial of
23/// service written in one query parameter.
24pub const MAX_PAGE_SIZE: usize = 100;
25
26/// Which page of a collection the client asked for.
27///
28/// JSON:API leaves pagination strategy to the implementation and only fixes
29/// the `page` family of parameters. Both common strategies are supported, and
30/// a request may use one or the other — never both:
31///
32/// - **Offset** — `?page[offset]=20&page[limit]=10`. Gives `first`, `prev`,
33///   `next` and, when storage reports a total, `last`.
34/// - **Cursor** — `?page[cursor]=t_20&page[size]=10`. Stable while rows are
35///   being inserted, and the only sound choice on a large table, at the cost
36///   of no `last` link and no page count.
37///
38/// A [`List`](crate::crud::List) implementation matches on this. Storage that
39/// only supports one strategy returns
40/// [`ErrorCode::InvalidParameter`] for
41/// the other rather than pretending.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Page {
44    /// `page[offset]` / `page[limit]`.
45    Offset {
46        /// How many resources to skip. Zero on the first page.
47        offset: usize,
48        /// How many to return, already clamped to [`MAX_PAGE_SIZE`].
49        limit: usize,
50    },
51    /// `page[cursor]` / `page[size]`.
52    Cursor {
53        /// Where to resume — the value storage handed back last time.
54        ///
55        /// `None` is the first page, so a client starts by sending
56        /// `page[size]` alone.
57        after: Option<String>,
58        /// How many to return, already clamped to [`MAX_PAGE_SIZE`].
59        size: usize,
60    },
61}
62
63impl Default for Page {
64    /// The first page, by offset — what a bare `GET /todos` means.
65    fn default() -> Self {
66        Self::Offset {
67            offset: 0,
68            limit: DEFAULT_PAGE_SIZE,
69        }
70    }
71}
72
73impl Page {
74    /// How many resources this page holds, whichever strategy is in use.
75    pub fn size(&self) -> usize {
76        match self {
77            Self::Offset { limit, .. } => *limit,
78            Self::Cursor { size, .. } => *size,
79        }
80    }
81}
82
83/// One `?sort=` key: a field, and its direction.
84///
85/// JSON:API spells descending with a leading `-`, so `?sort=-created,message`
86/// is "newest first, then by message".
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Sort {
89    field: String,
90    descending: bool,
91}
92
93impl Sort {
94    /// The field to sort on, with the `-` stripped.
95    ///
96    /// Not checked against the resource's schema: sorting is storage's to
97    /// interpret, and only storage knows which columns are indexed or
98    /// whether an attribute is even stored. Reject what you do not support
99    /// with [`ErrorCode::InvalidParameter`].
100    pub fn field(&self) -> &str {
101        &self.field
102    }
103
104    /// Whether the key was written `-field`.
105    pub fn descending(&self) -> bool {
106        self.descending
107    }
108}
109
110/// Everything a collection request asked for.
111///
112/// Handed to [`List::list`](crate::crud::List::list). Paging is always
113/// present — a request that names no page gets the default — and `sort` is
114/// empty unless the client sent one.
115#[derive(Debug, Clone, Default)]
116pub struct Query {
117    page: Page,
118    sort: Vec<Sort>,
119}
120
121impl Query {
122    /// The page the client asked for.
123    pub fn page(&self) -> &Page {
124        &self.page
125    }
126
127    /// The sort keys, in the order given. Empty when `?sort=` was absent.
128    ///
129    /// Applying them is storage's business, and so is refusing a field it
130    /// cannot sort on — see [`Sort::field`].
131    pub fn sort(&self) -> &[Sort] {
132        &self.sort
133    }
134
135    /// Parse a raw query string.
136    ///
137    /// Unknown parameters are ignored rather than refused: `?utm_source=…`
138    /// on a shared link should not fail the request, and JSON:API reserves
139    /// only the families it defines.
140    pub fn parse(query: &str, ctx: &Context) -> Result<Self, JsonApiError> {
141        let params = split(query);
142
143        Ok(Self {
144            page: page_from(&params, ctx)?,
145            sort: sort_from(&params),
146        })
147    }
148}
149
150/// `key=value&key=value` → a map, with `%xx` and `+` decoded.
151fn split(query: &str) -> BTreeMap<String, String> {
152    query
153        .split('&')
154        .filter(|pair| !pair.is_empty())
155        .map(|pair| match pair.split_once('=') {
156            Some((key, value)) => (decode(key), decode(value)),
157            None => (decode(pair), String::new()),
158        })
159        .collect()
160}
161
162/// Percent-decoding, plus `+` as a space.
163///
164/// `page[offset]` arrives as `page%5Boffset%5D` from most clients, so the
165/// brackets have to survive the round trip.
166fn decode(raw: &str) -> String {
167    let bytes = raw.as_bytes();
168    let mut out = Vec::with_capacity(bytes.len());
169    let mut i = 0;
170
171    while i < bytes.len() {
172        match bytes[i] {
173            b'+' => {
174                out.push(b' ');
175                i += 1;
176            }
177            b'%' if i + 2 < bytes.len() => {
178                let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
179                match hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
180                    Some(byte) => {
181                        out.push(byte);
182                        i += 3;
183                    }
184                    // Not a valid escape: keep the `%` as written.
185                    None => {
186                        out.push(b'%');
187                        i += 1;
188                    }
189                }
190            }
191            byte => {
192                out.push(byte);
193                i += 1;
194            }
195        }
196    }
197
198    String::from_utf8_lossy(&out).into_owned()
199}
200
201/// Which paging strategy the parameters describe.
202fn page_from(params: &BTreeMap<String, String>, ctx: &Context) -> Result<Page, JsonApiError> {
203    let offset = params.get("page[offset]");
204    let limit = params.get("page[limit]");
205    let cursor = params.get("page[cursor]");
206    let size = params.get("page[size]");
207
208    let is_offset = offset.is_some() || limit.is_some();
209    let is_cursor = cursor.is_some() || size.is_some();
210
211    // Mixing the two is a client bug worth naming: silently honouring one
212    // would page through the collection in a way the caller did not ask for.
213    if is_offset && is_cursor {
214        return Err(invalid(
215            ctx,
216            "page",
217            "use either `page[offset]`/`page[limit]` or `page[cursor]`/`page[size]`, not both",
218        ));
219    }
220
221    if is_cursor {
222        return Ok(Page::Cursor {
223            after: cursor.filter(|value| !value.is_empty()).cloned(),
224            size: number(size, "page[size]", DEFAULT_PAGE_SIZE, ctx)?.min(MAX_PAGE_SIZE),
225        });
226    }
227
228    Ok(Page::Offset {
229        offset: number(offset, "page[offset]", 0, ctx)?,
230        limit: number(limit, "page[limit]", DEFAULT_PAGE_SIZE, ctx)?.min(MAX_PAGE_SIZE),
231    })
232}
233
234/// One numeric parameter, or its default.
235fn number(
236    raw: Option<&String>,
237    name: &str,
238    default: usize,
239    ctx: &Context,
240) -> Result<usize, JsonApiError> {
241    match raw {
242        None => Ok(default),
243        Some(value) => value.parse().map_err(|_| {
244            invalid(
245                ctx,
246                name,
247                format!("`{name}` must be a non-negative whole number, not `{value}`"),
248            )
249        }),
250    }
251}
252
253/// `?sort=-created,message` → the keys, in order.
254///
255/// Empty keys are dropped, so a trailing comma is not an error.
256fn sort_from(params: &BTreeMap<String, String>) -> Vec<Sort> {
257    let Some(raw) = params.get("sort") else {
258        return Vec::new();
259    };
260
261    raw.split(',')
262        .map(str::trim)
263        .filter(|key| !key.is_empty() && *key != "-")
264        .map(|key| match key.strip_prefix('-') {
265            Some(field) => Sort {
266                field: field.to_string(),
267                descending: true,
268            },
269            None => Sort {
270                field: key.to_string(),
271                descending: false,
272            },
273        })
274        .collect()
275}
276
277/// A `400` naming the parameter at fault.
278fn invalid(ctx: &Context, parameter: &str, detail: impl Into<String>) -> JsonApiError {
279    JsonApiError::in_request(ErrorCode::InvalidParameter, ctx)
280        .detail(detail)
281        .parameter(parameter)
282}
283
284/// Build a collection's pagination links.
285///
286/// The URLs a client follows rather than assembling: `self` always, `first`
287/// and `prev` when there is somewhere back to go, `next` when there is more,
288/// and `last` only when the total is known. Sort keys are carried across
289/// every link, so following `next` does not silently reorder the collection.
290pub struct Paginator<'a> {
291    base: &'a str,
292    query: &'a Query,
293}
294
295impl<'a> Paginator<'a> {
296    /// Links for a collection served at `base`.
297    pub fn new(base: &'a str, query: &'a Query) -> Self {
298        Self { base, query }
299    }
300
301    /// The links for one page.
302    ///
303    /// `returned` is how many rows this page actually holds, `total` the size
304    /// of the collection when storage counted it, `cursor` where the next
305    /// page resumes under cursor paging, and `has_more` whether the
306    /// collection continues past this page when storage knows exactly.
307    pub fn links(
308        &self,
309        returned: usize,
310        total: Option<usize>,
311        cursor: Option<&str>,
312        has_more: Option<bool>,
313    ) -> crate::document::Links {
314        match self.query.page() {
315            Page::Offset { offset, limit } => {
316                self.offset_links(*offset, *limit, returned, total, has_more)
317            }
318            Page::Cursor { size, .. } => self.cursor_links(*size, cursor),
319        }
320    }
321
322    /// `first`/`prev`/`next`, and `last` when the total is known.
323    fn offset_links(
324        &self,
325        offset: usize,
326        limit: usize,
327        returned: usize,
328        total: Option<usize>,
329        has_more: Option<bool>,
330    ) -> crate::document::Links {
331        let mut links = crate::document::Links::this(self.offset_url(offset, limit));
332
333        links = links.first(self.offset_url(0, limit));
334
335        if offset > 0 {
336            links = links.prev(self.offset_url(offset.saturating_sub(limit), limit));
337        }
338
339        // Storage that answered exactly is believed: it read past the page
340        // and knows. Otherwise, with a total, "more" is arithmetic; without
341        // either, a full page is taken as evidence there may be more — the
342        // client discovers the end by following `next` into an empty page,
343        // which is the cost of not counting.
344        let more = match (has_more, total) {
345            (Some(more), _) => more,
346            (None, Some(total)) => offset + returned < total,
347            (None, None) => returned == limit && limit > 0,
348        };
349
350        if more {
351            links = links.next(self.offset_url(offset + limit, limit));
352        }
353
354        if let Some(total) = total
355            && limit > 0
356        {
357            // The offset of the final page: the largest multiple of `limit`
358            // below `total`. An empty collection's last page is its first.
359            let last = total.saturating_sub(1) / limit * limit;
360            links = links.last(self.offset_url(last, limit));
361        }
362
363        links
364    }
365
366    /// `self`, and `next` when storage handed back a cursor.
367    ///
368    /// No `first`, `prev` or `last`: a cursor names one position, and walking
369    /// backwards or jumping to the end needs a cursor the server does not
370    /// have.
371    fn cursor_links(&self, size: usize, cursor: Option<&str>) -> crate::document::Links {
372        let current = match self.query.page() {
373            Page::Cursor { after, .. } => after.as_deref(),
374            Page::Offset { .. } => None,
375        };
376
377        let mut links = crate::document::Links::this(self.cursor_url(current, size));
378
379        if let Some(cursor) = cursor {
380            links = links.next(self.cursor_url(Some(cursor), size));
381        }
382
383        links
384    }
385
386    fn offset_url(&self, offset: usize, limit: usize) -> String {
387        format!(
388            "{}?page[offset]={offset}&page[limit]={limit}{}",
389            self.base,
390            self.sort_suffix()
391        )
392    }
393
394    fn cursor_url(&self, after: Option<&str>, size: usize) -> String {
395        match after {
396            Some(cursor) => format!(
397                "{}?page[cursor]={}&page[size]={size}{}",
398                self.base,
399                encode(cursor),
400                self.sort_suffix()
401            ),
402            None => format!("{}?page[size]={size}{}", self.base, self.sort_suffix()),
403        }
404    }
405
406    /// `&sort=…`, or nothing when the request carried no sort.
407    fn sort_suffix(&self) -> String {
408        let keys = self.query.sort();
409        if keys.is_empty() {
410            return String::new();
411        }
412
413        let joined = keys
414            .iter()
415            .map(|key| {
416                if key.descending() {
417                    format!("-{}", key.field())
418                } else {
419                    key.field().to_string()
420                }
421            })
422            .collect::<Vec<_>>()
423            .join(",");
424
425        format!("&sort={}", encode(&joined))
426    }
427}
428
429/// Percent-encode what must survive a round trip through a URL.
430///
431/// A cursor is storage's opaque string and may hold anything; the sort list
432/// keeps its commas and minus signs, which are legal unencoded.
433fn encode(raw: &str) -> String {
434    raw.bytes()
435        .map(|byte| match byte {
436            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b',' => {
437                (byte as char).to_string()
438            }
439            other => format!("%{other:02X}"),
440        })
441        .collect()
442}