1use 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
80pub const MAX_QUERY_BYTES: usize = 16 * 1024;
82pub const MAX_PARAMS: usize = 1000;
84pub const MAX_CONDITIONS: usize = 64;
86pub const MAX_VALUES: usize = 200;
88pub const MAX_TEXT: usize = 256;
90pub const MAX_CURSOR: usize = 1024;
92pub const MAX_SORTS: usize = 4;
94pub const MAX_FIELD: usize = 64;
96pub const MAX_PAGE: u64 = 10_000_000;
98pub const MAX_PAGE_SIZE: u64 = 10_000;
100
101#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
103#[non_exhaustive]
104pub enum Op {
105 Eq,
107 Ne,
109 Gt,
111 Gte,
113 Lt,
115 Lte,
117 In,
119 NotIn,
121 Contains,
123 StartsWith,
125 Null,
127}
128
129impl Op {
130 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 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 pub fn parse(name: &str) -> Option<Op> {
164 Op::ALL.into_iter().find(|op| op.name() == name)
165 }
166
167 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#[derive(Clone, Debug, PartialEq, Eq)]
182pub struct Condition {
183 pub field: String,
185 pub op: Op,
187 pub values: Vec<String>,
189}
190
191impl Condition {
192 pub fn param(&self) -> String {
195 param_of(&self.field, self.op)
196 }
197
198 pub fn value(&self) -> &str {
200 self.values.first().map_or("", String::as_str)
201 }
202
203 pub fn null_flag(&self) -> Option<bool> {
205 (self.op == Op::Null).then(|| self.value() == "true")
206 }
207}
208
209fn 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#[derive(Clone, Debug, PartialEq, Eq)]
220pub struct SortKey {
221 pub field: String,
223 pub descending: bool,
225}
226
227impl SortKey {
228 pub fn term(&self) -> String {
230 if self.descending {
231 format!("-{}", self.field)
232 } else {
233 self.field.clone()
234 }
235 }
236}
237
238#[derive(Clone, Debug, PartialEq, Eq)]
241pub struct Problem {
242 pub param: String,
244 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
259pub struct ListQuery {
260 pub filter: Vec<Condition>,
262 pub sort: Vec<SortKey>,
264 pub search: Option<String>,
266 pub page: Option<u64>,
268 pub per_page: Option<u64>,
270 pub cursor: Option<String>,
273 pub before: Option<String>,
275 pub limit: Option<u64>,
277}
278
279#[derive(Clone, Debug, PartialEq, Eq)]
281pub enum Paging {
282 Pages {
284 page: u64,
286 per_page: u64,
288 },
289 Cursor {
291 cursor: Option<String>,
293 before: Option<String>,
295 limit: u64,
297 },
298}
299
300impl ListQuery {
301 pub fn new() -> Self {
303 Self::default()
304 }
305
306 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 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 pub fn eq(&self, field: &str) -> Option<&str> {
334 self.condition(field, Op::Eq).map(Condition::value)
335 }
336
337 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 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 pub fn is_cursor(&self) -> bool {
397 self.cursor.is_some() || self.before.is_some() || self.limit.is_some()
398 }
399}
400
401fn 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
413pub 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
443fn 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
452fn 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
464fn 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
480fn 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#[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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
734#[non_exhaustive]
735pub enum Kind {
736 Text,
738 Int,
740 Decimal,
742 Bool,
744 Date,
746 DateTime,
748 Uuid,
750 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
859pub struct Field {
860 pub name: &'static str,
862 pub kind: Kind,
864 pub ops: Option<&'static [Op]>,
866 pub column: Option<&'static str>,
868 pub by_app: bool,
872}
873
874impl Field {
875 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 pub const fn text(name: &'static str) -> Self {
888 Self::new(name, Kind::Text)
889 }
890
891 pub const fn int(name: &'static str) -> Self {
893 Self::new(name, Kind::Int)
894 }
895
896 pub const fn decimal(name: &'static str) -> Self {
898 Self::new(name, Kind::Decimal)
899 }
900
901 pub const fn boolean(name: &'static str) -> Self {
903 Self::new(name, Kind::Bool)
904 }
905
906 pub const fn date(name: &'static str) -> Self {
908 Self::new(name, Kind::Date)
909 }
910
911 pub const fn datetime(name: &'static str) -> Self {
913 Self::new(name, Kind::DateTime)
914 }
915
916 pub const fn uuid(name: &'static str) -> Self {
918 Self::new(name, Kind::Uuid)
919 }
920
921 pub const fn one_of(name: &'static str, words: &'static [&'static str]) -> Self {
923 Self::new(name, Kind::OneOf(words))
924 }
925
926 pub const fn ops(mut self, ops: &'static [Op]) -> Self {
928 self.ops = Some(ops);
929 self
930 }
931
932 pub const fn column(mut self, column: &'static str) -> Self {
935 self.column = Some(column);
936 self
937 }
938
939 pub const fn by_app(mut self) -> Self {
941 self.by_app = true;
942 self
943 }
944
945 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 pub const fn source(&self) -> &'static str {
955 match self.column {
956 Some(column) => column,
957 None => self.name,
958 }
959 }
960}
961
962#[derive(Clone, Copy, Debug, PartialEq, Eq)]
964#[non_exhaustive]
965pub enum Search {
966 Off,
968 Columns(&'static [&'static str]),
970 ByApp,
973}
974
975#[derive(Clone, Copy, Debug, PartialEq, Eq)]
978pub struct ListSpec {
979 pub fields: &'static [Field],
981 pub sorts: &'static [&'static str],
983 pub default_sort: &'static [&'static str],
985 pub search: Search,
987 pub default_per_page: u64,
989 pub max_per_page: u64,
991 pub two_way_cursors: bool,
993}
994
995impl ListSpec {
996 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 pub const fn sortable(mut self, sorts: &'static [&'static str]) -> Self {
1012 self.sorts = sorts;
1013 self
1014 }
1015
1016 pub const fn default_sort(mut self, sorts: &'static [&'static str]) -> Self {
1019 self.default_sort = sorts;
1020 self
1021 }
1022
1023 pub const fn searchable(mut self, columns: &'static [&'static str]) -> Self {
1025 self.search = Search::Columns(columns);
1026 self
1027 }
1028
1029 pub const fn searchable_by_app(mut self) -> Self {
1031 self.search = Search::ByApp;
1032 self
1033 }
1034
1035 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 pub const fn two_way_cursors(mut self) -> Self {
1044 self.two_way_cursors = true;
1045 self
1046 }
1047
1048 pub fn field(&self, name: &str) -> Option<&'static Field> {
1050 self.fields.iter().find(|field| field.name == name)
1051 }
1052
1053 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 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 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 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
1184fn 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#[derive(Clone, Debug, PartialEq, Eq)]
1199pub struct ListError {
1200 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 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
1230pub trait ListResource {
1234 const SPEC: ListSpec;
1236}
1237
1238pub struct List<R>(pub ListQuery, PhantomData<fn() -> R>);
1257
1258impl<R> List<R> {
1259 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 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 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}