use core::fmt::Display;
use async_graphql::{
OutputType,
connection::{
Connection as RelayConnection, ConnectionNameType, CursorType, DefaultConnectionName,
DefaultEdgeName, DisableNodesField, Edge as RelayEdge, EdgeNameType, EmptyFields,
},
};
use super::{ErrorCode, ToErrorCode};
use crate::{
Cursor, CursorError, CursorValue,
query::{DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, Page},
};
#[cfg(test)]
mod raised_tests;
#[cfg(test)]
mod tests;
pub type Connection<N, V, C = DefaultConnectionName, D = DefaultEdgeName> =
RelayConnection<Cursor<V>, N, EmptyFields, EmptyFields, C, D, DisableNodesField>;
impl<V> CursorType for Cursor<V>
where
V: CursorValue,
{
type Error = CursorError;
#[inline]
fn decode_cursor(text: &str) -> Result<Self, Self::Error> {
Self::decode(text)
}
#[inline]
fn encode_cursor(&self) -> String {
self.encode()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PageArgument {
First,
Last,
After,
Before,
}
impl PageArgument {
#[inline]
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::First => "first",
Self::Last => "last",
Self::After => "after",
Self::Before => "before",
}
}
#[inline]
#[must_use]
pub const fn is_forward(self) -> bool {
matches!(self, Self::First | Self::After)
}
}
impl Display for PageArgument {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageError {
Directions {
forward: PageArgument,
backward: PageArgument,
},
Cursor {
argument: PageArgument,
cause: CursorError,
},
}
impl Display for PageError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Directions { forward, backward } => write!(
f,
"`{forward}` walks forward and `{backward}` walks backward, and a page runs one way — keep \
the arguments of one direction"
),
Self::Cursor { argument, cause } => write!(f, "`{argument}` is not a cursor: {cause}"),
}
}
}
impl core::error::Error for PageError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Directions { .. } => None,
Self::Cursor { cause, .. } => Some(cause),
}
}
}
impl ToErrorCode for PageError {
#[inline]
fn error_code(&self) -> ErrorCode {
match self {
Self::Directions { .. } => ErrorCode::AmbiguousPageDirection,
Self::Cursor { .. } => ErrorCode::UnusableCursor,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PageRequest<V> {
Forward {
first: Option<u32>,
after: Option<Cursor<V>>,
},
Backward {
last: Option<u32>,
before: Option<Cursor<V>>,
},
}
impl<V> PageRequest<V>
where
V: CursorValue,
{
pub fn of(
first: Option<u32>,
last: Option<u32>,
after: Option<&str>,
before: Option<&str>,
) -> Result<Self, PageError> {
let written = [
first.map(|_| PageArgument::First),
last.map(|_| PageArgument::Last),
after.map(|_| PageArgument::After),
before.map(|_| PageArgument::Before),
];
let side = |forward: bool| {
written
.into_iter()
.flatten()
.find(|argument| argument.is_forward() == forward)
};
if let (Some(forward), Some(backward)) = (side(true), side(false)) {
return Err(PageError::Directions { forward, backward });
}
let decode = |argument, text: Option<&str>| {
text
.map(Cursor::<V>::decode)
.transpose()
.map_err(|cause| PageError::Cursor { argument, cause })
};
if last.is_some() || before.is_some() {
return Ok(Self::Backward {
last,
before: decode(PageArgument::Before, before)?,
});
}
Ok(Self::Forward {
first,
after: decode(PageArgument::After, after)?,
})
}
}
impl<V> PageRequest<V> {
#[inline]
#[must_use]
pub const fn size(&self) -> u32 {
let asked = match self {
Self::Forward { first: size, .. } | Self::Backward { last: size, .. } => *size,
};
match asked {
Some(asked) if asked > MAX_PAGE_SIZE => MAX_PAGE_SIZE,
Some(asked) => asked,
None => DEFAULT_PAGE_SIZE,
}
}
#[inline]
#[must_use]
pub const fn is_forward(&self) -> bool {
matches!(self, Self::Forward { .. })
}
#[inline]
#[must_use]
pub fn position(&self) -> Option<&Cursor<V>> {
match self {
Self::Forward { after: at, .. } | Self::Backward { before: at, .. } => at.as_ref(),
}
}
}
impl<R, V> Page<R, V>
where
V: CursorValue,
{
pub fn into_connection<N, E, C, D>(
self,
mut node: impl FnMut(R) -> Result<N, E>,
) -> Result<Connection<N, V, C, D>, E>
where
N: OutputType,
V: Send + Sync,
C: ConnectionNameType,
D: EdgeNameType,
{
let (has_next, has_previous) = (self.has_next_page(), self.has_previous_page());
let mut connection = Connection::new(has_previous, has_next);
for edge in self.into_edges() {
let (record, cursor) = edge.into_parts();
connection.edges.push(RelayEdge::new(cursor, node(record)?));
}
Ok(connection)
}
pub fn into_connection_of<N, C, D>(
self,
nodes: Vec<Option<N>>,
) -> Result<Connection<N, V, C, D>, UnraisedPage>
where
N: OutputType,
V: Send + Sync,
C: ConnectionNameType,
D: EdgeNameType,
{
let (has_next, has_previous) = (self.has_next_page(), self.has_previous_page());
let edges = self.into_edges();
let of = edges.len();
let missing = nodes.iter().filter(|node| node.is_none()).count() + of.abs_diff(nodes.len());
if missing > 0 {
return Err(UnraisedPage { missing, of });
}
let mut connection = Connection::new(has_previous, has_next);
for (edge, node) in edges.into_vec().into_iter().zip(nodes) {
let (_, cursor) = edge.into_parts();
let Some(node) = node else {
return Err(UnraisedPage { missing: 1, of });
};
connection.edges.push(RelayEdge::new(cursor, node));
}
Ok(connection)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnraisedPage {
missing: usize,
of: usize,
}
impl UnraisedPage {
#[inline]
#[must_use]
pub const fn missing(&self) -> usize {
self.missing
}
#[inline]
#[must_use]
pub const fn of(&self) -> usize {
self.of
}
}
impl Display for UnraisedPage {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"{} of {} rows on this page were never raised onto the wire — the gather that fills them \
answered for fewer addresses than the page asked about",
self.missing, self.of
)
}
}
impl std::error::Error for UnraisedPage {}