1#![forbid(unsafe_code)]
30
31use std::sync::Arc;
32
33use jmap_server::{Dispatcher, HandlerFuture, JmapHandler};
34
35pub mod backend;
36mod helpers;
37#[cfg(feature = "memory")]
42pub mod memory;
43pub mod task;
44pub mod task_list;
45pub mod task_notification;
46
47pub use backend::{
48 AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
49 JmapBackend, JmapObject, QueryChangesResult, QueryObject, QueryResult, SetError, SetErrorType,
50 SetObject, TaskListProperty, TaskNotificationProperty, TaskProperty, TasksBackend,
51};
52pub use task::{
53 handle_task_changes, handle_task_copy, handle_task_get, handle_task_query,
54 handle_task_query_changes, handle_task_set,
55};
56pub use task_list::{handle_task_list_changes, handle_task_list_get, handle_task_list_set};
57pub use task_notification::{
58 handle_task_notification_changes, handle_task_notification_get, handle_task_notification_query,
59 handle_task_notification_query_changes, handle_task_notification_set,
60};
61
62pub use jmap_tasks_types::JMAP_TASKS_URI;
64
65pub fn register_tasks_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
106where
107 B: TasksBackend + 'static,
108{
109 macro_rules! reg {
115 ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident| $body:expr) => {{
116 let backend_arc: Arc<B> = Arc::clone(&$backend);
117 let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
118 backend_arc,
119 move |$b: Arc<B>, $ci: String, $a: serde_json::Value, $ctx: B::CallerCtx| {
120 Box::pin(async move { $body }) as HandlerFuture
121 },
122 ));
123 dispatcher.register($method, h);
124 }};
125 }
126
127 reg!("TaskList/get", backend, |b, _ci, a, ctx| {
129 handle_task_list_get(&*b, &ctx, a).await
130 });
131 reg!("TaskList/changes", backend, |b, _ci, a, ctx| {
132 handle_task_list_changes(&*b, &ctx, a).await
133 });
134 reg!("TaskList/set", backend, |b, _ci, a, ctx| {
135 handle_task_list_set(&*b, &ctx, a).await
136 });
137
138 reg!("Task/get", backend, |b, _ci, a, ctx| {
140 handle_task_get(&*b, &ctx, a).await
141 });
142 reg!("Task/changes", backend, |b, _ci, a, ctx| {
143 handle_task_changes(&*b, &ctx, a).await
144 });
145 reg!("Task/set", backend, |b, _ci, a, ctx| {
146 handle_task_set(&*b, &ctx, a).await
147 });
148 reg!("Task/copy", backend, |b, ci, a, ctx| {
149 handle_task_copy(&*b, &ctx, a, &ci).await
150 });
151 reg!("Task/query", backend, |b, _ci, a, ctx| {
152 handle_task_query(&*b, &ctx, a).await
153 });
154 reg!("Task/queryChanges", backend, |b, _ci, a, ctx| {
155 handle_task_query_changes(&*b, &ctx, a).await
156 });
157
158 reg!("TaskNotification/get", backend, |b, _ci, a, ctx| {
160 handle_task_notification_get(&*b, &ctx, a).await
161 });
162 reg!("TaskNotification/changes", backend, |b, _ci, a, ctx| {
163 handle_task_notification_changes(&*b, &ctx, a).await
164 });
165 reg!("TaskNotification/set", backend, |b, _ci, a, ctx| {
166 handle_task_notification_set(&*b, &ctx, a).await
167 });
168 reg!("TaskNotification/query", backend, |b, _ci, a, ctx| {
169 handle_task_notification_query(&*b, &ctx, a).await
170 });
171 reg!(
172 "TaskNotification/queryChanges",
173 backend,
174 |b, _ci, a, ctx| handle_task_notification_query_changes(&*b, &ctx, a).await
175 );
176}
177
178pub use jmap_server::ClosureHandler;
197
198#[cfg(test)]
203#[deny(clippy::await_holding_lock)]
204pub(crate) mod test_support {
205 use std::collections::HashMap;
208 use std::sync::atomic::{AtomicU32, Ordering};
209 use std::sync::{Arc, Mutex};
210
211 use jmap_server::{
212 BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
213 JmapBackend, JmapObject, QueryChangesResult, QueryObject, QueryResult, SetError,
214 SetErrorType, SetObject,
215 };
216 use jmap_tasks_types::{Task, TaskList, TaskNotification};
217 use jmap_types::{Id, State};
218
219 use crate::backend::TasksBackend;
220
221 #[derive(Debug)]
223 pub struct MockError(pub String);
224
225 impl std::fmt::Display for MockError {
226 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227 write!(f, "mock error: {}", self.0)
228 }
229 }
230
231 impl std::error::Error for MockError {}
232
233 #[derive(Default, Clone)]
235 struct AccountState {
236 task_lists: HashMap<Id, TaskList>,
237 tasks: HashMap<Id, Task>,
238 notifications: HashMap<Id, TaskNotification>,
239 task_list_state: u64,
240 task_state: u64,
241 notification_state: u64,
242 }
243
244 #[derive(Clone)]
246 pub struct MockBackend {
247 state: Arc<Mutex<HashMap<String, AccountState>>>,
248 pub per_user_calls: Arc<AtomicU32>,
251 }
252
253 impl MockBackend {
254 pub fn new() -> Self {
256 Self {
257 state: Arc::new(Mutex::new(HashMap::new())),
258 per_user_calls: Arc::new(AtomicU32::new(0)),
259 }
260 }
261
262 pub fn new_with_account(account_id: &str) -> Self {
264 let b = Self::new();
265 b.state
266 .lock()
267 .unwrap()
268 .insert(account_id.to_owned(), AccountState::default());
269 b
270 }
271
272 pub fn add_account(&mut self, account_id: &str) {
276 self.state
277 .lock()
278 .unwrap()
279 .entry(account_id.to_owned())
280 .or_default();
281 }
282
283 pub fn add_notification(&mut self, account_id: &str, notif_id: &str) {
285 let notif: TaskNotification = serde_json::from_value(serde_json::json!({
286 "id": notif_id,
287 "created": "2024-01-01T00:00:00Z",
288 "changedBy": { "@type": "Person", "name": "Test" },
289 "type": "created",
290 "taskId": "task1"
291 }))
292 .expect("test fixture must deserialize");
293 let mut guard = self.state.lock().unwrap();
294 let acct = guard.entry(account_id.to_owned()).or_default();
295 acct.notifications.insert(Id::from(notif_id), notif);
296 }
297
298 pub fn seed_task(&mut self, account_id: &str, task_id: &str, is_draft: bool) {
302 let task: Task = serde_json::from_value(serde_json::json!({
303 "id": task_id,
304 "isDraft": is_draft
305 }))
306 .expect("task seed fixture must deserialize");
307 let mut guard = self.state.lock().unwrap();
308 let acct = guard.entry(account_id.to_owned()).or_default();
309 acct.tasks.insert(Id::from(task_id), task);
310 }
311
312 pub fn add_task_list_with_task(&mut self, account_id: &str, list_id: &str) {
314 let task_list: TaskList = serde_json::from_value(serde_json::json!({
315 "id": list_id,
316 "name": "Test List",
317 "sortOrder": 0,
318 "isSubscribed": true,
319 "myRights": {
320 "mayReadItems": true,
321 "mayWriteAll": true,
322 "mayWriteOwn": true,
323 "mayUpdatePrivate": true,
324 "mayRSVP": true,
325 "mayAdmin": true,
326 "mayDelete": true
327 }
328 }))
329 .expect("task list fixture must deserialize");
330 let mut guard = self.state.lock().unwrap();
331 let acct = guard.entry(account_id.to_owned()).or_default();
332 acct.task_lists.insert(Id::from(list_id), task_list);
333 let task: Task = serde_json::from_value(serde_json::json!({
335 "id": "task1",
336 "taskListId": list_id
337 }))
338 .expect("task fixture must deserialize");
339 acct.tasks.insert(Id::from("task1"), task);
340 }
341 }
342
343 impl JmapBackend for MockBackend {
344 type Error = MockError;
345 type CallerCtx = ();
346
347 async fn account_exists(&self, _caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
348 Ok(self.state.lock().unwrap().contains_key(account_id.as_ref()))
349 }
350
351 async fn get_objects<O: GetObject + Send + Sync>(
352 &self,
353 _caller: &(),
354 account_id: &Id,
355 ids: Option<&[Id]>,
356 _properties: Option<&[String]>,
357 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
358 let guard = self.state.lock().unwrap();
363 let Some(acct) = guard.get(account_id.as_ref()) else {
364 return Ok((vec![], vec![]));
365 };
366
367 let mut found: Vec<O> = Vec::new();
368 let mut not_found: Vec<Id> = Vec::new();
369
370 if let Some(id_slice) = ids {
371 for id in id_slice {
372 if let Some(task) = acct.tasks.get(id) {
373 match serde_json::to_value(task)
374 .ok()
375 .and_then(|v| serde_json::from_value::<O>(v).ok())
376 {
377 Some(obj) => found.push(obj),
378 None => not_found.push(id.clone()),
379 }
380 } else {
381 not_found.push(id.clone());
382 }
383 }
384 }
385 Ok((found, not_found))
388 }
389
390 async fn get_state<O: JmapObject + Send + Sync>(
391 &self,
392 _caller: &(),
393 _account_id: &Id,
394 ) -> Result<State, Self::Error> {
395 Ok(State::from("0"))
396 }
397
398 async fn get_changes<O: JmapObject + Send + Sync>(
399 &self,
400 _caller: &(),
401 _account_id: &Id,
402 _since_state: &State,
403 _max_changes: Option<u64>,
404 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
405 Ok(ChangesResult::new(
406 vec![],
407 vec![],
408 vec![],
409 false,
410 State::from("0"),
411 ))
412 }
413
414 async fn query_objects<O: QueryObject + Send + Sync>(
415 &self,
416 _caller: &(),
417 _account_id: &Id,
418 _filter: Option<&O::Filter>,
419 _sort: Option<&[O::Comparator]>,
420 _limit: Option<u64>,
421 _position: i64,
422 _anchor: Option<&Id>,
423 _anchor_offset: i64,
424 ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
425 Ok(QueryResult::new(
426 vec![],
427 0,
428 Some(0),
429 State::from("0"),
430 false,
431 ))
432 }
433
434 async fn query_changes<O: QueryObject + Send + Sync>(
435 &self,
436 _caller: &(),
437 _account_id: &Id,
438 since_query_state: &State,
439 _filter: Option<&O::Filter>,
440 _sort: Option<&[O::Comparator]>,
441 _max_changes: Option<u64>,
442 _up_to_id: Option<&Id>,
443 _collapse_threads: bool,
444 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
445 Ok(QueryChangesResult::new(
446 since_query_state.clone(),
447 State::from("0"),
448 Some(0),
449 vec![],
450 vec![],
451 ))
452 }
453 }
454
455 impl TasksBackend for MockBackend {
456 async fn create_object<O: SetObject + Send + Sync>(
457 &self,
458 _caller: &(),
459 _account_id: &Id,
460 _create_id: &str,
461 obj: O,
462 ) -> Result<(Id, O), BackendSetError<Self::Error>> {
463 Ok((Id::from("mock-id-1"), obj))
464 }
465
466 async fn update_object<O: SetObject + Send + Sync>(
467 &self,
468 _caller: &(),
469 _account_id: &Id,
470 _id: &Id,
471 _patch: O::Patch,
472 ) -> Result<Option<O>, BackendSetError<Self::Error>> {
473 Err(BackendSetError::SetError(SetError::new(
474 SetErrorType::Forbidden,
475 )))
476 }
477
478 async fn destroy_object<O: SetObject + Send + Sync>(
479 &self,
480 _caller: &(),
481 account_id: &Id,
482 id: &Id,
483 ) -> Result<(), BackendSetError<Self::Error>> {
484 let mut guard = self.state.lock().unwrap();
485 if let Some(acct) = guard.get_mut(account_id.as_ref()) {
486 if acct.notifications.remove(id).is_some() {
487 acct.notification_state += 1;
488 return Ok(());
489 }
490 if acct.tasks.remove(id).is_some() {
491 acct.task_state += 1;
492 return Ok(());
493 }
494 if acct.task_lists.remove(id).is_some() {
495 acct.task_list_state += 1;
496 return Ok(());
497 }
498 }
499 Err(BackendSetError::SetError(SetError::new(
500 SetErrorType::NotFound,
501 )))
502 }
503
504 fn supports_type<O: JmapObject>(
505 &self,
506 _caller: &Self::CallerCtx,
507 _account_id: &jmap_types::Id,
508 ) -> bool {
509 true
510 }
511
512 async fn update_task_per_user(
513 &self,
514 caller: &(),
515 account_id: &Id,
516 id: &Id,
517 patch: jmap_types::PatchObject,
518 ) -> Result<Option<Task>, BackendSetError<Self::Error>> {
519 self.per_user_calls.fetch_add(1, Ordering::Relaxed);
521 self.update_object::<Task>(caller, account_id, id, patch)
523 .await
524 }
525
526 async fn task_list_has_tasks(
527 &self,
528 _caller: &(),
529 account_id: &Id,
530 task_list_id: &Id,
531 ) -> Result<bool, MockError> {
532 let guard = self.state.lock().unwrap();
533 if let Some(acct) = guard.get(account_id.as_ref()) {
534 return Ok(acct.tasks.values().any(|t| {
535 t.task_list_id
536 .as_ref()
537 .is_some_and(|lid| lid == task_list_id)
538 }));
539 }
540 Ok(false)
541 }
542 }
543}
544
545#[cfg(test)]
550mod tests {
551 use jmap_types::Invocation;
552 use std::sync::atomic::Ordering;
553 use std::sync::Arc;
554
555 use jmap_server::{Dispatcher, JmapRequest, State};
556 use serde_json::json;
557
558 use super::*;
559 use crate::test_support::MockBackend;
560
561 fn single_call(method: &str, args: serde_json::Value, call_id: &str) -> JmapRequest {
563 JmapRequest::new(
564 vec!["urn:ietf:params:jmap:tasks".into()],
565 vec![Invocation::new(method, args, call_id)],
566 None,
567 )
568 }
569
570 #[tokio::test]
575 async fn registers_all_14_methods() {
576 let backend = Arc::new(MockBackend::new_with_account("acc1"));
577 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
578 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
579
580 let methods = [
581 ("TaskList/get", json!({"accountId": "acc1", "ids": null})),
582 (
583 "TaskList/changes",
584 json!({"accountId": "acc1", "sinceState": "0"}),
585 ),
586 ("TaskList/set", json!({"accountId": "acc1", "destroy": []})),
587 ("Task/get", json!({"accountId": "acc1", "ids": null})),
588 (
589 "Task/changes",
590 json!({"accountId": "acc1", "sinceState": "0"}),
591 ),
592 ("Task/set", json!({"accountId": "acc1", "destroy": []})),
593 (
594 "Task/copy",
595 json!({"fromAccountId": "acc1", "accountId": "acc1", "create": {}}),
596 ),
597 (
598 "Task/query",
599 json!({"accountId": "acc1", "filter": null, "sort": null}),
600 ),
601 (
602 "Task/queryChanges",
603 json!({"accountId": "acc1", "sinceQueryState": "0"}),
604 ),
605 (
606 "TaskNotification/get",
607 json!({"accountId": "acc1", "ids": null}),
608 ),
609 (
610 "TaskNotification/changes",
611 json!({"accountId": "acc1", "sinceState": "0"}),
612 ),
613 (
614 "TaskNotification/set",
615 json!({"accountId": "acc1", "destroy": []}),
616 ),
617 (
618 "TaskNotification/query",
619 json!({"accountId": "acc1", "filter": null, "sort": null}),
620 ),
621 (
622 "TaskNotification/queryChanges",
623 json!({"accountId": "acc1", "sinceQueryState": "0"}),
624 ),
625 ];
626
627 for (method, args) in methods {
628 let req = single_call(method, args, "c0");
629 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
630 assert_eq!(
631 resp.method_responses.len(),
632 1,
633 "{method}: expected 1 response"
634 );
635 let Invocation {
636 arguments: resp_args,
637 ..
638 } = &resp.method_responses[0];
639 assert_ne!(
640 resp_args["type"], "unknownMethod",
641 "{method}: must not be unknownMethod — is it registered?"
642 );
643 }
644 }
645
646 #[tokio::test]
649 async fn task_notification_set_create_returns_forbidden() {
650 let backend = Arc::new(MockBackend::new_with_account("acc1"));
651 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
652 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
653
654 let req = single_call(
655 "TaskNotification/set",
656 json!({
657 "accountId": "acc1",
658 "create": {
659 "c1": {
660 "id": "x",
661 "created": "2024-01-01T00:00:00Z",
662 "changedBy": { "@type": "Person", "name": "A" },
663 "type": "created",
664 "taskId": "t1"
665 }
666 }
667 }),
668 "c0",
669 );
670 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
671 let Invocation {
672 arguments: args, ..
673 } = &resp.method_responses[0];
674 assert!(
675 args.get("type").is_none(),
676 "must not be a top-level error: {args}"
677 );
678 assert_eq!(
679 args["notCreated"]["c1"]["type"], "forbidden",
680 "create must be forbidden: {args}"
681 );
682 }
683
684 #[tokio::test]
690 async fn task_list_set_destroy_with_tasks_returns_task_list_has_task() {
691 let mut backend = MockBackend::new_with_account("acc1");
692 backend.add_task_list_with_task("acc1", "list1");
693 let backend = Arc::new(backend);
694
695 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
696 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
697
698 let req = single_call(
699 "TaskList/set",
700 json!({
701 "accountId": "acc1",
702 "destroy": ["list1"],
703 "onDestroyRemoveTasks": false
704 }),
705 "c0",
706 );
707 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
708 let Invocation {
709 arguments: args, ..
710 } = &resp.method_responses[0];
711 assert!(
712 args.get("type").is_none(),
713 "must not be a top-level error: {args}"
714 );
715 assert_eq!(
716 args["notDestroyed"]["list1"]["type"], "taskListHasTask",
717 "must return taskListHasTask when list has tasks: {args}"
718 );
719 }
720
721 #[tokio::test]
726 async fn isdraft_revert_via_dispatcher() {
727 let mut backend = MockBackend::new_with_account("acc1");
728 backend.seed_task("acc1", "t1", false);
729 let backend = Arc::new(backend);
730
731 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
732 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
733
734 let req = single_call(
735 "Task/set",
736 json!({
737 "accountId": "acc1",
738 "update": { "t1": { "isDraft": true } }
739 }),
740 "c0",
741 );
742 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
743 let Invocation {
744 arguments: args, ..
745 } = &resp.method_responses[0];
746 assert!(
747 args.get("type").is_none(),
748 "must not be a top-level error: {args}"
749 );
750 assert_eq!(
751 args["notUpdated"]["t1"]["type"], "invalidProperties",
752 "isDraft revert must be invalidProperties: {args}"
753 );
754 assert_eq!(
755 args["notUpdated"]["t1"]["properties"][0], "isDraft",
756 "isDraft must be listed in properties: {args}"
757 );
758 }
759
760 #[tokio::test]
763 async fn isdraft_draft_to_publish_allowed() {
764 let mut backend = MockBackend::new_with_account("acc1");
765 backend.seed_task("acc1", "t1", true);
766 let backend = Arc::new(backend);
767
768 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
769 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
770
771 let req = single_call(
772 "Task/set",
773 json!({
774 "accountId": "acc1",
775 "update": { "t1": { "isDraft": false } }
776 }),
777 "c0",
778 );
779 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
780 let Invocation {
781 arguments: args, ..
782 } = &resp.method_responses[0];
783 if let Some(not_updated) = args["notUpdated"].as_object() {
785 if let Some(err) = not_updated.get("t1") {
786 assert_ne!(
787 err["type"].as_str(),
788 Some("invalidProperties"),
789 "isDraft:false must not produce invalidProperties: {args}"
790 );
791 }
792 }
793 }
794
795 #[tokio::test]
798 async fn utcstart_not_in_default_properties() {
799 let backend = Arc::new(MockBackend::new_with_account("acc1"));
800 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
801 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
802
803 let req = single_call(
804 "Task/get",
805 json!({ "accountId": "acc1", "ids": null, "properties": ["id"] }),
806 "c0",
807 );
808 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
809 let Invocation {
810 arguments: args, ..
811 } = &resp.method_responses[0];
812 assert!(args.get("type").is_none(), "must not be error: {args}");
813 for item in args["list"].as_array().into_iter().flatten() {
814 assert!(
815 item.get("utcStart").is_none(),
816 "utcStart must not appear when not requested: {item}"
817 );
818 }
819 }
820
821 #[tokio::test]
825 async fn utcstart_returned_when_requested() {
826 let backend = Arc::new(MockBackend::new_with_account("acc1"));
827 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
828 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
829
830 let req = single_call(
831 "Task/get",
832 json!({
833 "accountId": "acc1",
834 "ids": null,
835 "properties": ["id", "utcStart"]
836 }),
837 "c0",
838 );
839 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
840 let Invocation {
841 arguments: args, ..
842 } = &resp.method_responses[0];
843 assert!(
844 args.get("type").is_none(),
845 "Task/get with utcStart must not error: {args}"
846 );
847 }
848
849 #[tokio::test]
855 async fn compute_utc_times_receives_validated_account_id() {
856 use std::sync::Mutex;
857
858 use jmap_server::{
859 BackendChangesError, BackendSetError, ChangesResult, GetObject, JmapBackend,
860 JmapObject, QueryChangesResult, QueryObject, QueryResult, SetObject,
861 };
862 use jmap_tasks_types::Task;
863 use jmap_types::{Id, UTCDate};
864
865 use crate::backend::TasksBackend;
866 use crate::test_support::MockError;
867
868 struct AccountIdRecorder {
873 observed: Mutex<Vec<Id>>,
874 }
875
876 impl JmapBackend for AccountIdRecorder {
877 type Error = MockError;
878 type CallerCtx = ();
879
880 async fn account_exists(
881 &self,
882 _caller: &(),
883 _account_id: &Id,
884 ) -> Result<bool, Self::Error> {
885 Ok(true)
886 }
887
888 async fn get_objects<O: GetObject + Send + Sync>(
889 &self,
890 _caller: &(),
891 _account_id: &Id,
892 _ids: Option<&[Id]>,
893 _properties: Option<&[String]>,
894 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
895 let item = json!({ "id": "t1" });
899 match serde_json::from_value::<O>(item) {
900 Ok(obj) => Ok((vec![obj], vec![])),
901 Err(_) => Ok((vec![], vec![])),
902 }
903 }
904
905 async fn get_state<O: JmapObject + Send + Sync>(
906 &self,
907 _caller: &(),
908 _account_id: &Id,
909 ) -> Result<State, Self::Error> {
910 Ok(State::from("s0"))
911 }
912
913 async fn get_changes<O: JmapObject + Send + Sync>(
914 &self,
915 _caller: &(),
916 _account_id: &Id,
917 _since_state: &State,
918 _max_changes: Option<u64>,
919 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
920 Ok(ChangesResult::new(
921 vec![],
922 vec![],
923 vec![],
924 false,
925 State::from("s0"),
926 ))
927 }
928
929 async fn query_objects<O: QueryObject + Send + Sync>(
930 &self,
931 _caller: &(),
932 _account_id: &Id,
933 _filter: Option<&O::Filter>,
934 _sort: Option<&[O::Comparator]>,
935 _limit: Option<u64>,
936 _position: i64,
937 _anchor: Option<&Id>,
938 _anchor_offset: i64,
939 ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
940 Ok(QueryResult::new(
941 vec![],
942 0,
943 Some(0),
944 State::from("s0"),
945 false,
946 ))
947 }
948
949 async fn query_changes<O: QueryObject + Send + Sync>(
950 &self,
951 _caller: &(),
952 _account_id: &Id,
953 since_query_state: &State,
954 _filter: Option<&O::Filter>,
955 _sort: Option<&[O::Comparator]>,
956 _max_changes: Option<u64>,
957 _up_to_id: Option<&Id>,
958 _collapse_threads: bool,
959 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
960 Ok(QueryChangesResult::new(
961 since_query_state.clone(),
962 State::from("s0"),
963 Some(0),
964 vec![],
965 vec![],
966 ))
967 }
968 }
969
970 impl TasksBackend for AccountIdRecorder {
971 async fn create_object<O: SetObject + Send + Sync>(
972 &self,
973 _caller: &(),
974 _account_id: &Id,
975 _create_id: &str,
976 obj: O,
977 ) -> Result<(Id, O), BackendSetError<Self::Error>> {
978 Ok((Id::from("t1"), obj))
979 }
980
981 async fn update_object<O: SetObject + Send + Sync>(
982 &self,
983 _caller: &(),
984 _account_id: &Id,
985 _id: &Id,
986 _patch: O::Patch,
987 ) -> Result<Option<O>, BackendSetError<Self::Error>> {
988 Ok(None)
989 }
990
991 async fn destroy_object<O: SetObject + Send + Sync>(
992 &self,
993 _caller: &(),
994 _account_id: &Id,
995 _id: &Id,
996 ) -> Result<(), BackendSetError<Self::Error>> {
997 Ok(())
998 }
999
1000 fn supports_type<O: JmapObject>(
1001 &self,
1002 _caller: &Self::CallerCtx,
1003 _account_id: &jmap_types::Id,
1004 ) -> bool {
1005 true
1006 }
1007
1008 async fn task_list_has_tasks(
1009 &self,
1010 _caller: &(),
1011 _account_id: &Id,
1012 _task_list_id: &Id,
1013 ) -> Result<bool, MockError> {
1014 Ok(false)
1015 }
1016
1017 async fn compute_utc_times(
1018 &self,
1019 _caller: &(),
1020 account_id: &Id,
1021 _task: &Task,
1022 _tz_hint: Option<&str>,
1023 ) -> (Option<UTCDate>, Option<UTCDate>) {
1024 self.observed.lock().unwrap().push(account_id.clone());
1025 (None, None)
1026 }
1027 }
1028
1029 let backend = Arc::new(AccountIdRecorder {
1030 observed: Mutex::new(Vec::new()),
1031 });
1032 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
1033 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
1034
1035 let req = single_call(
1036 "Task/get",
1037 json!({
1038 "accountId": "acc1",
1039 "ids": null,
1040 "properties": ["id", "utcStart"]
1041 }),
1042 "c0",
1043 );
1044 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
1045 let Invocation {
1046 arguments: args, ..
1047 } = &resp.method_responses[0];
1048 assert!(
1049 args.get("type").is_none(),
1050 "Task/get with utcStart must not error: {args}"
1051 );
1052
1053 let seen = backend.observed.lock().unwrap().clone();
1054 assert_eq!(
1055 seen,
1056 vec![Id::from("acc1")],
1057 "compute_utc_times must receive the request's accountId exactly once \
1058 (one Task synthesized, utcStart requested)"
1059 );
1060 }
1061
1062 #[tokio::test]
1065 async fn per_user_patch_split() {
1066 let backend = Arc::new(MockBackend::new_with_account("acc1"));
1067 let mut dispatcher: Dispatcher<()> = Dispatcher::new();
1068 register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
1069
1070 let before = backend.per_user_calls.load(Ordering::Relaxed);
1071
1072 let req = single_call(
1073 "Task/set",
1074 json!({
1075 "accountId": "acc1",
1076 "update": { "t1": { "color": "#ff0000" } }
1077 }),
1078 "c0",
1079 );
1080 let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
1081 let Invocation {
1082 arguments: args, ..
1083 } = &resp.method_responses[0];
1084 assert!(
1085 args.get("type").is_none(),
1086 "must not be top-level error: {args}"
1087 );
1088
1089 let after = backend.per_user_calls.load(Ordering::Relaxed);
1090 assert_eq!(
1091 after - before,
1092 1,
1093 "per_user update must have been called exactly once for a color-only patch"
1094 );
1095 }
1096}