use async_graphql::{EmptyMutation, EmptySubscription, InputType, Name, Object, Schema, Value};
use super::{Connection, PageArgument, PageError, PageRequest};
use crate::{
Cursor, CursorValue, ErrorCode, FieldName, OrderDirection, OrderTerm, Orderings, SubjectPath,
TermName, ToSubjectPath,
query::{DEFAULT_PAGE_SIZE, Edge, MAX_PAGE_SIZE, Page},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::OneofObject)]
enum CueOrderBy {
Title(OrderDirection),
}
impl ToSubjectPath for CueOrderBy {
fn subject_path(&self) -> SubjectPath {
const SUBJECT: SubjectPath = SubjectPath::new(&[TermName::new("title")]);
SUBJECT
}
}
const ORDER: &[OrderTerm] = &[OrderTerm::new(
TermName::new("title"),
FieldName::new("title"),
OrderDirection::Asc,
)];
#[derive(Debug, Clone, PartialEq, Eq)]
enum CueCursor {
Title(String),
}
impl CursorValue for CueCursor {
fn write_cursor(&self, out: &mut Vec<u8>) {
match self {
Self::Title(title) => {
out.push(0);
title.write_cursor(out);
}
}
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
let (tag, rest) = bytes.split_first()?;
match *tag {
0 => String::read_cursor(rest).map(Self::Title),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Cue {
title: String,
}
struct CueOutput {
title: String,
}
#[Object(name = "Cue")]
impl CueOutput {
async fn title(&self) -> &str {
&self.title
}
}
const CUES: &[&str] = &["alpha", "beta", "delta", "epsilon", "gamma"];
fn page(request: &PageRequest<CueCursor>) -> Page<Cue, CueCursor> {
let at = request.position().map(|cursor| {
let values = cursor
.resume(ORDER)
.expect("the fixture mints every cursor under this order");
match values[0].clone() {
Some(CueCursor::Title(title)) => title,
None => unreachable!("`title` is NOT NULL in this fixture"),
}
});
let size = request.size() as usize;
let (rows, has_next, has_previous) = if request.is_forward() {
let rest: Vec<&str> = CUES
.iter()
.copied()
.filter(|title| at.as_deref().is_none_or(|at| *title > at))
.collect();
let has_previous = rest.len() != CUES.len();
let has_next = rest.len() > size;
(
rest.into_iter().take(size).collect::<Vec<&str>>(),
has_next,
has_previous,
)
} else {
let rest: Vec<&str> = CUES
.iter()
.copied()
.filter(|title| at.as_deref().is_none_or(|at| *title < at))
.collect();
let has_next = rest.len() != CUES.len();
let has_previous = rest.len() > size;
let start = rest.len().saturating_sub(size);
(rest[start..].to_vec(), has_next, has_previous)
};
let edges = rows
.into_iter()
.map(|title| {
let cursor = Cursor::at(ORDER, vec![Some(CueCursor::Title(title.to_owned()))]);
Edge::new(
Cue {
title: title.to_owned(),
},
cursor,
)
})
.collect::<Vec<_>>();
Page::new(edges, has_next, has_previous)
}
struct Query;
#[Object]
impl Query {
async fn cues(
&self,
order_by: Option<Orderings<CueOrderBy>>,
first: Option<u32>,
last: Option<u32>,
after: Option<String>,
before: Option<String>,
) -> async_graphql::Result<Connection<CueOutput, CueCursor>> {
let order = order_by.unwrap_or_default();
let _ = order.len();
let request = PageRequest::of(first, last, after.as_deref(), before.as_deref())
.map_err(|refusal| crate::refused(&refusal))?;
page(&request).into_connection(|cue| async_graphql::Result::Ok(CueOutput { title: cue.title }))
}
}
fn schema() -> Schema<Query, EmptyMutation, EmptySubscription> {
Schema::new(Query, EmptyMutation, EmptySubscription)
}
fn written_order() -> Orderings<CueOrderBy> {
InputType::parse(Some(Value::List(Vec::new()))).expect("an empty list is a written order")
}
fn pick<'v>(value: &'v Value, path: &str) -> &'v Value {
let mut at = value;
for segment in path.split('.') {
at = match at {
Value::Object(fields) => fields
.get(&Name::new(segment))
.unwrap_or_else(|| panic!("`{segment}` of `{path}` is not in {value}")),
Value::List(items) => {
let index: usize = segment.parse().expect("a list is indexed by a number");
items
.get(index)
.unwrap_or_else(|| panic!("`{segment}` of `{path}` is not in {value}"))
}
other => panic!("`{path}` runs past {other}"),
};
}
at
}
fn text<'v>(value: &'v Value, path: &str) -> &'v str {
match pick(value, path) {
Value::String(text) => text,
other => panic!("`{path}` is not a string: {other}"),
}
}
fn flag(value: &Value, path: &str) -> bool {
match pick(value, path) {
Value::Boolean(flag) => *flag,
other => panic!("`{path}` is not a boolean: {other}"),
}
}
async fn answered(query: &str) -> Value {
let response = schema().execute(query).await;
assert!(response.errors.is_empty(), "{:?}", response.errors);
response.data
}
async fn refusal(query: &str) -> (String, Option<String>) {
let response = schema().execute(query).await;
let error = response
.errors
.first()
.unwrap_or_else(|| panic!("this query is refused: {query}"))
.clone();
let code = error
.extensions
.as_ref()
.and_then(|extensions| extensions.get(ErrorCode::EXTENSION))
.and_then(|value| match value {
Value::String(word) => Some(word.clone()),
_ => None,
});
(error.message, code)
}
#[test]
fn the_connection_renders_the_ruled_shape() {
let sdl = schema().sdl();
let block = |head: &str| {
let at = sdl
.find(head)
.unwrap_or_else(|| panic!("`{head}` is in the schema: {sdl}"));
let rest = &sdl[at..];
let end = rest.find("\n}").unwrap_or(rest.len());
rest[..end].to_owned()
};
let connection = block("type CueConnection {");
assert!(connection.contains("pageInfo: PageInfo!"), "{connection}");
assert!(connection.contains("edges: [CueEdge!]!"), "{connection}");
assert!(
!connection.contains("nodes"),
"the `nodes` shortcut is a word no ruling carries: {connection}"
);
let edge = block("type CueEdge {");
assert!(edge.contains("node: Cue!"), "{edge}");
assert!(edge.contains("cursor: String!"), "{edge}");
let info = block("type PageInfo {");
for field in [
"hasPreviousPage: Boolean!",
"hasNextPage: Boolean!",
"startCursor: String",
"endCursor: String",
] {
assert!(info.contains(field), "`{field}` is missing from {info}");
}
}
#[test]
fn the_list_field_takes_the_order_door_and_relays_four() {
let sdl = schema().sdl();
let field = sdl
.lines()
.map(str::trim)
.find(|line| line.starts_with("cues("))
.unwrap_or_else(|| panic!("`cues` is a field of the schema: {sdl}"))
.to_owned();
assert_eq!(
field,
"cues(orderBy: [CueOrderBy!], first: Int, last: Int, after: String, before: String): \
CueConnection!"
);
assert!(!field.contains("skip"), "{field}");
}
#[tokio::test]
async fn a_page_resumes_at_the_cursor_it_handed_out() {
let data = answered(
"{ cues(orderBy: [{title: ASC}], first: 2) { edges { node { title } cursor } \
pageInfo { hasNextPage hasPreviousPage endCursor } } }",
)
.await;
assert_eq!(text(&data, "cues.edges.0.node.title"), "alpha");
assert_eq!(text(&data, "cues.edges.1.node.title"), "beta");
assert!(flag(&data, "cues.pageInfo.hasNextPage"));
assert!(!flag(&data, "cues.pageInfo.hasPreviousPage"));
let end = text(&data, "cues.pageInfo.endCursor").to_owned();
assert_eq!(text(&data, "cues.edges.1.cursor"), end);
assert_eq!(
end,
Cursor::at(ORDER, vec![Some(CueCursor::Title(String::from("beta")))]).encode(),
"the string a client holds is the frame the boundary row's values encode to"
);
let data = answered(&format!(
"{{ cues(orderBy: [{{title: ASC}}], first: 2, after: {end:?}) {{ edges {{ node {{ title }} }} \
pageInfo {{ hasNextPage hasPreviousPage }} }} }}"
))
.await;
assert_eq!(text(&data, "cues.edges.0.node.title"), "delta");
assert_eq!(text(&data, "cues.edges.1.node.title"), "epsilon");
assert!(flag(&data, "cues.pageInfo.hasNextPage"));
assert!(
flag(&data, "cues.pageInfo.hasPreviousPage"),
"a resumed page approximates the side it did not walk, which is relay's own permitted answer"
);
}
#[tokio::test]
async fn the_backward_walk_answers_in_display_order() {
let data = answered(
"{ cues(orderBy: [{title: ASC}], last: 2) { edges { node { title } } \
pageInfo { hasPreviousPage } } }",
)
.await;
assert_eq!(text(&data, "cues.edges.0.node.title"), "epsilon");
assert_eq!(text(&data, "cues.edges.1.node.title"), "gamma");
assert!(flag(&data, "cues.pageInfo.hasPreviousPage"));
}
#[tokio::test]
async fn a_page_with_no_written_order_runs_on_the_key_default() {
let defaulted = answered("{ cues(first: 2) { edges { node { title } } } }").await;
assert_eq!(text(&defaulted, "cues.edges.0.node.title"), "alpha");
assert_eq!(text(&defaulted, "cues.edges.1.node.title"), "beta");
let bare = answered("{ cues { edges { node { title } } pageInfo { hasNextPage } } }").await;
assert_eq!(text(&bare, "cues.edges.0.node.title"), "alpha");
let empty = answered("{ cues(orderBy: [], first: 2) { edges { node { title } } } }").await;
assert_eq!(empty, defaulted);
}
#[test]
fn an_absent_order_normalises_to_the_empty_one() {
let argument: Option<Orderings<CueOrderBy>> = CUES.is_empty().then(written_order);
let absent = argument.unwrap_or_default();
assert!(absent.is_empty());
assert_eq!(absent.len(), written_order().len());
assert_eq!(absent.into_terms(), written_order().into_terms());
}
#[tokio::test]
async fn a_page_that_names_two_directions_is_refused() {
let (message, code) =
refusal("{ cues(orderBy: [{title: ASC}], first: 2, last: 2) { edges { node { title } } } }")
.await;
assert!(
message.contains("`first` walks forward and `last` walks backward"),
"{message}"
);
assert_eq!(code.as_deref(), Some("AMBIGUOUS_PAGE_DIRECTION"));
let (message, code) = refusal(
"{ cues(orderBy: [{title: ASC}], first: 2, before: \"x\") { edges { node { title } } } }",
)
.await;
assert!(
message.contains("`first` walks forward and `before` walks backward"),
"{message}"
);
assert_eq!(code.as_deref(), Some("AMBIGUOUS_PAGE_DIRECTION"));
}
#[tokio::test]
async fn a_cursor_that_is_not_one_is_refused() {
let (message, code) = refusal(
"{ cues(orderBy: [{title: ASC}], after: \"not a cursor\") { edges { node { title } } } }",
)
.await;
assert!(message.contains("`after` is not a cursor"), "{message}");
assert_eq!(code.as_deref(), Some("UNUSABLE_CURSOR"));
}
#[test]
fn the_arguments_partition_the_way_the_typestate_does() {
assert!(PageArgument::First.is_forward());
assert!(PageArgument::After.is_forward());
assert!(!PageArgument::Last.is_forward());
assert!(!PageArgument::Before.is_forward());
assert_eq!(PageArgument::First.to_string(), "first");
assert_eq!(PageArgument::Before.to_string(), "before");
}
#[test]
fn the_legal_combinations_are_the_ones_the_builder_can_spell() {
let of = |first, last, after, before| PageRequest::<CueCursor>::of(first, last, after, before);
for (first, last, after, before, legal) in [
(None, None, None, None, true),
(Some(2), None, None, None, true),
(None, Some(2), None, None, true),
(None, None, Some("x"), None, true),
(None, None, None, Some("x"), true),
(Some(2), None, Some("x"), None, true),
(None, Some(2), None, Some("x"), true),
(Some(2), Some(2), None, None, false),
(Some(2), None, None, Some("x"), false),
(None, Some(2), Some("x"), None, false),
(None, None, Some("x"), Some("x"), false),
] {
let answer = of(first, last, after, before);
let spelled = !matches!(answer, Err(PageError::Directions { .. }));
assert_eq!(
spelled, legal,
"first={first:?} last={last:?} after={after:?} before={before:?} → {answer:?}"
);
}
}
#[test]
fn the_size_is_defaulted_and_clamped_where_the_engine_would() {
let forward = |first| PageRequest::<CueCursor>::Forward { first, after: None };
assert_eq!(forward(None).size(), DEFAULT_PAGE_SIZE);
assert_eq!(forward(Some(7)).size(), 7);
assert_eq!(forward(Some(u32::MAX)).size(), MAX_PAGE_SIZE);
assert_eq!(
PageRequest::<CueCursor>::Backward {
last: Some(u32::MAX),
before: None,
}
.size(),
MAX_PAGE_SIZE
);
}