Skip to main content

navree_http/
list.rs

1//! List queries: the one grammar every Navree list speaks.
2//!
3//! A list is a page of rows that can be filtered, searched, sorted and paged:
4//! a JSON endpoint, an admin panel's table, a Navree UI table, a Next.js or
5//! Nuxt data table. All of them write and read the same query string:
6//!
7//! ```text
8//! filter[status]=active                  equal
9//! filter[created_at][gte]=2026-10-01     an operator
10//! filter[stage][in]=lead,won             one of several values
11//! filter[owner_id][null]=true            is NULL (false: is not NULL)
12//! sort=-created_at,name                  descending with a leading "-"
13//! search=agra
14//! page=2&per_page=25                     numbered pages, or
15//! cursor=eyJpZCI6NDJ9&limit=50           cursor pages
16//! ```
17//!
18//! | Operator | Means | Value |
19//! |---|---|---|
20//! | `eq` (or none) | equals | one value |
21//! | `ne` | does not equal | one value |
22//! | `gt`, `gte`, `lt`, `lte` | greater than, at least, less than, at most | one value |
23//! | `in`, `not_in` | is one of, is none of | a comma list; the key may repeat |
24//! | `contains` | contains this text, ignoring case | text |
25//! | `starts_with` | starts with this text, ignoring case | text |
26//! | `null` | is NULL (`true`) or is not NULL (`false`) | `true`, `false`, `1` or `0` |
27//!
28//! Anything else in the query string (`owner_id=3`, `range=30d`) is not the
29//! list query's: it is left for the handler's own extractors.
30//!
31//! There are two ways to read it:
32//!
33//! - [`ListQuery::parse_lenient`] reads the syntax and reports what is wrong
34//!   as [`Problem`]s while keeping everything that is right. Screens use it:
35//!   an old or edited address should still show a page.
36//! - [`ListSpec::parse`] is strict. A resource declares which fields can be
37//!   filtered, how, and which can be sorted or searched, in a [`ListSpec`];
38//!   anything outside that list, a value of the wrong type, an operator the
39//!   field does not take or a page size past the limit is a 400 that names
40//!   the parameter. The [`List`] extractor does this for a handler.
41//!
42//! ```
43//! use navree_http::list::{Field, ListResource, ListSpec, Op};
44//!
45//! /// `GET /api/v1/deals`.
46//! struct Deals;
47//!
48//! impl ListResource for Deals {
49//!     const SPEC: ListSpec = ListSpec::new(&[
50//!         Field::one_of("stage", &["lead", "won", "lost"]),
51//!         Field::int("amount_cents"),
52//!         Field::date("expected_close_date"),
53//!         Field::uuid("owner_id"),
54//!     ])
55//!     .sortable(&["amount_cents", "created_at"])
56//!     .searchable(&["title"]);
57//! }
58//!
59//! let query = Deals::SPEC
60//!     .parse("filter[stage][in]=lead,won&filter[amount_cents][gte]=100000&sort=-amount_cents")
61//!     .unwrap();
62//! assert_eq!(query.filter[0].op, Op::In);
63//! assert_eq!(query.filter[0].values, ["lead", "won"]);
64//!
65//! // The 400 names the parameter.
66//! let error = Deals::SPEC.parse("filter[password][contains]=x").unwrap_err();
67//! assert_eq!(error.problems[0].param, "filter[password][contains]");
68//! ```
69
70use std::collections::BTreeMap;
71use std::fmt;
72use std::marker::PhantomData;
73use std::ops::Deref;
74
75use http::request::Parts;
76
77use crate::AppError;
78use crate::extract::{FromRequestParts, urlencoded};
79
80/// The most bytes of a query string read.
81pub const MAX_QUERY_BYTES: usize = 16 * 1024;
82/// The most parameters read from a query string.
83pub const MAX_PARAMS: usize = 1000;
84/// The most filter conditions kept.
85pub const MAX_CONDITIONS: usize = 64;
86/// The most values one `in` or `not_in` condition keeps.
87pub const MAX_VALUES: usize = 200;
88/// The longest filter value or search text, in bytes.
89pub const MAX_TEXT: usize = 256;
90/// The longest cursor, in bytes.
91pub const MAX_CURSOR: usize = 1024;
92/// The most sort fields kept.
93pub const MAX_SORTS: usize = 4;
94/// The longest field name, in characters.
95pub const MAX_FIELD: usize = 64;
96/// The highest page number.
97pub const MAX_PAGE: u64 = 10_000_000;
98/// The largest page size the syntax allows; a [`ListSpec`] sets a lower one.
99pub const MAX_PAGE_SIZE: u64 = 10_000;
100
101/// What a condition compares with.
102#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
103#[non_exhaustive]
104pub enum Op {
105    /// Equals (`filter[f]=v`, or `filter[f][eq]=v`).
106    Eq,
107    /// Does not equal.
108    Ne,
109    /// Greater than.
110    Gt,
111    /// Greater than or equal to.
112    Gte,
113    /// Less than.
114    Lt,
115    /// Less than or equal to.
116    Lte,
117    /// Is one of a list.
118    In,
119    /// Is none of a list.
120    NotIn,
121    /// Contains this text, ignoring case.
122    Contains,
123    /// Starts with this text, ignoring case.
124    StartsWith,
125    /// Is NULL (`true`) or is not NULL (`false`).
126    Null,
127}
128
129impl Op {
130    /// Every operator.
131    pub const ALL: [Op; 11] = [
132        Op::Eq,
133        Op::Ne,
134        Op::Gt,
135        Op::Gte,
136        Op::Lt,
137        Op::Lte,
138        Op::In,
139        Op::NotIn,
140        Op::Contains,
141        Op::StartsWith,
142        Op::Null,
143    ];
144
145    /// The operator as the query string spells it (`gte`, `not_in`).
146    pub const fn name(self) -> &'static str {
147        match self {
148            Op::Eq => "eq",
149            Op::Ne => "ne",
150            Op::Gt => "gt",
151            Op::Gte => "gte",
152            Op::Lt => "lt",
153            Op::Lte => "lte",
154            Op::In => "in",
155            Op::NotIn => "not_in",
156            Op::Contains => "contains",
157            Op::StartsWith => "starts_with",
158            Op::Null => "null",
159        }
160    }
161
162    /// The operator spelled `name`, exactly (`gte` and not `GTE`).
163    pub fn parse(name: &str) -> Option<Op> {
164        Op::ALL.into_iter().find(|op| op.name() == name)
165    }
166
167    /// Whether the operator takes a list (`in`, `not_in`).
168    pub const fn takes_list(self) -> bool {
169        matches!(self, Op::In | Op::NotIn)
170    }
171}
172
173impl fmt::Display for Op {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        f.write_str(self.name())
176    }
177}
178
179/// One filter: a field, an operator and its values (one value, except for
180/// `in` and `not_in`).
181#[derive(Clone, Debug, PartialEq, Eq)]
182pub struct Condition {
183    /// The field's name.
184    pub field: String,
185    /// The operator.
186    pub op: Op,
187    /// The values, never empty. For `null`: `"true"` or `"false"`.
188    pub values: Vec<String>,
189}
190
191impl Condition {
192    /// The query parameter that carries it: `filter[stage]` for equality,
193    /// `filter[amount][gte]` for the rest.
194    pub fn param(&self) -> String {
195        param_of(&self.field, self.op)
196    }
197
198    /// The first value.
199    pub fn value(&self) -> &str {
200        self.values.first().map_or("", String::as_str)
201    }
202
203    /// For `null`: whether the field must be NULL.
204    pub fn null_flag(&self) -> Option<bool> {
205        (self.op == Op::Null).then(|| self.value() == "true")
206    }
207}
208
209/// The query parameter of a condition on `field` with operator `op`.
210fn param_of(field: &str, op: Op) -> String {
211    if op == Op::Eq {
212        format!("filter[{field}]")
213    } else {
214        format!("filter[{field}][{op}]")
215    }
216}
217
218/// One sort field.
219#[derive(Clone, Debug, PartialEq, Eq)]
220pub struct SortKey {
221    /// The field's name.
222    pub field: String,
223    /// Whether the order is descending (`-field`).
224    pub descending: bool,
225}
226
227impl SortKey {
228    /// `-field` or `field`.
229    pub fn term(&self) -> String {
230        if self.descending {
231            format!("-{}", self.field)
232        } else {
233            self.field.clone()
234        }
235    }
236}
237
238/// Something wrong in a query string: the parameter, and what is wrong with
239/// it.
240#[derive(Clone, Debug, PartialEq, Eq)]
241pub struct Problem {
242    /// The parameter, as written (`filter[stage][in]`, `per_page`).
243    pub param: String,
244    /// What is wrong, in a sentence.
245    pub message: String,
246}
247
248impl Problem {
249    fn new(param: impl Into<String>, message: impl Into<String>) -> Self {
250        Self {
251            param: param.into(),
252            message: message.into(),
253        }
254    }
255}
256
257/// A list query, as data. Every member is optional.
258#[derive(Clone, Debug, Default, PartialEq, Eq)]
259pub struct ListQuery {
260    /// The filters, all of which must hold.
261    pub filter: Vec<Condition>,
262    /// The fields to sort by, in order.
263    pub sort: Vec<SortKey>,
264    /// The text to search for.
265    pub search: Option<String>,
266    /// The page number, from 1 (numbered pages).
267    pub page: Option<u64>,
268    /// The page size (numbered pages).
269    pub per_page: Option<u64>,
270    /// The page after this position (cursor pages): the `next_cursor` of the
271    /// page before.
272    pub cursor: Option<String>,
273    /// The page before this position (cursor pages that go both ways).
274    pub before: Option<String>,
275    /// The page size (cursor pages).
276    pub limit: Option<u64>,
277}
278
279/// How a list is paged, with the defaults filled in.
280#[derive(Clone, Debug, PartialEq, Eq)]
281pub enum Paging {
282    /// Numbered pages.
283    Pages {
284        /// The page number, from 1.
285        page: u64,
286        /// The page size.
287        per_page: u64,
288    },
289    /// Cursor pages.
290    Cursor {
291        /// The page after this position; the first page without one.
292        cursor: Option<String>,
293        /// The page before this position.
294        before: Option<String>,
295        /// The page size.
296        limit: u64,
297    },
298}
299
300impl ListQuery {
301    /// An empty query.
302    pub fn new() -> Self {
303        Self::default()
304    }
305
306    /// Reads the list query's parameters from `query` (the query string, with
307    /// or without its `?`), keeping everything that is right and reporting
308    /// the rest. It reads at most [`MAX_QUERY_BYTES`] bytes and
309    /// [`MAX_PARAMS`] parameters.
310    ///
311    /// ```
312    /// use navree_http::list::ListQuery;
313    ///
314    /// let (query, problems) = ListQuery::parse_lenient("filter[stage]=won&page=0&owner_id=3");
315    /// assert_eq!(query.filter.len(), 1);
316    /// assert_eq!(query.page, None);
317    /// assert_eq!(problems[0].param, "page");
318    /// ```
319    pub fn parse_lenient(query: &str) -> (ListQuery, Vec<Problem>) {
320        let mut reader = Reader::default();
321        reader.read(query.strip_prefix('?').unwrap_or(query));
322        (reader.list, reader.problems)
323    }
324
325    /// The condition on `field` with operator `op`.
326    pub fn condition(&self, field: &str, op: Op) -> Option<&Condition> {
327        self.filter
328            .iter()
329            .find(|condition| condition.field == field && condition.op == op)
330    }
331
332    /// The value of `filter[field]=value`.
333    pub fn eq(&self, field: &str) -> Option<&str> {
334        self.condition(field, Op::Eq).map(Condition::value)
335    }
336
337    /// Writes the query back as a query string: the parameters a list query
338    /// owns, in the order filter, sort, search, page, per_page, cursor,
339    /// before, limit, with a field's conditions together and `eq` written
340    /// plain. The encoding is `URLSearchParams`' (a space is `+`, a bracket
341    /// is `%5B`), so the same query is the same string in the browser.
342    ///
343    /// ```
344    /// use navree_http::list::ListQuery;
345    ///
346    /// let (query, _) = ListQuery::parse_lenient("sort=-name&filter[stage][in]=a,b&page=2");
347    /// assert_eq!(query.to_query_string(), "filter%5Bstage%5D%5Bin%5D=a%2Cb&sort=-name&page=2");
348    /// ```
349    pub fn to_query_string(&self) -> String {
350        let mut out = String::new();
351        let mut done: Vec<&str> = Vec::new();
352        for first in &self.filter {
353            if done.contains(&first.field.as_str()) {
354                continue;
355            }
356            done.push(&first.field);
357            for condition in self.filter.iter().filter(|c| c.field == first.field) {
358                pair(&mut out, &condition.param(), &condition.values.join(","));
359            }
360        }
361        if !self.sort.is_empty() {
362            let terms: Vec<String> = self.sort.iter().map(SortKey::term).collect();
363            pair(&mut out, "sort", &terms.join(","));
364        }
365        if let Some(search) = &self.search {
366            pair(&mut out, "search", search);
367        }
368        if let Some(page) = self.page {
369            pair(&mut out, "page", &page.to_string());
370        }
371        if let Some(per_page) = self.per_page {
372            pair(&mut out, "per_page", &per_page.to_string());
373        }
374        if let Some(cursor) = &self.cursor {
375            pair(&mut out, "cursor", cursor);
376        }
377        if let Some(before) = &self.before {
378            pair(&mut out, "before", before);
379        }
380        if let Some(limit) = self.limit {
381            pair(&mut out, "limit", &limit.to_string());
382        }
383        out
384    }
385
386    /// The same query on page `page` (page 1 leaves `page` out), without a
387    /// cursor.
388    pub fn on_page(mut self, page: u64) -> Self {
389        self.page = (page > 1).then_some(page);
390        self.cursor = None;
391        self.before = None;
392        self
393    }
394
395    /// Whether the query pages by cursor (`cursor`, `before` or `limit`).
396    pub fn is_cursor(&self) -> bool {
397        self.cursor.is_some() || self.before.is_some() || self.limit.is_some()
398    }
399}
400
401/// Appends `name=value` to a query string being written.
402fn pair(out: &mut String, name: &str, value: &str) {
403    if !out.is_empty() {
404        out.push('&');
405    }
406    encode_component_into(out, name);
407    out.push('=');
408    encode_component_into(out, value);
409}
410
411const HEX: &[u8; 16] = b"0123456789ABCDEF";
412
413/// Encodes `text` the way `URLSearchParams` does: letters, digits and
414/// `*-._` stay, a space is `+`, every other byte is `%XX`.
415///
416/// ```
417/// use navree_http::list::encode_component;
418///
419/// assert_eq!(encode_component("filter[a b]"), "filter%5Ba+b%5D");
420/// ```
421pub fn encode_component(text: &str) -> String {
422    let mut out = String::with_capacity(text.len());
423    encode_component_into(&mut out, text);
424    out
425}
426
427fn encode_component_into(out: &mut String, text: &str) {
428    for byte in text.bytes() {
429        match byte {
430            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'*' | b'-' | b'.' | b'_' => {
431                out.push(char::from(byte));
432            }
433            b' ' => out.push('+'),
434            _ => {
435                out.push('%');
436                out.push(char::from(HEX[usize::from(byte >> 4)]));
437                out.push(char::from(HEX[usize::from(byte & 15)]));
438            }
439        }
440    }
441}
442
443/// A field or sort name: a letter or `_`, then letters, digits, `_` and `.`,
444/// at most [`MAX_FIELD`] long.
445fn valid_name(name: &str) -> bool {
446    let mut chars = name.chars();
447    matches!(chars.next(), Some(first) if first.is_ascii_alphabetic() || first == '_')
448        && name.len() <= MAX_FIELD
449        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
450}
451
452/// `text` cut to at most `max` bytes, at a character boundary.
453fn clip(text: &str, max: usize) -> &str {
454    if text.len() <= max {
455        return text;
456    }
457    let mut end = max;
458    while !text.is_char_boundary(end) {
459        end -= 1;
460    }
461    &text[..end]
462}
463
464/// `filter[field]` or `filter[field][op]` as (field, op).
465fn split_filter_key(key: &str) -> Option<(&str, Option<&str>)> {
466    let rest = key.strip_prefix("filter[")?;
467    let close = rest.find(']')?;
468    let field = &rest[..close];
469    let after = &rest[close + 1..];
470    if after.is_empty() {
471        return Some((field, None));
472    }
473    let op = after.strip_prefix('[')?.strip_suffix(']')?;
474    if op.contains(['[', ']']) {
475        return None;
476    }
477    Some((field, Some(op)))
478}
479
480/// A positive whole number of digits only, at most `max`.
481fn count(value: &str, max: u64) -> Result<u64, &'static str> {
482    if !value.bytes().all(|byte| byte.is_ascii_digit()) {
483        return Err("must be a positive whole number");
484    }
485    match value.parse::<u64>() {
486        Ok(0) => Err("must be at least 1"),
487        Ok(n) if n > max => Err("is too large"),
488        Ok(n) => Ok(n),
489        Err(_) => Err("is too large"),
490    }
491}
492
493/// The reader behind [`ListQuery::parse_lenient`].
494#[derive(Default)]
495struct Reader {
496    list: ListQuery,
497    problems: Vec<Problem>,
498    sort_full: bool,
499}
500
501impl Reader {
502    fn problem(&mut self, param: impl Into<String>, message: impl Into<String>) {
503        self.problems.push(Problem::new(param, message));
504    }
505
506    fn read(&mut self, query: &str) {
507        let mut bytes = query.as_bytes();
508        if bytes.len() > MAX_QUERY_BYTES {
509            self.problem(
510                "query",
511                format!("the query string must not exceed {MAX_QUERY_BYTES} bytes"),
512            );
513            bytes = &bytes[..MAX_QUERY_BYTES];
514        }
515        for (read, (name, value)) in urlencoded::parse(bytes).enumerate() {
516            if read >= MAX_PARAMS {
517                self.problem(
518                    "query",
519                    format!("a list query takes at most {MAX_PARAMS} parameters"),
520                );
521                break;
522            }
523            let (name, value) = (&*name, &*value);
524            match name {
525                "sort" => self.sort(value),
526                "search" => self.search(value),
527                "page" => self.number(name, value, MAX_PAGE),
528                "per_page" | "limit" => self.number(name, value, MAX_PAGE_SIZE),
529                "cursor" | "before" => self.cursor(name, value),
530                "filter" => self.problem(
531                    name,
532                    "write a filter as filter[field]=value or filter[field][operator]=value",
533                ),
534                _ if name.starts_with("filter[") => self.filter(name, value),
535                _ => {}
536            }
537        }
538        let numbered = self.list.page.is_some() || self.list.per_page.is_some();
539        if numbered && self.list.is_cursor() {
540            let param = if self.list.cursor.is_some() {
541                "cursor"
542            } else if self.list.before.is_some() {
543                "before"
544            } else {
545                "limit"
546            };
547            self.problem(
548                param,
549                "use page and per_page, or cursor and limit, not both",
550            );
551        }
552    }
553
554    fn sort(&mut self, value: &str) {
555        for term in value.split(',').map(str::trim).filter(|t| !t.is_empty()) {
556            let (field, descending) = term
557                .strip_prefix('-')
558                .map_or((term, false), |field| (field, true));
559            if !valid_name(field) {
560                self.problem("sort", format!("`{term}` is not a field name"));
561            } else if self.list.sort.iter().any(|key| key.field == field) {
562                self.problem("sort", format!("`{field}` is sorted twice"));
563            } else if self.list.sort.len() >= MAX_SORTS {
564                if !self.sort_full {
565                    self.sort_full = true;
566                    self.problem("sort", format!("sort by at most {MAX_SORTS} fields"));
567                }
568            } else {
569                self.list.sort.push(SortKey {
570                    field: field.to_owned(),
571                    descending,
572                });
573            }
574        }
575    }
576
577    fn search(&mut self, value: &str) {
578        let value = value.trim();
579        if value.is_empty() {
580            return;
581        }
582        if value.contains('\0') {
583            self.problem("search", "must not contain a NUL character");
584            return;
585        }
586        if value.len() > MAX_TEXT {
587            self.problem("search", format!("must not exceed {MAX_TEXT} bytes"));
588        }
589        self.list.search = Some(clip(value, MAX_TEXT).to_owned());
590    }
591
592    fn number(&mut self, name: &str, value: &str, max: u64) {
593        if value.is_empty() {
594            return;
595        }
596        match count(value, max) {
597            Ok(n) => match name {
598                "page" => self.list.page = Some(n),
599                "per_page" => self.list.per_page = Some(n),
600                _ => self.list.limit = Some(n),
601            },
602            Err(why) => self.problem(name, format!("{name} {why}")),
603        }
604    }
605
606    fn cursor(&mut self, name: &str, value: &str) {
607        if value.is_empty() {
608            return;
609        }
610        if value.contains('\0') {
611            self.problem(name, "must not contain a NUL character");
612        } else if value.len() > MAX_CURSOR {
613            self.problem(name, format!("must not exceed {MAX_CURSOR} bytes"));
614        } else if name == "cursor" {
615            self.list.cursor = Some(value.to_owned());
616        } else {
617            self.list.before = Some(value.to_owned());
618        }
619    }
620
621    fn filter(&mut self, key: &str, value: &str) {
622        let Some((field, op)) = split_filter_key(key) else {
623            self.problem(
624                key,
625                "write a filter as filter[field]=value or filter[field][operator]=value",
626            );
627            return;
628        };
629        if !valid_name(field) {
630            self.problem(
631                key,
632                format!("`{field}` is not a field name (letters, digits, _ and . only)"),
633            );
634            return;
635        }
636        let op = match op {
637            None => Op::Eq,
638            Some(name) => match Op::parse(name) {
639                Some(op) => op,
640                None => {
641                    self.problem(
642                        key,
643                        format!(
644                            "`{name}` is not an operator; use one of: {}",
645                            Op::ALL.map(Op::name).join(", ")
646                        ),
647                    );
648                    return;
649                }
650            },
651        };
652        if value.trim().is_empty() {
653            return;
654        }
655        if value.contains('\0') {
656            self.problem(key, "must not contain a NUL character");
657            return;
658        }
659        let param = param_of(field, op);
660        let values: Vec<String> = match op {
661            Op::In | Op::NotIn => value
662                .split(',')
663                .filter(|part| !part.is_empty())
664                .map(str::to_owned)
665                .collect(),
666            Op::Null => match value {
667                "true" | "1" => vec!["true".to_owned()],
668                "false" | "0" => vec!["false".to_owned()],
669                _ => {
670                    self.problem(param, "must be true or false");
671                    return;
672                }
673            },
674            _ => vec![value.to_owned()],
675        };
676        if values.iter().any(|v| v.len() > MAX_TEXT) {
677            self.problem(param, format!("a value must not exceed {MAX_TEXT} bytes"));
678            return;
679        }
680        if values.is_empty() {
681            return;
682        }
683        let at = self
684            .list
685            .filter
686            .iter()
687            .position(|c| c.field == field && c.op == op);
688        match at {
689            Some(at) if op.takes_list() => {
690                for value in values {
691                    if self.list.filter[at].values.len() >= MAX_VALUES {
692                        self.problem(param, format!("takes at most {MAX_VALUES} values"));
693                        return;
694                    }
695                    self.list.filter[at].values.push(value);
696                }
697            }
698            Some(_) => self.problem(param, "is given twice; the first is used"),
699            None if self.list.filter.len() >= MAX_CONDITIONS => self.problem(
700                "filter",
701                format!("a list query takes at most {MAX_CONDITIONS} filters"),
702            ),
703            None => {
704                let mut values = values;
705                if values.len() > MAX_VALUES {
706                    values.truncate(MAX_VALUES);
707                    self.problem(param, format!("takes at most {MAX_VALUES} values"));
708                }
709                // A field's conditions stay together, as `to_query_string`
710                // writes them, so a query reads back as itself.
711                let at = self
712                    .list
713                    .filter
714                    .iter()
715                    .rposition(|c| c.field == field)
716                    .map_or(self.list.filter.len(), |last| last + 1);
717                self.list.filter.insert(
718                    at,
719                    Condition {
720                        field: field.to_owned(),
721                        op,
722                        values,
723                    },
724                );
725            }
726        }
727    }
728}
729
730// ---- What a resource allows --------------------------------------------------------
731
732/// What a filter field holds, and so what a value may look like.
733#[derive(Clone, Copy, Debug, PartialEq, Eq)]
734#[non_exhaustive]
735pub enum Kind {
736    /// Text.
737    Text,
738    /// A whole number (`i64`).
739    Int,
740    /// A decimal number, written with digits and one point (`12.50`).
741    Decimal,
742    /// `true` or `false`.
743    Bool,
744    /// A date, `YYYY-MM-DD`.
745    Date,
746    /// A date, or a date and time with an offset (RFC 3339).
747    DateTime,
748    /// A UUID, in its hyphenated form.
749    Uuid,
750    /// One of these words.
751    OneOf(&'static [&'static str]),
752}
753
754const TEXT_OPS: &[Op] = &[
755    Op::Eq,
756    Op::Ne,
757    Op::Contains,
758    Op::StartsWith,
759    Op::In,
760    Op::NotIn,
761    Op::Null,
762];
763const ORDERED_OPS: &[Op] = &[
764    Op::Eq,
765    Op::Ne,
766    Op::Gt,
767    Op::Gte,
768    Op::Lt,
769    Op::Lte,
770    Op::In,
771    Op::NotIn,
772    Op::Null,
773];
774const SET_OPS: &[Op] = &[Op::Eq, Op::Ne, Op::In, Op::NotIn, Op::Null];
775const BOOL_OPS: &[Op] = &[Op::Eq, Op::Ne, Op::Null];
776
777impl Kind {
778    /// The operators a field of this kind takes unless it says otherwise.
779    pub const fn default_ops(self) -> &'static [Op] {
780        match self {
781            Kind::Text => TEXT_OPS,
782            Kind::Int | Kind::Decimal | Kind::Date | Kind::DateTime => ORDERED_OPS,
783            Kind::Uuid | Kind::OneOf(_) => SET_OPS,
784            Kind::Bool => BOOL_OPS,
785        }
786    }
787
788    /// Whether `text` is a value of this kind.
789    pub fn check(self, text: &str) -> Result<(), String> {
790        let wrong = |what: &str| Err(format!("`{}` is not {what}", clip(text, 40)));
791        match self {
792            Kind::Text => Ok(()),
793            Kind::Int => match text.parse::<i64>() {
794                Ok(_) => Ok(()),
795                Err(_) => wrong("a whole number"),
796            },
797            Kind::Decimal => {
798                let digits = text.strip_prefix('-').unwrap_or(text);
799                let (whole, fraction) = digits.split_once('.').unwrap_or((digits, "0"));
800                let ok = !whole.is_empty()
801                    && !fraction.is_empty()
802                    && whole.len() + fraction.len() <= 38
803                    && whole
804                        .bytes()
805                        .chain(fraction.bytes())
806                        .all(|b| b.is_ascii_digit());
807                if ok {
808                    Ok(())
809                } else {
810                    wrong("a decimal number")
811                }
812            }
813            Kind::Bool => match text {
814                "true" | "false" => Ok(()),
815                _ => wrong("true or false"),
816            },
817            Kind::Date => {
818                if is_date(text) {
819                    Ok(())
820                } else {
821                    wrong("a date (YYYY-MM-DD)")
822                }
823            }
824            Kind::DateTime => {
825                if is_date(text) || chrono::DateTime::parse_from_rfc3339(text).is_ok() {
826                    Ok(())
827                } else {
828                    wrong("a date or a date and time (2026-11-05 or 2026-11-05T10:30:00Z)")
829                }
830            }
831            Kind::Uuid => {
832                if text.len() == 36 && uuid::Uuid::parse_str(text).is_ok() {
833                    Ok(())
834                } else {
835                    wrong("a UUID")
836                }
837            }
838            Kind::OneOf(words) => {
839                if words.contains(&text) {
840                    Ok(())
841                } else {
842                    Err(format!(
843                        "`{}` is not one of: {}",
844                        clip(text, 40),
845                        words.join(", ")
846                    ))
847                }
848            }
849        }
850    }
851}
852
853fn is_date(text: &str) -> bool {
854    text.len() == 10 && chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d").is_ok()
855}
856
857/// One field a list can be filtered by.
858#[derive(Clone, Copy, Debug, PartialEq, Eq)]
859pub struct Field {
860    /// The name in the query string.
861    pub name: &'static str,
862    /// What it holds.
863    pub kind: Kind,
864    /// The operators it takes; those of its kind when `None`.
865    pub ops: Option<&'static [Op]>,
866    /// The column or document field it reads, when that is not its name.
867    pub column: Option<&'static str>,
868    /// Whether the handler applies it (a computed filter such as
869    /// `due=overdue`): the query is checked as for any field, and
870    /// `Builder::list` leaves the condition to the handler.
871    pub by_app: bool,
872}
873
874impl Field {
875    /// A field of `kind`.
876    pub const fn new(name: &'static str, kind: Kind) -> Self {
877        Self {
878            name,
879            kind,
880            ops: None,
881            column: None,
882            by_app: false,
883        }
884    }
885
886    /// A text field.
887    pub const fn text(name: &'static str) -> Self {
888        Self::new(name, Kind::Text)
889    }
890
891    /// A whole-number field.
892    pub const fn int(name: &'static str) -> Self {
893        Self::new(name, Kind::Int)
894    }
895
896    /// A decimal field.
897    pub const fn decimal(name: &'static str) -> Self {
898        Self::new(name, Kind::Decimal)
899    }
900
901    /// A true-or-false field.
902    pub const fn boolean(name: &'static str) -> Self {
903        Self::new(name, Kind::Bool)
904    }
905
906    /// A date field.
907    pub const fn date(name: &'static str) -> Self {
908        Self::new(name, Kind::Date)
909    }
910
911    /// A date-and-time field.
912    pub const fn datetime(name: &'static str) -> Self {
913        Self::new(name, Kind::DateTime)
914    }
915
916    /// A UUID field.
917    pub const fn uuid(name: &'static str) -> Self {
918        Self::new(name, Kind::Uuid)
919    }
920
921    /// A field that holds one of `words`.
922    pub const fn one_of(name: &'static str, words: &'static [&'static str]) -> Self {
923        Self::new(name, Kind::OneOf(words))
924    }
925
926    /// Narrows (or widens) the operators the field takes.
927    pub const fn ops(mut self, ops: &'static [Op]) -> Self {
928        self.ops = Some(ops);
929        self
930    }
931
932    /// Reads the column `column` (`companies.name`) instead of a column named
933    /// like the field.
934    pub const fn column(mut self, column: &'static str) -> Self {
935        self.column = Some(column);
936        self
937    }
938
939    /// The handler applies the field, not `Builder::list`.
940    pub const fn by_app(mut self) -> Self {
941        self.by_app = true;
942        self
943    }
944
945    /// The operators the field takes.
946    pub const fn allowed_ops(&self) -> &'static [Op] {
947        match self.ops {
948            Some(ops) => ops,
949            None => self.kind.default_ops(),
950        }
951    }
952
953    /// The column the field reads.
954    pub const fn source(&self) -> &'static str {
955        match self.column {
956            Some(column) => column,
957            None => self.name,
958        }
959    }
960}
961
962/// Whether and how a list is searched.
963#[derive(Clone, Copy, Debug, PartialEq, Eq)]
964#[non_exhaustive]
965pub enum Search {
966    /// `search` is refused.
967    Off,
968    /// `search` matches text in any of these columns, ignoring case.
969    Columns(&'static [&'static str]),
970    /// `search` is accepted and the handler applies it (a search that
971    /// matches words, or several tables).
972    ByApp,
973}
974
975/// What a list allows in its query: the allow-list of one resource. Build it
976/// as a constant.
977#[derive(Clone, Copy, Debug, PartialEq, Eq)]
978pub struct ListSpec {
979    /// The fields that can be filtered.
980    pub fields: &'static [Field],
981    /// The fields that can be sorted by.
982    pub sorts: &'static [&'static str],
983    /// The sort when the query gives none (`-created_at`).
984    pub default_sort: &'static [&'static str],
985    /// Searching.
986    pub search: Search,
987    /// The page size when the query gives none.
988    pub default_per_page: u64,
989    /// The largest page size.
990    pub max_per_page: u64,
991    /// Whether `before` is accepted (a list that pages both ways by cursor).
992    pub two_way_cursors: bool,
993}
994
995impl ListSpec {
996    /// A list filterable by `fields`: no sorting, no search, pages of 15 up
997    /// to 100.
998    pub const fn new(fields: &'static [Field]) -> Self {
999        Self {
1000            fields,
1001            sorts: &[],
1002            default_sort: &[],
1003            search: Search::Off,
1004            default_per_page: 15,
1005            max_per_page: 100,
1006            two_way_cursors: false,
1007        }
1008    }
1009
1010    /// The fields the list can be sorted by.
1011    pub const fn sortable(mut self, sorts: &'static [&'static str]) -> Self {
1012        self.sorts = sorts;
1013        self
1014    }
1015
1016    /// The sort when the query gives none: field names, `-` in front for
1017    /// descending. The fields need not be sortable by the client.
1018    pub const fn default_sort(mut self, sorts: &'static [&'static str]) -> Self {
1019        self.default_sort = sorts;
1020        self
1021    }
1022
1023    /// `search` matches these columns.
1024    pub const fn searchable(mut self, columns: &'static [&'static str]) -> Self {
1025        self.search = Search::Columns(columns);
1026        self
1027    }
1028
1029    /// `search` is accepted, and the handler applies it.
1030    pub const fn searchable_by_app(mut self) -> Self {
1031        self.search = Search::ByApp;
1032        self
1033    }
1034
1035    /// The default and the largest page size.
1036    pub const fn page_size(mut self, default: u64, max: u64) -> Self {
1037        self.default_per_page = default;
1038        self.max_per_page = max;
1039        self
1040    }
1041
1042    /// Accepts `before`.
1043    pub const fn two_way_cursors(mut self) -> Self {
1044        self.two_way_cursors = true;
1045        self
1046    }
1047
1048    /// The filter field called `name`.
1049    pub fn field(&self, name: &str) -> Option<&'static Field> {
1050        self.fields.iter().find(|field| field.name == name)
1051    }
1052
1053    /// Reads `query` strictly: the list query's syntax, then this list's
1054    /// allow-list. A problem anywhere is an error naming every problem.
1055    pub fn parse(&self, query: &str) -> Result<ListQuery, ListError> {
1056        let (list, mut problems) = ListQuery::parse_lenient(query);
1057        problems.extend(self.check(&list));
1058        if problems.is_empty() {
1059            Ok(list)
1060        } else {
1061            Err(ListError { problems })
1062        }
1063    }
1064
1065    /// What in `list` this list does not allow.
1066    pub fn check(&self, list: &ListQuery) -> Vec<Problem> {
1067        let mut problems = Vec::new();
1068        for condition in &list.filter {
1069            let param = condition.param();
1070            let Some(field) = self.field(&condition.field) else {
1071                problems.push(Problem::new(
1072                    param,
1073                    format!(
1074                        "`{}` is not a filter of this list{}",
1075                        condition.field,
1076                        names(self.fields.iter().map(|field| field.name))
1077                    ),
1078                ));
1079                continue;
1080            };
1081            if !field.allowed_ops().contains(&condition.op) {
1082                let ops: Vec<&str> = field.allowed_ops().iter().map(|op| op.name()).collect();
1083                problems.push(Problem::new(
1084                    param,
1085                    format!(
1086                        "`{}` does not take `{}`; it takes: {}",
1087                        field.name,
1088                        condition.op,
1089                        ops.join(", ")
1090                    ),
1091                ));
1092                continue;
1093            }
1094            if condition.op == Op::Null {
1095                continue;
1096            }
1097            if condition.op == Op::StartsWith
1098                && condition
1099                    .values
1100                    .iter()
1101                    .any(|v| v.contains(['%', '_', '\\']))
1102            {
1103                problems.push(Problem::new(
1104                    param,
1105                    "a starts_with value cannot contain %, _ or a backslash",
1106                ));
1107                continue;
1108            }
1109            for value in &condition.values {
1110                if let Err(message) = field.kind.check(value) {
1111                    problems.push(Problem::new(param.clone(), message));
1112                    break;
1113                }
1114            }
1115        }
1116        for key in &list.sort {
1117            if !self.sorts.contains(&key.field.as_str()) {
1118                problems.push(Problem::new(
1119                    "sort",
1120                    format!(
1121                        "`{}` is not a sort of this list{}",
1122                        key.field,
1123                        names(self.sorts.iter().copied())
1124                    ),
1125                ));
1126            }
1127        }
1128        if list.search.is_some() && self.search == Search::Off {
1129            problems.push(Problem::new("search", "this list cannot be searched"));
1130        }
1131        for (param, size) in [("per_page", list.per_page), ("limit", list.limit)] {
1132            if let Some(size) = size.filter(|size| *size > self.max_per_page) {
1133                problems.push(Problem::new(
1134                    param,
1135                    format!("{param} must not exceed {} (got {size})", self.max_per_page),
1136                ));
1137            }
1138        }
1139        if list.before.is_some() && !self.two_way_cursors {
1140            problems.push(Problem::new("before", "this list pages forward only"));
1141        }
1142        problems
1143    }
1144
1145    /// How `list` pages, the page size defaulted.
1146    pub fn paging(&self, list: &ListQuery) -> Paging {
1147        if list.is_cursor() {
1148            Paging::Cursor {
1149                cursor: list.cursor.clone(),
1150                before: list.before.clone(),
1151                limit: list.limit.unwrap_or(self.default_per_page),
1152            }
1153        } else {
1154            Paging::Pages {
1155                page: list.page.unwrap_or(1),
1156                per_page: list.per_page.unwrap_or(self.default_per_page),
1157            }
1158        }
1159    }
1160
1161    /// The sort to apply: the query's, else the list's default.
1162    pub fn sort_of(&self, list: &ListQuery) -> Vec<SortKey> {
1163        if !list.sort.is_empty() {
1164            return list.sort.clone();
1165        }
1166        self.default_sort
1167            .iter()
1168            .map(|term| {
1169                term.strip_prefix('-').map_or_else(
1170                    || SortKey {
1171                        field: (*term).to_owned(),
1172                        descending: false,
1173                    },
1174                    |field| SortKey {
1175                        field: field.to_owned(),
1176                        descending: true,
1177                    },
1178                )
1179            })
1180            .collect()
1181    }
1182}
1183
1184/// `; use one of: a, b` for a non-empty list of names.
1185fn names<'a>(names: impl Iterator<Item = &'a str>) -> String {
1186    let names: Vec<&str> = names.collect();
1187    if names.is_empty() {
1188        String::new()
1189    } else {
1190        format!("; use one of: {}", names.join(", "))
1191    }
1192}
1193
1194/// A query a list does not allow: every [`Problem`] found. It converts into
1195/// a 400 [`AppError`] that names each parameter (`?` in a handler does it).
1196/// It is not a `std::error::Error`, like `AppError`, so the conversion is
1197/// not the 500 every other error becomes.
1198#[derive(Clone, Debug, PartialEq, Eq)]
1199pub struct ListError {
1200    /// The problems, in the order found. Never empty.
1201    pub problems: Vec<Problem>,
1202}
1203
1204impl fmt::Display for ListError {
1205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1206        for (at, problem) in self.problems.iter().enumerate() {
1207            if at > 0 {
1208                f.write_str("; ")?;
1209            }
1210            write!(f, "{}: {}", problem.param, problem.message)?;
1211        }
1212        Ok(())
1213    }
1214}
1215
1216impl From<ListError> for AppError {
1217    /// A 400 whose `errors` map each parameter to its messages.
1218    fn from(error: ListError) -> Self {
1219        let mut errors: BTreeMap<String, Vec<String>> = BTreeMap::new();
1220        for problem in error.problems {
1221            errors
1222                .entry(problem.param)
1223                .or_default()
1224                .push(problem.message);
1225        }
1226        AppError::validation(errors)
1227    }
1228}
1229
1230// ---- The extractor -----------------------------------------------------------------
1231
1232/// A resource that is listed: its [`ListSpec`].
1233pub trait ListResource {
1234    /// What the list allows in its query.
1235    const SPEC: ListSpec;
1236}
1237
1238/// The list query of a request, read strictly against `R`'s [`ListSpec`]: a
1239/// handler that takes `List<Deals>` gets a query it can trust, or the request
1240/// ends in a 400 that names the parameter.
1241///
1242/// ```
1243/// use navree_http::list::{Field, List, ListResource, ListSpec};
1244///
1245/// struct Deals;
1246///
1247/// impl ListResource for Deals {
1248///     const SPEC: ListSpec = ListSpec::new(&[Field::int("amount_cents")]);
1249/// }
1250///
1251/// async fn index(list: List<Deals>) -> String {
1252///     format!("{} filters", list.filter.len())
1253/// }
1254/// # let _ = index;
1255/// ```
1256pub struct List<R>(pub ListQuery, PhantomData<fn() -> R>);
1257
1258impl<R> List<R> {
1259    /// The query.
1260    pub fn into_inner(self) -> ListQuery {
1261        self.0
1262    }
1263}
1264
1265impl<R> Deref for List<R> {
1266    type Target = ListQuery;
1267
1268    fn deref(&self) -> &ListQuery {
1269        &self.0
1270    }
1271}
1272
1273impl<R> Clone for List<R> {
1274    fn clone(&self) -> Self {
1275        List(self.0.clone(), PhantomData)
1276    }
1277}
1278
1279impl<R> fmt::Debug for List<R> {
1280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1281        f.debug_tuple("List").field(&self.0).finish()
1282    }
1283}
1284
1285impl<R: ListResource> List<R> {
1286    /// Reads `uri`'s query string against `R`.
1287    pub fn from_uri(uri: &http::Uri) -> Result<Self, ListError> {
1288        R::SPEC
1289            .parse(uri.query().unwrap_or_default())
1290            .map(|query| List(query, PhantomData))
1291    }
1292}
1293
1294impl<R: ListResource> FromRequestParts for List<R> {
1295    type Rejection = AppError;
1296
1297    async fn from_request_parts(parts: &mut Parts) -> Result<Self, AppError> {
1298        Self::from_uri(&parts.uri).map_err(AppError::from)
1299    }
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304    use super::*;
1305
1306    struct Deals;
1307
1308    impl ListResource for Deals {
1309        const SPEC: ListSpec = ListSpec::new(&[
1310            Field::one_of("stage", &["lead", "won", "lost"]),
1311            Field::int("amount_cents"),
1312            Field::decimal("rate"),
1313            Field::boolean("hot"),
1314            Field::date("closes_on"),
1315            Field::datetime("created_at"),
1316            Field::uuid("owner_id"),
1317            Field::text("title"),
1318            Field::text("company_name").column("companies.name"),
1319            Field::text("code").ops(&[Op::Eq]),
1320        ])
1321        .sortable(&["amount_cents", "created_at", "title"])
1322        .default_sort(&["-created_at"])
1323        .searchable(&["title"])
1324        .page_size(15, 100);
1325    }
1326
1327    fn strict(query: &str) -> Result<ListQuery, ListError> {
1328        Deals::SPEC.parse(query)
1329    }
1330
1331    fn params(error: ListError) -> Vec<String> {
1332        error.problems.into_iter().map(|p| p.param).collect()
1333    }
1334
1335    #[test]
1336    fn a_fields_conditions_are_read_together_and_read_back_as_themselves() {
1337        let (query, problems) =
1338            ListQuery::parse_lenient("filter[a]=x&filter[b]=%&filter[a][ne]=0&filter[b][gt]=1");
1339        assert!(problems.is_empty(), "{problems:?}");
1340        let order: Vec<(&str, Op)> = query
1341            .filter
1342            .iter()
1343            .map(|c| (c.field.as_str(), c.op))
1344            .collect();
1345        assert_eq!(
1346            order,
1347            [("a", Op::Eq), ("a", Op::Ne), ("b", Op::Eq), ("b", Op::Gt)]
1348        );
1349        let (again, _) = ListQuery::parse_lenient(&query.to_query_string());
1350        assert_eq!(again, query);
1351    }
1352
1353    #[test]
1354    fn reads_every_part() {
1355        let list = strict(
1356            "filter[stage][in]=lead,won&filter[amount_cents][gte]=1000&filter[hot]=true\
1357             &filter[owner_id][null]=false&sort=-amount_cents,title&search=Sutlej&page=3&per_page=50",
1358        )
1359        .unwrap();
1360        assert_eq!(list.filter.len(), 4);
1361        assert_eq!(list.filter[0].op, Op::In);
1362        assert_eq!(list.filter[0].values, ["lead", "won"]);
1363        assert_eq!(list.filter[1].field, "amount_cents");
1364        assert_eq!(list.filter[1].op, Op::Gte);
1365        assert_eq!(list.eq("hot"), Some("true"));
1366        assert_eq!(list.filter[3].null_flag(), Some(false));
1367        assert_eq!(list.sort[0].term(), "-amount_cents");
1368        assert_eq!(list.search.as_deref(), Some("Sutlej"));
1369        assert_eq!(
1370            Deals::SPEC.paging(&list),
1371            Paging::Pages {
1372                page: 3,
1373                per_page: 50
1374            }
1375        );
1376    }
1377
1378    #[test]
1379    fn an_empty_query_is_an_empty_list() {
1380        let list = strict("").unwrap();
1381        assert_eq!(list, ListQuery::default());
1382        assert_eq!(
1383            Deals::SPEC.paging(&list),
1384            Paging::Pages {
1385                page: 1,
1386                per_page: 15
1387            }
1388        );
1389        assert_eq!(Deals::SPEC.sort_of(&list)[0].term(), "-created_at");
1390    }
1391
1392    #[test]
1393    fn cursor_pages_default_their_size() {
1394        let list = strict("cursor=abc").unwrap();
1395        assert_eq!(
1396            Deals::SPEC.paging(&list),
1397            Paging::Cursor {
1398                cursor: Some("abc".to_owned()),
1399                before: None,
1400                limit: 15
1401            }
1402        );
1403        let list = strict("limit=20").unwrap();
1404        assert!(list.is_cursor());
1405    }
1406
1407    #[test]
1408    fn a_field_outside_the_allow_list_is_named() {
1409        let error = strict("filter[password][contains]=x&filter[stage]=won").unwrap_err();
1410        assert_eq!(error.problems.len(), 1);
1411        assert_eq!(error.problems[0].param, "filter[password][contains]");
1412        assert!(
1413            error.problems[0].message.contains("use one of: stage"),
1414            "{error}"
1415        );
1416    }
1417
1418    #[test]
1419    fn an_operator_the_field_does_not_take_is_refused() {
1420        assert_eq!(
1421            params(strict("filter[hot][gte]=true").unwrap_err()),
1422            ["filter[hot][gte]"]
1423        );
1424        assert_eq!(
1425            params(strict("filter[code][contains]=x").unwrap_err()),
1426            ["filter[code][contains]"]
1427        );
1428        assert_eq!(
1429            params(strict("filter[stage][starts_with]=l").unwrap_err()),
1430            ["filter[stage][starts_with]"]
1431        );
1432        assert!(strict("filter[title][starts_with]=Su").is_ok());
1433        // A prefix is matched with LIKE, so its wildcards are not allowed.
1434        assert!(strict("filter[title][starts_with]=Su%25").is_err());
1435        assert!(strict("filter[title][starts_with]=S_").is_err());
1436        assert!(strict("filter[closes_on][lte]=2026-11-05").is_ok());
1437    }
1438
1439    #[test]
1440    fn values_are_checked_against_the_kind() {
1441        for (query, param) in [
1442            ("filter[amount_cents]=1.5", "filter[amount_cents]"),
1443            ("filter[amount_cents][in]=1,x", "filter[amount_cents][in]"),
1444            ("filter[rate]=1e5", "filter[rate]"),
1445            ("filter[rate]=.5", "filter[rate]"),
1446            ("filter[hot]=yes", "filter[hot]"),
1447            ("filter[closes_on]=2026-13-01", "filter[closes_on]"),
1448            ("filter[closes_on]=2026-1-1", "filter[closes_on]"),
1449            (
1450                "filter[created_at][gte]=yesterday",
1451                "filter[created_at][gte]",
1452            ),
1453            ("filter[owner_id]=not-a-uuid", "filter[owner_id]"),
1454            (
1455                "filter[owner_id]=00000000000000000000000000000000",
1456                "filter[owner_id]",
1457            ),
1458            ("filter[stage]=won,lost", "filter[stage]"),
1459            ("filter[stage]=archived", "filter[stage]"),
1460        ] {
1461            assert_eq!(params(strict(query).unwrap_err()), [param], "{query}");
1462        }
1463        for query in [
1464            "filter[amount_cents]=-5",
1465            "filter[rate]=-12.50",
1466            "filter[hot]=false",
1467            "filter[closes_on]=2026-02-28",
1468            "filter[created_at][lt]=2026-11-05T10:30:00%2B05:30",
1469            "filter[created_at][lt]=2026-11-05",
1470            "filter[owner_id]=0190a5c4-7d2e-7c3a-9d1e-0f4b6a7c8d9e",
1471            "filter[stage][in]=lead,won",
1472        ] {
1473            assert!(strict(query).is_ok(), "{query}");
1474        }
1475    }
1476
1477    #[test]
1478    fn sorts_search_and_page_sizes_are_limited() {
1479        assert_eq!(params(strict("sort=password").unwrap_err()), ["sort"]);
1480        assert_eq!(params(strict("per_page=101").unwrap_err()), ["per_page"]);
1481        assert_eq!(params(strict("limit=101").unwrap_err()), ["limit"]);
1482        assert_eq!(params(strict("before=abc").unwrap_err()), ["before"]);
1483        assert!(strict("per_page=100").is_ok());
1484        struct Quiet;
1485        impl ListResource for Quiet {
1486            const SPEC: ListSpec = ListSpec::new(&[]);
1487        }
1488        assert_eq!(
1489            params(Quiet::SPEC.parse("search=x").unwrap_err()),
1490            ["search"]
1491        );
1492    }
1493
1494    #[test]
1495    fn every_problem_is_reported_at_once() {
1496        let error = strict("filter[x]=1&sort=y&page=0&filter[hot]=maybe").unwrap_err();
1497        assert_eq!(params(error), ["page", "filter[x]", "filter[hot]", "sort"]);
1498    }
1499
1500    #[test]
1501    fn problems_become_a_400_naming_the_parameters() {
1502        let error = AppError::from(strict("filter[x]=1&page=0").unwrap_err());
1503        assert_eq!(error.status.as_u16(), 400);
1504        let errors = error.errors.unwrap();
1505        assert!(errors.contains_key("filter[x]"));
1506        assert!(errors.contains_key("page"));
1507    }
1508
1509    #[test]
1510    fn the_extractor_reads_the_uri() {
1511        let uri: http::Uri = "/deals?filter[stage]=won&page=2".parse().unwrap();
1512        let list = List::<Deals>::from_uri(&uri).unwrap();
1513        assert_eq!(list.eq("stage"), Some("won"));
1514        assert_eq!(list.page, Some(2));
1515        let uri: http::Uri = "/deals?filter[nope]=1".parse().unwrap();
1516        assert!(List::<Deals>::from_uri(&uri).is_err());
1517    }
1518
1519    #[test]
1520    fn the_query_string_round_trips() {
1521        let text = "filter%5Bstage%5D%5Bin%5D=lead%2Cwon&filter%5Bamount_cents%5D%5Bgte%5D=100&sort=-title&search=Sutlej+Supply&page=2&per_page=25";
1522        let (list, problems) = ListQuery::parse_lenient(text);
1523        assert!(problems.is_empty());
1524        let (again, _) = ListQuery::parse_lenient(&list.to_query_string());
1525        assert_eq!(list, again);
1526        assert_eq!(list.clone().on_page(1).page, None);
1527        assert_eq!(list.on_page(3).page, Some(3));
1528    }
1529
1530    #[test]
1531    fn a_query_string_may_start_with_a_question_mark() {
1532        let (list, problems) = ListQuery::parse_lenient("?search=a");
1533        assert!(problems.is_empty());
1534        assert_eq!(list.search.as_deref(), Some("a"));
1535    }
1536
1537    #[test]
1538    fn the_whole_query_is_clipped_not_trusted() {
1539        let long = format!("search={}", "a".repeat(MAX_QUERY_BYTES * 2));
1540        let (list, problems) = ListQuery::parse_lenient(&long);
1541        assert!(problems.iter().any(|p| p.param == "query"));
1542        assert!(list.search.is_none() || list.search.as_ref().unwrap().len() <= MAX_TEXT);
1543    }
1544
1545    #[test]
1546    fn search_is_cut_on_a_character_boundary() {
1547        let text = "ਪ".repeat(200);
1548        let (list, problems) = ListQuery::parse_lenient(&format!("search={text}"));
1549        assert_eq!(problems.len(), 1);
1550        let search = list.search.unwrap();
1551        assert!(search.len() <= MAX_TEXT);
1552        assert!(search.chars().all(|c| c == 'ਪ'));
1553    }
1554
1555    #[test]
1556    fn the_numbers_of_conditions_and_values_are_capped() {
1557        let many: String = (0..MAX_CONDITIONS + 10)
1558            .map(|n| format!("filter[f{n}]=1"))
1559            .collect::<Vec<_>>()
1560            .join("&");
1561        let (list, problems) = ListQuery::parse_lenient(&many);
1562        assert_eq!(list.filter.len(), MAX_CONDITIONS);
1563        assert!(problems.iter().any(|p| p.param == "filter"));
1564
1565        let values: String = (0..MAX_VALUES + 50)
1566            .map(|n| n.to_string())
1567            .collect::<Vec<_>>()
1568            .join(",");
1569        let (list, problems) = ListQuery::parse_lenient(&format!("filter[id][in]={values}"));
1570        assert_eq!(list.filter[0].values.len(), MAX_VALUES);
1571        assert_eq!(problems.len(), 1);
1572    }
1573
1574    #[test]
1575    fn many_parameters_stop_the_read() {
1576        let many: String = (0..MAX_PARAMS + 5)
1577            .map(|n| format!("x{n}=1"))
1578            .collect::<Vec<_>>()
1579            .join("&");
1580        let (_, problems) = ListQuery::parse_lenient(&many);
1581        assert!(problems.iter().any(|p| p.param == "query"));
1582    }
1583
1584    #[test]
1585    fn encoding_matches_url_search_params() {
1586        assert_eq!(encode_component("a b"), "a+b");
1587        assert_eq!(encode_component("a~b"), "a%7Eb");
1588        assert_eq!(encode_component("a*b-c.d_e"), "a*b-c.d_e");
1589        assert_eq!(encode_component("ਪ"), "%E0%A8%AA");
1590        assert_eq!(encode_component("a,b[c]"), "a%2Cb%5Bc%5D");
1591    }
1592
1593    #[test]
1594    fn operators_know_their_names() {
1595        for op in Op::ALL {
1596            assert_eq!(Op::parse(op.name()), Some(op));
1597        }
1598        assert_eq!(Op::parse("GTE"), None);
1599        assert_eq!(Op::parse(""), None);
1600    }
1601}