use std::collections::BTreeMap;
use serde_json::Value;
use super::semantics::{matches_filters, sort_resources};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Selection {
pub filters: BTreeMap<String, String>,
pub sort: Option<String>,
pub offset: usize,
pub limit: Option<usize>,
pub after: Option<String>,
pub before: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Matched {
pub items: Vec<Value>,
pub total: usize,
}
impl Matched {
#[must_use]
pub fn new(items: Vec<Value>, total: usize) -> Self {
Self { items, total }
}
#[must_use]
pub fn complete(items: Vec<Value>) -> Self {
Self {
total: items.len(),
items,
}
}
}
impl Selection {
pub fn from_query(query: &BTreeMap<String, String>) -> Result<Self, String> {
fn number(query: &BTreeMap<String, String>, name: &str) -> Result<Option<usize>, String> {
let Some(raw) = query.get(name) else {
return Ok(None);
};
raw.parse()
.map(Some)
.map_err(|_| format!("`{name}` must be a non-negative integer, not {raw:?}"))
}
Ok(Self {
filters: query
.iter()
.filter(|(key, _)| !super::semantics::is_reserved(key))
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
sort: query.get("sort").cloned(),
offset: number(query, "offset")?.unwrap_or(0),
limit: number(query, "limit")?,
after: query.get("after").cloned(),
before: query.get("before").cloned(),
})
}
#[must_use]
pub fn capped_at(mut self, max: usize) -> Self {
self.limit = Some(self.limit.map_or(max, |limit| limit.min(max)));
self
}
#[must_use]
pub fn apply(&self, resources: Vec<Value>) -> Matched {
let mut kept: Vec<Value> = resources
.into_iter()
.filter(|resource| matches_filters(resource, &self.filters))
.collect();
if let Some(sort) = &self.sort {
sort_resources(&mut kept, sort);
}
if self.after.is_some() || self.before.is_some() {
let start = match &self.after {
Some(cursor) => match position_of(&kept, cursor) {
Some(index) => index + 1,
None => kept.len(),
},
None => 0,
};
let end = match &self.before {
Some(cursor) => position_of(&kept, cursor).unwrap_or(0),
None => kept.len(),
};
kept = kept
.into_iter()
.take(end.max(start))
.skip(start)
.collect::<Vec<_>>();
}
let total = kept.len();
let items = kept
.into_iter()
.skip(self.offset)
.take(self.limit.unwrap_or(usize::MAX))
.collect();
Matched { items, total }
}
}
fn position_of(resources: &[Value], cursor: &str) -> Option<usize> {
resources
.iter()
.position(|resource| resource.get("id").and_then(Value::as_str) == Some(cursor))
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum StoreError {
#[error("accepted for asynchronous processing")]
Accepted {
monitor: Option<String>,
},
#[error("{0}")]
Invalid(String),
#[error("{0}")]
Unprocessable(String),
#[error("{0}")]
Conflict(String),
#[error("{0}")]
Forbidden(String),
#[error("{0}")]
Internal(String),
}
pub type StoreResult<T> = std::result::Result<T, StoreError>;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Replaced {
Updated(Value),
Missing,
Stale,
}
#[async_trait::async_trait]
pub trait ResourceStore: Send + Sync {
async fn list(&self, collection: &str, selection: &Selection) -> StoreResult<Matched>;
async fn get(&self, collection: &str, id: &str) -> StoreResult<Option<Value>>;
async fn create(&self, collection: &str, resource: Value) -> StoreResult<Value>;
async fn replace(
&self,
collection: &str,
id: &str,
resource: Value,
) -> StoreResult<Option<Value>>;
async fn delete(&self, collection: &str, id: &str) -> StoreResult<bool>;
async fn replace_if_unchanged(
&self,
collection: &str,
id: &str,
resource: Value,
expected_tag: &str,
) -> StoreResult<Replaced> {
match self.get(collection, id).await? {
None => Ok(Replaced::Missing),
Some(current) if super::entity_tag(¤t) != expected_tag => Ok(Replaced::Stale),
Some(_) => Ok(self
.replace(collection, id, resource)
.await?
.map_or(Replaced::Missing, Replaced::Updated)),
}
}
async fn delete_if_unchanged(
&self,
collection: &str,
id: &str,
expected_tag: &str,
) -> StoreResult<Replaced> {
match self.get(collection, id).await? {
None => Ok(Replaced::Missing),
Some(current) if super::entity_tag(¤t) != expected_tag => Ok(Replaced::Stale),
Some(current) => {
if self.delete(collection, id).await? {
Ok(Replaced::Updated(current))
} else {
Ok(Replaced::Missing)
}
}
}
}
async fn has_collection(&self, collection: &str) -> bool {
let _ = collection;
true
}
}
#[cfg(test)]
mod tests {
use super::*;
fn query(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect()
}
#[test]
fn reserved_parameters_are_not_filters() {
let selection = Selection::from_query(&query(&[
("fields", "id,name"),
("sort", "-name"),
("offset", "10"),
("limit", "5"),
("lifecycleStatus", "Active"),
]))
.expect("well-formed paging parameters");
assert_eq!(selection.filters, query(&[("lifecycleStatus", "Active")]));
assert_eq!(selection.sort.as_deref(), Some("-name"));
assert_eq!(selection.offset, 10);
assert_eq!(selection.limit, Some(5));
}
#[test]
fn total_counts_matches_not_the_page() {
let resources = (0..10)
.map(|i| serde_json::json!({"id": i.to_string(), "state": "active"}))
.collect();
let matched = Selection::from_query(&query(&[("state", "active"), ("limit", "3")]))
.expect("well-formed")
.apply(resources);
assert_eq!(matched.items.len(), 3);
assert_eq!(matched.total, 10);
}
#[test]
fn an_absent_limit_returns_everything_after_the_offset() {
let resources = (0..5)
.map(|i| serde_json::json!({"id": i.to_string()}))
.collect();
let matched = Selection::from_query(&query(&[("offset", "2")]))
.expect("well-formed")
.apply(resources);
assert_eq!(matched.items.len(), 3);
assert_eq!(matched.total, 5);
}
#[test]
fn filtering_happens_before_paging() {
let resources = (0..10)
.map(|i| serde_json::json!({"id": i.to_string(), "odd": i % 2 == 1}))
.collect();
let matched = Selection::from_query(&query(&[("odd", "true"), ("limit", "2")]))
.expect("well-formed")
.apply(resources);
assert_eq!(matched.total, 5);
assert_eq!(matched.items.len(), 2);
assert_eq!(matched.items[0]["id"], "1");
}
}
#[cfg(test)]
mod cursor_tests {
use super::*;
use std::collections::BTreeMap;
fn resources() -> Vec<Value> {
(1..=5)
.map(|n| serde_json::json!({"id": n.to_string(), "name": format!("r{n}")}))
.collect()
}
fn select(pairs: &[(&str, &str)]) -> Selection {
let query: BTreeMap<String, String> = pairs
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect();
Selection::from_query(&query).expect("well-formed")
}
fn ids(matched: &Matched) -> Vec<&str> {
matched
.items
.iter()
.filter_map(|item| item.get("id").and_then(Value::as_str))
.collect()
}
#[test]
fn after_starts_from_the_resource_following_the_cursor() {
let matched = select(&[("after", "2")]).apply(resources());
assert_eq!(ids(&matched), ["3", "4", "5"]);
assert_eq!(matched.total, 3);
}
#[test]
fn before_stops_at_the_resource_preceding_the_cursor() {
let matched = select(&[("before", "4")]).apply(resources());
assert_eq!(ids(&matched), ["1", "2", "3"]);
}
#[test]
fn the_two_cursors_bound_a_window() {
let matched = select(&[("after", "1"), ("before", "5")]).apply(resources());
assert_eq!(ids(&matched), ["2", "3", "4"]);
}
#[test]
fn an_unknown_cursor_selects_nothing() {
assert!(
select(&[("after", "nope")])
.apply(resources())
.items
.is_empty()
);
assert!(
select(&[("before", "nope")])
.apply(resources())
.items
.is_empty()
);
}
#[test]
fn a_cursor_is_not_mistaken_for_an_attribute_filter() {
let selection = select(&[("after", "2"), ("before", "5"), ("filter", "$[*]")]);
assert!(selection.filters.is_empty());
}
#[test]
fn cursors_compose_with_limit() {
let matched = select(&[("after", "1"), ("limit", "2")]).apply(resources());
assert_eq!(ids(&matched), ["2", "3"]);
assert_eq!(matched.total, 4);
}
}