pub use jmap_types::{
GetObject, JmapObject, QueryObject, ReservedExtrasKey, SetError, SetErrorType, SetObject,
};
#[non_exhaustive]
#[derive(Debug)]
pub enum BackendSetError<E> {
SetError(Box<SetError>),
Other(E),
}
impl<E: std::fmt::Display> std::fmt::Display for BackendSetError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SetError(se) => write!(f, "set error: {se}"),
Self::Other(e) => write!(f, "{e}"),
}
}
}
impl<E: std::error::Error + 'static> std::error::Error for BackendSetError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Other(e) => Some(e),
_ => None,
}
}
}
impl<E> From<SetError> for BackendSetError<E> {
fn from(e: SetError) -> Self {
Self::SetError(Box::new(e))
}
}
impl<E> From<Box<SetError>> for BackendSetError<E> {
fn from(e: Box<SetError>) -> Self {
Self::SetError(e)
}
}
impl<E: std::fmt::Display> BackendSetError<E> {
pub fn into_set_error_or_method_error(self) -> Result<SetError, jmap_types::JmapError> {
match self {
Self::SetError(se) => Ok(*se),
Self::Other(e) => Err(crate::handlers::server_fail_from_backend(&e)),
}
}
}
pub fn backend_set_error_value<E: std::fmt::Display>(err: BackendSetError<E>) -> serde_json::Value {
match err {
BackendSetError::SetError(se) => serde_json::Value::from(*se),
BackendSetError::Other(e) => crate::handlers::server_fail_value_from_backend(&e),
}
}
#[non_exhaustive]
#[derive(Debug)]
pub enum BackendChangesError<E> {
CannotCalculate,
TooManyChanges {
limit: u64,
},
Other(E),
}
impl<E: std::fmt::Display> std::fmt::Display for BackendChangesError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::CannotCalculate => write!(f, "cannot calculate changes"),
Self::TooManyChanges { limit } => write!(f, "too many changes (limit: {limit})"),
Self::Other(e) => write!(f, "{e}"),
}
}
}
impl<E: std::error::Error + 'static> std::error::Error for BackendChangesError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Other(e) => Some(e),
_ => None,
}
}
}
impl<E> From<E> for BackendChangesError<E> {
fn from(e: E) -> Self {
Self::Other(e)
}
}
impl<E: std::error::Error> From<BackendChangesError<E>> for jmap_types::JmapError {
fn from(e: BackendChangesError<E>) -> Self {
match e {
BackendChangesError::CannotCalculate => {
jmap_types::JmapError::cannot_calculate_changes()
}
BackendChangesError::TooManyChanges { limit } => {
jmap_types::JmapError::too_many_changes_with_limit(limit)
}
BackendChangesError::Other(_inner) => {
jmap_types::JmapError::server_fail(crate::handlers::SERVER_FAIL_INTERNAL_DESC)
}
}
}
}
#[non_exhaustive]
#[derive(Debug)]
pub enum BackendQueryError<E> {
Method(jmap_types::JmapError),
Other(E),
}
impl<E: std::fmt::Display> std::fmt::Display for BackendQueryError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Method(e) => write!(f, "{e}"),
Self::Other(e) => write!(f, "{e}"),
}
}
}
impl<E: std::error::Error + 'static> std::error::Error for BackendQueryError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Method(_) => None,
Self::Other(e) => Some(e),
}
}
}
impl<E> From<E> for BackendQueryError<E> {
fn from(e: E) -> Self {
Self::Other(e)
}
}
impl<E> From<BackendQueryError<E>> for jmap_types::JmapError {
fn from(e: BackendQueryError<E>) -> Self {
match e {
BackendQueryError::Method(err) => err,
BackendQueryError::Other(_inner) => {
jmap_types::JmapError::server_fail(crate::handlers::SERVER_FAIL_INTERNAL_DESC)
}
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ChangesResult {
pub created: Vec<jmap_types::Id>,
pub updated: Vec<jmap_types::Id>,
pub destroyed: Vec<jmap_types::Id>,
pub has_more_changes: bool,
pub new_state: jmap_types::State,
pub updated_properties: Option<Vec<String>>,
}
impl ChangesResult {
pub fn new(
created: Vec<jmap_types::Id>,
updated: Vec<jmap_types::Id>,
destroyed: Vec<jmap_types::Id>,
has_more_changes: bool,
new_state: jmap_types::State,
) -> Self {
Self {
created,
updated,
destroyed,
has_more_changes,
new_state,
updated_properties: None,
}
}
#[must_use]
pub fn with_updated_properties(mut self, updated_properties: Option<Vec<String>>) -> Self {
self.updated_properties = updated_properties;
self
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct QueryResult {
pub ids: Vec<jmap_types::Id>,
pub position: u64,
pub total: Option<u64>,
pub query_state: jmap_types::State,
pub can_calculate_changes: bool,
}
impl QueryResult {
pub fn new(
ids: Vec<jmap_types::Id>,
position: u64,
total: Option<u64>,
query_state: jmap_types::State,
can_calculate_changes: bool,
) -> Self {
Self {
ids,
position,
total,
query_state,
can_calculate_changes,
}
}
pub fn new_clamped(
ids: Vec<jmap_types::Id>,
position_signed: i64,
total: Option<u64>,
query_state: jmap_types::State,
can_calculate_changes: bool,
) -> Self {
let position = u64::try_from(position_signed.max(0)).unwrap_or(0);
Self::new(ids, position, total, query_state, can_calculate_changes)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct AddedItem {
pub id: jmap_types::Id,
pub index: u64,
}
impl AddedItem {
pub fn new(id: jmap_types::Id, index: u64) -> Self {
Self { id, index }
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct QueryChangesResult {
pub old_query_state: jmap_types::State,
pub new_query_state: jmap_types::State,
pub total: Option<u64>,
pub removed: Vec<jmap_types::Id>,
pub added: Vec<AddedItem>,
}
impl QueryChangesResult {
pub fn new(
old_query_state: jmap_types::State,
new_query_state: jmap_types::State,
total: Option<u64>,
removed: Vec<jmap_types::Id>,
added: Vec<AddedItem>,
) -> Self {
Self {
old_query_state,
new_query_state,
total,
removed,
added,
}
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct ChangesParams<'a> {
pub since_state: &'a jmap_types::State,
pub max_changes: Option<u64>,
pub ignore_metadata_only_changes: bool,
}
impl<'a> ChangesParams<'a> {
pub fn new(since_state: &'a jmap_types::State) -> Self {
Self {
since_state,
max_changes: None,
ignore_metadata_only_changes: false,
}
}
#[must_use]
pub fn max_changes(mut self, max_changes: Option<u64>) -> Self {
self.max_changes = max_changes;
self
}
#[must_use]
pub fn ignore_metadata_only_changes(mut self, ignore: bool) -> Self {
self.ignore_metadata_only_changes = ignore;
self
}
}
#[non_exhaustive]
pub struct QueryParams<'a, O: QueryObject> {
pub filter: Option<&'a O::Filter>,
pub sort: Option<&'a [O::Comparator]>,
pub limit: Option<u64>,
pub position: i64,
pub anchor: Option<&'a jmap_types::Id>,
pub anchor_offset: i64,
pub language: Option<&'a [jmap_types::i18n::LanguageRange]>,
}
impl<'a, O: QueryObject> QueryParams<'a, O> {
pub fn new() -> Self {
Self {
filter: None,
sort: None,
limit: None,
position: 0,
anchor: None,
anchor_offset: 0,
language: None,
}
}
#[must_use]
pub fn filter(mut self, filter: Option<&'a O::Filter>) -> Self {
self.filter = filter;
self
}
#[must_use]
pub fn sort(mut self, sort: Option<&'a [O::Comparator]>) -> Self {
self.sort = sort;
self
}
#[must_use]
pub fn limit(mut self, limit: Option<u64>) -> Self {
self.limit = limit;
self
}
#[must_use]
pub fn position(mut self, position: i64) -> Self {
self.position = position;
self
}
#[must_use]
pub fn anchor(mut self, anchor: Option<&'a jmap_types::Id>) -> Self {
self.anchor = anchor;
self
}
#[must_use]
pub fn anchor_offset(mut self, anchor_offset: i64) -> Self {
self.anchor_offset = anchor_offset;
self
}
#[must_use]
pub fn language(mut self, language: Option<&'a [jmap_types::i18n::LanguageRange]>) -> Self {
self.language = language;
self
}
}
impl<O: QueryObject> Default for QueryParams<'_, O> {
fn default() -> Self {
Self::new()
}
}
impl<O: QueryObject> Clone for QueryParams<'_, O> {
fn clone(&self) -> Self {
*self
}
}
impl<O: QueryObject> Copy for QueryParams<'_, O> {}
impl<O: QueryObject> std::fmt::Debug for QueryParams<'_, O>
where
O::Filter: std::fmt::Debug,
O::Comparator: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QueryParams")
.field("filter", &self.filter)
.field("sort", &self.sort)
.field("limit", &self.limit)
.field("position", &self.position)
.field("anchor", &self.anchor)
.field("anchor_offset", &self.anchor_offset)
.field("language", &self.language)
.finish()
}
}
#[non_exhaustive]
pub struct QueryChangesParams<'a, O: QueryObject> {
pub since_query_state: &'a jmap_types::State,
pub filter: Option<&'a O::Filter>,
pub sort: Option<&'a [O::Comparator]>,
pub max_changes: Option<u64>,
pub up_to_id: Option<&'a jmap_types::Id>,
pub collapse_threads: bool,
pub language: Option<&'a [jmap_types::i18n::LanguageRange]>,
}
impl<'a, O: QueryObject> QueryChangesParams<'a, O> {
pub fn new(since_query_state: &'a jmap_types::State) -> Self {
Self {
since_query_state,
filter: None,
sort: None,
max_changes: None,
up_to_id: None,
collapse_threads: false,
language: None,
}
}
#[must_use]
pub fn filter(mut self, filter: Option<&'a O::Filter>) -> Self {
self.filter = filter;
self
}
#[must_use]
pub fn sort(mut self, sort: Option<&'a [O::Comparator]>) -> Self {
self.sort = sort;
self
}
#[must_use]
pub fn max_changes(mut self, max_changes: Option<u64>) -> Self {
self.max_changes = max_changes;
self
}
#[must_use]
pub fn up_to_id(mut self, up_to_id: Option<&'a jmap_types::Id>) -> Self {
self.up_to_id = up_to_id;
self
}
#[must_use]
pub fn collapse_threads(mut self, collapse_threads: bool) -> Self {
self.collapse_threads = collapse_threads;
self
}
#[must_use]
pub fn language(mut self, language: Option<&'a [jmap_types::i18n::LanguageRange]>) -> Self {
self.language = language;
self
}
}
impl<O: QueryObject> Clone for QueryChangesParams<'_, O> {
fn clone(&self) -> Self {
*self
}
}
impl<O: QueryObject> Copy for QueryChangesParams<'_, O> {}
impl<O: QueryObject> std::fmt::Debug for QueryChangesParams<'_, O>
where
O::Filter: std::fmt::Debug,
O::Comparator: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QueryChangesParams")
.field("since_query_state", &self.since_query_state)
.field("filter", &self.filter)
.field("sort", &self.sort)
.field("max_changes", &self.max_changes)
.field("up_to_id", &self.up_to_id)
.field("collapse_threads", &self.collapse_threads)
.field("language", &self.language)
.finish()
}
}
pub trait JmapBackend: JmapAccounts + JmapReads {}
impl<T: JmapAccounts + JmapReads> JmapBackend for T {}
pub trait JmapAccounts: Send + Sync + 'static {
type Error: std::error::Error + Send + Sync + 'static;
type CallerCtx: Clone + Send + Sync + 'static;
fn account_exists(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send;
fn principal_id(caller: &Self::CallerCtx) -> Option<&jmap_types::Id> {
let _ = caller;
None
}
fn accept_language(caller: &Self::CallerCtx) -> Option<&str> {
let _ = caller;
None
}
fn max_objects_in_set(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
let _ = (caller, account_id);
500
}
fn max_objects_in_get(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
let _ = (caller, account_id);
500
}
fn metadata_info<O: JmapObject>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> Option<jmap_metadata_types::DataTypeMetadataInfo> {
let _ = (caller, account_id);
None
}
fn i18n_info(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> Option<crate::I18nInfo> {
let _ = (caller, account_id);
None
}
}
pub trait JmapReads: JmapAccounts {
fn get_objects<O: GetObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
ids: Option<&[jmap_types::Id]>,
properties: Option<&[String]>,
) -> impl std::future::Future<Output = Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error>> + Send;
fn get_state<O: JmapObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<jmap_types::State, Self::Error>> + Send;
fn get_changes<O: JmapObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
params: ChangesParams<'_>,
) -> impl std::future::Future<Output = Result<ChangesResult, BackendChangesError<Self::Error>>> + Send;
fn query_objects<O: QueryObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
params: QueryParams<'_, O>,
) -> impl std::future::Future<Output = Result<QueryResult, BackendQueryError<Self::Error>>> + Send;
fn query_changes<O: QueryObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
params: QueryChangesParams<'_, O>,
) -> impl std::future::Future<
Output = Result<QueryChangesResult, BackendChangesError<Self::Error>>,
> + Send;
}
pub trait DelegateJmapReads: JmapAccounts {
type Target: JmapReads<Error = Self::Error, CallerCtx = Self::CallerCtx>;
fn jmap_reads(&self) -> &Self::Target;
}
impl<T: DelegateJmapReads> JmapReads for T {
fn get_objects<O: GetObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
ids: Option<&[jmap_types::Id]>,
properties: Option<&[String]>,
) -> impl std::future::Future<Output = Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error>> + Send
{
self.jmap_reads()
.get_objects(caller, account_id, ids, properties)
}
fn get_state<O: JmapObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<jmap_types::State, Self::Error>> + Send {
self.jmap_reads().get_state::<O>(caller, account_id)
}
fn get_changes<O: JmapObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
params: ChangesParams<'_>,
) -> impl std::future::Future<Output = Result<ChangesResult, BackendChangesError<Self::Error>>> + Send
{
self.jmap_reads()
.get_changes::<O>(caller, account_id, params)
}
fn query_objects<O: QueryObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
params: QueryParams<'_, O>,
) -> impl std::future::Future<Output = Result<QueryResult, BackendQueryError<Self::Error>>> + Send
{
self.jmap_reads().query_objects(caller, account_id, params)
}
fn query_changes<O: QueryObject + Send + Sync>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
params: QueryChangesParams<'_, O>,
) -> impl std::future::Future<
Output = Result<QueryChangesResult, BackendChangesError<Self::Error>>,
> + Send {
self.jmap_reads().query_changes(caller, account_id, params)
}
}
pub trait DelegateJmapAccounts: Send + Sync + 'static {
type Target: JmapAccounts;
fn jmap_accounts(&self) -> &Self::Target;
fn account_exists(
&self,
caller: &<Self::Target as JmapAccounts>::CallerCtx,
account_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<bool, <Self::Target as JmapAccounts>::Error>> + Send
{
self.jmap_accounts().account_exists(caller, account_id)
}
fn principal_id(caller: &<Self::Target as JmapAccounts>::CallerCtx) -> Option<&jmap_types::Id> {
<Self::Target as JmapAccounts>::principal_id(caller)
}
fn accept_language(caller: &<Self::Target as JmapAccounts>::CallerCtx) -> Option<&str> {
<Self::Target as JmapAccounts>::accept_language(caller)
}
fn max_objects_in_set(
&self,
caller: &<Self::Target as JmapAccounts>::CallerCtx,
account_id: &jmap_types::Id,
) -> u64 {
self.jmap_accounts().max_objects_in_set(caller, account_id)
}
fn max_objects_in_get(
&self,
caller: &<Self::Target as JmapAccounts>::CallerCtx,
account_id: &jmap_types::Id,
) -> u64 {
self.jmap_accounts().max_objects_in_get(caller, account_id)
}
fn metadata_info<O: JmapObject>(
&self,
caller: &<Self::Target as JmapAccounts>::CallerCtx,
account_id: &jmap_types::Id,
) -> Option<jmap_metadata_types::DataTypeMetadataInfo> {
self.jmap_accounts().metadata_info::<O>(caller, account_id)
}
fn i18n_info(
&self,
caller: &<Self::Target as JmapAccounts>::CallerCtx,
account_id: &jmap_types::Id,
) -> Option<crate::I18nInfo> {
self.jmap_accounts().i18n_info(caller, account_id)
}
}
impl<T: DelegateJmapAccounts> JmapAccounts for T {
type Error = <T::Target as JmapAccounts>::Error;
type CallerCtx = <T::Target as JmapAccounts>::CallerCtx;
fn account_exists(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
DelegateJmapAccounts::account_exists(self, caller, account_id)
}
fn principal_id(caller: &Self::CallerCtx) -> Option<&jmap_types::Id> {
<T as DelegateJmapAccounts>::principal_id(caller)
}
fn accept_language(caller: &Self::CallerCtx) -> Option<&str> {
<T as DelegateJmapAccounts>::accept_language(caller)
}
fn max_objects_in_set(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
DelegateJmapAccounts::max_objects_in_set(self, caller, account_id)
}
fn max_objects_in_get(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
DelegateJmapAccounts::max_objects_in_get(self, caller, account_id)
}
fn metadata_info<O: JmapObject>(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> Option<jmap_metadata_types::DataTypeMetadataInfo> {
DelegateJmapAccounts::metadata_info::<O>(self, caller, account_id)
}
fn i18n_info(
&self,
caller: &Self::CallerCtx,
account_id: &jmap_types::Id,
) -> Option<crate::I18nInfo> {
DelegateJmapAccounts::i18n_info(self, caller, account_id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backend_changes_error_cannot_calculate_maps_to_cannot_calculate_changes() {
let err = jmap_types::JmapError::from(
BackendChangesError::<std::convert::Infallible>::CannotCalculate,
);
assert_eq!(
err.error_type.to_string(),
"cannotCalculateChanges",
"CannotCalculate must produce cannotCalculateChanges; got: {:?}",
err.error_type
);
}
#[test]
fn backend_changes_error_nonzero_limit_maps_to_too_many_changes() {
let err = jmap_types::JmapError::from(
BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 50 },
);
assert_eq!(
err.error_type.to_string(),
"tooManyChanges",
"limit=50 must produce tooManyChanges; got: {:?}",
err.error_type
);
}
#[test]
fn backend_changes_error_zero_limit_maps_to_too_many_changes() {
let err = jmap_types::JmapError::from(
BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 0 },
);
assert_eq!(
serde_json::to_value(&err).unwrap(),
serde_json::json!({"type": "tooManyChanges", "limit": 0})
);
}
#[test]
fn backend_changes_error_other_drops_display_text() {
#[derive(Debug)]
struct LeakyError(&'static str);
impl std::fmt::Display for LeakyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for LeakyError {}
const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
let err: BackendChangesError<LeakyError> = BackendChangesError::Other(LeakyError(CANARY));
let jmap_err = jmap_types::JmapError::from(err);
let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
let wire_str = wire.to_string();
assert!(
!wire_str.contains(CANARY),
"From<BackendChangesError<E>> for JmapError must not echo \
backend error Display onto the wire; got {wire_str}"
);
assert_eq!(
wire["description"],
crate::handlers::SERVER_FAIL_INTERNAL_DESC,
"description must be the static 'internal error' string"
);
assert_eq!(wire["type"], "serverFail");
}
#[test]
fn backend_set_error_other_drops_display_text() {
struct LeakyError(&'static str);
impl std::fmt::Display for LeakyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
let err: BackendSetError<LeakyError> = BackendSetError::Other(LeakyError(CANARY));
let Err(jmap_err) = err.into_set_error_or_method_error() else {
panic!("Other must map to a method-level JmapError");
};
let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
assert!(
!wire.to_string().contains(CANARY),
"into_set_error_or_method_error must not echo backend Display; got {wire}"
);
assert_eq!(
wire,
serde_json::json!({"type": "serverFail", "description": "internal error"})
);
}
#[test]
fn backend_set_error_set_error_passes_through() {
let err: BackendSetError<std::fmt::Error> =
BackendSetError::SetError(Box::new(SetError::new(SetErrorType::Forbidden)));
let se = err
.into_set_error_or_method_error()
.expect("SetError arm must be Ok");
assert_eq!(
serde_json::to_value(&se).expect("SetError must serialize"),
serde_json::json!({"type": "forbidden"})
);
}
#[test]
fn backend_set_error_value_set_error_is_verbatim() {
let err: BackendSetError<std::fmt::Error> = BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::NotFound).with_description("gone"),
));
assert_eq!(
backend_set_error_value(err),
serde_json::json!({"type": "notFound", "description": "gone"})
);
}
#[test]
fn backend_set_error_value_other_is_redacted_server_fail() {
const CANARY: &str = "TOKEN-DO-NOT-LEAK-5e7e44";
let err: BackendSetError<&str> = BackendSetError::Other(CANARY);
let wire = backend_set_error_value(err);
assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
assert_eq!(
wire,
serde_json::json!({"type": "serverFail", "description": "internal error"})
);
}
#[derive(Debug)]
struct StubError;
impl std::fmt::Display for StubError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("stub")
}
}
impl std::error::Error for StubError {}
struct StubBackend;
impl JmapAccounts for StubBackend {
type Error = StubError;
type CallerCtx = ();
async fn account_exists(
&self,
_caller: &(),
_account_id: &jmap_types::Id,
) -> Result<bool, Self::Error> {
unreachable!("stub backend: only default methods are exercised")
}
}
impl JmapReads for StubBackend {
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &jmap_types::Id,
_ids: Option<&[jmap_types::Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error> {
unreachable!("stub backend: only default methods are exercised")
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &jmap_types::Id,
) -> Result<jmap_types::State, Self::Error> {
unreachable!("stub backend: only default methods are exercised")
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &jmap_types::Id,
_params: ChangesParams<'_>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
unreachable!("stub backend: only default methods are exercised")
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &jmap_types::Id,
_params: QueryParams<'_, O>,
) -> Result<QueryResult, BackendQueryError<Self::Error>> {
unreachable!("stub backend: only default methods are exercised")
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
_account_id: &jmap_types::Id,
_params: QueryChangesParams<'_, O>,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
unreachable!("stub backend: only default methods are exercised")
}
}
#[test]
fn principal_id_default_impl_returns_none_for_unit_caller_ctx() {
let caller: <StubBackend as JmapAccounts>::CallerCtx = ();
let id = <StubBackend as JmapAccounts>::principal_id(&caller);
assert!(
id.is_none(),
"default principal_id impl must return None; got Some({:?})",
id
);
}
#[test]
fn max_objects_in_set_default_impl_returns_500() {
let backend = StubBackend;
let caller: <StubBackend as JmapAccounts>::CallerCtx = ();
let id = jmap_types::Id::from("any-account");
assert_eq!(
backend.max_objects_in_set(&caller, &id),
500,
"default max_objects_in_set must return 500"
);
}
#[test]
fn max_objects_in_get_default_impl_returns_500() {
let caller: <StubBackend as JmapAccounts>::CallerCtx = ();
let id = jmap_types::Id::from("any-account");
assert_eq!(StubBackend.max_objects_in_get(&caller, &id), 500);
}
#[test]
fn backend_set_error_display() {
let se: BackendSetError<StubError> = BackendSetError::SetError(Box::new(
SetError::new(SetErrorType::NotFound).with_description("gone"),
));
assert_eq!(se.to_string(), "set error: notFound: gone");
assert_eq!(BackendSetError::Other(StubError).to_string(), "stub");
}
#[test]
fn backend_changes_error_display() {
assert_eq!(
BackendChangesError::<StubError>::CannotCalculate.to_string(),
"cannot calculate changes"
);
assert_eq!(
BackendChangesError::<StubError>::TooManyChanges { limit: 7 }.to_string(),
"too many changes (limit: 7)"
);
assert_eq!(BackendChangesError::Other(StubError).to_string(), "stub");
}
#[test]
fn backend_query_error_display() {
let method = jmap_types::JmapError::server_fail("x");
let expected = method.to_string();
assert_eq!(
BackendQueryError::<StubError>::Method(method).to_string(),
expected
);
assert_eq!(BackendQueryError::Other(StubError).to_string(), "stub");
}
#[test]
fn backend_errors_source_is_wrapped_other_only() {
use std::error::Error as _;
let is_stub = |e: Option<&(dyn std::error::Error + 'static)>| {
e.is_some_and(|s| s.downcast_ref::<StubError>().is_some())
};
assert!(is_stub(BackendSetError::Other(StubError).source()));
assert!(
BackendSetError::<StubError>::from(SetError::new(SetErrorType::Forbidden))
.source()
.is_none()
);
assert!(is_stub(BackendChangesError::from(StubError).source()));
assert!(
BackendChangesError::<StubError>::CannotCalculate
.source()
.is_none()
);
assert!(
BackendChangesError::<StubError>::TooManyChanges { limit: 1 }
.source()
.is_none()
);
assert!(is_stub(BackendQueryError::from(StubError).source()));
assert!(
BackendQueryError::<StubError>::Method(jmap_types::JmapError::server_fail("x"))
.source()
.is_none()
);
}
}