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