Skip to main content

jmap_tasks_server/
lib.rs

1//! JMAP Tasks extension method handlers (draft-ietf-jmap-tasks-06).
2//!
3//! # Usage
4//!
5//! Implement [`TasksBackend`] for your storage layer, then call
6//! [`register_tasks_handlers`] to wire all method names into a
7//! [`jmap_server::Dispatcher`]:
8//!
9//! ```rust,no_run
10//! # use std::sync::Arc;
11//! # use jmap_tasks_server::{TasksBackend, register_tasks_handlers};
12//! # use jmap_server::{Dispatcher, JmapBackend};
13//! # fn example<B: TasksBackend<CallerCtx = ()> + 'static>(backend: B) {
14//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
15//! register_tasks_handlers(&mut dispatcher, Arc::new(backend));
16//! # }
17//! ```
18//!
19//! # `memory` feature (reference implementation)
20//!
21//! Enable the `memory` feature to expose the `memory::MemoryBackend`
22//! reference implementation of [`TasksBackend`]. This is the same backend
23//! used by this crate's own integration tests, intended for downstream
24//! contributors to study and for smoke tests / examples that do not want
25//! to stand up a real database. **Not production.** API stability is
26//! opt-in via this feature and may break across minor versions while the
27//! crate is pre-1.0.
28
29#![cfg_attr(docsrs, feature(doc_cfg))]
30#![forbid(unsafe_code)]
31// bd:JMAP-uqhn.4 — narrowing and sign-changing `as` casts are banned;
32// use `try_from`. Widening `usize as u64` stays legal (these lints do
33// not fire on it): it is lossless on every target Rust supports.
34#![warn(
35    clippy::cast_possible_truncation,
36    clippy::cast_possible_wrap,
37    clippy::cast_sign_loss
38)]
39
40use std::sync::Arc;
41
42use jmap_server::{
43    CallContext, ClosureHandler, ConditionalBackend, Dispatcher, HandlerFuture, JmapHandler,
44    RegistrationError, SetSupport,
45};
46
47mod backend;
48mod helpers;
49mod history;
50/// In-memory reference implementation of [`TasksBackend`].
51///
52/// Gated behind `feature = "memory"`. Not production. See [`memory`] for
53/// the full module documentation.
54#[cfg(feature = "memory")]
55pub mod memory;
56mod task;
57mod task_list;
58mod task_notification;
59pub mod workflow;
60
61pub use backend::{TaskQueryArgs, TasksBackend, TasksLimits};
62pub use history::{
63    handle_task_get_with_history, handle_task_list_get_with_history,
64    handle_task_list_set_with_history, handle_task_query_changes_with_history,
65    handle_task_query_with_history, handle_task_set_with_history,
66    register_tasks_handlers_with_history,
67};
68pub use jmap_tasks_types::{TaskListProperty, TaskNotificationProperty, TaskProperty};
69pub use task::{
70    handle_task_changes, handle_task_copy, handle_task_get, handle_task_query,
71    handle_task_query_changes, handle_task_set,
72};
73pub use task_list::{handle_task_list_changes, handle_task_list_get, handle_task_list_set};
74pub use task_notification::{
75    handle_task_notification_changes, handle_task_notification_get, handle_task_notification_query,
76    handle_task_notification_query_changes, handle_task_notification_set,
77};
78
79/// Capability URI for `urn:ietf:params:jmap:tasks`.
80pub use jmap_tasks_types::JMAP_TASKS_URI;
81
82// ---------------------------------------------------------------------------
83// register_tasks_handlers — the main entry point for consumers
84// ---------------------------------------------------------------------------
85
86/// Register all JMAP Tasks method handlers with `dispatcher`.
87///
88/// `backend` is wrapped in [`Arc`] so it is cloned cheaply into each handler.
89/// You may pass any `Arc<B>` — the function clones it internally into each
90/// registered handler closure. Sharing the same `Arc<B>` across this call
91/// and other application-level uses of the backend is a memory
92/// optimization, not a correctness requirement; separate `Arc<B>` instances
93/// pointing at the same underlying backend would also work.
94///
95/// After this call, the dispatcher handles:
96/// `TaskList/get`, `TaskList/changes`, `TaskList/set`,
97/// `Task/get`, `Task/changes`, `Task/set`, `Task/copy`,
98/// `Task/query`, `Task/queryChanges`,
99/// `TaskNotification/get`, `TaskNotification/changes`,
100/// `TaskNotification/set`, `TaskNotification/query`,
101/// `TaskNotification/queryChanges`.
102///
103/// # Re-registration semantics
104///
105/// This function calls [`Dispatcher::register`] once per
106/// draft-ietf-jmap-tasks-06 method name. `Dispatcher::register`
107/// **silently overwrites** any pre-existing handler under the same
108/// method name (the underlying primitive is `HashMap::insert`). Three
109/// consequences callers MUST be aware of:
110///
111/// - **Double-call**: invoking this function twice on the same
112///   dispatcher loses the first set's handlers. The second call wins.
113/// - **Custom overrides go LAST**: to replace a single handler (e.g.
114///   provide a custom `Task/get`), call this function FIRST, then
115///   `dispatcher.register("Task/get", my_override)`. The inverse
116///   order silently undoes the custom handler.
117/// - **No collision diagnostic**: there is no error or log when a
118///   handler is overwritten. The contract is "last register wins" and
119///   the caller is responsible for ordering.
120///
121/// [`Dispatcher::register`]: jmap_server::Dispatcher::register
122pub fn register_tasks_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
123where
124    B: TasksBackend + 'static,
125{
126    // Helper: register one method with a closure taking
127    // (Arc<B>, call_id, args, ctx). `$ctx` is the per-request caller context
128    // (`B::CallerCtx`) forwarded by the dispatcher; closures pass `&ctx` to the
129    // inner `handle_*` fn. `$ci` is the call_id string — most handlers ignore
130    // it (`_ci`); only `Task/copy` uses it.
131    // Each optional trailing ident binds the `CallContext` field of that name:
132    // `created_ids`, the request-wide creation id map (RFC 8620 §5.3) that
133    // `/set` handlers use to resolve `#creationId` references, or `using`,
134    // the request's capability list (draft-ietf-jmap-metadata-05 §3).
135    macro_rules! reg {
136        ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident $(, $field:ident)*| $body:expr) => {{
137            let backend_arc: Arc<B> = Arc::clone(&$backend);
138            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
139                backend_arc,
140                move |$b: Arc<B>, cx: CallContext<B::CallerCtx>| {
141                    let CallContext {
142                        call_id: $ci,
143                        args: $a,
144                        caller: $ctx,
145                        $($field,)*
146                        ..
147                    } = cx;
148                    Box::pin(async move { $body }) as HandlerFuture
149                },
150            ));
151            dispatcher.register($method, h);
152        }};
153    }
154
155    // TaskList
156    reg!("TaskList/get", backend, |b, _ci, a, ctx, using| {
157        handle_task_list_get(&*b, &ctx, a, &using).await
158    });
159    reg!("TaskList/changes", backend, |b, _ci, a, ctx, using| {
160        handle_task_list_changes(&*b, &ctx, a, &using).await
161    });
162    reg!("TaskList/set", backend, |b, _ci, a, ctx, using| {
163        handle_task_list_set(&*b, &ctx, a, &using).await
164    });
165
166    // Task
167    reg!("Task/get", backend, |b, _ci, a, ctx, using| {
168        handle_task_get(&*b, &ctx, a, &using).await
169    });
170    reg!("Task/changes", backend, |b, _ci, a, ctx, using| {
171        handle_task_changes(&*b, &ctx, a, &using).await
172    });
173    reg!("Task/set", backend, |b, _ci, a, ctx, created_ids, using| {
174        handle_task_set(&*b, &ctx, &created_ids, a, &using).await
175    });
176    reg!("Task/copy", backend, |b, ci, a, ctx, using| {
177        handle_task_copy(&*b, &ctx, a, &ci, &using).await
178    });
179    reg!("Task/query", backend, |b, _ci, a, ctx, using| {
180        handle_task_query(&*b, &ctx, a, &using).await
181    });
182    reg!("Task/queryChanges", backend, |b, _ci, a, ctx, using| {
183        handle_task_query_changes(&*b, &ctx, a, &using).await
184    });
185
186    // TaskNotification
187    reg!("TaskNotification/get", backend, |b, _ci, a, ctx| {
188        handle_task_notification_get(&*b, &ctx, a).await
189    });
190    reg!("TaskNotification/changes", backend, |b, _ci, a, ctx| {
191        handle_task_notification_changes(&*b, &ctx, a).await
192    });
193    reg!("TaskNotification/set", backend, |b, _ci, a, ctx| {
194        handle_task_notification_set(&*b, &ctx, a).await
195    });
196    reg!("TaskNotification/query", backend, |b, _ci, a, ctx| {
197        handle_task_notification_query(&*b, &ctx, a).await
198    });
199    reg!(
200        "TaskNotification/queryChanges",
201        backend,
202        |b, _ci, a, ctx| handle_task_notification_query_changes(&*b, &ctx, a).await
203    );
204}
205
206/// Opt this crate's registered Foo/set methods in to
207/// draft-ietf-jmap-conditional-02 (`ifUnchangedBy` and `atomic`;
208/// docs/design/DECISIONS.md decisions 1 and 17).
209///
210/// Call after [`register_tasks_handlers`]. Attaches [`SetSupport`] to each
211/// of `TaskList/set`, `Task/set` and `TaskNotification/set` that is
212/// registered, and skips the rest; no handler is re-registered.
213///
214/// The dispatcher reads preconditions through each type's `/get` and runs
215/// each call in the scope `backend` opens
216/// ([`ConditionalBackend::begin_set`]), which must roll back
217/// `onDestroyRemoveTasks` cascades under `atomic`. A deployment that hides
218/// a Task's `chatId` from some readers (draft-atwood-jmap-chat-tasks-00)
219/// reports it from [`ConditionalBackend::hidden_properties`], e.g. with
220/// `jmap_chat_tasks_server::task_hidden_properties`. Advertise
221/// `urn:ietf:params:jmap:conditional` only once
222/// [`Dispatcher::conditional_ready`] is true for the whole dispatcher.
223pub fn register_tasks_conditional<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
224where
225    B: TasksBackend + ConditionalBackend + 'static,
226{
227    fn attach<C: Clone + Send + 'static>(
228        dispatcher: &mut Dispatcher<C>,
229        method: &str,
230        support: SetSupport<C>,
231    ) {
232        match dispatcher.attach_set_support(method, support) {
233            Ok(()) | Err(RegistrationError::NotRegistered(_)) => {}
234            Err(e) => unreachable!("{method} pairs with its own data type: {e}"),
235        }
236    }
237    macro_rules! attach {
238        ($($t:ident),*) => {$(
239            attach(
240                dispatcher,
241                concat!(stringify!($t), "/set"),
242                SetSupport::new::<jmap_tasks_types::$t, B>(Arc::clone(&backend)),
243            );
244        )*};
245    }
246    attach!(TaskList, Task, TaskNotification);
247}
248
249// ---------------------------------------------------------------------------
250// test_support — in-memory mock backend used by inline tests
251// ---------------------------------------------------------------------------
252
253#[cfg(test)]
254#[deny(clippy::await_holding_lock)]
255pub(crate) mod test_support {
256    //! In-memory mock backend for unit tests.
257
258    use std::collections::HashMap;
259    use std::sync::atomic::{AtomicU32, Ordering};
260    use std::sync::{Arc, Mutex};
261
262    use jmap_server::{
263        BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
264        JmapAccounts, JmapObject, JmapReads, QueryChangesParams, QueryChangesResult, QueryObject,
265        QueryParams, QueryResult, SetError, SetErrorType, SetObject,
266    };
267    use jmap_tasks_types::{Task, TaskList, TaskNotification};
268    use jmap_types::{Id, State};
269
270    use crate::TasksBackend;
271
272    /// Minimal error type for the mock backend.
273    ///
274    /// `#[non_exhaustive]` with a named field, mirroring the canonical
275    /// `jmap-mail-server` `MemoryError`: reads go through
276    /// [`MockError::description`], so structured context can be added later
277    /// without a breaking change. No mock path fails yet, so it has no
278    /// constructor.
279    #[non_exhaustive]
280    #[derive(Debug)]
281    pub struct MockError {
282        description: String,
283    }
284
285    impl MockError {
286        /// Human-readable description of the underlying failure.
287        pub fn description(&self) -> &str {
288            &self.description
289        }
290    }
291
292    impl std::fmt::Display for MockError {
293        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294            write!(f, "mock error: {}", self.description())
295        }
296    }
297
298    impl std::error::Error for MockError {}
299
300    /// In-memory state for one account.
301    #[derive(Default, Clone)]
302    struct AccountState {
303        task_lists: HashMap<Id, TaskList>,
304        tasks: HashMap<Id, Task>,
305        notifications: HashMap<Id, TaskNotification>,
306        task_list_state: u64,
307        task_state: u64,
308        notification_state: u64,
309    }
310
311    /// In-memory mock backend for testing.
312    #[derive(Clone)]
313    pub struct MockBackend {
314        state: Arc<Mutex<HashMap<String, AccountState>>>,
315        /// Counts how many times `update_task_per_user` was called.
316        /// Used by integration tests to verify per-user routing.
317        pub per_user_calls: Arc<AtomicU32>,
318    }
319
320    impl MockBackend {
321        /// Create a backend with no accounts registered.
322        pub fn new() -> Self {
323            Self {
324                state: Arc::new(Mutex::new(HashMap::new())),
325                per_user_calls: Arc::new(AtomicU32::new(0)),
326            }
327        }
328
329        /// Create a backend with the given account already registered.
330        pub fn new_with_account(account_id: &str) -> Self {
331            let b = Self::new();
332            b.state
333                .lock()
334                .unwrap()
335                .insert(account_id.to_owned(), AccountState::default());
336            b
337        }
338
339        /// Register an additional account on an existing backend. Used by
340        /// Task/copy tests that need two valid accounts (`fromAccountId`
341        /// and `accountId` must differ per RFC 8620 §5.4).
342        pub fn add_account(&mut self, account_id: &str) {
343            self.state
344                .lock()
345                .unwrap()
346                .entry(account_id.to_owned())
347                .or_default();
348        }
349
350        /// Pre-populate a TaskNotification in the given account.
351        pub fn add_notification(&mut self, account_id: &str, notif_id: &str) {
352            let notif: TaskNotification = serde_json::from_value(serde_json::json!({
353                "id": notif_id,
354                "created": "2024-01-01T00:00:00Z",
355                "changedBy": { "@type": "Person", "name": "Test" },
356                "type": "created",
357                "taskId": "task1"
358            }))
359            .expect("test fixture must deserialize");
360            let mut guard = self.state.lock().unwrap();
361            let acct = guard.entry(account_id.to_owned()).or_default();
362            acct.notifications.insert(Id::from(notif_id), notif);
363        }
364
365        /// Pre-populate a Task with a specific `isDraft` value in the given account.
366        ///
367        /// Used by tests for the isDraft immutability enforcement path.
368        pub fn seed_task(&mut self, account_id: &str, task_id: &str, is_draft: bool) {
369            let task: Task = serde_json::from_value(serde_json::json!({
370                "id": task_id,
371                "isDraft": is_draft
372            }))
373            .expect("task seed fixture must deserialize");
374            let mut guard = self.state.lock().unwrap();
375            let acct = guard.entry(account_id.to_owned()).or_default();
376            acct.tasks.insert(Id::from(task_id), task);
377        }
378
379        /// Pre-populate a TaskList with a task in the given account.
380        pub fn add_task_list_with_task(&mut self, account_id: &str, list_id: &str) {
381            let task_list: TaskList = serde_json::from_value(serde_json::json!({
382                "id": list_id,
383                "name": "Test List",
384                "sortOrder": 0,
385                "isSubscribed": true,
386                "myRights": {
387                    "mayReadItems": true,
388                    "mayWriteAll": true,
389                    "mayWriteOwn": true,
390                    "mayUpdatePrivate": true,
391                    "mayRSVP": true,
392                    "mayAdmin": true,
393                    "mayDelete": true
394                }
395            }))
396            .expect("task list fixture must deserialize");
397            let mut guard = self.state.lock().unwrap();
398            let acct = guard.entry(account_id.to_owned()).or_default();
399            acct.task_lists.insert(Id::from(list_id), task_list);
400            // Add a task referencing the list
401            let task: Task = serde_json::from_value(serde_json::json!({
402                "id": "task1",
403                "taskListId": list_id
404            }))
405            .expect("task fixture must deserialize");
406            acct.tasks.insert(Id::from("task1"), task);
407        }
408    }
409
410    impl JmapAccounts for MockBackend {
411        type Error = MockError;
412        type CallerCtx = ();
413
414        async fn account_exists(&self, _caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
415            Ok(self.state.lock().unwrap().contains_key(account_id.as_ref()))
416        }
417    }
418
419    impl JmapReads for MockBackend {
420        async fn get_objects<O: GetObject + Send + Sync>(
421            &self,
422            _caller: &(),
423            account_id: &Id,
424            ids: Option<&[Id]>,
425            _properties: Option<&[String]>,
426        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
427            // Attempt to serve from the tasks store via a serde round-trip.
428            // When O = Task this is identity; for other types the deserialize
429            // step will fail (no data in the store matches) and we fall back
430            // to empty — preserving the prior behaviour for TaskList/get etc.
431            let guard = self.state.lock().unwrap();
432            let Some(acct) = guard.get(account_id.as_ref()) else {
433                return Ok((vec![], vec![]));
434            };
435
436            let mut found: Vec<O> = Vec::new();
437            let mut not_found: Vec<Id> = Vec::new();
438
439            if let Some(id_slice) = ids {
440                for id in id_slice {
441                    if let Some(task) = acct.tasks.get(id) {
442                        match serde_json::to_value(task)
443                            .ok()
444                            .and_then(|v| serde_json::from_value::<O>(v).ok())
445                        {
446                            Some(obj) => found.push(obj),
447                            None => not_found.push(id.clone()),
448                        }
449                    } else {
450                        not_found.push(id.clone());
451                    }
452                }
453            }
454            // If no specific ids were requested, serve nothing (empty list) —
455            // the isDraft check always passes specific ids.
456            Ok((found, not_found))
457        }
458
459        async fn get_state<O: JmapObject + Send + Sync>(
460            &self,
461            _caller: &(),
462            _account_id: &Id,
463        ) -> Result<State, Self::Error> {
464            Ok(State::from("0"))
465        }
466
467        async fn get_changes<O: JmapObject + Send + Sync>(
468            &self,
469            _caller: &(),
470            _account_id: &Id,
471            _params: jmap_server::ChangesParams<'_>,
472        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
473            Ok(ChangesResult::new(
474                vec![],
475                vec![],
476                vec![],
477                false,
478                State::from("0"),
479            ))
480        }
481
482        async fn query_objects<O: QueryObject + Send + Sync>(
483            &self,
484            _caller: &(),
485            _account_id: &Id,
486            _params: QueryParams<'_, O>,
487        ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
488            Ok(QueryResult::new(
489                vec![],
490                0,
491                Some(0),
492                State::from("0"),
493                false,
494            ))
495        }
496
497        async fn query_changes<O: QueryObject + Send + Sync>(
498            &self,
499            _caller: &(),
500            _account_id: &Id,
501            params: QueryChangesParams<'_, O>,
502        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
503            let QueryChangesParams {
504                since_query_state, ..
505            } = params;
506            Ok(QueryChangesResult::new(
507                since_query_state.clone(),
508                State::from("0"),
509                Some(0),
510                vec![],
511                vec![],
512            ))
513        }
514    }
515
516    impl TasksBackend for MockBackend {
517        async fn create_object<O, F>(
518            &self,
519            _caller: &(),
520            _account_id: &Id,
521            _create_id: &str,
522            build: F,
523        ) -> Result<(Id, O), BackendSetError<Self::Error>>
524        where
525            O: SetObject + Send + Sync,
526            F: FnOnce(&Id) -> O + Send,
527        {
528            {
529                let id = Id::from("mock-id-1");
530                let obj = build(&id);
531                Ok((id, obj))
532            }
533        }
534
535        async fn copy_object<O: SetObject + Send + Sync>(
536            &self,
537            _caller: &(),
538            _from_account_id: &Id,
539            _to_account_id: &Id,
540            obj: O,
541            _create: &serde_json::Value,
542        ) -> Result<(Id, O), BackendSetError<Self::Error>> {
543            Ok((Id::from("mock-id-1"), obj))
544        }
545
546        /// Rejects every update with `forbidden`, except that a Task patch
547        /// setting `isDraft: true` on a stored Task that is not a draft is
548        /// `invalidProperties` naming `isDraft`: the backend half of
549        /// draft-tasks-06 §4 "This may only be set to true upon creation",
550        /// which `TasksBackend::update_object` requires of every backend.
551        async fn update_object<O: SetObject + Send + Sync>(
552            &self,
553            _caller: &(),
554            account_id: &Id,
555            id: &Id,
556            patch: O::Patch,
557        ) -> Result<Option<O>, BackendSetError<Self::Error>> {
558            let sets_draft = serde_json::to_value(&patch)
559                .ok()
560                .and_then(|p| p.get("isDraft").and_then(|v| v.as_bool()))
561                == Some(true);
562            let stored_not_draft = self
563                .state
564                .lock()
565                .unwrap()
566                .get(account_id.as_ref())
567                .and_then(|a| a.tasks.get(id))
568                .is_some_and(|t| t.is_draft != Some(true));
569            if O::TYPE_NAME == "Task" && sets_draft && stored_not_draft {
570                return Err(BackendSetError::SetError(Box::new(
571                    SetError::new(SetErrorType::InvalidProperties)
572                        .with_properties(vec!["isDraft".to_owned()]),
573                )));
574            }
575            Err(BackendSetError::SetError(Box::new(SetError::new(
576                SetErrorType::Forbidden,
577            ))))
578        }
579
580        async fn destroy_object<O: SetObject + Send + Sync>(
581            &self,
582            _caller: &(),
583            account_id: &Id,
584            id: &Id,
585        ) -> Result<(), BackendSetError<Self::Error>> {
586            let mut guard = self.state.lock().unwrap();
587            if let Some(acct) = guard.get_mut(account_id.as_ref()) {
588                if acct.notifications.remove(id).is_some() {
589                    acct.notification_state += 1;
590                    return Ok(());
591                }
592                if acct.tasks.remove(id).is_some() {
593                    acct.task_state += 1;
594                    return Ok(());
595                }
596                if acct.task_lists.remove(id).is_some() {
597                    acct.task_list_state += 1;
598                    return Ok(());
599                }
600            }
601            Err(BackendSetError::SetError(Box::new(SetError::new(
602                SetErrorType::NotFound,
603            ))))
604        }
605
606        fn supports_type<O: JmapObject>(
607            &self,
608            _caller: &Self::CallerCtx,
609            _account_id: &jmap_types::Id,
610        ) -> bool {
611            true
612        }
613
614        async fn update_task_per_user(
615            &self,
616            caller: &(),
617            account_id: &Id,
618            id: &Id,
619            patch: jmap_types::PatchObject,
620        ) -> Result<Option<Task>, BackendSetError<Self::Error>> {
621            // Track that this per-user path was called.
622            self.per_user_calls.fetch_add(1, Ordering::Relaxed);
623            // Delegate to update_object (same outcome as default impl).
624            self.update_object::<Task>(caller, account_id, id, patch)
625                .await
626        }
627
628        async fn query_tasks(
629            &self,
630            caller: &(),
631            account_id: &Id,
632            params: QueryParams<'_, Task>,
633            _args: &crate::TaskQueryArgs,
634        ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
635            self.query_objects::<Task>(caller, account_id, params).await
636        }
637
638        async fn task_list_has_tasks(
639            &self,
640            _caller: &(),
641            account_id: &Id,
642            task_list_id: &Id,
643        ) -> Result<bool, MockError> {
644            let guard = self.state.lock().unwrap();
645            if let Some(acct) = guard.get(account_id.as_ref()) {
646                return Ok(acct.tasks.values().any(|t| {
647                    t.task_list_id
648                        .as_ref()
649                        .is_some_and(|lid| lid == task_list_id)
650                }));
651            }
652            Ok(false)
653        }
654    }
655}
656
657// ---------------------------------------------------------------------------
658// Tests
659// ---------------------------------------------------------------------------
660
661#[cfg(test)]
662mod tests {
663    use jmap_types::Invocation;
664    use std::sync::Arc;
665    use std::sync::atomic::Ordering;
666
667    use jmap_server::{Dispatcher, JmapRequest, State};
668    use serde_json::json;
669
670    use super::*;
671    use crate::test_support::MockBackend;
672
673    // Helper: build a minimal JmapRequest with one method call.
674    fn single_call(method: &str, args: serde_json::Value, call_id: &str) -> JmapRequest {
675        JmapRequest::new(
676            vec!["urn:ietf:params:jmap:tasks".into()],
677            vec![Invocation::new(method, args, call_id)],
678            None,
679        )
680    }
681
682    /// Oracle: register_tasks_handlers registers all 14 JMAP Tasks methods.
683    ///
684    /// Verification: each method name returns a non-error response when
685    /// dispatched with a valid account (not `unknownMethod`).
686    #[tokio::test]
687    async fn registers_all_14_methods() {
688        let backend = Arc::new(MockBackend::new_with_account("acc1"));
689        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
690        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
691
692        let methods = [
693            ("TaskList/get", json!({"accountId": "acc1", "ids": null})),
694            (
695                "TaskList/changes",
696                json!({"accountId": "acc1", "sinceState": "0"}),
697            ),
698            ("TaskList/set", json!({"accountId": "acc1", "destroy": []})),
699            ("Task/get", json!({"accountId": "acc1", "ids": null})),
700            (
701                "Task/changes",
702                json!({"accountId": "acc1", "sinceState": "0"}),
703            ),
704            ("Task/set", json!({"accountId": "acc1", "destroy": []})),
705            (
706                "Task/copy",
707                json!({"fromAccountId": "acc1", "accountId": "acc1", "create": {}}),
708            ),
709            (
710                "Task/query",
711                json!({"accountId": "acc1", "filter": null, "sort": null}),
712            ),
713            (
714                "Task/queryChanges",
715                json!({"accountId": "acc1", "sinceQueryState": "0"}),
716            ),
717            (
718                "TaskNotification/get",
719                json!({"accountId": "acc1", "ids": null}),
720            ),
721            (
722                "TaskNotification/changes",
723                json!({"accountId": "acc1", "sinceState": "0"}),
724            ),
725            (
726                "TaskNotification/set",
727                json!({"accountId": "acc1", "destroy": []}),
728            ),
729            (
730                "TaskNotification/query",
731                json!({"accountId": "acc1", "filter": null, "sort": null}),
732            ),
733            (
734                "TaskNotification/queryChanges",
735                json!({"accountId": "acc1", "sinceQueryState": "0"}),
736            ),
737        ];
738
739        for (method, args) in methods {
740            let req = single_call(method, args, "c0");
741            let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
742            assert_eq!(
743                resp.method_responses.len(),
744                1,
745                "{method}: expected 1 response"
746            );
747            let Invocation {
748                arguments: resp_args,
749                ..
750            } = &resp.method_responses[0];
751            assert_ne!(
752                resp_args["type"], "unknownMethod",
753                "{method}: must not be unknownMethod — is it registered?"
754            );
755        }
756    }
757
758    /// Oracle: TaskNotification/set with create entries → notCreated contains
759    /// `forbidden` for every create entry; no top-level error.
760    #[tokio::test]
761    async fn task_notification_set_create_returns_forbidden() {
762        let backend = Arc::new(MockBackend::new_with_account("acc1"));
763        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
764        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
765
766        let req = single_call(
767            "TaskNotification/set",
768            json!({
769                "accountId": "acc1",
770                "create": {
771                    "c1": {
772                        "id": "x",
773                        "created": "2024-01-01T00:00:00Z",
774                        "changedBy": { "@type": "Person", "name": "A" },
775                        "type": "created",
776                        "taskId": "t1"
777                    }
778                }
779            }),
780            "c0",
781        );
782        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
783        let Invocation {
784            arguments: args, ..
785        } = &resp.method_responses[0];
786        assert!(
787            args.get("type").is_none(),
788            "must not be a top-level error: {args}"
789        );
790        assert_eq!(
791            args["notCreated"]["c1"]["type"], "forbidden",
792            "create must be forbidden: {args}"
793        );
794    }
795
796    /// Oracle: TaskList/set destroy with tasks returns taskListHasTask error
797    /// (draft-ietf-jmap-tasks-06 §3.4).
798    ///
799    /// When `onDestroyRemoveTasks` is false (default) and the task list has tasks,
800    /// the destroy should fail with a custom `taskListHasTask` error.
801    #[tokio::test]
802    async fn task_list_set_destroy_with_tasks_returns_task_list_has_task() {
803        let mut backend = MockBackend::new_with_account("acc1");
804        backend.add_task_list_with_task("acc1", "list1");
805        let backend = Arc::new(backend);
806
807        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
808        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
809
810        let req = single_call(
811            "TaskList/set",
812            json!({
813                "accountId": "acc1",
814                "destroy": ["list1"],
815                "onDestroyRemoveTasks": false
816            }),
817            "c0",
818        );
819        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
820        let Invocation {
821            arguments: args, ..
822        } = &resp.method_responses[0];
823        assert!(
824            args.get("type").is_none(),
825            "must not be a top-level error: {args}"
826        );
827        assert_eq!(
828            args["notDestroyed"]["list1"]["type"], "taskListHasTask",
829            "must return taskListHasTask when list has tasks: {args}"
830        );
831    }
832
833    // ── Integration tests: isDraft, utcStart, per-user routing ──────────────
834
835    /// Oracle: draft-tasks-06 §4 — isDraft false→true revert is rejected via
836    /// dispatcher (end-to-end path through register_tasks_handlers).
837    #[tokio::test]
838    async fn isdraft_revert_via_dispatcher() {
839        let mut backend = MockBackend::new_with_account("acc1");
840        backend.seed_task("acc1", "t1", false);
841        let backend = Arc::new(backend);
842
843        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
844        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
845
846        let req = single_call(
847            "Task/set",
848            json!({
849                "accountId": "acc1",
850                "update": { "t1": { "isDraft": true } }
851            }),
852            "c0",
853        );
854        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
855        let Invocation {
856            arguments: args, ..
857        } = &resp.method_responses[0];
858        assert!(
859            args.get("type").is_none(),
860            "must not be a top-level error: {args}"
861        );
862        assert_eq!(
863            args["notUpdated"]["t1"]["type"], "invalidProperties",
864            "isDraft revert must be invalidProperties: {args}"
865        );
866        assert_eq!(
867            args["notUpdated"]["t1"]["properties"][0], "isDraft",
868            "isDraft must be listed in properties: {args}"
869        );
870    }
871
872    /// Oracle: draft-tasks-06 §4 — isDraft false (draft → published) is always
873    /// allowed; the handler must not pre-reject it.
874    #[tokio::test]
875    async fn isdraft_draft_to_publish_allowed() {
876        let mut backend = MockBackend::new_with_account("acc1");
877        backend.seed_task("acc1", "t1", true);
878        let backend = Arc::new(backend);
879
880        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
881        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
882
883        let req = single_call(
884            "Task/set",
885            json!({
886                "accountId": "acc1",
887                "update": { "t1": { "isDraft": false } }
888            }),
889            "c0",
890        );
891        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
892        let Invocation {
893            arguments: args, ..
894        } = &resp.method_responses[0];
895        // The patch must NOT be pre-rejected with invalidProperties.
896        if let Some(not_updated) = args["notUpdated"].as_object()
897            && let Some(err) = not_updated.get("t1")
898        {
899            assert_ne!(
900                err["type"].as_str(),
901                Some("invalidProperties"),
902                "isDraft:false must not produce invalidProperties: {args}"
903            );
904        }
905    }
906
907    /// Oracle: draft-tasks-06 §4 (utcStart/utcDue paragraphs) — utcStart is NOT returned
908    /// when not in the properties list.
909    #[tokio::test]
910    async fn utcstart_not_in_default_properties() {
911        let backend = Arc::new(MockBackend::new_with_account("acc1"));
912        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
913        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
914
915        let req = single_call(
916            "Task/get",
917            json!({ "accountId": "acc1", "ids": null, "properties": ["id"] }),
918            "c0",
919        );
920        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
921        let Invocation {
922            arguments: args, ..
923        } = &resp.method_responses[0];
924        assert!(args.get("type").is_none(), "must not be error: {args}");
925        for item in args["list"].as_array().into_iter().flatten() {
926            assert!(
927                item.get("utcStart").is_none(),
928                "utcStart must not appear when not requested: {item}"
929            );
930        }
931    }
932
933    /// Oracle: draft-tasks-06 §4 — when utcStart is explicitly requested,
934    /// the handler invokes compute_utc_times (default: returns None, so
935    /// no value injected), but no error is raised.
936    #[tokio::test]
937    async fn utcstart_returned_when_requested() {
938        let backend = Arc::new(MockBackend::new_with_account("acc1"));
939        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
940        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
941
942        let req = single_call(
943            "Task/get",
944            json!({
945                "accountId": "acc1",
946                "ids": null,
947                "properties": ["id", "utcStart"]
948            }),
949            "c0",
950        );
951        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
952        let Invocation {
953            arguments: args, ..
954        } = &resp.method_responses[0];
955        assert!(
956            args.get("type").is_none(),
957            "Task/get with utcStart must not error: {args}"
958        );
959    }
960
961    /// Oracle: bd:JMAP-ops7.25 — the `account_id` argument plumbed into
962    /// `TasksBackend::compute_utc_times` matches the request's `accountId`
963    /// and is delivered as a validated [`Id`]. Locks in the args-threading
964    /// contract: a backend that overrides `compute_utc_times` can rely on
965    /// receiving the caller-validated account id.
966    ///
967    /// Also oracle: draft-tasks-06 §4 (utcStart is computed from `start` and
968    /// `timeZone`) and RFC 8620 §5.1 ("only the properties listed in the
969    /// array are returned"). The stub's stored task has `start` and
970    /// `timeZone`, and its `compute_utc_times` returns the hand-written
971    /// `2024-06-15T09:00:00Z` only when `start` reaches it, so a request
972    /// for `["id", "utcStart"]` must return exactly `id` and that value.
973    #[tokio::test]
974    async fn compute_utc_times_receives_validated_account_id() {
975        use std::sync::Mutex;
976
977        use jmap_server::{
978            BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
979            JmapAccounts, JmapObject, JmapReads, QueryChangesParams, QueryChangesResult,
980            QueryObject, QueryParams, QueryResult, SetObject,
981        };
982        use jmap_tasks_types::Task;
983        use jmap_types::{Id, UTCDate};
984
985        use crate::TasksBackend;
986        use crate::test_support::MockError;
987
988        /// Minimal recording backend that returns exactly one Task on
989        /// `get_objects::<Task>` (so the handler's augmentation loop fires
990        /// once) and captures the `account_id` argument that `compute_utc_times`
991        /// receives.
992        struct AccountIdRecorder {
993            observed: Mutex<Vec<Id>>,
994        }
995
996        impl JmapAccounts for AccountIdRecorder {
997            type Error = MockError;
998            type CallerCtx = ();
999
1000            async fn account_exists(
1001                &self,
1002                _caller: &(),
1003                _account_id: &Id,
1004            ) -> Result<bool, Self::Error> {
1005                Ok(true)
1006            }
1007        }
1008
1009        impl JmapReads for AccountIdRecorder {
1010            async fn get_objects<O: GetObject + Send + Sync>(
1011                &self,
1012                _caller: &(),
1013                _account_id: &Id,
1014                _ids: Option<&[Id]>,
1015                _properties: Option<&[String]>,
1016            ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1017                // Synthesize one Task via JSON round-trip. Non-Task types
1018                // get back an empty list (handler exercise here is
1019                // Task/get only).
1020                let item = json!({
1021                    "id": "t1",
1022                    "start": "2024-06-15T09:00:00",
1023                    "timeZone": "Etc/UTC"
1024                });
1025                match serde_json::from_value::<O>(item) {
1026                    Ok(obj) => Ok((vec![obj], vec![])),
1027                    Err(_) => Ok((vec![], vec![])),
1028                }
1029            }
1030
1031            async fn get_state<O: JmapObject + Send + Sync>(
1032                &self,
1033                _caller: &(),
1034                _account_id: &Id,
1035            ) -> Result<State, Self::Error> {
1036                Ok(State::from("s0"))
1037            }
1038
1039            async fn get_changes<O: JmapObject + Send + Sync>(
1040                &self,
1041                _caller: &(),
1042                _account_id: &Id,
1043                _params: jmap_server::ChangesParams<'_>,
1044            ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1045                Ok(ChangesResult::new(
1046                    vec![],
1047                    vec![],
1048                    vec![],
1049                    false,
1050                    State::from("s0"),
1051                ))
1052            }
1053
1054            async fn query_objects<O: QueryObject + Send + Sync>(
1055                &self,
1056                _caller: &(),
1057                _account_id: &Id,
1058                _params: QueryParams<'_, O>,
1059            ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
1060                Ok(QueryResult::new(
1061                    vec![],
1062                    0,
1063                    Some(0),
1064                    State::from("s0"),
1065                    false,
1066                ))
1067            }
1068
1069            async fn query_changes<O: QueryObject + Send + Sync>(
1070                &self,
1071                _caller: &(),
1072                _account_id: &Id,
1073                params: QueryChangesParams<'_, O>,
1074            ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1075                let QueryChangesParams {
1076                    since_query_state, ..
1077                } = params;
1078                Ok(QueryChangesResult::new(
1079                    since_query_state.clone(),
1080                    State::from("s0"),
1081                    Some(0),
1082                    vec![],
1083                    vec![],
1084                ))
1085            }
1086        }
1087
1088        impl TasksBackend for AccountIdRecorder {
1089            async fn create_object<O, F>(
1090                &self,
1091                _caller: &(),
1092                _account_id: &Id,
1093                _create_id: &str,
1094                build: F,
1095            ) -> Result<(Id, O), BackendSetError<Self::Error>>
1096            where
1097                O: SetObject + Send + Sync,
1098                F: FnOnce(&Id) -> O + Send,
1099            {
1100                {
1101                    let id = Id::from("t1");
1102                    let obj = build(&id);
1103                    Ok((id, obj))
1104                }
1105            }
1106
1107            async fn copy_object<O: SetObject + Send + Sync>(
1108                &self,
1109                _caller: &(),
1110                _from_account_id: &Id,
1111                _to_account_id: &Id,
1112                obj: O,
1113                _create: &serde_json::Value,
1114            ) -> Result<(Id, O), BackendSetError<Self::Error>> {
1115                Ok((Id::from("t1"), obj))
1116            }
1117
1118            async fn update_object<O: SetObject + Send + Sync>(
1119                &self,
1120                _caller: &(),
1121                _account_id: &Id,
1122                _id: &Id,
1123                _patch: O::Patch,
1124            ) -> Result<Option<O>, BackendSetError<Self::Error>> {
1125                Ok(None)
1126            }
1127
1128            async fn update_task_per_user(
1129                &self,
1130                caller: &(),
1131                account_id: &Id,
1132                id: &Id,
1133                patch: jmap_types::PatchObject,
1134            ) -> Result<Option<jmap_tasks_types::Task>, BackendSetError<Self::Error>> {
1135                self.update_object::<jmap_tasks_types::Task>(caller, account_id, id, patch)
1136                    .await
1137            }
1138
1139            async fn destroy_object<O: SetObject + Send + Sync>(
1140                &self,
1141                _caller: &(),
1142                _account_id: &Id,
1143                _id: &Id,
1144            ) -> Result<(), BackendSetError<Self::Error>> {
1145                Ok(())
1146            }
1147
1148            fn supports_type<O: JmapObject>(
1149                &self,
1150                _caller: &Self::CallerCtx,
1151                _account_id: &jmap_types::Id,
1152            ) -> bool {
1153                true
1154            }
1155
1156            async fn query_tasks(
1157                &self,
1158                caller: &(),
1159                account_id: &Id,
1160                params: QueryParams<'_, Task>,
1161                _args: &crate::TaskQueryArgs,
1162            ) -> Result<QueryResult, BackendQueryError<MockError>> {
1163                self.query_objects::<Task>(caller, account_id, params).await
1164            }
1165
1166            async fn task_list_has_tasks(
1167                &self,
1168                _caller: &(),
1169                _account_id: &Id,
1170                _task_list_id: &Id,
1171            ) -> Result<bool, MockError> {
1172                Ok(false)
1173            }
1174
1175            async fn compute_utc_times(
1176                &self,
1177                _caller: &(),
1178                account_id: &Id,
1179                task: &Task,
1180                _tz_hint: Option<&str>,
1181            ) -> (Option<UTCDate>, Option<UTCDate>) {
1182                self.observed.lock().unwrap().push(account_id.clone());
1183                let fixed = task
1184                    .start
1185                    .as_ref()
1186                    .map(|_| UTCDate::from("2024-06-15T09:00:00Z"));
1187                (fixed.clone(), fixed)
1188            }
1189        }
1190
1191        let backend = Arc::new(AccountIdRecorder {
1192            observed: Mutex::new(Vec::new()),
1193        });
1194        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
1195        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
1196
1197        let req = single_call(
1198            "Task/get",
1199            json!({
1200                "accountId": "acc1",
1201                "ids": null,
1202                "properties": ["id", "utcStart"]
1203            }),
1204            "c0",
1205        );
1206        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
1207        let Invocation {
1208            arguments: args, ..
1209        } = &resp.method_responses[0];
1210        assert!(
1211            args.get("type").is_none(),
1212            "Task/get with utcStart must not error: {args}"
1213        );
1214
1215        let seen = backend.observed.lock().unwrap().clone();
1216        assert_eq!(
1217            seen,
1218            vec![Id::from("acc1")],
1219            "compute_utc_times must receive the request's accountId exactly once \
1220             (one Task synthesized, utcStart requested)"
1221        );
1222        assert_eq!(
1223            args["list"],
1224            json!([{ "id": "t1", "utcStart": "2024-06-15T09:00:00Z" }]),
1225            "utcStart must be computed from the stored start, and only the \
1226             requested properties returned"
1227        );
1228    }
1229
1230    /// Oracle: draft-tasks-06 §4.5.1 — a per-user-only patch is routed to
1231    /// `update_task_per_user`. MockBackend tracks the call count.
1232    #[tokio::test]
1233    async fn per_user_patch_split() {
1234        let backend = Arc::new(MockBackend::new_with_account("acc1"));
1235        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
1236        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
1237
1238        let before = backend.per_user_calls.load(Ordering::Relaxed);
1239
1240        let req = single_call(
1241            "Task/set",
1242            json!({
1243                "accountId": "acc1",
1244                "update": { "t1": { "color": "#ff0000" } }
1245            }),
1246            "c0",
1247        );
1248        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
1249        let Invocation {
1250            arguments: args, ..
1251        } = &resp.method_responses[0];
1252        assert!(
1253            args.get("type").is_none(),
1254            "must not be top-level error: {args}"
1255        );
1256
1257        let after = backend.per_user_calls.load(Ordering::Relaxed);
1258        assert_eq!(
1259            after - before,
1260            1,
1261            "per_user update must have been called exactly once for a color-only patch"
1262        );
1263    }
1264}