1#![cfg_attr(docsrs, feature(doc_cfg))]
30#![forbid(unsafe_code)]
31#![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#[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
79pub use jmap_tasks_types::JMAP_TASKS_URI;
81
82pub fn register_tasks_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
123where
124 B: TasksBackend + 'static,
125{
126 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 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 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 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
206pub 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#[cfg(test)]
254#[deny(clippy::await_holding_lock)]
255pub(crate) mod test_support {
256 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 #[non_exhaustive]
280 #[derive(Debug)]
281 pub struct MockError {
282 description: String,
283 }
284
285 impl MockError {
286 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 #[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 #[derive(Clone)]
313 pub struct MockBackend {
314 state: Arc<Mutex<HashMap<String, AccountState>>>,
315 pub per_user_calls: Arc<AtomicU32>,
318 }
319
320 impl MockBackend {
321 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 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 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 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 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 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 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 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 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 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 self.per_user_calls.fetch_add(1, Ordering::Relaxed);
623 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#[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 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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 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 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 #[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}