Skip to main content

jmap_tasks_server/
memory.rs

1//! In-memory reference implementation of [`TasksBackend`].
2//!
3//! # This is a reference implementation, not production
4//!
5//! `MemoryBackend` is intended for three audiences:
6//!
7//! 1. **Workspace integration tests** — every `tests/*.rs` integration test
8//!    in this crate exercises method handlers against this backend.
9//! 2. **Downstream contributors** — a documented, complete, source-readable
10//!    implementation of the [`TasksBackend`] trait to
11//!    study when writing a real (database-backed) backend.
12//! 3. **Examples and smoke tests** — boot a real JMAP-for-Tasks dispatcher
13//!    with one line of code, without standing up a database.
14//!
15//! It is **not** suitable for production: all state is held in `HashMap`s
16//! behind one [`jmap_server::ScopedState`], persistence is not implemented, and a number
17//! of draft-ietf-jmap-tasks-06 edge cases are simplified (see source
18//! comments). In particular, UTC-time conversion
19//! ([`compute_utc_times`](crate::TasksBackend::compute_utc_times))
20//! inherits the trait's default (no time-zone conversion), and
21//! [`update_task_per_user`](crate::TasksBackend::update_task_per_user)
22//! stores per-user patches on the shared object (single-user backend).
23//! `Task/query` has no time-zone database and no recurrence engine:
24//! `after` / `before` on a task whose `timeZone` is not the query's is
25//! `unsupportedFilter`, and with `expandRecurrences` a recurring match is
26//! `cannotCalculateOccurrences`, and a sort by `start` over tasks in more
27//! than one zone is `unsupportedSort` (see
28//! [`query_tasks`](crate::TasksBackend::query_tasks) on `MemoryBackend`).
29//!
30//! # Feature flag and API stability
31//!
32//! This module is gated behind `feature = "memory"` and is **not** enabled
33//! by default. Its public API stability is opt-in: it may break across
34//! minor versions while the crate is pre-1.0.
35//!
36//! # Example
37//!
38//! ```rust,ignore
39//! use std::sync::Arc;
40//! use jmap_tasks_server::{memory::MemoryBackend, register_tasks_handlers};
41//! use jmap_server::Dispatcher;
42//!
43//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
44//! register_tasks_handlers(&mut dispatcher, Arc::new(MemoryBackend::new()));
45//! ```
46//!
47//! # Concurrency
48//!
49//! The store is a [`jmap_server::ScopedState`]: a `std::sync::Mutex` behind
50//! a gate that a draft-ietf-jmap-conditional-02 Foo/set scope holds
51//! (`MemoryBackend`'s `ConditionalBackend` impl). Async backend methods
52//! take `lock().await`, which waits while another task's scope is open;
53//! sync setup and seeding helpers take `lock_unscoped()`. With no scope
54//! open the gate is free. The `await_holding_lock` clippy lint is enabled
55//! module-wide and enforces that no lock guard is held across an
56//! `.await`.
57//!
58//! `ScopedState` takes a poisoned mutex anyway, so a panic while holding
59//! the guard (already a bug in this module) does not panic every later
60//! call; an atomic scope that panicked is rolled back to its snapshot.
61//! The crate's tests never poison the lock. A production backend should
62//! implement the trait with its own locking
63//! rather than copy this pattern.
64//!
65//! # Tracking
66//!
67//! Greenfield reference impl per Beads issue JMAP-hwdv (epic) and
68//! JMAP-hwdv.7 (this crate, mirror of canonical JMAP-hwdv.1 in
69//! jmap-mail-server, following the multi-type-store shape established
70//! by jmap-chat-server's `MemoryBackend` and the derived-index pattern
71//! pioneered in JMAP-hwdv.5 jmap-calendars-server).
72
73#![allow(async_fn_in_trait)]
74#![deny(clippy::await_holding_lock)]
75
76mod history;
77
78use std::cmp::Ordering;
79use std::collections::{BTreeSet, HashMap, HashSet};
80use std::marker::PhantomData;
81
82use crate::{TaskQueryArgs, TasksBackend};
83use jmap_metadata_server::{
84    ChangedProperties, MetadataCondition, MetadataFilterError, MetadataOnlyChanges, SetKind,
85    changed_properties, check_metadata_depth, check_metadata_write, is_metadata_property,
86    metadata_path_exists, metadata_text_contains, metadata_text_equals,
87};
88use jmap_metadata_types::{DataTypeMetadataInfo, MetadataTextMatch};
89use jmap_object_history_server::{ChangeEvent, ChangeKind, fold_restore};
90use jmap_server::{
91    AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
92    JmapAccounts, JmapObject, JmapReads, MemoryCaller, QueryChangesParams, QueryChangesResult,
93    QueryObject, QueryParams, QueryResult, SetError, SetErrorType, SetObject,
94};
95use jmap_server::{
96    BeginSetError, ConditionalBackend, PatchPathError, ScopedState, SetScope, SetScopeRequest,
97    apply_patch_object, check_patch_paths, limit_or_max, resolve_query_start,
98};
99use jmap_tasks_types::{
100    Task, TaskComparator, TaskComparatorProperty, TaskFilterCondition, TaskList,
101};
102use jmap_types::{Id, JmapError, State};
103
104// ---------------------------------------------------------------------------
105// Error type
106// ---------------------------------------------------------------------------
107
108/// Opaque storage-layer error returned by [`MemoryBackend`] operations.
109///
110/// The inner description is a human-readable string intended for
111/// diagnostic logging; it is not a stable wire-format identifier.
112///
113/// # Forward compatibility
114///
115/// This type is `#[non_exhaustive]` and uses a named-field shape so
116/// future revisions can add structured context (error kind, source
117/// reference, account id, etc.) without a breaking change. Outside-
118/// crate construction goes through [`MemoryError::new`]; outside-crate
119/// reads go through [`MemoryError::description`].
120#[non_exhaustive]
121#[derive(Debug)]
122pub struct MemoryError {
123    description: String,
124}
125
126impl MemoryError {
127    /// Construct a [`MemoryError`] from a human-readable description.
128    pub fn new(description: impl Into<String>) -> Self {
129        Self {
130            description: description.into(),
131        }
132    }
133
134    /// Human-readable description of the underlying failure.
135    pub fn description(&self) -> &str {
136        &self.description
137    }
138
139    /// Construct a [`MemoryError`] for a `serde_json` failure during
140    /// `context` (the operation that failed).
141    ///
142    /// Only the error's [`serde_json::error::Category`] is kept. A serde
143    /// data error quotes the offending value (`invalid type: string
144    /// "alice@example.com", expected u64`), and the `JmapAccounts::Error`
145    /// contract forbids PII and blob content in `Display` output
146    /// (bd:JMAP-510h.37).
147    pub(crate) fn serde(context: impl std::fmt::Display, e: &serde_json::Error) -> Self {
148        Self::new(format!("{context}: serde_json {:?} error", e.classify()))
149    }
150}
151
152impl std::fmt::Display for MemoryError {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        write!(f, "MemoryBackend error: {}", self.description)
155    }
156}
157
158impl std::error::Error for MemoryError {}
159
160// ---------------------------------------------------------------------------
161// Change log
162// ---------------------------------------------------------------------------
163
164/// Per-ID fate tracker for RFC 8620 §5.2 ID deduplication across change log
165/// entries in one `/changes` window.
166///
167/// - created+updated → `Created`
168/// - created+destroyed → omitted (the client never knew the object)
169/// - updated+destroyed → `Destroyed`
170/// - updated+updated → `Updated`
171///
172/// Mirrors the canonical jmap-mail-server `IdFate` enum.
173#[derive(Debug, Clone, Copy)]
174enum IdFate {
175    Created,
176    Updated,
177    Destroyed,
178}
179
180/// A change log entry for one state transition.
181#[derive(Clone, Debug)]
182struct ChangeEntry {
183    /// The state counter AFTER this change.
184    new_state: u64,
185    created: Vec<Id>,
186    updated: Vec<Id>,
187    destroyed: Vec<Id>,
188    /// The top-level properties this change altered on every id in
189    /// `updated`, or `None` when not known. Feeds
190    /// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges` and
191    /// `updatedProperties`.
192    updated_props: Option<BTreeSet<String>>,
193    /// Ids restored from object history (draft-ietf-jmap-object-history
194    /// §5.1).
195    restored: Vec<Id>,
196}
197
198impl ChangeEntry {
199    /// `true` for an update that changed only `metadata` and/or
200    /// `privateMetadata` (draft-ietf-jmap-metadata-05 §3.3).
201    fn is_metadata_only_update(&self) -> bool {
202        self.created.is_empty()
203            && self.destroyed.is_empty()
204            && self.updated_props.as_ref().is_some_and(|props| {
205                !props.is_empty() && props.iter().all(|p| is_metadata_property(p))
206            })
207    }
208}
209
210// ---------------------------------------------------------------------------
211// Inner state
212// ---------------------------------------------------------------------------
213
214/// Per-account auxiliary state that is not keyed by object type.
215#[derive(Default, Clone)]
216struct AccountAux {
217    /// Refcount of [`TaskList`] ids by the number of Tasks attached to each
218    /// (drives `TaskList/set` destroy rejection with `taskListHasTask`
219    /// per draft-ietf-jmap-tasks-06 §3.4 when `onDestroyRemoveTasks` is
220    /// `false`). Maintained incrementally: `inc_task_ref` on Task create,
221    /// `dec_task_ref` on Task destroy, both on a taskListId change. O(1)
222    /// per Task mutation — the previous full-scan recompute was O(N).
223    /// Entries are removed when the count drops to 0 so `task_list_has_tasks`
224    /// can read presence-as-truthy instead of value-as-truthy.
225    task_list_refcount: HashMap<Id, u64>,
226}
227
228/// Shared inner state, behind a [`ScopedState`] so a conditional Foo/set
229/// can isolate and roll it back (docs/design/conditional.md §7).
230#[derive(Default, Clone)]
231struct Inner {
232    /// `type_name` → `account_id` → `id → serialized object`
233    objects: HashMap<&'static str, HashMap<String, HashMap<Id, serde_json::Value>>>,
234    /// `type_name` → `account_id` → current state counter
235    states: HashMap<&'static str, HashMap<String, u64>>,
236    /// `type_name` → `account_id` → ordered change entries
237    change_log: HashMap<&'static str, HashMap<String, Vec<ChangeEntry>>>,
238    /// `account_id` → auxiliary per-account state (derived indexes)
239    aux: HashMap<String, AccountAux>,
240    /// Explicitly registered account ids (accounts may exist with no objects yet).
241    known_accounts: HashSet<String>,
242    /// `type_name` → the draft-ietf-jmap-metadata-05 §1.2.1
243    /// [`DataTypeMetadataInfo`] set by [`MemoryBackend::with_metadata_info`].
244    /// A type without an entry does not have the metadata properties.
245    metadata_info: HashMap<&'static str, DataTypeMetadataInfo>,
246    /// Object history, once `MemoryBackend::with_object_history` turns it
247    /// on.
248    history: Option<jmap_object_history_server::HistoryStore>,
249}
250
251impl Inner {
252    fn current_state(&self, type_name: &'static str, account_id: &str) -> u64 {
253        self.states
254            .get(type_name)
255            .and_then(|m| m.get(account_id))
256            .copied()
257            .unwrap_or(0)
258    }
259
260    fn bump_state(&mut self, type_name: &'static str, account_id: &str) -> u64 {
261        let entry = self
262            .states
263            .entry(type_name)
264            .or_default()
265            .entry(account_id.to_owned())
266            .or_insert(0);
267        *entry += 1;
268        *entry
269    }
270
271    /// The store for `type_name` in `account_id`, created empty on first
272    /// use. Pure storage: it never registers the account (bd:JMAP-ayoz.36);
273    /// mutations check `require_account` first.
274    fn objects_mut(
275        &mut self,
276        type_name: &'static str,
277        account_id: &str,
278    ) -> &mut HashMap<Id, serde_json::Value> {
279        self.objects
280            .entry(type_name)
281            .or_default()
282            .entry(account_id.to_owned())
283            .or_default()
284    }
285
286    /// `Err` unless `account_id` was registered. Creates and copies are
287    /// per-object mutations, not account lifecycle operations
288    /// (bd:JMAP-ayoz.2, JMAP-ayoz.36): one aimed at an unknown account fails
289    /// instead of registering it. The handlers answer `accountNotFound`
290    /// before this is reached; it guards direct backend callers.
291    fn require_account(&self, account_id: &str) -> Result<(), BackendSetError<MemoryError>> {
292        if self.known_accounts.contains(account_id) {
293            Ok(())
294        } else {
295            Err(BackendSetError::Other(MemoryError::new(format!(
296                "unknown account {account_id:?}"
297            ))))
298        }
299    }
300
301    /// `notFound` for an update or destroy in an account nobody registered:
302    /// it has no objects (RFC 8620 §5.3).
303    fn require_account_for_target(
304        &self,
305        account_id: &str,
306    ) -> Result<(), BackendSetError<MemoryError>> {
307        if self.known_accounts.contains(account_id) {
308            Ok(())
309        } else {
310            Err(BackendSetError::SetError(Box::new(SetError::new(
311                SetErrorType::NotFound,
312            ))))
313        }
314    }
315
316    fn objects_ref(
317        &self,
318        type_name: &'static str,
319        account_id: &str,
320    ) -> Option<&HashMap<Id, serde_json::Value>> {
321        self.objects.get(type_name).and_then(|m| m.get(account_id))
322    }
323
324    fn change_log_mut(
325        &mut self,
326        type_name: &'static str,
327        account_id: &str,
328    ) -> &mut Vec<ChangeEntry> {
329        self.change_log
330            .entry(type_name)
331            .or_default()
332            .entry(account_id.to_owned())
333            .or_default()
334    }
335
336    fn aux_mut(&mut self, account_id: &str) -> &mut AccountAux {
337        self.aux.entry(account_id.to_owned()).or_default()
338    }
339
340    fn aux_ref(&self, account_id: &str) -> Option<&AccountAux> {
341        self.aux.get(account_id)
342    }
343
344    /// Read `taskListId` out of a serialized Task value, if present.
345    /// The `workflowStatuses` of task list `list_id`, or `None` when the
346    /// list is not stored or has none (the default applies).
347    fn workflow_statuses(&mut self, account_id: &str, list_id: Option<&Id>) -> Option<Vec<String>> {
348        let list = self
349            .objects_mut(TaskList::TYPE_NAME, account_id)
350            .get(list_id?)?;
351        serde_json::from_value(list.get("workflowStatuses")?.clone()).ok()
352    }
353
354    /// Decision 42 on Task `task` under the lock
355    /// ([`crate::workflow::apply_workflow_status`]).
356    fn apply_workflow(
357        &mut self,
358        account_id: &str,
359        task: &mut serde_json::Value,
360        write: crate::workflow::WorkflowWrite<'_>,
361    ) -> Result<bool, BackendSetError<MemoryError>> {
362        let list = Self::task_list_id_of(task);
363        let statuses = self.workflow_statuses(account_id, list.as_ref());
364        let serde_json::Value::Object(map) = task else {
365            return Ok(false);
366        };
367        crate::workflow::apply_workflow_status(
368            map,
369            write,
370            statuses.as_deref(),
371            jmap_server::now_utc_string().as_ref(),
372        )
373        .map_err(BackendSetError::SetError)
374    }
375
376    fn task_list_id_of(task: &serde_json::Value) -> Option<Id> {
377        task.get("taskListId")
378            .and_then(|v| v.as_str())
379            .map(Id::from)
380    }
381
382    /// Increment the refcount for `list_id` in the given account by one.
383    /// Called when a Task is created or its `taskListId` changes to
384    /// `list_id`. No-op when `list_id` is `None` (well-formed Tasks
385    /// always have a taskListId but the helper is defensive against
386    /// partial mid-write state).
387    fn inc_task_ref(&mut self, account_id: &str, list_id: Option<Id>) {
388        if let Some(id) = list_id {
389            *self
390                .aux_mut(account_id)
391                .task_list_refcount
392                .entry(id)
393                .or_insert(0) += 1;
394        }
395    }
396
397    /// Decrement the refcount for `list_id` in the given account by one.
398    /// Removes the entry when the count drops to zero so `task_list_has_tasks`
399    /// can read presence-as-truthy. Safe to call with `None` or an unknown
400    /// id (no-op).
401    fn dec_task_ref(&mut self, account_id: &str, list_id: Option<Id>) {
402        let Some(id) = list_id else { return };
403        let aux = self.aux_mut(account_id);
404        if let Some(count) = aux.task_list_refcount.get_mut(&id) {
405            *count = count.saturating_sub(1);
406            if *count == 0 {
407                aux.task_list_refcount.remove(&id);
408            }
409        }
410    }
411}
412
413// ---------------------------------------------------------------------------
414// MemoryBackend
415// ---------------------------------------------------------------------------
416
417/// A fully in-memory implementation of [`TasksBackend`].
418///
419/// Stores objects as serialized JSON; each mutation bumps a monotonic state
420/// counter and records a change log entry. Used as both the integration-test
421/// harness and the canonical example for backend implementors.
422///
423/// Cloning is cheap and **shared-state**: every clone retains an
424/// handle to the *same* underlying object store and change
425/// log. See the [`Clone`] impl below for the contract; a casual reader who
426/// reaches for `#[derive(Clone)]` semantics will be wrong. To get a snapshot
427/// with independent state, construct a fresh `MemoryBackend::new()` and seed
428/// it via `register_account` / the typed test helpers.
429///
430/// `C` is the [`JmapAccounts::CallerCtx`]: [`Id`], the caller's Principal
431/// id, by default, or `()` for a deployment without identity. This
432/// backend keeps no per-user state, so every caller acts as the account
433/// owner; [`JmapAccounts::principal_id`] returns
434/// [`MemoryCaller::principal`].
435#[non_exhaustive]
436pub struct MemoryBackend<C = Id> {
437    inner: ScopedState<Inner>,
438    caller: PhantomData<fn() -> C>,
439}
440
441/// An empty backend: [`MemoryBackend::new`] for any caller context, such
442/// as `MemoryBackend::<()>::default()` for a deployment without identity.
443impl<C> Default for MemoryBackend<C> {
444    fn default() -> Self {
445        Self {
446            inner: ScopedState::default(),
447            caller: PhantomData,
448        }
449    }
450}
451
452/// Manual `Clone` impl, NOT `#[derive(Clone)]`.
453///
454/// Cloning a [`MemoryBackend`] does **not** copy any state — both the
455/// original and the clone hold handles to the same [`ScopedState`] and
456/// observe each other's mutations. This is intentional: handler registration
457/// in [`crate::register_tasks_handlers`] takes `Arc<B>` and each method
458/// handler closure clones it; without shared mutation semantics, every
459/// handler would see a snapshot stale by the time it runs. The manual impl
460/// exists (instead of `#[derive(Clone)]`) so the contract is visible at the
461/// type, not buried in the module docs.
462impl<C> Clone for MemoryBackend<C> {
463    fn clone(&self) -> Self {
464        Self {
465            inner: self.inner.clone(),
466            caller: PhantomData,
467        }
468    }
469}
470
471impl MemoryBackend {
472    /// Create a new, empty `MemoryBackend`.
473    ///
474    /// Its callers are Principal ids (`C = Id`);
475    /// `MemoryBackend::<()>::default()` takes callers without identity.
476    pub fn new() -> Self {
477        Self::default()
478    }
479}
480
481impl<C: MemoryCaller> MemoryBackend<C> {
482    /// Register `account_id` as known and return `self`, for
483    /// builder-style fixture setup. Until then the account is unknown
484    /// (`accountNotFound`, RFC 8620 §3.6.2). Idempotent; the id is stored
485    /// without RFC 8620 §1.2 validation.
486    ///
487    /// # Panics
488    ///
489    /// In debug builds, if `account_id` is the empty string (RFC 8620
490    /// §1.2, bd:JMAP-dx0s).
491    #[must_use]
492    pub fn with_account(self, account_id: &Id) -> Self {
493        self.register_account(account_id);
494        self
495    }
496
497    /// Give `data_type` the draft-ietf-jmap-metadata-05 `metadata`
498    /// property, configured by `info` (the [`DataTypeMetadataInfo`] of -05
499    /// §1.2.1).
500    ///
501    /// Without this call a type has no metadata: `Foo/set` rejects a
502    /// write to `metadata` or `privateMetadata` with `invalidProperties`
503    /// and `Foo/query` rejects a metadata filter condition with
504    /// `unsupportedFilter`. With it, `Foo/set` validates metadata writes
505    /// (-05 §3.2, §4.1), `Task/query` evaluates the -05 §3.6 conditions,
506    /// and `Foo/changes` honours `ignoreMetadataOnlyChanges` and reports
507    /// `updatedProperties` (-05 §3.3). Advertising the capability in the
508    /// session is the server's job: list `info` under `data_type` in the
509    /// account's `urn:ietf:params:jmap:metadata` `dataTypes`.
510    ///
511    /// [`TaskList`] writes need `myRights.maySetMetadata` on the `TaskList`, and
512    /// Task writes need it on the Task's `TaskList` before and after the
513    /// update, or on the `taskListId` of a create (-05 §4.1). An absent
514    /// `maySetMetadata` allows the write (fail-open, JMAP-bghk). This
515    /// backend never sets Task `updated`, so a metadata-only change leaves
516    /// it alone, as -05 §3.1 requires.
517    ///
518    /// # Panics
519    ///
520    /// Panics if `data_type` is not `"TaskList"` or `"Task"` (the rights
521    /// object of draft-ietf-jmap-tasks-06 §3 and the type it contains;
522    /// -05 §4.1), or if `info.supports_private` is true: this backend has
523    /// no per-user state to own `privateMetadata`
524    /// (-05 §2).
525    #[must_use]
526    pub fn with_metadata_info(self, data_type: &str, info: DataTypeMetadataInfo) -> Self {
527        let type_name = metadata_type_name(data_type).unwrap_or_else(|| {
528            panic!("MemoryBackend supports metadata only on TaskList and Task, not {data_type:?}")
529        });
530        assert!(
531            !info.supports_private,
532            "MemoryBackend does not support privateMetadata (supportsPrivate must be false)"
533        );
534        self.inner
535            .lock_unscoped()
536            .metadata_info
537            .insert(type_name, info);
538        self
539    }
540
541    /// Test-only entry point that registers an account as known even
542    /// if it has no objects yet. Production callers must not use this
543    /// method; the API stability disclaimer on the `memory` feature
544    /// applies doubly here.
545    ///
546    /// The name is retained (not renamed to `register_account_for_test`)
547    /// for backward compatibility with the workspace's existing
548    /// integration test suite, which calls this method through the
549    /// public API surface. `#[doc(hidden)]` removes it from `cargo doc`
550    /// output so downstream consumers do not see it as a documented
551    /// part of the surface.
552    #[doc(hidden)]
553    pub fn register_account(&self, account_id: &Id) {
554        debug_assert!(
555            !account_id.as_ref().is_empty(),
556            "register_account: account_id must not be the empty string \
557             (RFC 8620 §1.2, bd:JMAP-dx0s)"
558        );
559        let mut inner = self.inner.lock_unscoped();
560        inner.known_accounts.insert(account_id.as_ref().to_owned());
561        inner.aux.entry(account_id.as_ref().to_owned()).or_default();
562    }
563
564    /// Seed a pre-existing object into the store without bumping the
565    /// state counter or recording a change-log entry. Test-fixture setup
566    /// only; registers `account_id` as known. Mirrors
567    /// `jmap_mail_server::memory::MemoryBackend::seed_object`.
568    ///
569    /// `type_name` is the `TYPE_NAME` of a type this backend stores:
570    /// `"TaskList"`, `"Task"`, or `"TaskNotification"`. A seeded Task's
571    /// `taskListId` is counted in the [`TaskList`] reference index.
572    ///
573    /// # Panics
574    ///
575    /// If `type_name` is not one of the names above, or `value` is not a
576    /// JSON object whose `id` string equals `id`.
577    pub fn seed_object(
578        &self,
579        account_id: &Id,
580        type_name: &'static str,
581        id: &Id,
582        value: serde_json::Value,
583    ) {
584        const KNOWN_TYPES: &[&str] = &[
585            jmap_tasks_types::TaskList::TYPE_NAME,
586            jmap_tasks_types::Task::TYPE_NAME,
587            jmap_tasks_types::TaskNotification::TYPE_NAME,
588        ];
589        assert!(
590            KNOWN_TYPES.contains(&type_name),
591            "seed_object: type_name {type_name:?} is not one of the known \
592             TYPE_NAME values {KNOWN_TYPES:?}"
593        );
594        let obj = value.as_object().unwrap_or_else(|| {
595            panic!("seed_object: value must be a JSON object with an `id` field, got {value:?}")
596        });
597        let value_id = obj
598            .get("id")
599            .and_then(serde_json::Value::as_str)
600            .unwrap_or_else(|| {
601                panic!(
602                    "seed_object: value must contain an `id` string field; got value = {value:?}"
603                )
604            });
605        assert_eq!(
606            value_id,
607            id.as_ref(),
608            "seed_object: value's `id` field {value_id:?} does not match the \
609             `id` argument {id:?}"
610        );
611        let account_id = account_id.as_ref();
612        let mut inner = self.inner.lock_unscoped();
613        inner.known_accounts.insert(account_id.to_owned());
614        let list_id = if type_name == "Task" {
615            Inner::task_list_id_of(&value)
616        } else {
617            None
618        };
619        let prev = inner
620            .objects_mut(type_name, account_id)
621            .insert(id.clone(), value);
622        if type_name == "Task" {
623            // If this id was already seeded, decrement its prior taskListId
624            // refcount first to keep the index correct on re-seed.
625            if let Some(old) = prev.as_ref() {
626                inner.dec_task_ref(account_id, Inner::task_list_id_of(old));
627            }
628            inner.inc_task_ref(account_id, list_id);
629        }
630    }
631}
632
633// ---------------------------------------------------------------------------
634// JmapBackend impl (read-side supertrait)
635// ---------------------------------------------------------------------------
636
637impl<C: MemoryCaller> JmapAccounts for MemoryBackend<C> {
638    type Error = MemoryError;
639    type CallerCtx = C;
640
641    /// [`MemoryCaller::principal`].
642    fn principal_id(caller: &C) -> Option<&Id> {
643        caller.principal()
644    }
645
646    /// The info set by [`MemoryBackend::with_metadata_info`], the same for
647    /// every account.
648    fn metadata_info<O: JmapObject>(
649        &self,
650        _caller: &C,
651        _account_id: &Id,
652    ) -> Option<DataTypeMetadataInfo> {
653        self.inner
654            .lock_unscoped()
655            .metadata_info
656            .get(O::TYPE_NAME)
657            .cloned()
658    }
659
660    async fn account_exists(&self, _caller: &C, account_id: &Id) -> Result<bool, Self::Error> {
661        let inner = self.inner.lock().await;
662        Ok(inner.known_accounts.contains(account_id.as_ref()))
663    }
664}
665
666impl<C: MemoryCaller> JmapReads for MemoryBackend<C> {
667    async fn get_objects<O: GetObject + Send + Sync>(
668        &self,
669        _caller: &C,
670        account_id: &Id,
671        ids: Option<&[Id]>,
672        _properties: Option<&[String]>,
673    ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
674        let inner = self.inner.lock().await;
675        let map = inner.objects_ref(O::TYPE_NAME, account_id.as_ref());
676
677        // The deserialize error closure is shared by both branches.
678        let deser_err = |e: serde_json::Error| {
679            MemoryError::serde(format_args!("deserialize {}", O::TYPE_NAME), &e)
680        };
681
682        match ids {
683            None => {
684                // Collect every stored object; bail on the first deserialize
685                // error via the standard `Result<Vec<_>, _>` collect idiom.
686                let list = map
687                    .map(|m| {
688                        m.values()
689                            .map(|val| O::deserialize(val).map_err(deser_err))
690                            .collect::<Result<Vec<_>, _>>()
691                    })
692                    .transpose()?
693                    .unwrap_or_default();
694                Ok((list, vec![]))
695            }
696            Some(id_slice) => {
697                // Two output vecs (found + not_found) — keep the explicit
698                // loop, but use `?` instead of a manual `match Err { return }`.
699                let mut found = Vec::new();
700                let mut not_found = Vec::new();
701                for id in id_slice {
702                    match map.and_then(|m| m.get(id)) {
703                        Some(val) => found.push(O::deserialize(val).map_err(deser_err)?),
704                        None => not_found.push(id.clone()),
705                    }
706                }
707                Ok((found, not_found))
708            }
709        }
710    }
711
712    async fn get_state<O: JmapObject + Send + Sync>(
713        &self,
714        _caller: &C,
715        account_id: &Id,
716    ) -> Result<State, Self::Error> {
717        let inner = self.inner.lock().await;
718        let n = inner.current_state(O::TYPE_NAME, account_id.as_ref());
719        Ok(State::from(n.to_string()))
720    }
721
722    async fn get_changes<O: JmapObject + Send + Sync>(
723        &self,
724        _caller: &C,
725        account_id: &Id,
726        params: jmap_server::ChangesParams<'_>,
727    ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
728        let since_state = params.since_state;
729        let max_changes = params.max_changes;
730        // draft-ietf-jmap-metadata-05 §3: jmap_server::handle_changes has
731        // already folded a `using` without the capability into this flag.
732        let mode = if params.ignore_metadata_only_changes {
733            MetadataOnlyChanges::Ignore
734        } else {
735            MetadataOnlyChanges::Report
736        };
737        let inner = self.inner.lock().await;
738
739        let since_n: u64 = since_state
740            .as_ref()
741            .parse()
742            .map_err(|_| BackendChangesError::CannotCalculate)?;
743
744        let log = inner
745            .change_log
746            .get(O::TYPE_NAME)
747            .and_then(|m| m.get(account_id.as_ref()))
748            .map(Vec::as_slice)
749            .unwrap_or(&[]);
750
751        let mut relevant: Vec<&ChangeEntry> =
752            log.iter().filter(|e| e.new_state > since_n).collect();
753
754        let current_state = inner.current_state(O::TYPE_NAME, account_id.as_ref());
755
756        // RFC 8620 §5.2: over maxChanges "the server SHOULD generate an
757        // update to take the client to an intermediate state", and only
758        // when "unable to calculate an intermediate state" return
759        // cannotCalculateChanges. Whole entries are taken, oldest first,
760        // while their ids fit; an entry's ids bound what it adds after the
761        // dedup below. A metadata-only update under Ignore adds none: -05
762        // §3.3 "Excluded ids do not count toward maxChanges". The first
763        // entry alone over the limit has no intermediate state.
764        let mut has_more = false;
765        if let Some(max) = max_changes {
766            let mut ids = 0u64;
767            if let Some(cut) = relevant.iter().position(|e| {
768                if !(mode == MetadataOnlyChanges::Ignore && e.is_metadata_only_update()) {
769                    ids +=
770                        (e.created.len() + e.updated.len() + e.destroyed.len() + e.restored.len())
771                            as u64;
772                }
773                ids > max
774            }) {
775                if cut == 0 {
776                    return Err(BackendChangesError::TooManyChanges { limit: max });
777                }
778                relevant.truncate(cut);
779                has_more = true;
780            }
781        }
782        let new_state = match relevant.last() {
783            Some(e) if has_more => e.new_state,
784            _ => current_state,
785        };
786
787        // RFC 8620 §5.2 ID deduplication across the window, using the
788        // canonical jmap-mail-server `IdFate` rules. `order` keeps first-seen
789        // order so the response lists are deterministic.
790        let mut fates: HashMap<Id, IdFate> = HashMap::new();
791        let mut order: Vec<Id> = Vec::new();
792        let mut window_props = ChangedProperties::new();
793        for entry in &relevant {
794            for id in &entry.created {
795                if fates.insert(id.clone(), IdFate::Created).is_none() {
796                    order.push(id.clone());
797                }
798            }
799            for id in &entry.updated {
800                window_props.record(id.as_ref(), entry.updated_props.as_ref());
801                let fate = match fates.get(id) {
802                    Some(IdFate::Created) => IdFate::Created,
803                    Some(IdFate::Destroyed) => IdFate::Destroyed,
804                    _ => IdFate::Updated,
805                };
806                if fates.insert(id.clone(), fate).is_none() {
807                    order.push(id.clone());
808                }
809            }
810            for id in &entry.destroyed {
811                // "If a record has been created AND destroyed since the old
812                // state, the server SHOULD remove the id from the response
813                // entirely." (RFC 8620 §5.2)
814                if matches!(fates.get(id), Some(IdFate::Created)) {
815                    fates.remove(id);
816                } else if fates.insert(id.clone(), IdFate::Destroyed).is_none() {
817                    order.push(id.clone());
818                }
819            }
820        }
821
822        // Object history -04 §5.1: an id restored in the window is
823        // classified by whether it existed at sinceState and exists now,
824        // "exactly as if the object had never been destroyed between them".
825        let mut events: HashMap<Id, Vec<ChangeEvent>> = HashMap::new();
826        for entry in &relevant {
827            for (ids, event) in [
828                (&entry.created, ChangeEvent::Created),
829                (&entry.updated, ChangeEvent::Updated),
830                (&entry.destroyed, ChangeEvent::Destroyed),
831                (&entry.restored, ChangeEvent::Restored),
832            ] {
833                for id in ids {
834                    events.entry(id.clone()).or_default().push(event);
835                }
836            }
837        }
838        for (id, list) in &events {
839            if !list.contains(&ChangeEvent::Restored) {
840                continue;
841            }
842            let fate = match fold_restore(list) {
843                Some(ChangeKind::Created) => IdFate::Created,
844                Some(ChangeKind::Destroyed) => IdFate::Destroyed,
845                Some(_) => {
846                    // A restore is never metadata-only.
847                    window_props.record(id.as_ref(), None);
848                    IdFate::Updated
849                }
850                None => {
851                    fates.remove(id);
852                    continue;
853                }
854            };
855            if fates.insert(id.clone(), fate).is_none() {
856                order.push(id.clone());
857            }
858        }
859
860        let mut created: Vec<Id> = Vec::new();
861        let mut updated: Vec<Id> = Vec::new();
862        let mut destroyed: Vec<Id> = Vec::new();
863        // `fates.remove` emits each id once and skips ids omitted above.
864        for id in order {
865            match fates.remove(&id) {
866                Some(IdFate::Created) => created.push(id),
867                // -05 §3.3: under Ignore, "exclude from the updated array
868                // any id whose only changes since sinceState ... are
869                // confined to metadata and/or privateMetadata".
870                Some(IdFate::Updated)
871                    if mode == MetadataOnlyChanges::Ignore
872                        && window_props.is_metadata_only(id.as_ref()) => {}
873                Some(IdFate::Updated) => updated.push(id),
874                Some(IdFate::Destroyed) => destroyed.push(id),
875                None => {}
876            }
877        }
878
879        // -05 §3.3 `updatedProperties`; no tasks type has the RFC 8621
880        // §2.2 count properties that only Mailbox/changes may list.
881        let updated_properties = window_props.updated_properties(&updated, mode, &[]);
882        Ok(ChangesResult::new(
883            created,
884            updated,
885            destroyed,
886            has_more,
887            State::from(new_state.to_string()),
888        )
889        .with_updated_properties(updated_properties))
890    }
891
892    /// Returns the matching object ids in this account, sorted by id unless
893    /// a Task sort says otherwise, paginated by `position` and `limit`.
894    ///
895    /// # Task sort
896    ///
897    /// A Task `sort` may use the docs/specs/jmap-tasks-local.md Sorting
898    /// properties `id`, `uid`, `start`, `created` and `updated`, with no
899    /// collation or `i;octet`, `i;ascii-casemap` or `i;unicode-casemap`
900    /// (applied to `id` and `uid`). Ties are broken by id; a task without
901    /// the sort property comes after the tasks with it in ascending order.
902    /// With no time-zone database, `start` is compared as a `LocalDateTime`
903    /// string and the call is `unsupportedSort` when the matched tasks
904    /// with a `start` are in more than one zone (a floating task counts as
905    /// the query's zone, here `Etc/UTC`). Any other sort property, and any
906    /// sort of another type, is `unsupportedSort`.
907    ///
908    /// # Filter and other sorts are NOT honored
909    ///
910    /// This reference implementation supports exactly one filter shape: a
911    /// single Task condition whose only set fields are `inTaskLists` (which
912    /// the `TaskList/set` `onDestroyRemoveTasks` cascade, draft-tasks-06
913    /// §3.4, needs), `workflowStatus`, `progress`, `after` and `before`
914    /// (jmapio/jmap #456; see [`TasksBackend::query_tasks`] for the
915    /// time-zone limit; here the query zone is `Etc/UTC`), and the
916    /// draft-ietf-jmap-metadata-05
917    /// §3.6 shared-metadata conditions once [`MemoryBackend::with_metadata_info`]
918    /// opts Task in. It does **not** support any other filter, or any sort
919    /// beyond the Task sort above. RFC 8620 §5.5 mandates that an unsupported `filter` produces
920    /// `unsupportedFilter` at the method level, and an unsupported `sort`
921    /// produces `unsupportedSort`. A production backend MUST inspect both
922    /// arguments against the type's [`QueryObject`] supported sets and
923    /// reject queries that exceed them.
924    ///
925    /// To prevent consumers copying the silent-drop shape into a real
926    /// backend (a workspace test-integrity hazard documented in the
927    /// `MemoryBackend` module rustdoc), this method **fails loud** when
928    /// either argument is non-trivial:
929    ///
930    /// - `filter` is `Some` carrying any non-null field other than those
931    ///   Task fields, or any operator tree it cannot evaluate → returns
932    ///   [`BackendQueryError::Method`] carrying `unsupportedFilter`. A
933    ///   metadata condition on a type that is not opted in is also
934    ///   `unsupportedFilter`, and a malformed one `invalidArguments`
935    ///   (draft-ietf-jmap-metadata-05 §3.6).
936    /// - `sort` is `Some` with a comparator other than the Task sort above
937    ///   → returns [`BackendQueryError::Method`] carrying `unsupportedSort`.
938    ///
939    /// Callers that want "all objects in this account" pass
940    /// `filter = None`, `sort = None`.
941    ///
942    /// Mirrors the reference-impl correctness teaching applied to the
943    /// isDraft re-check in `update_object` (bd:JMAP-h47t.4): the demo
944    /// backend models the spec invariant rather than the spec-violating
945    /// shortcut.
946    async fn query_objects<O: QueryObject + Send + Sync>(
947        &self,
948        caller: &C,
949        account_id: &Id,
950        params: QueryParams<'_, O>,
951    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
952        self.query_impl(caller, account_id, params, &TaskQueryArgs::default())
953            .await
954    }
955
956    /// Returns the changes to a `/query` result set since `since_query_state`.
957    ///
958    /// RFC 8620 §5.6: `/queryChanges` reports changes to the results of
959    /// the same query, so `filter` and `sort` are those of the original
960    /// `/query` and are applied by re-running [`Self::query_objects`]
961    /// (a filter it refuses fails here the same way). `removed` holds the
962    /// destroyed ids and the updated ids that no longer match (a Task moved
963    /// out of the queried `inTaskLists`); `added` holds the created and
964    /// updated ids that match now, with their index in the current result.
965    /// Mirrors the canonical `jmap-mail-server` `MemoryBackend::query_changes`.
966    async fn query_changes<O: QueryObject + Send + Sync>(
967        &self,
968        caller: &C,
969        account_id: &Id,
970        params: QueryChangesParams<'_, O>,
971    ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
972        let QueryChangesParams {
973            since_query_state,
974            filter,
975            sort,
976            max_changes,
977            ..
978        } = params;
979        let changes = self
980            .get_changes::<O>(
981                caller,
982                account_id,
983                jmap_server::ChangesParams::new(since_query_state).max_changes(max_changes),
984            )
985            .await?;
986
987        // The current result of the same query, unpaginated: `added`
988        // indices are positions in it (RFC 8620 §5.6).
989        let current = self
990            .query_objects::<O>(
991                caller,
992                account_id,
993                QueryParams::new().filter(filter).sort(sort),
994            )
995            .await
996            .map_err(|e| match e {
997                BackendQueryError::Other(e) => BackendChangesError::Other(e),
998                // Changes to a query the server cannot run cannot be
999                // calculated; the client's follow-up /query receives the
1000                // method error itself.
1001                _ => BackendChangesError::CannotCalculate,
1002            })?;
1003        let created_set: HashSet<&Id> = changes.created.iter().collect();
1004        let updated_set: HashSet<&Id> = changes.updated.iter().collect();
1005
1006        // Every destroyed or updated id: an update may touch a filter or
1007        // sort property, so RFC 8620 §5.6 requires the id in `removed` and,
1008        // if it still matches, reinserted via `added`.
1009        let mut removed: Vec<Id> = changes
1010            .destroyed
1011            .iter()
1012            .chain(changes.updated.iter())
1013            .cloned()
1014            .collect();
1015        removed.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
1016        removed.dedup();
1017
1018        // Created or updated ids that match the query now.
1019        let added: Vec<AddedItem> = current
1020            .ids
1021            .iter()
1022            .enumerate()
1023            .filter(|(_, id)| created_set.contains(id) || updated_set.contains(id))
1024            .map(|(pos, id)| AddedItem::new(id.clone(), pos as u64))
1025            .collect();
1026
1027        Ok(QueryChangesResult::new(
1028            since_query_state.clone(),
1029            changes.new_state,
1030            current.total,
1031            removed,
1032            added,
1033        ))
1034    }
1035}
1036
1037/// The `TYPE_NAME` of the type named `data_type` if it is one this backend
1038/// can give draft-ietf-jmap-metadata-05 properties: [`TaskList`], which has a
1039/// rights object (draft-ietf-jmap-tasks-06 §3 `myRights`), and Task, which
1040/// "takes the right from its containers" (-05 §4.1).
1041fn metadata_type_name(data_type: &str) -> Option<&'static str> {
1042    [TaskList::TYPE_NAME, Task::TYPE_NAME]
1043        .into_iter()
1044        .find(|t| *t == data_type)
1045}
1046
1047fn invalid_metadata_property(property: &str, description: &str) -> BackendSetError<MemoryError> {
1048    BackendSetError::SetError(Box::new(
1049        SetError::new(SetErrorType::InvalidProperties)
1050            .with_properties([property])
1051            .with_description(description),
1052    ))
1053}
1054
1055impl Inner {
1056    /// draft-ietf-jmap-metadata-05 §3.2 rules 1 to 3 for a metadata write
1057    /// on a `type_name` object, before the write is applied. Returns the
1058    /// type's [`DataTypeMetadataInfo`] for the rule 4 check after applying,
1059    /// or `None` when `entry` writes no metadata.
1060    ///
1061    /// `entry` is the create object or update patch, `stored` the object
1062    /// before an update (`None` on create), and `containers` the [`TaskList`]
1063    /// ids whose `maySetMetadata` a Task write needs (-05 §4.1). Rule 1's
1064    /// `notFound` is the caller's: this backend has no read rights, so
1065    /// only a missing object is unreadable.
1066    fn check_metadata_set(
1067        &self,
1068        type_name: &'static str,
1069        account_id: &str,
1070        kind: SetKind,
1071        entry: &serde_json::Map<String, serde_json::Value>,
1072        stored: Option<&serde_json::Map<String, serde_json::Value>>,
1073        containers: &[&str],
1074    ) -> Result<Option<DataTypeMetadataInfo>, BackendSetError<MemoryError>> {
1075        let Some(first) = entry.keys().find(|k| crate::helpers::is_metadata_key(k)) else {
1076            return Ok(None);
1077        };
1078        // -05 §1.2.1: an unlisted type "does not gain the metadata or
1079        // privateMetadata properties".
1080        let Some(info) = self.metadata_info.get(type_name) else {
1081            return Err(invalid_metadata_property(
1082                first,
1083                "metadata is not supported on this data type",
1084            ));
1085        };
1086        // Rule 1 / -05 §4.1: "A write to metadata without maySetMetadata
1087        // MUST be rejected with a "forbidden" SetError". A TaskList has
1088        // its own rights; a Task takes the right from its TaskList. An
1089        // absent right or container allows the write (fail-open,
1090        // JMAP-bghk).
1091        let writes_shared = entry.keys().any(|k| {
1092            crate::helpers::is_metadata_key(k)
1093                && k.split_once('/').map_or(k.as_str(), |(root, _)| root) == "metadata"
1094        });
1095        let denies = |rights: Option<&serde_json::Value>| {
1096            rights
1097                .and_then(|r| r.get("maySetMetadata"))
1098                .and_then(serde_json::Value::as_bool)
1099                == Some(false)
1100        };
1101        let forbidden = writes_shared
1102            && if type_name == TaskList::TYPE_NAME {
1103                denies(stored.and_then(|l| l.get("myRights")))
1104            } else {
1105                let lists = self.objects_ref(TaskList::TYPE_NAME, account_id);
1106                containers.iter().any(|id| {
1107                    denies(
1108                        lists
1109                            .and_then(|l| l.get(*id))
1110                            .and_then(|list| list.get("myRights")),
1111                    )
1112                })
1113            };
1114        if forbidden {
1115            return Err(BackendSetError::SetError(Box::new(
1116                SetError::new(SetErrorType::Forbidden)
1117                    .with_description("maySetMetadata is required to write metadata"),
1118            )));
1119        }
1120        check_metadata_write(kind, entry, stored, info)
1121            .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
1122        Ok(Some(info.clone()))
1123    }
1124}
1125
1126/// The [`TaskList`] ids a Task update's metadata write needs `maySetMetadata`
1127/// on: the `TaskList` the Task is in before the update and the one `patch`
1128/// moves it to (-05 §4.1: "on every container both before and after the
1129/// change"). draft-ietf-jmap-tasks-06 §4: a Task belongs to exactly one
1130/// `TaskList`, named by the string `taskListId`.
1131fn task_update_containers<'a>(
1132    stored: &'a serde_json::Map<String, serde_json::Value>,
1133    patch: &'a serde_json::Map<String, serde_json::Value>,
1134) -> Vec<&'a str> {
1135    [stored.get("taskListId"), patch.get("taskListId")]
1136        .into_iter()
1137        .flatten()
1138        .filter_map(serde_json::Value::as_str)
1139        .collect()
1140}
1141
1142/// draft-ietf-jmap-metadata-05 §3.2 checks for a created object `val` of
1143/// type `type_name`: rules 1 to 3 on the metadata properties of
1144/// `supplied`, the create object, then rule 4 on the values it supplied as
1145/// stored in `val`. A `Foo/set` create passes `val` as both; a `/copy`
1146/// passes its create object, so the copied values are not revalidated
1147/// (-05 §3.4: "maxDepth applies only to values supplied in the create
1148/// object"). A Task needs `maySetMetadata` on the [`TaskList`] of
1149/// its `taskListId` (-05 §4.1: "on create, on the containers given in the
1150/// create"). Types without the -05 properties pass unchecked.
1151fn check_metadata_create(
1152    inner: &Inner,
1153    type_name: &'static str,
1154    account_id: &str,
1155    supplied: &serde_json::Value,
1156    val: &serde_json::Value,
1157) -> Result<(), BackendSetError<MemoryError>> {
1158    let (Some(type_name), Some(supplied), Some(obj)) = (
1159        metadata_type_name(type_name),
1160        supplied.as_object(),
1161        val.as_object(),
1162    ) else {
1163        return Ok(());
1164    };
1165    let entry: serde_json::Map<String, serde_json::Value> = supplied
1166        .iter()
1167        .filter(|(k, _)| is_metadata_property(k))
1168        .map(|(k, v)| (k.clone(), v.clone()))
1169        .collect();
1170    let containers: Vec<&str> = if type_name == Task::TYPE_NAME {
1171        obj.get("taskListId")
1172            .and_then(serde_json::Value::as_str)
1173            .into_iter()
1174            .collect()
1175    } else {
1176        Vec::new()
1177    };
1178    if let Some(info) = inner.check_metadata_set(
1179        type_name,
1180        account_id,
1181        SetKind::Create,
1182        &entry,
1183        None,
1184        &containers,
1185    )? {
1186        check_metadata_depth(&entry, obj, &info)
1187            .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
1188    }
1189    Ok(())
1190}
1191
1192/// The six draft-ietf-jmap-metadata-05 §3.6 `FilterCondition` fields.
1193const METADATA_CONDITION_KEYS: [&str; 6] = [
1194    "metadataExists",
1195    "privateMetadataExists",
1196    "metadataTextContains",
1197    "privateMetadataTextContains",
1198    "metadataTextEquals",
1199    "privateMetadataTextEquals",
1200];
1201
1202/// The three -05 §3.6 conditions on shared `metadata` that this backend
1203/// evaluates; the `privateMetadata*` three never pass
1204/// [`check_metadata_filter`] because `supportsPrivate` is false.
1205const SHARED_METADATA_CONDITION_KEYS: [&str; 3] = [
1206    "metadataExists",
1207    "metadataTextContains",
1208    "metadataTextEquals",
1209];
1210
1211/// The Task `FilterCondition` properties this backend evaluates (jmapio/jmap
1212/// #456), besides the shared-metadata ones; any other set property is
1213/// `unsupportedFilter`.
1214const TASK_CONDITION_KEYS: [&str; 5] = [
1215    "inTaskLists",
1216    "workflowStatus",
1217    "progress",
1218    "after",
1219    "before",
1220];
1221
1222/// Whether the stored Task `task` matches `c`, the conditions in
1223/// [`TASK_CONDITION_KEYS`] and the shared-metadata ones; `query_zone` is
1224/// the Task/query `timeZone`.
1225///
1226/// `after` / `before` follow [`TaskFilterCondition`]: the task's end is its
1227/// `due` (or `start`), its beginning its `start` (or `due`), and a task
1228/// with neither matches neither. This backend has no time-zone database,
1229/// so it compares local times only when the task is floating or in
1230/// `query_zone`, where both read in the same zone and the fixed-width
1231/// RFC 8984 `LocalDateTime` strings order as the times do. A task in
1232/// another zone makes the query `unsupportedFilter` (RFC 8620 §5.5: the
1233/// server "cannot process the given filter").
1234fn task_matches(
1235    c: &TaskFilterCondition,
1236    task: &serde_json::Value,
1237    query_zone: &str,
1238) -> Result<bool, BackendQueryError<MemoryError>> {
1239    let str_of = |key: &str| task.get(key).and_then(serde_json::Value::as_str);
1240    if let Some(lists) = &c.in_task_lists
1241        && !str_of("taskListId").is_some_and(|l| lists.iter().any(|id| id.as_ref() == l))
1242    {
1243        return Ok(false);
1244    }
1245    if let Some(status) = &c.workflow_status
1246        && str_of("workflowStatus") != Some(status.as_str())
1247    {
1248        return Ok(false);
1249    }
1250    if let Some(progress) = &c.progress
1251        && str_of("progress") != Some(progress.as_str())
1252    {
1253        return Ok(false);
1254    }
1255    if c.after.is_some() || c.before.is_some() {
1256        if str_of("timeZone").is_some_and(|z| z != query_zone) {
1257            let mut err = JmapError::unsupported_filter();
1258            err.description = Some(
1259                "after/before on a task in another time zone needs a time-zone database".to_owned(),
1260            );
1261            return Err(BackendQueryError::Method(err));
1262        }
1263        let (start, due) = (str_of("start"), str_of("due"));
1264        if let Some(after) = &c.after
1265            && !due.or(start).is_some_and(|end| end > after.as_ref())
1266        {
1267            return Ok(false);
1268        }
1269        if let Some(before) = &c.before
1270            && !start.or(due).is_some_and(|begin| begin < before.as_ref())
1271        {
1272            return Ok(false);
1273        }
1274    }
1275    Ok(metadata_matches(
1276        task.get("metadata").and_then(serde_json::Value::as_object),
1277        c.metadata_exists.as_deref(),
1278        c.metadata_text_contains.as_ref(),
1279        c.metadata_text_equals.as_ref(),
1280    ))
1281}
1282
1283/// The Task/query sort as [`TaskComparator`]s, checked against what this
1284/// backend can evaluate: the docs/specs/jmap-tasks-local.md Sorting
1285/// properties ("MUST be supported for sorting: `id`, `uid`, `start`. The
1286/// following SHOULD be supported: `created`, `updated`."), with no
1287/// collation or one of [`text_cmp`]'s. Anything else is `unsupportedSort`
1288/// (RFC 8620 §5.5).
1289fn task_sort<C: serde::Serialize>(
1290    sort: &[C],
1291) -> Result<Vec<TaskComparator>, BackendQueryError<MemoryError>> {
1292    sort.iter()
1293        .map(|c| {
1294            let v = jmap_server::serialize_value(c).map_err(BackendQueryError::Method)?;
1295            let c: TaskComparator = serde_json::from_value(v)
1296                .map_err(|e| BackendQueryError::Method(JmapError::server_fail(e.to_string())))?;
1297            let known = matches!(
1298                c.property,
1299                TaskComparatorProperty::Id
1300                    | TaskComparatorProperty::Uid
1301                    | TaskComparatorProperty::Start
1302                    | TaskComparatorProperty::Created
1303                    | TaskComparatorProperty::Updated
1304            );
1305            if known && text_cmp(c.collation.as_deref(), "", "").is_some() {
1306                Ok(c)
1307            } else {
1308                Err(BackendQueryError::Method(JmapError::unsupported_sort()))
1309            }
1310        })
1311        .collect()
1312}
1313
1314/// String comparison under a supported RFC 4790 collation (`None` is
1315/// `i;octet`); `None` back for any other collation.
1316fn text_cmp(collation: Option<&str>, a: &str, b: &str) -> Option<Ordering> {
1317    match collation {
1318        None | Some("i;octet") => Some(a.cmp(b)),
1319        Some("i;ascii-casemap") => Some(a.to_ascii_lowercase().cmp(&b.to_ascii_lowercase())),
1320        Some("i;unicode-casemap") => Some(a.to_lowercase().cmp(&b.to_lowercase())),
1321        Some(_) => None,
1322    }
1323}
1324
1325/// Sorting by `start` "orders tasks by the absolute time they start, not
1326/// by the lexical value of `start`; a floating task's start is read in the
1327/// `timeZone` argument" (docs/specs/jmap-tasks-local.md Sorting). With no
1328/// time-zone database the backend can do that only by comparing `start`
1329/// values that are all in one zone (a task's `timeZone`, or `query_zone`
1330/// when it floats); tasks in several zones are `unsupportedSort`.
1331fn check_one_start_zone(
1332    matched: &[(&Id, &serde_json::Value)],
1333    query_zone: &str,
1334) -> Result<(), BackendQueryError<MemoryError>> {
1335    let mut zones = matched
1336        .iter()
1337        .filter(|(_, t)| t.get("start").is_some_and(serde_json::Value::is_string))
1338        .map(|(_, t)| {
1339            t.get("timeZone")
1340                .and_then(serde_json::Value::as_str)
1341                .unwrap_or(query_zone)
1342        });
1343    let first = zones.next();
1344    if zones.any(|z| Some(z) != first) {
1345        let mut err = JmapError::unsupported_sort();
1346        err.description = Some(
1347            "sorting tasks in several time zones by start needs a time-zone database".to_owned(),
1348        );
1349        return Err(BackendQueryError::Method(err));
1350    }
1351    Ok(())
1352}
1353
1354/// Order two matched Tasks by `comparators` (from [`task_sort`]), then by
1355/// id so the order is stable (RFC 8620 §5.5). A task without the sort
1356/// property comes after every task with it in ascending order (the spec
1357/// leaves this open). `start` compares as a `LocalDateTime` string, which
1358/// [`check_one_start_zone`] made safe; `created` and `updated` compare as
1359/// `UTCDate`s with the trailing `Z` (RFC 8620 §1.4) dropped, so a
1360/// fractional-second value sorts after the whole second.
1361fn compare_tasks(
1362    comparators: &[TaskComparator],
1363    (a_id, a): &(&Id, &serde_json::Value),
1364    (b_id, b): &(&Id, &serde_json::Value),
1365) -> Ordering {
1366    for c in comparators {
1367        let text = |id: &Id, t: &serde_json::Value| -> Option<String> {
1368            let s = |k: &str| t.get(k).and_then(serde_json::Value::as_str);
1369            match c.property {
1370                TaskComparatorProperty::Id => Some(id.as_ref().to_owned()),
1371                TaskComparatorProperty::Uid => s("uid").map(str::to_owned),
1372                TaskComparatorProperty::Start => s("start").map(str::to_owned),
1373                TaskComparatorProperty::Created => {
1374                    s("created").map(|v| v.trim_end_matches('Z').to_owned())
1375                }
1376                TaskComparatorProperty::Updated => {
1377                    s("updated").map(|v| v.trim_end_matches('Z').to_owned())
1378                }
1379                _ => None,
1380            }
1381        };
1382        let is_text = matches!(
1383            c.property,
1384            TaskComparatorProperty::Id | TaskComparatorProperty::Uid
1385        );
1386        let ord = match (text(a_id, a), text(b_id, b)) {
1387            (Some(x), Some(y)) if is_text => {
1388                text_cmp(c.collation.as_deref(), &x, &y).unwrap_or(Ordering::Equal)
1389            }
1390            (Some(x), Some(y)) => x.cmp(&y),
1391            (Some(_), None) => Ordering::Less,
1392            (None, Some(_)) => Ordering::Greater,
1393            (None, None) => Ordering::Equal,
1394        };
1395        let ord = if c.is_ascending { ord } else { ord.reverse() };
1396        if ord != Ordering::Equal {
1397            return ord;
1398        }
1399    }
1400    a_id.as_ref().cmp(b_id.as_ref())
1401}
1402
1403/// `true` when the stored Task `task` recurs: it has a non-empty
1404/// `recurrenceRules` or `recurrenceOverrides` (RFC 8984 §4.3).
1405fn is_recurring(task: &serde_json::Value) -> bool {
1406    let non_empty = |key: &str| match task.get(key) {
1407        Some(serde_json::Value::Array(a)) => !a.is_empty(),
1408        Some(serde_json::Value::Object(o)) => !o.is_empty(),
1409        _ => false,
1410    };
1411    non_empty("recurrenceRules") || non_empty("recurrenceOverrides")
1412}
1413
1414/// Validate the draft-ietf-jmap-metadata-05 §3.6 conditions on every leaf
1415/// of `filter`, a `FilterCondition` or `FilterOperator` tree (RFC 8620 §5.5),
1416/// before any object is matched.
1417///
1418/// A type without `info` has no metadata (-05 §1.2.1: it "does not gain
1419/// the metadata or privateMetadata properties"), so a metadata leaf is
1420/// `unsupportedFilter` (RFC 8620 §5.5: "The filter is syntactically valid,
1421/// but the server cannot process it"). Otherwise
1422/// [`MetadataCondition::take_from`] applies -05 §3.6: a malformed path is
1423/// `invalidArguments`, and a `privateMetadata*` condition is
1424/// `unsupportedFilter` because `supportsPrivate` is false.
1425fn check_metadata_filter(
1426    filter: &serde_json::Value,
1427    info: Option<&DataTypeMetadataInfo>,
1428) -> Result<(), BackendQueryError<MemoryError>> {
1429    let unsupported = |description: String| {
1430        let mut err = JmapError::unsupported_filter();
1431        err.description = Some(description);
1432        BackendQueryError::Method(err)
1433    };
1434    if filter.get("operator").is_some() {
1435        return filter
1436            .get("conditions")
1437            .and_then(serde_json::Value::as_array)
1438            .into_iter()
1439            .flatten()
1440            .try_for_each(|f| check_metadata_filter(f, info));
1441    }
1442    let Some(leaf) = filter.as_object() else {
1443        return Ok(());
1444    };
1445    if !METADATA_CONDITION_KEYS
1446        .iter()
1447        .any(|k| leaf.get(*k).is_some_and(|v| !v.is_null()))
1448    {
1449        return Ok(());
1450    }
1451    let Some(info) = info else {
1452        return Err(unsupported(
1453            "metadata filter conditions are not supported".to_owned(),
1454        ));
1455    };
1456    MetadataCondition::take_from(&mut leaf.clone(), info)
1457        .map(drop)
1458        .map_err(|e| match e {
1459            MetadataFilterError::InvalidArguments(d) => {
1460                BackendQueryError::Method(JmapError::invalid_arguments(d))
1461            }
1462            other => unsupported(other.to_string()),
1463        })
1464}
1465
1466/// Match the draft-ietf-jmap-metadata-05 §3.6 shared-metadata conditions of
1467/// one filter leaf against an object's `metadata` (absent means `{}`, -05
1468/// §2). The `privateMetadata*` conditions never reach this point:
1469/// [`check_metadata_filter`] rejects them, since this backend has
1470/// `supportsPrivate` false.
1471fn metadata_matches(
1472    metadata: Option<&serde_json::Map<String, serde_json::Value>>,
1473    exists: Option<&str>,
1474    contains: Option<&MetadataTextMatch>,
1475    equals: Option<&MetadataTextMatch>,
1476) -> bool {
1477    let empty = serde_json::Map::new();
1478    let metadata = metadata.unwrap_or(&empty);
1479    exists.is_none_or(|p| metadata_path_exists(metadata, p))
1480        && contains.is_none_or(|m| metadata_text_contains(metadata, m))
1481        && equals.is_none_or(|m| metadata_text_equals(metadata, m))
1482}
1483
1484/// Rebuild `obj` with `id` as its `id` property, for a `/copy` that
1485/// stores a record read from another account under a new id.
1486fn with_id<O: SetObject>(obj: &O, id: &Id) -> Result<O, BackendSetError<MemoryError>> {
1487    let mut val = serde_json::to_value(obj)
1488        .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize copied object", &e)))?;
1489    if let Some(map) = val.as_object_mut() {
1490        map.insert(
1491            "id".to_owned(),
1492            serde_json::Value::String(id.as_ref().to_owned()),
1493        );
1494    }
1495    serde_json::from_value(val)
1496        .map_err(|e| BackendSetError::Other(MemoryError::serde("deserialize copied object", &e)))
1497}
1498
1499impl<C: MemoryCaller> MemoryBackend<C> {
1500    /// Store the object `build` returns for a new id in `account_id`: the
1501    /// body of [`TasksBackend::create_object`] and
1502    /// [`TasksBackend::copy_object`]. `supplied` is the `/copy` create
1503    /// object whose metadata is validated (-05 §3.4); `None` validates the
1504    /// stored object itself, as a `Foo/set` create does.
1505    async fn store_created<O: SetObject>(
1506        &self,
1507        account_id: &Id,
1508        build: impl FnOnce(&Id) -> Result<O, BackendSetError<MemoryError>>,
1509        supplied: Option<&serde_json::Value>,
1510    ) -> Result<(Id, O), BackendSetError<MemoryError>> {
1511        let server_id = Id::from(uuid::Uuid::new_v4().to_string());
1512        // Object history §5.1 covers Task/copy too: a fresh v4 UUID never
1513        // reuses a destroyed id.
1514        let mut stored_obj = build(&server_id)?;
1515        let mut val = serde_json::to_value(&stored_obj)
1516            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize", &e)))?;
1517
1518        let mut inner = self.inner.lock().await;
1519        // Decision 42 (workflowStatus and progress), under the lock so the
1520        // list's workflowStatuses cannot change in between.
1521        if O::TYPE_NAME == Task::TYPE_NAME
1522            && inner.apply_workflow(
1523                account_id.as_ref(),
1524                &mut val,
1525                crate::workflow::WorkflowWrite::Create,
1526            )?
1527        {
1528            stored_obj = O::deserialize(&val)
1529                .map_err(|e| BackendSetError::Other(MemoryError::serde("deserialize", &e)))?;
1530        }
1531        debug_assert!(!inner.history_retains(O::TYPE_NAME, account_id, &server_id));
1532        check_metadata_create(
1533            &inner,
1534            O::TYPE_NAME,
1535            account_id.as_ref(),
1536            supplied.unwrap_or(&val),
1537            &val,
1538        )?;
1539        inner.require_account(account_id.as_ref())?;
1540
1541        let task_list_id = if O::TYPE_NAME == "Task" {
1542            Inner::task_list_id_of(&val)
1543        } else {
1544            None
1545        };
1546
1547        let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
1548        inner
1549            .objects_mut(O::TYPE_NAME, account_id.as_ref())
1550            .insert(server_id.clone(), val);
1551        inner
1552            .change_log_mut(O::TYPE_NAME, account_id.as_ref())
1553            .push(ChangeEntry {
1554                new_state,
1555                created: vec![server_id.clone()],
1556                updated: vec![],
1557                destroyed: vec![],
1558                restored: vec![],
1559                updated_props: None,
1560            });
1561
1562        if O::TYPE_NAME == "Task" {
1563            inner.inc_task_ref(account_id.as_ref(), task_list_id);
1564        }
1565
1566        Ok((server_id, stored_obj))
1567    }
1568}
1569
1570// ---------------------------------------------------------------------------
1571// TasksBackend impl
1572// ---------------------------------------------------------------------------
1573
1574impl<C: MemoryCaller> MemoryBackend<C> {
1575    /// The body of [`JmapReads::query_objects`] and
1576    /// [`TasksBackend::query_tasks`]; `task_args` applies to Task only.
1577    async fn query_impl<O: QueryObject + Send + Sync>(
1578        &self,
1579        caller: &C,
1580        account_id: &Id,
1581        params: QueryParams<'_, O>,
1582        task_args: &TaskQueryArgs,
1583    ) -> Result<QueryResult, BackendQueryError<MemoryError>> {
1584        let QueryParams {
1585            filter,
1586            sort,
1587            limit,
1588            position,
1589            anchor,
1590            anchor_offset,
1591            ..
1592        } = params;
1593        // Fail loud on any non-trivial filter. A `None` or all-fields-None
1594        // filter passes (matches everything); any populated field this
1595        // backend cannot evaluate, and any operator tree, is answered with
1596        // `unsupportedFilter` (RFC 8620 §5.5: "A server MUST reject the call
1597        // with an unsupportedFilter error if it cannot process the given
1598        // filter").
1599        //
1600        // The generic `O::Filter` is the concrete `TaskFilter`,
1601        // `TaskNotificationFilter` or (TaskList) `Value` here. A serializer
1602        // failure surfaces as serverFail rather than a panic or a silently
1603        // dropped filter (see the jmap-mail-server memory backend).
1604        //
1605        // draft-ietf-jmap-metadata-05 §3.6: on an opted-in Task the shared
1606        // `metadata*` conditions are evaluable in the same leaf;
1607        // [`check_metadata_filter`] validates them first, also inside an
1608        // operator tree, so a malformed path is `invalidArguments`.
1609        let inner = self.inner.lock().await;
1610        let is_task = O::TYPE_NAME == Task::TYPE_NAME;
1611        let mut task_condition: Option<TaskFilterCondition> = None;
1612        if let Some(f) = filter {
1613            let v = jmap_server::serialize_value(f).map_err(BackendQueryError::Method)?;
1614            check_metadata_filter(&v, inner.metadata_info.get(O::TYPE_NAME))?;
1615            if v.get("operator").is_some() {
1616                return Err(BackendQueryError::Method(JmapError::unsupported_filter()));
1617            }
1618            let any_field_set = match v.as_object() {
1619                Some(m) => m.iter().any(|(k, val)| {
1620                    !val.is_null()
1621                        && !(is_task
1622                            && (TASK_CONDITION_KEYS.contains(&k.as_str())
1623                                || SHARED_METADATA_CONDITION_KEYS.contains(&k.as_str())))
1624                }),
1625                // Filter serialized as something other than an object (only
1626                // possible for TaskList's untyped `Value`): treat as
1627                // non-trivial.
1628                None => true,
1629            };
1630            if any_field_set {
1631                return Err(BackendQueryError::Method(JmapError::unsupported_filter()));
1632            }
1633            if is_task {
1634                task_condition = Some(serde_json::from_value(v).map_err(|e| {
1635                    BackendQueryError::Method(JmapError::server_fail(e.to_string()))
1636                })?);
1637            }
1638        }
1639
1640        // Task sorts by the local profile's properties (task_sort); any
1641        // other type's non-empty sort fails loud, RFC 8620 §5.5: "A server
1642        // MUST reject the call with an unsupportedSort error if it cannot
1643        // sort by the given properties."
1644        let comparators = match sort.filter(|s| !s.is_empty()) {
1645            None => Vec::new(),
1646            Some(s) if is_task => task_sort(s)?,
1647            Some(_) => return Err(BackendQueryError::Method(JmapError::unsupported_sort())),
1648        };
1649
1650        let query_zone = task_args.time_zone.as_deref().unwrap_or("Etc/UTC");
1651        let mut matched: Vec<(&Id, &serde_json::Value)> = Vec::new();
1652        if let Some(objects) = inner.objects_ref(O::TYPE_NAME, account_id.as_ref()) {
1653            for (id, v) in objects {
1654                let keep = match &task_condition {
1655                    None => true,
1656                    Some(c) => task_matches(c, v, query_zone)?,
1657                };
1658                if keep {
1659                    matched.push((id, v));
1660                }
1661            }
1662        }
1663
1664        if is_task && task_args.expand_recurrences {
1665            // TasksBackend::query_tasks: the backend re-checks the
1666            // maxExpandedQueryDuration cap the handler pre-checked.
1667            let too_long = task_condition
1668                .as_ref()
1669                .and_then(crate::task::expand_duration_seconds)
1670                .is_some_and(|secs| {
1671                    u64::try_from(secs).is_ok_and(|secs| {
1672                        secs > self
1673                            .limits(caller, account_id)
1674                            .max_expanded_query_duration_seconds
1675                    })
1676                });
1677            if too_long {
1678                return Err(BackendQueryError::Method(JmapError::custom(
1679                    "expandDurationTooLarge",
1680                )));
1681            }
1682            // No recurrence engine: a non-recurring task is its own single
1683            // instance, so its id stands; a recurring one cannot be expanded.
1684            if matched.iter().any(|(_, v)| is_recurring(v)) {
1685                return Err(BackendQueryError::Method(JmapError::custom(
1686                    "cannotCalculateOccurrences",
1687                )));
1688            }
1689        }
1690
1691        if comparators
1692            .iter()
1693            .any(|c| c.property == TaskComparatorProperty::Start)
1694        {
1695            check_one_start_zone(&matched, query_zone)?;
1696        }
1697        matched.sort_by(|a, b| compare_tasks(&comparators, a, b));
1698        let ids: Vec<Id> = matched.into_iter().map(|(k, _)| k.clone()).collect();
1699
1700        let total = ids.len() as u64;
1701        let query_state = State::from(
1702            inner
1703                .current_state(O::TYPE_NAME, account_id.as_ref())
1704                .to_string()
1705                .as_str(),
1706        );
1707
1708        // RFC 8620 §5.5 position / anchor / anchorOffset.
1709        let start = resolve_query_start(&ids, position, anchor, anchor_offset)
1710            .map_err(BackendQueryError::Method)?;
1711
1712        let ids: Vec<Id> = ids[start..]
1713            .iter()
1714            .take(limit_or_max(limit))
1715            .cloned()
1716            .collect();
1717
1718        Ok(QueryResult::new(
1719            ids,
1720            start as u64,
1721            Some(total),
1722            query_state,
1723            true,
1724        ))
1725    }
1726}
1727
1728impl<C: MemoryCaller> TasksBackend for MemoryBackend<C> {
1729    async fn create_object<O, F>(
1730        &self,
1731        _caller: &C,
1732        account_id: &Id,
1733        _create_id: &str,
1734        build: F,
1735    ) -> Result<(Id, O), BackendSetError<Self::Error>>
1736    where
1737        O: SetObject + Send + Sync,
1738        F: FnOnce(&Id) -> O + Send,
1739    {
1740        self.store_created(account_id, |id| Ok(build(id)), None)
1741            .await
1742    }
1743
1744    async fn copy_object<O: SetObject + Send + Sync>(
1745        &self,
1746        _caller: &C,
1747        _from_account_id: &Id,
1748        to_account_id: &Id,
1749        obj: O,
1750        create: &serde_json::Value,
1751    ) -> Result<(Id, O), BackendSetError<Self::Error>> {
1752        // -05 §3.4: the create object's metadata follows the Foo/set create
1753        // rules; the copied values are not revalidated.
1754        self.store_created(to_account_id, |id| with_id(&obj, id), Some(create))
1755            .await
1756    }
1757
1758    async fn update_object<O: SetObject + Send + Sync>(
1759        &self,
1760        _caller: &C,
1761        account_id: &Id,
1762        id: &Id,
1763        patch: O::Patch,
1764    ) -> Result<Option<O>, BackendSetError<Self::Error>> {
1765        let patch_val = serde_json::to_value(&patch)
1766            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize patch", &e)))?;
1767        let invalid_patch = |e: PatchPathError| {
1768            BackendSetError::SetError(Box::new(
1769                SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
1770            ))
1771        };
1772        // draft-ietf-jmap-metadata-05 §3.2: "Patch errors that can be
1773        // determined from the request alone (for example, two paths where
1774        // one is a prefix of the other) MUST be reported with
1775        // "invalidPatch" before rule 1 is evaluated."
1776        if let serde_json::Value::Object(patch_map) = &patch_val {
1777            check_patch_paths(patch_map).map_err(invalid_patch)?;
1778        }
1779
1780        let mut inner = self.inner.lock().await;
1781        inner.require_account_for_target(account_id.as_ref())?;
1782
1783        // -05 §3.2 rule 1: "If the user cannot read the related object,
1784        // reject with "notFound"" comes before "forbidden". Here only a
1785        // missing object is unreadable.
1786        let existing = inner
1787            .objects_mut(O::TYPE_NAME, account_id.as_ref())
1788            .get(id)
1789            .cloned();
1790
1791        let Some(mut current) = existing else {
1792            return Err(BackendSetError::SetError(Box::new(SetError::new(
1793                SetErrorType::NotFound,
1794            ))));
1795        };
1796        // Object history: the version this update replaces.
1797        let previous = current.clone();
1798
1799        let was_draft = current.get("isDraft").and_then(|v| v.as_bool()) == Some(true);
1800
1801        // Snapshot the pre-patch taskListId so the refcount update below
1802        // can compute the (old → new) transition without re-fetching after
1803        // the patch applies.
1804        let old_task_list_id = if O::TYPE_NAME == "Task" {
1805            Inner::task_list_id_of(&current)
1806        } else {
1807            None
1808        };
1809
1810        // JMAP patch (RFC 8620 §5.3): keys are JSON Pointer paths (e.g.
1811        // "participants/p1/participationStatus"), applied all-or-nothing by
1812        // the shared `apply_patch_object`, so an invalidPatch leaves the
1813        // stored object unchanged. Values replace wholesale; the helper caps
1814        // path plus value nesting depth.
1815        let mut updated_props = None;
1816        if let (serde_json::Value::Object(base), serde_json::Value::Object(patch_map)) =
1817            (&mut current, &patch_val)
1818        {
1819            // -05 §3.2 rules 1 to 3 run before the patch is applied.
1820            let metadata_info = if metadata_type_name(O::TYPE_NAME).is_some() {
1821                let containers = if O::TYPE_NAME == Task::TYPE_NAME {
1822                    task_update_containers(base, patch_map)
1823                } else {
1824                    Vec::new()
1825                };
1826                inner.check_metadata_set(
1827                    O::TYPE_NAME,
1828                    account_id.as_ref(),
1829                    SetKind::Update,
1830                    patch_map,
1831                    Some(base),
1832                    &containers,
1833                )?
1834            } else {
1835                None
1836            };
1837            // -05 §2 `metadata` has "default: {}", so a
1838            // `metadata/<namespace>` pointer finds its parent.
1839            if metadata_info.is_some() {
1840                base.entry("metadata")
1841                    .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
1842            }
1843            let before = base.clone();
1844            // The value-dependent patch errors (missing parent, path through
1845            // an array or a Binary value) land here, after rule 3 and before rule 4 (-05 §3.2).
1846            apply_patch_object(base, patch_map).map_err(invalid_patch)?;
1847            if let Some(info) = &metadata_info {
1848                // -05 §3.2: "In an update, null is equivalent to {}"; the
1849                // patch removed the property instead.
1850                for property in ["metadata", "privateMetadata"] {
1851                    if patch_map
1852                        .get(property)
1853                        .is_some_and(serde_json::Value::is_null)
1854                    {
1855                        base.insert(
1856                            property.to_owned(),
1857                            serde_json::Value::Object(serde_json::Map::new()),
1858                        );
1859                    }
1860                }
1861                // -05 §3.2 rule 4 runs on the value as it would be stored.
1862                check_metadata_depth(patch_map, base, info)
1863                    .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
1864            }
1865            updated_props = Some(changed_properties(&before, base));
1866        }
1867
1868        // Re-validate the patched copy against the typed object before
1869        // storing: a null or wrong-typed value on a required property would
1870        // otherwise be persisted and make every later /get fail to
1871        // deserialize. Name the property when the patch touches only one.
1872        if let Err(e) = O::deserialize(&current) {
1873            let mut heads: Vec<String> = patch_val
1874                .as_object()
1875                .into_iter()
1876                .flat_map(|m| m.keys())
1877                .map(|k| {
1878                    let head = k.split('/').next().unwrap_or(k);
1879                    head.replace("~1", "/").replace("~0", "~")
1880                })
1881                .collect();
1882            heads.sort_unstable();
1883            heads.dedup();
1884            let mut err =
1885                SetError::new(SetErrorType::InvalidProperties).with_description(e.to_string());
1886            if heads.len() == 1 {
1887                err = err.with_properties(heads);
1888            }
1889            return Err(BackendSetError::SetError(Box::new(err)));
1890        }
1891
1892        // Backend-side isDraft re-check (draft-ietf-jmap-tasks-06 §4 isDraft
1893        // paragraph): "This may only be set to true upon creation." Compare
1894        // the effective post-patch value against the stored one so that any
1895        // path to true (including a null patch followed by true) is rejected.
1896        // The handler does not pre-check this (bd:JMAP-h47t.29): workspace
1897        // AGENTS.md "Permission enforcement: backend canonical" makes the
1898        // backend the only enforcement point, atomically with the mutation.
1899        if O::TYPE_NAME == "Task"
1900            && !was_draft
1901            && current.get("isDraft").and_then(|v| v.as_bool()) == Some(true)
1902        {
1903            return Err(BackendSetError::SetError(Box::new(
1904                SetError::new(SetErrorType::InvalidProperties)
1905                    .with_properties(vec!["isDraft".to_owned()]),
1906            )));
1907        }
1908
1909        // Decision 42 (workflowStatus and progress) on the patched Task,
1910        // atomically with the write.
1911        let mut echo = false;
1912        if O::TYPE_NAME == Task::TYPE_NAME {
1913            let written: Vec<String> = patch_val
1914                .as_object()
1915                .into_iter()
1916                .flat_map(|m| m.keys())
1917                .map(|k| {
1918                    let head = k.split('/').next().unwrap_or(k);
1919                    head.replace("~1", "/").replace("~0", "~")
1920                })
1921                .collect();
1922            let empty = serde_json::Map::new();
1923            let before = previous.as_object().unwrap_or(&empty);
1924            echo = inner.apply_workflow(
1925                account_id.as_ref(),
1926                &mut current,
1927                crate::workflow::WorkflowWrite::Update {
1928                    before,
1929                    written: &written,
1930                },
1931            )?;
1932        }
1933
1934        let new_task_list_id = if O::TYPE_NAME == "Task" {
1935            Inner::task_list_id_of(&current)
1936        } else {
1937            None
1938        };
1939        let echoed = if echo {
1940            Some(
1941                O::deserialize(&current)
1942                    .map_err(|e| BackendSetError::Other(MemoryError::serde("deserialize", &e)))?,
1943            )
1944        } else {
1945            None
1946        };
1947
1948        inner.record_replace(O::TYPE_NAME, account_id, id, previous);
1949        let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
1950        inner
1951            .objects_mut(O::TYPE_NAME, account_id.as_ref())
1952            .insert(id.clone(), current);
1953        inner
1954            .change_log_mut(O::TYPE_NAME, account_id.as_ref())
1955            .push(ChangeEntry {
1956                new_state,
1957                created: vec![],
1958                updated: vec![id.clone()],
1959                destroyed: vec![],
1960                restored: vec![],
1961                updated_props,
1962            });
1963
1964        if O::TYPE_NAME == "Task" && old_task_list_id != new_task_list_id {
1965            inner.dec_task_ref(account_id.as_ref(), old_task_list_id);
1966            inner.inc_task_ref(account_id.as_ref(), new_task_list_id);
1967        }
1968
1969        Ok(echoed)
1970    }
1971
1972    /// `Task/query` over the stored tasks.
1973    ///
1974    /// Evaluates `inTaskLists`, `workflowStatus`, `progress`, `after`,
1975    /// `before` and the shared-metadata conditions in one `FilterCondition`;
1976    /// anything else, and any operator tree, is `unsupportedFilter`, as is
1977    /// `after` / `before` on a task whose `timeZone` is not the query's
1978    /// (there is no time-zone database). With `expandRecurrences` the
1979    /// `maxExpandedQueryDuration` cap ([`TasksBackend::limits`]) is checked
1980    /// again; non-recurring matches keep their ids as their single
1981    /// instances, and a recurring match is `cannotCalculateOccurrences`,
1982    /// since there is no recurrence engine. Sorting is as in
1983    /// [`JmapReads::query_objects`], with `start` and floating tasks read
1984    /// in the `timeZone` argument.
1985    async fn query_tasks(
1986        &self,
1987        caller: &C,
1988        account_id: &Id,
1989        params: QueryParams<'_, Task>,
1990        args: &TaskQueryArgs,
1991    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
1992        self.query_impl(caller, account_id, params, args).await
1993    }
1994
1995    async fn update_task_per_user(
1996        &self,
1997        caller: &C,
1998        account_id: &Id,
1999        id: &Id,
2000        patch: jmap_types::PatchObject,
2001    ) -> Result<Option<jmap_tasks_types::Task>, BackendSetError<Self::Error>> {
2002        // ponytail: single-user backend (every caller is the owner), so per-user state is
2003        // the shared object. `update_object` never writes `updated`, which
2004        // keeps draft-ietf-jmap-tasks-06 §4.5.1 intact. A multi-user backend
2005        // stores the patch per user instead.
2006        self.update_object::<jmap_tasks_types::Task>(caller, account_id, id, patch)
2007            .await
2008    }
2009
2010    async fn destroy_object<O: SetObject + Send + Sync>(
2011        &self,
2012        _caller: &C,
2013        account_id: &Id,
2014        id: &Id,
2015    ) -> Result<(), BackendSetError<Self::Error>> {
2016        let mut inner = self.inner.lock().await;
2017        inner.require_account_for_target(account_id.as_ref())?;
2018
2019        let removed = inner
2020            .objects_mut(O::TYPE_NAME, account_id.as_ref())
2021            .remove(id);
2022
2023        match removed {
2024            Some(val) => {
2025                inner.record_destroy(O::TYPE_NAME, account_id, id, val.clone());
2026                let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
2027                inner
2028                    .change_log_mut(O::TYPE_NAME, account_id.as_ref())
2029                    .push(ChangeEntry {
2030                        new_state,
2031                        created: vec![],
2032                        updated: vec![],
2033                        destroyed: vec![id.clone()],
2034                        restored: vec![],
2035                        updated_props: None,
2036                    });
2037                if O::TYPE_NAME == "Task" {
2038                    inner.dec_task_ref(account_id.as_ref(), Inner::task_list_id_of(&val));
2039                }
2040                Ok(())
2041            }
2042            None => Err(BackendSetError::SetError(Box::new(SetError::new(
2043                SetErrorType::NotFound,
2044            )))),
2045        }
2046    }
2047
2048    fn supports_type<O: JmapObject>(&self, _caller: &C, _account_id: &jmap_types::Id) -> bool {
2049        matches!(O::TYPE_NAME, "TaskList" | "Task" | "TaskNotification")
2050    }
2051
2052    async fn task_list_has_tasks(
2053        &self,
2054        _caller: &C,
2055        account_id: &Id,
2056        task_list_id: &Id,
2057    ) -> Result<bool, MemoryError> {
2058        let inner = self.inner.lock().await;
2059        Ok(inner
2060            .aux_ref(account_id.as_ref())
2061            .is_some_and(|a| a.task_list_refcount.contains_key(task_list_id)))
2062    }
2063}
2064
2065// ---------------------------------------------------------------------------
2066// ConditionalBackend (draft-ietf-jmap-conditional-02)
2067// ---------------------------------------------------------------------------
2068
2069/// Conditional tasks Foo/set (bd JMAP-y1yu.11): the whole store is one
2070/// [`ScopedState`], so a scope isolates every type in every account, and an
2071/// atomic rollback restores objects, state strings, change logs and the
2072/// derived per-account indexes together, `onDestroyRemoveTasks` cascades
2073/// included.
2074///
2075/// Commit checks nothing beyond what the handlers already check:
2076/// `taskListHasTask` is judged within one TaskList/set, which moves no
2077/// Tasks; draft-ietf-jmap-tasks-06 sets no uniqueness rule for [`TaskList`]
2078/// `role`; and this backend has no cross-object caps.
2079impl<C: MemoryCaller> ConditionalBackend for MemoryBackend<C> {
2080    async fn begin_set(
2081        &self,
2082        _caller: &C,
2083        request: SetScopeRequest<'_>,
2084    ) -> Result<Box<dyn SetScope>, BeginSetError<MemoryError>> {
2085        Ok(self
2086            .inner
2087            .open(request, |_: &Inner, _: &Inner| Vec::new())
2088            .await)
2089    }
2090}
2091
2092#[cfg(test)]
2093mod memory_error_tests {
2094    use super::MemoryError;
2095
2096    /// The `JmapAccounts::Error` contract: "Implementations MUST NOT
2097    /// include ... PII shaped like an email address" in `Display`
2098    /// output. serde_json data errors quote the offending value, so
2099    /// [`MemoryError::serde`] must drop the message (bd:JMAP-510h.37).
2100    #[test]
2101    fn serde_error_display_omits_offending_value() {
2102        let canary = "alice@example.com";
2103        let e = serde_json::from_value::<u64>(serde_json::Value::String(canary.into()))
2104            .expect_err("a string is not a u64");
2105        assert!(
2106            e.to_string().contains(canary),
2107            "precondition: serde_json quotes the value"
2108        );
2109
2110        let shown = MemoryError::serde("decode", &e).to_string();
2111        assert!(!shown.contains(canary), "canary leaked: {shown}");
2112        assert!(
2113            shown.contains("decode") && shown.contains("Data"),
2114            "{shown}"
2115        );
2116    }
2117}
2118
2119#[cfg(test)]
2120mod fixture_helper_tests {
2121    use super::*;
2122    use serde_json::json;
2123
2124    /// `with_account` makes the account known (RFC 8620 §3.6.2: an
2125    /// unknown accountId is `accountNotFound`, so `account_exists` is the
2126    /// observable).
2127    #[tokio::test]
2128    async fn with_account_registers_account() {
2129        let acc = Id::from("acc1");
2130        let backend = MemoryBackend::<()>::default().with_account(&acc);
2131        assert!(backend.account_exists(&(), &acc).await.unwrap());
2132        assert!(
2133            !backend
2134                .account_exists(&(), &Id::from("acc2"))
2135                .await
2136                .unwrap()
2137        );
2138    }
2139
2140    /// A seeded Task counts toward its TaskList's reference index.
2141    #[tokio::test]
2142    async fn seeded_task_marks_task_list_non_empty() {
2143        let acc = Id::from("acc1");
2144        let backend = MemoryBackend::<()>::default();
2145        backend.seed_object(
2146            &acc,
2147            "Task",
2148            &Id::from("t1"),
2149            json!({"id": "t1", "taskListId": "tl1"}),
2150        );
2151        assert!(
2152            backend
2153                .task_list_has_tasks(&(), &acc, &Id::from("tl1"))
2154                .await
2155                .unwrap()
2156        );
2157    }
2158
2159    #[test]
2160    #[should_panic(expected = "not one of the known")]
2161    fn seed_object_rejects_unknown_type_name() {
2162        MemoryBackend::<()>::default().seed_object(
2163            &Id::from("acc1"),
2164            "Tasklist",
2165            &Id::from("tl1"),
2166            json!({"id": "tl1"}),
2167        );
2168    }
2169
2170    /// A non-object value panics at the seed call instead of surfacing
2171    /// later as an opaque deserialize error from get_objects.
2172    #[test]
2173    #[should_panic(expected = "must be a JSON object")]
2174    fn seed_object_rejects_non_object_value() {
2175        MemoryBackend::<()>::default().seed_object(
2176            &Id::from("acc1"),
2177            "TaskList",
2178            &Id::from("tl1"),
2179            json!(42),
2180        );
2181    }
2182
2183    /// A value without an `id` field panics instead of storing a fixture
2184    /// whose `id` is absent on read-back.
2185    #[test]
2186    #[should_panic(expected = "must contain an `id` string field")]
2187    fn seed_object_rejects_value_without_id_field() {
2188        MemoryBackend::<()>::default().seed_object(
2189            &Id::from("acc1"),
2190            "TaskList",
2191            &Id::from("tl1"),
2192            json!({"name": "Work"}),
2193        );
2194    }
2195
2196    #[test]
2197    #[should_panic(expected = "does not match the `id` argument")]
2198    fn seed_object_rejects_id_mismatch() {
2199        MemoryBackend::<()>::default().seed_object(
2200            &Id::from("acc1"),
2201            "TaskList",
2202            &Id::from("tl1"),
2203            json!({"id": "tl2"}),
2204        );
2205    }
2206}
2207
2208#[cfg(all(test, debug_assertions))]
2209mod empty_account_id_tests {
2210    use super::{Id, MemoryBackend};
2211
2212    /// Oracle: RFC 8620 §1.2, an Id "is a String of at least 1 and a
2213    /// maximum of 255 octets in size" (bd:JMAP-dx0s).
2214    #[test]
2215    #[should_panic(expected = "account_id must not be the empty string")]
2216    fn register_account_rejects_empty_id() {
2217        MemoryBackend::<()>::default().register_account(&Id::from(""));
2218    }
2219}
2220
2221#[cfg(test)]
2222mod changes_tests {
2223    use super::*;
2224    use jmap_tasks_types::Task;
2225
2226    /// Oracle: RFC 8620 §5.2 /changes rules, expected lists written by hand.
2227    /// "If a record has been created AND destroyed since the old state, the
2228    /// server SHOULD remove the id from the response entirely"; a record
2229    /// created then updated is reported only in `created`; one updated then
2230    /// destroyed is reported only in `destroyed`.
2231    #[tokio::test]
2232    async fn get_changes_dedups_ids_across_window() {
2233        let backend = MemoryBackend::<()>::default();
2234        let id = |s: &str| Id::from(s);
2235        {
2236            let mut inner = backend.inner.lock_unscoped();
2237            let log = inner.change_log_mut(Task::TYPE_NAME, "acc1");
2238            log.push(ChangeEntry {
2239                new_state: 1,
2240                created: vec![id("eph"), id("fresh")],
2241                updated: vec![],
2242                destroyed: vec![],
2243                restored: vec![],
2244                updated_props: None,
2245            });
2246            log.push(ChangeEntry {
2247                new_state: 2,
2248                created: vec![],
2249                updated: vec![id("fresh"), id("old"), id("doomed")],
2250                destroyed: vec![id("eph")],
2251                restored: vec![],
2252                updated_props: None,
2253            });
2254            log.push(ChangeEntry {
2255                new_state: 3,
2256                created: vec![],
2257                updated: vec![id("old")],
2258                destroyed: vec![id("doomed"), id("gone")],
2259                restored: vec![],
2260                updated_props: None,
2261            });
2262        }
2263
2264        let changes = backend
2265            .get_changes::<Task>(
2266                &(),
2267                &id("acc1"),
2268                jmap_server::ChangesParams::new(&State::from("0")),
2269            )
2270            .await
2271            .expect("get_changes must succeed");
2272
2273        assert_eq!(changes.created, vec![id("fresh")]);
2274        assert_eq!(changes.updated, vec![id("old")]);
2275        assert_eq!(changes.destroyed, vec![id("doomed"), id("gone")]);
2276    }
2277}
2278
2279#[cfg(test)]
2280mod max_changes_tests {
2281    use super::*;
2282    use jmap_tasks_types::Task as T;
2283
2284    const CALLER: () = ();
2285
2286    /// A backend whose `T` log holds one state per element of `states`,
2287    /// each creating the listed ids.
2288    fn with_creates(states: &[&[&str]]) -> MemoryBackend<()> {
2289        let backend = MemoryBackend::<()>::default();
2290        let mut inner = backend.inner.lock_unscoped();
2291        for ids in states {
2292            let new_state = inner.bump_state(T::TYPE_NAME, "acc1");
2293            inner
2294                .change_log_mut(T::TYPE_NAME, "acc1")
2295                .push(ChangeEntry {
2296                    new_state,
2297                    created: ids.iter().map(|s| Id::from(*s)).collect(),
2298                    updated: vec![],
2299                    destroyed: vec![],
2300                    restored: vec![],
2301                    updated_props: None,
2302                });
2303        }
2304        drop(inner);
2305        backend
2306    }
2307
2308    /// Oracle: RFC 8620 §5.2, expected pages written by hand: "the server
2309    /// MUST ensure the number of ids returned across "created", "updated",
2310    /// and "destroyed" does not exceed this limit. If there are more
2311    /// changes than this ..., the server SHOULD generate an update to take
2312    /// the client to an intermediate state, from which the client can
2313    /// continue to call "Foo/changes" until it is fully up to date." Three
2314    /// one-create states against `maxChanges` 2 page as states 1-2, then 3.
2315    #[tokio::test]
2316    async fn over_max_changes_pages_through_intermediate_state() {
2317        let backend = with_creates(&[&["a"], &["b"], &["c"]]);
2318
2319        let first = changes(&backend, "0", 2).await.expect("first page");
2320        assert_eq!(sorted(first.created), [Id::from("a"), Id::from("b")]);
2321        assert!(first.has_more_changes);
2322        assert_eq!(first.new_state.as_ref(), "2");
2323
2324        let rest = changes(&backend, "2", 2).await.expect("second page");
2325        assert_eq!(rest.created, [Id::from("c")]);
2326        assert!(!rest.has_more_changes);
2327        assert_eq!(rest.new_state.as_ref(), "3");
2328    }
2329
2330    /// Oracle: RFC 8620 §5.2 "If it is unable to calculate an intermediate
2331    /// state, it MUST return a "cannotCalculateChanges" error response
2332    /// instead." One state creating three ids cannot be split under
2333    /// `maxChanges` 2.
2334    #[tokio::test]
2335    async fn one_state_over_max_changes_cannot_calculate() {
2336        let backend = with_creates(&[&["a", "b", "c"]]);
2337        assert!(matches!(
2338            changes(&backend, "0", 2).await,
2339            Err(BackendChangesError::TooManyChanges { limit: 2 })
2340        ));
2341    }
2342
2343    fn sorted(mut ids: Vec<Id>) -> Vec<Id> {
2344        ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
2345        ids
2346    }
2347
2348    async fn changes(
2349        backend: &MemoryBackend<()>,
2350        since: &str,
2351        max: u64,
2352    ) -> Result<ChangesResult, BackendChangesError<<MemoryBackend<()> as JmapAccounts>::Error>>
2353    {
2354        backend
2355            .get_changes::<T>(
2356                &CALLER,
2357                &Id::from("acc1"),
2358                jmap_server::ChangesParams::new(&State::from(since)).max_changes(Some(max)),
2359            )
2360            .await
2361    }
2362}