#![allow(async_fn_in_trait)]
#![deny(clippy::await_holding_lock)]
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use crate::{
AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
JmapBackend, JmapObject, QueryChangesResult, QueryObject, QueryResult, SetError, SetErrorType,
SetObject, TasksBackend,
};
use jmap_server::{apply_patch_object, resolve_query_start};
use jmap_types::{Id, State};
#[derive(Debug)]
pub struct MemoryError {
msg: String,
}
impl MemoryError {
pub fn new(msg: impl Into<String>) -> Self {
Self { msg: msg.into() }
}
pub fn message(&self) -> &str {
&self.msg
}
}
impl std::fmt::Display for MemoryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.msg)
}
}
impl std::error::Error for MemoryError {}
#[derive(Clone, Debug)]
struct ChangeEntry {
new_state: u64,
created: Vec<Id>,
updated: Vec<Id>,
destroyed: Vec<Id>,
}
#[derive(Default, Clone)]
struct AccountAux {
task_list_refcount: HashMap<Id, u64>,
}
#[derive(Default)]
struct Inner {
objects: HashMap<(&'static str, String), HashMap<Id, serde_json::Value>>,
states: HashMap<(&'static str, String), u64>,
change_log: HashMap<(&'static str, String), Vec<ChangeEntry>>,
aux: HashMap<String, AccountAux>,
known_accounts: HashSet<String>,
}
impl Inner {
fn current_state(&self, type_name: &'static str, account_id: &str) -> u64 {
self.states
.get(&(type_name, account_id.to_owned()))
.copied()
.unwrap_or(0)
}
fn bump_state(&mut self, type_name: &'static str, account_id: &str) -> u64 {
let entry = self
.states
.entry((type_name, account_id.to_owned()))
.or_insert(0);
*entry += 1;
*entry
}
fn objects_mut(
&mut self,
type_name: &'static str,
account_id: &str,
) -> &mut HashMap<Id, serde_json::Value> {
self.known_accounts.insert(account_id.to_owned());
self.objects
.entry((type_name, account_id.to_owned()))
.or_default()
}
fn objects_ref(
&self,
type_name: &'static str,
account_id: &str,
) -> Option<&HashMap<Id, serde_json::Value>> {
self.objects.get(&(type_name, account_id.to_owned()))
}
fn change_log_mut(
&mut self,
type_name: &'static str,
account_id: &str,
) -> &mut Vec<ChangeEntry> {
self.change_log
.entry((type_name, account_id.to_owned()))
.or_default()
}
fn aux_mut(&mut self, account_id: &str) -> &mut AccountAux {
self.known_accounts.insert(account_id.to_owned());
self.aux.entry(account_id.to_owned()).or_default()
}
fn aux_ref(&self, account_id: &str) -> Option<&AccountAux> {
self.aux.get(account_id)
}
fn task_list_id_of(task: &serde_json::Value) -> Option<Id> {
task.get("taskListId")
.and_then(|v| v.as_str())
.map(Id::from)
}
fn inc_task_ref(&mut self, account_id: &str, list_id: Option<Id>) {
if let Some(id) = list_id {
*self
.aux_mut(account_id)
.task_list_refcount
.entry(id)
.or_insert(0) += 1;
}
}
fn dec_task_ref(&mut self, account_id: &str, list_id: Option<Id>) {
let Some(id) = list_id else { return };
let aux = self.aux_mut(account_id);
if let Some(count) = aux.task_list_refcount.get_mut(&id) {
*count = count.saturating_sub(1);
if *count == 0 {
aux.task_list_refcount.remove(&id);
}
}
}
}
#[derive(Default)]
pub struct MemoryBackend {
inner: Arc<Mutex<Inner>>,
}
impl Clone for MemoryBackend {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
}
}
}
impl MemoryBackend {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_account(self, account_id: &str) -> Self {
self.register_account(&Id::from(account_id));
self
}
#[doc(hidden)]
pub fn register_account(&self, account_id: &Id) {
let mut inner = self.inner.lock().unwrap();
inner.known_accounts.insert(account_id.as_ref().to_owned());
inner.aux.entry(account_id.as_ref().to_owned()).or_default();
}
pub fn seed_object(
&self,
account_id: &str,
type_name: &'static str,
id: &str,
value: serde_json::Value,
) {
let mut inner = self.inner.lock().unwrap();
inner.known_accounts.insert(account_id.to_owned());
let list_id = if type_name == "Task" {
Inner::task_list_id_of(&value)
} else {
None
};
let prev = inner
.objects_mut(type_name, account_id)
.insert(Id::from(id), value);
if type_name == "Task" {
if let Some(old) = prev.as_ref() {
inner.dec_task_ref(account_id, Inner::task_list_id_of(old));
}
inner.inc_task_ref(account_id, list_id);
}
}
}
impl JmapBackend for MemoryBackend {
type Error = MemoryError;
type CallerCtx = ();
async fn account_exists(&self, _caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
let inner = self.inner.lock().unwrap();
Ok(inner.known_accounts.contains(account_id.as_ref()))
}
async fn get_objects<O: GetObject + Send + Sync>(
&self,
_caller: &(),
account_id: &Id,
ids: Option<&[Id]>,
_properties: Option<&[String]>,
) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
let inner = self.inner.lock().unwrap();
let map = inner.objects_ref(O::TYPE_NAME, account_id.as_ref());
let deser_err =
|e: serde_json::Error| MemoryError::new(format!("deserialize {}: {e}", O::TYPE_NAME));
match ids {
None => {
let list = map
.map(|m| {
m.values()
.map(|val| O::deserialize(val).map_err(deser_err))
.collect::<Result<Vec<_>, _>>()
})
.transpose()?
.unwrap_or_default();
Ok((list, vec![]))
}
Some(id_slice) => {
let mut found = Vec::new();
let mut not_found = Vec::new();
for id in id_slice {
match map.and_then(|m| m.get(id)) {
Some(val) => found.push(O::deserialize(val).map_err(deser_err)?),
None => not_found.push(id.clone()),
}
}
Ok((found, not_found))
}
}
}
async fn get_state<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
account_id: &Id,
) -> Result<State, Self::Error> {
let inner = self.inner.lock().unwrap();
let n = inner.current_state(O::TYPE_NAME, account_id.as_ref());
Ok(State::from(n.to_string()))
}
async fn get_changes<O: JmapObject + Send + Sync>(
&self,
_caller: &(),
account_id: &Id,
since_state: &State,
max_changes: Option<u64>,
) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
let inner = self.inner.lock().unwrap();
let since_n: u64 = since_state
.as_ref()
.parse()
.map_err(|_| BackendChangesError::CannotCalculate)?;
let log = inner
.change_log
.get(&(O::TYPE_NAME, account_id.as_ref().to_owned()))
.map(Vec::as_slice)
.unwrap_or(&[]);
let relevant: Vec<&ChangeEntry> = log.iter().filter(|e| e.new_state > since_n).collect();
let current_state = inner.current_state(O::TYPE_NAME, account_id.as_ref());
if let Some(max) = max_changes {
if relevant.len() as u64 > max {
return Err(BackendChangesError::TooManyChanges { limit: max });
}
}
let mut created: Vec<Id> = Vec::new();
let mut updated: Vec<Id> = Vec::new();
let mut destroyed: Vec<Id> = Vec::new();
for entry in &relevant {
for id in &entry.created {
if !destroyed.contains(id) && !created.contains(id) {
created.push(id.clone());
}
}
for id in &entry.updated {
if !destroyed.contains(id) && !created.contains(id) && !updated.contains(id) {
updated.push(id.clone());
}
}
for id in &entry.destroyed {
created.retain(|c| c != id);
updated.retain(|u| u != id);
if !destroyed.contains(id) {
destroyed.push(id.clone());
}
}
}
Ok(ChangesResult::new(
created,
updated,
destroyed,
false,
State::from(current_state.to_string()),
))
}
async fn query_objects<O: QueryObject + Send + Sync>(
&self,
_caller: &(),
account_id: &Id,
filter: Option<&O::Filter>,
sort: Option<&[O::Comparator]>,
limit: Option<u64>,
position: i64,
anchor: Option<&Id>,
anchor_offset: i64,
) -> Result<QueryResult, BackendQueryError<Self::Error>> {
if let Some(f) = filter {
let v = serde_json::to_value(f).expect("derive(Serialize) on plain data is infallible");
let any_field_set = match v.as_object() {
Some(m) => m.values().any(|val| !val.is_null()),
None => true,
};
if any_field_set {
return Err(BackendQueryError::Other(MemoryError::new(format!(
"MemoryBackend does not support filter on {}/query — reference \
implementation; a production backend MUST honor RFC 8620 §5.5 \
filter / supported_filter for {}",
O::TYPE_NAME,
O::TYPE_NAME
))));
}
}
if sort.is_some_and(|s| !s.is_empty()) {
return Err(BackendQueryError::Other(MemoryError::new(format!(
"MemoryBackend does not support sort on {}/query — reference \
implementation returns id-lexicographic order; a production \
backend MUST honor RFC 8620 §5.5 sort / supported_sort for {}",
O::TYPE_NAME,
O::TYPE_NAME
))));
}
let inner = self.inner.lock().unwrap();
let mut ids: Vec<Id> = inner
.objects_ref(O::TYPE_NAME, account_id.as_ref())
.map(|m| {
let mut keys: Vec<Id> = m.keys().cloned().collect();
keys.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
keys
})
.unwrap_or_default();
let total = ids.len() as u64;
let query_state = State::from(
inner
.current_state(O::TYPE_NAME, account_id.as_ref())
.to_string()
.as_str(),
);
let start = resolve_query_start(&ids, position, anchor, anchor_offset)
.map_err(BackendQueryError::Method)?;
ids = ids[start..]
.iter()
.take(limit.map_or(usize::MAX, |n| n as usize))
.cloned()
.collect();
Ok(QueryResult::new(
ids,
start as u64,
Some(total),
query_state,
true,
))
}
async fn query_changes<O: QueryObject + Send + Sync>(
&self,
caller: &(),
account_id: &Id,
since_query_state: &State,
_filter: Option<&O::Filter>,
_sort: Option<&[O::Comparator]>,
max_changes: Option<u64>,
_up_to_id: Option<&Id>,
_collapse_threads: bool,
) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
let changes = self
.get_changes::<O>(caller, account_id, since_query_state, max_changes)
.await?;
let inner = self.inner.lock().unwrap();
let new_query_state = State::from(
inner
.current_state(O::TYPE_NAME, account_id.as_ref())
.to_string()
.as_str(),
);
let current_ids: Vec<Id> = inner
.objects_ref(O::TYPE_NAME, account_id.as_ref())
.map(|m| {
let mut keys: Vec<Id> = m.keys().cloned().collect();
keys.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
keys
})
.unwrap_or_default();
let removed: Vec<Id> = changes.destroyed;
let added: Vec<AddedItem> = changes
.created
.iter()
.filter_map(|id| {
current_ids
.iter()
.position(|cur| cur == id)
.map(|idx| AddedItem::new(id.clone(), idx as u64))
})
.collect();
Ok(QueryChangesResult::new(
since_query_state.clone(),
new_query_state,
Some(current_ids.len() as u64),
removed,
added,
))
}
}
impl TasksBackend for MemoryBackend {
async fn create_object<O: SetObject + Send + Sync>(
&self,
_caller: &(),
account_id: &Id,
_create_id: &str,
obj: O,
) -> Result<(Id, O), BackendSetError<Self::Error>> {
let mut inner = self.inner.lock().unwrap();
inner.known_accounts.insert(account_id.as_ref().to_owned());
let server_id = Id::from(uuid::Uuid::new_v4().to_string());
let mut val = serde_json::to_value(&obj)
.map_err(|e| BackendSetError::Other(MemoryError::new(format!("serialize: {e}"))))?;
if let Some(map) = val.as_object_mut() {
map.insert(
"id".to_owned(),
serde_json::Value::String(server_id.as_ref().to_owned()),
);
}
let stored_obj: O = O::deserialize(&val).map_err(|e| {
BackendSetError::Other(MemoryError::new(format!("deserialize after create: {e}")))
})?;
let task_list_id = if O::TYPE_NAME == "Task" {
Inner::task_list_id_of(&val)
} else {
None
};
let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
inner
.objects_mut(O::TYPE_NAME, account_id.as_ref())
.insert(server_id.clone(), val);
inner
.change_log_mut(O::TYPE_NAME, account_id.as_ref())
.push(ChangeEntry {
new_state,
created: vec![server_id.clone()],
updated: vec![],
destroyed: vec![],
});
if O::TYPE_NAME == "Task" {
inner.inc_task_ref(account_id.as_ref(), task_list_id);
}
Ok((server_id, stored_obj))
}
async fn update_object<O: SetObject + Send + Sync>(
&self,
_caller: &(),
account_id: &Id,
id: &Id,
patch: O::Patch,
) -> Result<Option<O>, BackendSetError<Self::Error>> {
let mut inner = self.inner.lock().unwrap();
let existing = inner
.objects_mut(O::TYPE_NAME, account_id.as_ref())
.get(id)
.cloned();
let Some(mut current) = existing else {
return Err(BackendSetError::SetError(SetError::new(
SetErrorType::NotFound,
)));
};
let patch_val = serde_json::to_value(&patch).map_err(|e| {
BackendSetError::Other(MemoryError::new(format!("serialize patch: {e}")))
})?;
let was_draft = current.get("isDraft").and_then(|v| v.as_bool()) == Some(true);
let old_task_list_id = if O::TYPE_NAME == "Task" {
Inner::task_list_id_of(¤t)
} else {
None
};
if let (serde_json::Value::Object(base), serde_json::Value::Object(patch_map)) =
(&mut current, &patch_val)
{
apply_patch_object(base, patch_map).map_err(|e| {
BackendSetError::SetError(
SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
)
})?;
}
if let Err(e) = O::deserialize(¤t) {
let mut heads: Vec<String> = patch_val
.as_object()
.into_iter()
.flat_map(|m| m.keys())
.map(|k| {
let head = k.split('/').next().unwrap_or(k);
head.replace("~1", "/").replace("~0", "~")
})
.collect();
heads.sort_unstable();
heads.dedup();
let mut err =
SetError::new(SetErrorType::InvalidProperties).with_description(e.to_string());
if heads.len() == 1 {
err = err.with_properties(heads);
}
return Err(BackendSetError::SetError(err));
}
if O::TYPE_NAME == "Task"
&& !was_draft
&& current.get("isDraft").and_then(|v| v.as_bool()) == Some(true)
{
return Err(BackendSetError::SetError(
SetError::new(SetErrorType::InvalidProperties)
.with_properties(vec!["isDraft".to_owned()]),
));
}
let new_task_list_id = if O::TYPE_NAME == "Task" {
Inner::task_list_id_of(¤t)
} else {
None
};
let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
inner
.objects_mut(O::TYPE_NAME, account_id.as_ref())
.insert(id.clone(), current);
inner
.change_log_mut(O::TYPE_NAME, account_id.as_ref())
.push(ChangeEntry {
new_state,
created: vec![],
updated: vec![id.clone()],
destroyed: vec![],
});
if O::TYPE_NAME == "Task" && old_task_list_id != new_task_list_id {
inner.dec_task_ref(account_id.as_ref(), old_task_list_id);
inner.inc_task_ref(account_id.as_ref(), new_task_list_id);
}
Ok(None)
}
async fn destroy_object<O: SetObject + Send + Sync>(
&self,
_caller: &(),
account_id: &Id,
id: &Id,
) -> Result<(), BackendSetError<Self::Error>> {
let mut inner = self.inner.lock().unwrap();
let removed = inner
.objects_mut(O::TYPE_NAME, account_id.as_ref())
.remove(id);
match removed {
Some(val) => {
let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
inner
.change_log_mut(O::TYPE_NAME, account_id.as_ref())
.push(ChangeEntry {
new_state,
created: vec![],
updated: vec![],
destroyed: vec![id.clone()],
});
if O::TYPE_NAME == "Task" {
inner.dec_task_ref(account_id.as_ref(), Inner::task_list_id_of(&val));
}
Ok(())
}
None => Err(BackendSetError::SetError(SetError::new(
SetErrorType::NotFound,
))),
}
}
fn supports_type<O: JmapObject>(
&self,
_caller: &Self::CallerCtx,
_account_id: &jmap_types::Id,
) -> bool {
matches!(O::TYPE_NAME, "TaskList" | "Task" | "TaskNotification")
}
async fn task_list_has_tasks(
&self,
_caller: &(),
account_id: &Id,
task_list_id: &Id,
) -> Result<bool, MemoryError> {
let inner = self.inner.lock().unwrap();
Ok(inner
.aux_ref(account_id.as_ref())
.is_some_and(|a| a.task_list_refcount.contains_key(task_list_id)))
}
fn enforce_is_draft_atomically(&self) -> bool {
true
}
}