Skip to main content

jmap_tasks_server/
task.rs

1//! Task/* method handlers (draft-tasks-06 §4).
2//!
3//! The `isDraft` immutability constraint (once false, never true again) is
4//! enforced by [`crate::TasksBackend::update_object`], not by Task/set.
5//!
6//! # Wire-shape contract
7//!
8//! Every `handle_*` function in this module conforms to the canonical JMAP
9//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
10//! Object whose fields match the corresponding RFC 8620 §5 method shape
11//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3, `/copy` → §5.4,
12//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
13//! arguments defined by draft-tasks-06 §4. The returned `Value` is the
14//! corresponding method-response object per the same section refs.
15//!
16//! The returned `HandlerOutput::extra_invocations` carries any invocations
17//! that this handler injected into the request stream (RFC 8620 §6.3).
18//! For the standard `/get`, `/changes`, `/set`, `/query`, and
19//! `/queryChanges` handlers in this module the vector is **always
20//! empty**. `handle_task_copy` is the one exception: it MAY emit
21//! `Task/set` follow-up invocations when `onSuccessDestroyOriginal` is
22//! true (RFC 8620 §5.4).
23//!
24//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
25//! §3.6.2 and §5):
26//!
27//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
28//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
29//!   `maxObjectsInSet`;
30//! - `/set`, `/copy`: `stateMismatch`;
31//! - `/copy`: `fromAccountNotFound`;
32//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
33//! - `/queryChanges`: `tooManyChanges`;
34//! - `/query`, `/queryChanges`: `unsupportedFilter`;
35//! - `/query`: `unsupportedSort`, `anchorNotFound`.
36//!
37//! Per-target failures inside a `/set` or `/copy` call surface in the
38//! `notCreated` / `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`,
39//! not as `Err`.
40
41use std::collections::BTreeMap;
42
43use jmap_tasks_types::{Task, TaskComparator};
44use jmap_types::{Id, Invocation, JmapError, PatchObject};
45use serde::Deserialize;
46use serde_json::{Value, json};
47
48use crate::TasksBackend;
49use crate::helpers::{
50    SetAccumulators, check_metadata_entry, enforce_max_objects_in_set, extract_account_id,
51    finalize_set_response, reject_unsupported_sort, resolve_refs,
52};
53use jmap_server::{
54    HandlerOutput, backend_set_error_value, bool_arg, reject_read_only_patch, reject_server_set,
55    server_fail_from_backend, server_fail_value_from_backend,
56};
57
58// ---------------------------------------------------------------------------
59// Task/get
60// ---------------------------------------------------------------------------
61
62/// Handle a `Task/get` method call (draft-tasks-06 §4.5).
63///
64/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
65/// `ids`, optional `properties`); the returned `Value` is the §5.1
66/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
67///
68/// If `"utcStart"` or `"utcDue"` appear in the requested `properties` (or if
69/// `properties` is `null` — meaning all fields), [`TasksBackend::compute_utc_times`]
70/// is called for each returned task and the computed values are merged in
71/// (draft-tasks-06 §4, utcStart/utcDue paragraphs). The local-time inputs
72/// (`start`, `due`, `timeZone`, `timeZones`) are fetched for that even when
73/// `properties` leaves them out, and dropped again before the response, so
74/// only the requested properties are returned (RFC 8620 §5.1).
75///
76/// `using` is the request's capability list (pass
77/// [`jmap_server::CallContext::using`]). When the backend lists Task for
78/// draft-ietf-jmap-metadata-04 ([`JmapBackend::metadata_info`](jmap_server::JmapBackend::metadata_info)),
79/// `metadata` is returned as an object, by default only with
80/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
81/// `properties` may hold `metadata/<namespace>` subselectors (-04 §2,
82/// §3.1); see [`jmap_server::handle_get_with_metadata`].
83///
84/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
85pub async fn handle_task_get<B: TasksBackend>(
86    backend: &B,
87    caller: &B::CallerCtx,
88    mut args: Value,
89    using: &[String],
90) -> Result<HandlerOutput, JmapError> {
91    // Determine whether utcStart / utcDue are requested. compute_utc_times
92    // needs the local-time inputs, which handle_get would otherwise project
93    // away; fetch the missing ones and strip them again below.
94    let mut strip: Vec<&str> = Vec::new();
95    let (want_start, want_due) = match args.get_mut("properties") {
96        None | Some(Value::Null) => (true, true), // all properties requested
97        Some(Value::Array(props)) => {
98            let has = |name: &str| props.iter().any(|p| p == name);
99            let wanted = (has("utcStart"), has("utcDue"));
100            if wanted.0 || wanted.1 {
101                strip = ["start", "due", "timeZone", "timeZones"]
102                    .into_iter()
103                    .filter(|name| !has(name))
104                    .collect();
105                props.extend(strip.iter().map(|name| json!(name)));
106            }
107            wanted
108        }
109        _ => (false, false),
110    };
111
112    // Peek accountId to thread through compute_utc_times (bd:JMAP-ops7.25).
113    // handle_get re-extracts and re-validates idempotently below; a malformed
114    // or missing accountId surfaces here as invalidArguments before the
115    // delegate call.
116    let account_id: Id = args
117        .get("accountId")
118        .and_then(|v| v.as_str())
119        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))
120        .and_then(|s| {
121            Id::new_validated(s).map_err(|e| {
122                JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}"))
123            })
124        })?;
125
126    // Delegate to the generic get handler.
127    let HandlerOutput {
128        primary: mut response,
129        extra_invocations: tail,
130        ..
131    } = jmap_server::handle_get_with_metadata::<Task, B>(backend, caller, args, using).await?;
132
133    // If utcStart or utcDue were requested, augment each returned task.
134    if (want_start || want_due)
135        && let Some(Value::Array(list)) = response.get_mut("list")
136    {
137        for item in list.iter_mut() {
138            if let Ok(task) = Task::deserialize(&*item) {
139                let (utc_start, utc_due) = backend
140                    .compute_utc_times(caller, &account_id, &task, None)
141                    .await;
142                if let Some(s) = utc_start.filter(|_| want_start) {
143                    item["utcStart"] = Value::String(s.into_inner());
144                }
145                if let Some(d) = utc_due.filter(|_| want_due) {
146                    item["utcDue"] = Value::String(d.into_inner());
147                }
148            }
149            if let Some(obj) = item.as_object_mut() {
150                for name in &strip {
151                    obj.remove(*name);
152                }
153            }
154        }
155    }
156
157    Ok(HandlerOutput::new(response).with_extra(tail))
158}
159
160// ---------------------------------------------------------------------------
161// Task/changes
162// ---------------------------------------------------------------------------
163
164/// Handle a `Task/changes` method call (draft-tasks-06 §4.6).
165///
166/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
167/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
168/// `/changes` response shape (`accountId`, `oldState`, `newState`,
169/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
170///
171/// `using` is the request's capability list (pass
172/// [`jmap_server::CallContext::using`]); with
173/// `urn:ietf:params:jmap:metadata` the request may set
174/// draft-ietf-jmap-metadata-04 §3.3 `ignoreMetadataOnlyChanges`, and
175/// without it metadata-only changes are left out (-04 §3).
176///
177/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
178pub async fn handle_task_changes<B: TasksBackend>(
179    backend: &B,
180    caller: &B::CallerCtx,
181    args: Value,
182    using: &[String],
183) -> Result<HandlerOutput, JmapError> {
184    jmap_server::handle_changes::<Task, B>(backend, caller, args, using).await
185}
186
187// ---------------------------------------------------------------------------
188// Task/set
189// ---------------------------------------------------------------------------
190
191/// The Task properties that hold the id of another record, which a client
192/// may set to a `#creationId` reference (RFC 8620 §5.3).
193const TASK_ID_PROPERTIES: &[&str] = &["taskListId"];
194
195/// Handle a `Task/set` method call (draft-tasks-06 §4.7).
196///
197/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
198/// `ifInState`, optional `create` / `update` / `destroy` maps); the
199/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
200/// `oldState`, `newState`, plus the per-operation result maps).
201///
202/// **isDraft immutability**: this handler does not check `isDraft`. The
203/// backend's [`crate::TasksBackend::update_object`] MUST reject a patch that
204/// sets `isDraft: true` on a Task whose stored value is not `true` with
205/// `invalidProperties`, atomically with the write; the rejection is reported
206/// in `notUpdated`.
207///
208/// **`taskListId` references**: a `#creationId` value on create or update
209/// names a TaskList created earlier in the request and resolves against
210/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
211/// §5.3). An unknown reference is `invalidProperties` naming `taskListId`.
212///
213/// `using` is the request's capability list (pass
214/// [`jmap_server::CallContext::using`]): a write to `metadata` or
215/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
216/// `invalidProperties` (draft-ietf-jmap-metadata-04 §3), as is `null` for
217/// either in a create (-04 §3.2). The backend validates the rest.
218///
219/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
220pub async fn handle_task_set<B: TasksBackend>(
221    backend: &B,
222    caller: &B::CallerCtx,
223    created_ids: &BTreeMap<Id, Id>,
224    args: Value,
225    using: &[String],
226) -> Result<HandlerOutput, JmapError> {
227    let (account_id, mut args) = extract_account_id(args)?;
228
229    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
230    // error). Without this, a /set against an unknown accountId would silently
231    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
232    if !backend
233        .account_exists(caller, &account_id)
234        .await
235        .map_err(|e| server_fail_from_backend(&e))?
236    {
237        return Err(JmapError::account_not_found());
238    }
239
240    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
241    // unbounded /set batches before touching the storage layer.
242    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
243
244    let old_state = backend
245        .get_state::<Task>(caller, &account_id)
246        .await
247        .map_err(|e| server_fail_from_backend(&e))?;
248
249    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
250        && if_in_state != old_state.as_ref()
251    {
252        return Err(JmapError::state_mismatch());
253    }
254
255    let mut created = serde_json::Map::new();
256    let mut not_created = serde_json::Map::new();
257    let mut updated = serde_json::Map::new();
258    let mut not_updated = serde_json::Map::new();
259    let mut destroyed_list: Vec<Value> = Vec::new();
260    let mut not_destroyed = serde_json::Map::new();
261    let mut mutated = false;
262
263    // -----------------------------------------------------------------------
264    // create
265    // -----------------------------------------------------------------------
266    if let Some(Value::Object(create_map)) = args.remove("create") {
267        for (create_id, mut obj_val) in create_map {
268            if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Task>) {
269                not_created.insert(create_id, serde_json::Value::from(&err));
270                continue;
271            }
272            if let Some(Err(err)) = obj_val
273                .as_object()
274                .map(|o| check_metadata_entry(o, true, using))
275            {
276                not_created.insert(create_id, serde_json::Value::from(&*err));
277                continue;
278            }
279            if let Err(err) = resolve_refs(&mut obj_val, TASK_ID_PROPERTIES, created_ids) {
280                not_created.insert(create_id, serde_json::Value::from(&*err));
281                continue;
282            }
283            // `Task.id` is optional, so the create parses without one and
284            // `build` sets the id the backend mints.
285            let mut task: Task = match serde_path_to_error::deserialize(obj_val) {
286                Ok(t) => t,
287                Err(e) => {
288                    // RFC 8620 §5.3: invalidProperties SHOULD list the
289                    // invalid properties; the first path segment is the
290                    // top-level property whose value failed to parse.
291                    let mut err =
292                        json!({ "type": "invalidProperties", "description": e.to_string() });
293                    if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next()
294                    {
295                        err["properties"] = json!([key]);
296                    }
297                    not_created.insert(create_id, err);
298                    continue;
299                }
300            };
301
302            let build = move |id: &Id| {
303                task.id = Some(id.clone());
304                task
305            };
306            match backend
307                .create_object::<Task, _>(caller, &account_id, &create_id, build)
308                .await
309            {
310                Ok((_new_id, created_obj)) => {
311                    mutated = true;
312                    created.insert(create_id, jmap_server::serialize_value(&created_obj)?);
313                }
314                Err(e) => {
315                    not_created.insert(create_id, backend_set_error_value(e));
316                }
317            }
318        }
319    }
320
321    // -----------------------------------------------------------------------
322    // update
323    // -----------------------------------------------------------------------
324    if let Some(Value::Object(update_map)) = args.remove("update") {
325        for (id_str, mut patch_val) in update_map {
326            // isDraft immutability (draft-tasks-06 §4 isDraft paragraph) is
327            // enforced by the backend in update_object, atomically with the
328            // write (TasksBackend::update_object, bd:JMAP-h47t.29).
329            let id = match jmap_server::parse_wire_id(&id_str, "id") {
330                Ok(id) => id,
331                Err(err) => {
332                    not_updated.insert(id_str, serde_json::Value::from(&*err));
333                    continue;
334                }
335            };
336
337            // Route to the per-user update path when every patch key targets
338            // a per-user Task property (draft-tasks-06 §4.5.1).
339            //
340            // PatchObject keys are RFC 6901 JSON Pointers (RFC 8620 §5.3), so a
341            // per-user keyword toggle is sent as `keywords/done`, not bare
342            // `keywords`. Classify on the FIRST pointer segment (the substring
343            // before the first '/'), not the whole key.
344            //
345            // The null short-circuit that was here previously (`v.is_null() ||
346            // ...`) misclassified a delete-shared-property patch like
347            // `{"title": null}` as per-user-only, and an empty patch object as
348            // per-user-only via vacuous-truth on `iter().all`. Both go to
349            // `update_object` now: deletions are shared mutations, and an
350            // empty patch is a no-op that should not bump per-user state.
351            //
352            // Per-user property names (`keywords`, `color`, `freeBusyStatus`,
353            // `useDefaultAlerts`, `alerts`) contain no `/` or `~`, so a plain
354            // `split('/').next()` is correct without RFC 6901 unescaping.
355            let is_per_user_only = patch_val.as_object().is_some_and(|m| {
356                !m.is_empty()
357                    && m.keys().all(|k| {
358                        let head = k.split('/').next().unwrap_or(k);
359                        jmap_tasks_types::is_per_user_task_property(head)
360                    })
361            });
362
363            if let Err(err) = resolve_refs(&mut patch_val, TASK_ID_PROPERTIES, created_ids) {
364                not_updated.insert(id_str, serde_json::Value::from(&*err));
365                continue;
366            }
367
368            // Convert wire-format Value into a typed PatchObject. RFC 8620
369            // §5.3 mandates a PatchObject is a JSON Object; non-object
370            // values produce an `invalidPatch` SetError. Conversion runs
371            // after the isDraft and per-user-routing introspection above so
372            // those checks operate on the raw wire shape.
373            let patch = match serde_json::from_value::<PatchObject>(patch_val) {
374                Ok(p) => p,
375                Err(e) => {
376                    not_updated.insert(
377                        id_str,
378                        json!({ "type": "invalidPatch", "description": e.to_string() }),
379                    );
380                    continue;
381                }
382            };
383            if let Some(err) = reject_read_only_patch::<Task>(patch.as_map(), None) {
384                not_updated.insert(id_str, serde_json::Value::from(&err));
385                continue;
386            }
387            if let Err(err) = check_metadata_entry(patch.as_map(), false, using) {
388                not_updated.insert(id_str, serde_json::Value::from(&*err));
389                continue;
390            }
391
392            let update_result = if is_per_user_only {
393                backend
394                    .update_task_per_user(caller, &account_id, &id, patch)
395                    .await
396            } else {
397                backend
398                    .update_object::<Task>(caller, &account_id, &id, patch)
399                    .await
400            };
401
402            match update_result {
403                Ok(Some(obj)) => {
404                    mutated = true;
405                    updated.insert(id_str, jmap_server::serialize_value(&obj)?);
406                }
407                Ok(None) => {
408                    mutated = true;
409                    updated.insert(id_str, Value::Null);
410                }
411                Err(e) => {
412                    not_updated.insert(id_str, backend_set_error_value(e));
413                }
414            }
415        }
416    }
417
418    // -----------------------------------------------------------------------
419    // destroy
420    // -----------------------------------------------------------------------
421    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
422        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
423        // Two-pass validation is intentional: this up-front loop fails the whole
424        // request loudly; the `None => continue` arm in the inner match below
425        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
426        // delete this pre-check on the reasoning that the inner match handles
427        // non-string elements — silent-skip is the wrong behaviour per the
428        // workspace "silent-drop is a data-integrity bug class" rule
429        // (JMAP-wlip.1).
430        let id_strs: Vec<&str> = destroy_arr
431            .iter()
432            .map(|v| {
433                v.as_str().ok_or_else(|| {
434                    JmapError::invalid_arguments(format!(
435                        "destroy: every element must be a string Id; got {}",
436                        jmap_server::json_type_name(v)
437                    ))
438                })
439            })
440            .collect::<Result<_, _>>()?;
441        for id_str in id_strs {
442            let id_str = id_str.to_owned();
443            let id = match jmap_server::parse_wire_id(&id_str, "id") {
444                Ok(id) => id,
445                Err(err) => {
446                    not_destroyed.insert(id_str, serde_json::Value::from(&*err));
447                    continue;
448                }
449            };
450
451            match backend
452                .destroy_object::<Task>(caller, &account_id, &id)
453                .await
454            {
455                Ok(()) => {
456                    mutated = true;
457                    destroyed_list.push(Value::String(id_str));
458                }
459                Err(e) => {
460                    not_destroyed.insert(id_str, backend_set_error_value(e));
461                }
462            }
463        }
464    }
465
466    finalize_set_response::<B, Task>(
467        backend,
468        caller,
469        &account_id,
470        old_state,
471        mutated,
472        SetAccumulators {
473            created,
474            updated,
475            destroyed: destroyed_list,
476            not_created,
477            not_updated,
478            not_destroyed,
479        },
480    )
481    .await
482}
483
484// ---------------------------------------------------------------------------
485// Task/copy
486// ---------------------------------------------------------------------------
487
488/// Handle a `Task/copy` method call (draft-tasks-06 §4.8).
489///
490/// `args` is the RFC 8620 §5.4 `/copy` request shape (`fromAccountId`,
491/// optional `ifFromInState`, `accountId`, optional `ifInState`, `create`
492/// map, optional `onSuccessDestroyOriginal`, optional
493/// `destroyFromIfInState`); the returned `Value` is the §5.4 `/copy`
494/// response shape (`fromAccountId`, `accountId`, optional `oldState`,
495/// `newState`, optional `created`, optional `notCreated`).
496///
497/// `call_id` is the request's method-call id, used to construct any
498/// follow-up `Task/set` invocations injected when
499/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4 + §6.3).
500///
501/// Copies tasks from `fromAccountId` into the current account. The `create`
502/// map keys are client-side creation ids; the backend assigns new server-side
503/// ids.
504///
505/// `using` is the request's capability list (pass
506/// [`jmap_server::CallContext::using`]). draft-ietf-jmap-metadata-04 §3.4:
507/// the copy keeps the source's `metadata`, and its `privateMetadata` only
508/// with `urn:ietf:params:jmap:metadata` in `using` and when the
509/// destination supports it; neither is copied when the destination does
510/// not list Task ([`JmapBackend::metadata_info`](jmap_server::JmapBackend::metadata_info)).
511/// The create object "MAY include metadata and privateMetadata to override
512/// the copied values, with the same rules as a create in Foo/set": the
513/// handler rejects them without the capability and rejects `null`, and
514/// [`TasksBackend::copy_object`] validates the rest against the create
515/// object only: "Copied values are not revalidated against the
516/// destination account".
517///
518/// Returns `(response_args, extra_invocations)`. The extra invocation list
519/// is populated with a follow-up `Task/set` invocation when
520/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4); otherwise it is
521/// empty.
522pub async fn handle_task_copy<B: TasksBackend>(
523    backend: &B,
524    caller: &B::CallerCtx,
525    args: Value,
526    call_id: &str,
527    using: &[String],
528) -> Result<HandlerOutput, JmapError> {
529    let (to_account_id, mut args) = extract_account_id(args)?;
530
531    if !backend
532        .account_exists(caller, &to_account_id)
533        .await
534        .map_err(|e| server_fail_from_backend(&e))?
535    {
536        return Err(JmapError::account_not_found());
537    }
538
539    let from_account_id_str = args
540        .remove("fromAccountId")
541        .and_then(|v| v.as_str().map(|s| s.to_owned()))
542        .ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
543    let from_account_id = Id::new_validated(from_account_id_str)
544        .map_err(|e| JmapError::invalid_arguments(format!("fromAccountId: {e}")))?;
545
546    // RFC 8620 §5.4: fromAccountId MUST differ from accountId. The canonical
547    // sibling jmap-mail-server enforces this in handle_email_copy; without it
548    // a same-account "copy" silently produces a duplicate within the source
549    // account, contradicting the meaning of /copy.
550    if from_account_id == to_account_id {
551        return Err(JmapError::invalid_arguments(
552            "fromAccountId must be different from accountId",
553        ));
554    }
555
556    // RFC 8620 §5.4: validate fromAccountId resolves to a real account;
557    // emit the spec-canonical `fromAccountNotFound` (not the generic
558    // `accountNotFound`) when it does not.
559    if !backend
560        .account_exists(caller, &from_account_id)
561        .await
562        .map_err(|e| server_fail_from_backend(&e))?
563    {
564        return Err(JmapError::from_account_not_found());
565    }
566
567    // RFC 8620 §5.4 `ifFromInState`: if supplied, the source-account Task
568    // state MUST match; otherwise abort with stateMismatch. Probed before
569    // the destination state so a stale source guard fails fast.
570    if let Some(if_from_in_state) = args.get("ifFromInState").and_then(|v| v.as_str()) {
571        let from_state = backend
572            .get_state::<Task>(caller, &from_account_id)
573            .await
574            .map_err(|e| server_fail_from_backend(&e))?;
575        if if_from_in_state != from_state.as_ref() {
576            return Err(JmapError::state_mismatch());
577        }
578    }
579
580    let old_state = backend
581        .get_state::<Task>(caller, &to_account_id)
582        .await
583        .map_err(|e| server_fail_from_backend(&e))?;
584
585    // RFC 8620 §5.4 `ifInState`: if supplied, the destination-account Task
586    // state MUST match; otherwise abort with stateMismatch.
587    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
588        && if_in_state != old_state.as_ref()
589    {
590        return Err(JmapError::state_mismatch());
591    }
592
593    // RFC 8620 §5.4 `onSuccessDestroyOriginal` / `destroyFromIfInState`:
594    // parsed here so the request payload is consumed in handler-local order
595    // and so a clearly-shaped per-feature value is available below.
596    let on_success_destroy_original: bool = bool_arg(&args, "onSuccessDestroyOriginal", false);
597    let destroy_from_if_in_state: Option<String> = args
598        .get("destroyFromIfInState")
599        .and_then(|v| v.as_str())
600        .map(|s| s.to_owned());
601
602    let mut created = serde_json::Map::new();
603    let mut not_created = serde_json::Map::new();
604    let mut mutated = false;
605    // (create_id, source_id) pairs for entries that succeeded — fed to the
606    // implicit Task/set destroy below when onSuccessDestroyOriginal is true.
607    let mut copied_source_ids: Vec<(String, Id)> = Vec::new();
608
609    if let Some(Value::Object(create_map)) = args.remove("create") {
610        for (create_id, client_val) in create_map {
611            // RFC 8620 §5.4: the Foo object MUST contain an `id` property,
612            // which is the id (in the fromAccount) of the record to be copied.
613            // The earlier handler silently invented a "placeholder" id when
614            // the client omitted one, masking the missing-id case the spec
615            // treats as a hard requirement.
616            let Some(source_id_str) = client_val.get("id").and_then(|v| v.as_str()) else {
617                not_created.insert(
618                    create_id,
619                    json!({"type": "invalidProperties", "properties": ["id"]}),
620                );
621                continue;
622            };
623            let source_id: Id = match jmap_server::parse_wire_id(source_id_str, "id") {
624                Ok(id) => id,
625                Err(err) => {
626                    not_created.insert(create_id, serde_json::Value::from(&*err));
627                    continue;
628                }
629            };
630
631            // Fetch the source Task from `fromAccountId`. RFC 8620 §5.4 frames
632            // /copy as a read-from-source-then-create-in-destination operation;
633            // unknown source ids surface as `notFound` per-entry SetErrors.
634            let mut source_tasks: Vec<Task> = match backend
635                .get_objects::<Task>(
636                    caller,
637                    &from_account_id,
638                    Some(std::slice::from_ref(&source_id)),
639                    None,
640                )
641                .await
642            {
643                Ok((objs, not_found)) => {
644                    if !not_found.is_empty() || objs.is_empty() {
645                        not_created.insert(create_id, json!({"type": "notFound"}));
646                        continue;
647                    }
648                    objs
649                }
650                Err(e) => {
651                    not_created.insert(create_id, server_fail_value_from_backend(&e));
652                    continue;
653                }
654            };
655
656            // RFC 8620 §5.4: "any other properties included [in the create
657            // entry] are used instead of the current value for that property
658            // on the original." Serialize the source, overlay client-supplied
659            // properties, strip the source id so the backend assigns a fresh
660            // server id. Pattern mirrors jmap-calendars-server event.rs:610-642.
661            // draft-ietf-jmap-metadata-04 §3.4: metadata overrides follow the
662            // Foo/set create rules (§3, §3.2).
663            if let Some(Err(err)) = client_val
664                .as_object()
665                .map(|o| check_metadata_entry(o, true, using))
666            {
667                not_created.insert(create_id, Value::from(&*err));
668                continue;
669            }
670            // -04 §3.4: "When the request does not use this capability, only
671            // metadata is copied", "privateMetadata is not copied when the
672            // destination does not support it, and neither property is
673            // copied when the data type is not listed in the destination
674            // account". The overrides are merged in below.
675            let info = backend.metadata_info::<Task>(caller, &to_account_id);
676            if !jmap_server::uses_metadata(using)
677                || !info.as_ref().is_some_and(|i| i.supports_private)
678            {
679                source_tasks[0].private_metadata = None;
680            }
681            if info.is_none() {
682                source_tasks[0].metadata = None;
683            }
684            let Ok(Value::Object(mut merged)) = serde_json::to_value(&source_tasks[0]) else {
685                not_created.insert(
686                    create_id,
687                    json!({
688                        "type": "serverFail",
689                        "description": "failed to serialize source Task",
690                    }),
691                );
692                continue;
693            };
694            if let Value::Object(client_props) = &client_val {
695                for (k, v) in client_props {
696                    if k != "id" {
697                        merged.insert(k.clone(), v.clone());
698                    }
699                }
700            }
701            merged.remove("id");
702
703            let task: Task = match serde_path_to_error::deserialize(Value::Object(merged)) {
704                Ok(t) => t,
705                Err(e) => {
706                    // RFC 8620 §5.3: invalidProperties SHOULD list the
707                    // invalid properties; the first path segment is the
708                    // top-level property whose value failed to parse.
709                    let mut err =
710                        json!({ "type": "invalidProperties", "description": e.to_string() });
711                    if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next()
712                    {
713                        err["properties"] = json!([key]);
714                    }
715                    not_created.insert(create_id, err);
716                    continue;
717                }
718            };
719
720            // -04 §3.4: the backend validates only the metadata supplied in
721            // the create object; the copied values are not revalidated.
722            match backend
723                .copy_object(caller, &from_account_id, &to_account_id, task, &client_val)
724                .await
725            {
726                Ok((_new_id, created_task)) => {
727                    mutated = true;
728                    created.insert(
729                        create_id.clone(),
730                        jmap_server::serialize_value(&created_task)?,
731                    );
732                    copied_source_ids.push((create_id, source_id));
733                }
734                Err(e) => {
735                    not_created.insert(create_id, backend_set_error_value(e));
736                }
737            }
738        }
739    }
740
741    let new_state = if mutated {
742        backend
743            .get_state::<Task>(caller, &to_account_id)
744            .await
745            .map_err(|e| server_fail_from_backend(&e))?
746    } else {
747        old_state.clone()
748    };
749
750    let resp = json!({
751        "fromAccountId": from_account_id.as_ref(),
752        "accountId": to_account_id.as_ref(),
753        "oldState": old_state.as_ref(),
754        "newState": new_state.as_ref(),
755        "created":    if created.is_empty()     { Value::Null } else { Value::Object(created) },
756        "notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
757    });
758
759    // RFC 8620 §5.4 `onSuccessDestroyOriginal`: after emitting the Task/copy
760    // response, the server MUST make a single implicit Task/set call against
761    // fromAccountId destroying each successfully copied source record.
762    // `destroyFromIfInState`, if supplied, is passed through as the ifInState
763    // argument on that implicit call. The dispatcher returns the extra
764    // Invocation vec to the caller (RFC 8620 §6.3 chained responses).
765    // Pattern mirrors jmap-mail-server email.rs:2432-2575.
766    let mut extra: Vec<Invocation> = Vec::new();
767    if on_success_destroy_original && !copied_source_ids.is_empty() {
768        let from_old_state = backend
769            .get_state::<Task>(caller, &from_account_id)
770            .await
771            .map_err(|e| server_fail_from_backend(&e))?;
772
773        // Honour destroyFromIfInState on the implicit Task/set call. A
774        // mismatch yields a stateMismatch top-level error on the synthesized
775        // response (§5.4 inheriting §5.3 semantics on the chained call).
776        let mut destroy_state_mismatch = false;
777        if let Some(if_state) = destroy_from_if_in_state.as_deref()
778            && if_state != from_old_state.as_ref()
779        {
780            destroy_state_mismatch = true;
781        }
782
783        let mut destroyed_arr: Vec<Value> = Vec::new();
784        let mut not_destroyed = serde_json::Map::new();
785
786        if !destroy_state_mismatch {
787            for (_, source_id) in &copied_source_ids {
788                match backend
789                    .destroy_object::<Task>(caller, &from_account_id, source_id)
790                    .await
791                {
792                    Ok(()) => {
793                        destroyed_arr.push(Value::String(source_id.as_ref().to_owned()));
794                    }
795                    Err(e) => {
796                        not_destroyed
797                            .insert(source_id.as_ref().to_owned(), backend_set_error_value(e));
798                    }
799                }
800            }
801        }
802
803        let from_new_state = backend
804            .get_state::<Task>(caller, &from_account_id)
805            .await
806            .map_err(|e| server_fail_from_backend(&e))?;
807
808        let set_resp = if destroy_state_mismatch {
809            json!({
810                "type": "stateMismatch",
811            })
812        } else {
813            json!({
814                "accountId": from_account_id.as_ref(),
815                "oldState": from_old_state.as_ref(),
816                "newState": from_new_state.as_ref(),
817                "created": Value::Null,
818                "updated": Value::Null,
819                "destroyed": if destroyed_arr.is_empty() { Value::Null } else { Value::Array(destroyed_arr) },
820                "notCreated": Value::Null,
821                "notUpdated": Value::Null,
822                "notDestroyed": if not_destroyed.is_empty() { Value::Null } else { Value::Object(not_destroyed) },
823            })
824        };
825
826        let method_name = if destroy_state_mismatch {
827            "error".to_owned()
828        } else {
829            "Task/set".to_owned()
830        };
831        extra.push(Invocation::new(method_name, set_resp, call_id.to_owned()));
832    }
833
834    Ok(HandlerOutput::new(resp).with_extra(extra))
835}
836
837// ---------------------------------------------------------------------------
838// Task/query
839// ---------------------------------------------------------------------------
840
841/// Handle a `Task/query` method call (draft-tasks-06 §4.13).
842///
843/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
844/// optional `filter`, optional `sort`, optional `position`, optional
845/// `anchor`, optional `anchorOffset`, optional `limit`, optional
846/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
847/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
848/// `position`, `ids`, optional `total`).
849///
850/// `using` is the request's capability list (pass
851/// [`jmap_server::CallContext::using`]); without
852/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-04 §3.6
853/// filter condition is `unsupportedFilter` (-04 §3).
854///
855/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
856pub async fn handle_task_query<B: TasksBackend>(
857    backend: &B,
858    caller: &B::CallerCtx,
859    args: Value,
860    using: &[String],
861) -> Result<HandlerOutput, JmapError> {
862    jmap_server::reject_metadata_filter_arg(
863        &args,
864        jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
865        using,
866    )?;
867    reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
868    jmap_server::handle_query::<Task, B>(backend, caller, args).await
869}
870
871// ---------------------------------------------------------------------------
872// Task/queryChanges
873// ---------------------------------------------------------------------------
874
875/// Handle a `Task/queryChanges` method call (draft-tasks-06 §4.14).
876///
877/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
878/// optional `filter`, optional `sort`, `sinceQueryState`, optional
879/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
880/// returned `Value` is the §5.6 `/queryChanges` response shape
881/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
882/// `removed`, `added`).
883///
884/// `using` is the request's capability list (pass
885/// [`jmap_server::CallContext::using`]); without
886/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-04 §3.6
887/// filter condition is `unsupportedFilter` (-04 §3).
888///
889/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
890pub async fn handle_task_query_changes<B: TasksBackend>(
891    backend: &B,
892    caller: &B::CallerCtx,
893    args: Value,
894    using: &[String],
895) -> Result<HandlerOutput, JmapError> {
896    jmap_server::reject_metadata_filter_arg(
897        &args,
898        jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
899        using,
900    )?;
901    reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
902    jmap_server::handle_query_changes::<Task, B>(backend, caller, args).await
903}
904
905// ---------------------------------------------------------------------------
906// Tests
907// ---------------------------------------------------------------------------
908
909#[cfg(test)]
910mod tests {
911    use super::*;
912    use serde_json::json;
913
914    use crate::test_support::MockBackend;
915
916    /// Oracle: RFC 8620 §5.5 `unsupportedSort`: "The sort is syntactically
917    /// valid, but includes a property the server does not support sorting
918    /// on". draft-ietf-jmap-tasks-06 §4.13 defers to CalendarEvent/query, whose sort
919    /// properties are start, uid, recurrenceId, created and updated; `title` is not among them.
920    #[tokio::test]
921    async fn query_unlisted_sort_property_returns_unsupported_sort() {
922        let backend = MockBackend::new_with_account("acc1");
923        let args = json!({ "accountId": "acc1", "sort": [{ "property": "title" }] });
924        let err = handle_task_query(&backend, &(), args, &[])
925            .await
926            .expect_err("unlisted sort property must be rejected");
927        assert_eq!(err.error_type.to_string(), "unsupportedSort");
928    }
929
930    /// Oracle: as above; `Task/queryChanges` carries the same `sort`
931    /// (RFC 8620 §5.6).
932    #[tokio::test]
933    async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
934        let backend = MockBackend::new_with_account("acc1");
935        let args = json!({
936            "accountId": "acc1",
937            "sinceQueryState": "0",
938            "sort": [{ "property": "start" }, { "property": "title" }]
939        });
940        let err = handle_task_query_changes(&backend, &(), args, &[])
941            .await
942            .expect_err("unlisted sort property must be rejected");
943        assert_eq!(err.error_type.to_string(), "unsupportedSort");
944    }
945
946    /// Oracle: draft-ietf-jmap-tasks-06 §4.13 defers to CalendarEvent/query, whose sort
947    /// properties are start, uid, recurrenceId, created and updated, so a `start` sort is accepted.
948    #[tokio::test]
949    async fn query_listed_sort_property_is_accepted() {
950        let backend = MockBackend::new_with_account("acc1");
951        let args = json!({ "accountId": "acc1", "sort": [{ "property": "start" }] });
952        handle_task_query(&backend, &(), args, &[])
953            .await
954            .expect("listed sort property must not be rejected");
955    }
956
957    /// Oracle: Task/get with unknown accountId returns accountNotFound.
958    #[tokio::test]
959    async fn get_unknown_account_returns_account_not_found() {
960        let backend = MockBackend::new();
961        let args = json!({ "accountId": "unknown", "ids": null });
962        let result = handle_task_get(&backend, &(), args, &[]).await;
963        let err = result.expect_err("must return error for unknown account");
964        assert_eq!(err.error_type.to_string(), "accountNotFound");
965    }
966
967    /// Oracle: Task/copy missing fromAccountId returns invalidArguments.
968    #[tokio::test]
969    async fn copy_missing_from_account_id_returns_invalid_arguments() {
970        let backend = MockBackend::new_with_account("acc1");
971        let args = json!({
972            "accountId": "acc1",
973            "create": {}
974        });
975        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
976        let err = result.expect_err("must return error when fromAccountId missing");
977        assert_eq!(err.error_type.to_string(), "invalidArguments");
978    }
979
980    /// Oracle: RFC 8620 §5.4 — fromAccountId MUST be different from accountId.
981    /// A same-account request must be rejected with invalidArguments before
982    /// any per-create work. Matches the canonical sibling jmap-mail-server
983    /// at email.rs:2263-2268.
984    #[tokio::test]
985    async fn copy_same_account_returns_invalid_arguments() {
986        let backend = MockBackend::new_with_account("acc1");
987        let args = json!({
988            "accountId": "acc1",
989            "fromAccountId": "acc1",
990            "create": {}
991        });
992        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
993        let err = result.expect_err("must reject same-account Task/copy per RFC 8620 §5.4");
994        assert_eq!(err.error_type.to_string(), "invalidArguments");
995    }
996
997    /// Oracle: RFC 8620 §5.4 — `fromAccountId` that does not resolve to a
998    /// real account returns the spec-canonical `fromAccountNotFound` error,
999    /// not the generic `accountNotFound`.
1000    #[tokio::test]
1001    async fn copy_unknown_from_account_returns_from_account_not_found() {
1002        let backend = MockBackend::new_with_account("acc1");
1003        let args = json!({
1004            "accountId": "acc1",
1005            "fromAccountId": "no-such-account",
1006            "create": {}
1007        });
1008        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1009        let err = result.expect_err("must reject unknown fromAccountId");
1010        assert_eq!(err.error_type.to_string(), "fromAccountNotFound");
1011    }
1012
1013    /// Oracle: RFC 8620 §5.4 — `ifFromInState` mismatch on the source
1014    /// account returns `stateMismatch`.
1015    #[tokio::test]
1016    async fn copy_if_from_in_state_mismatch_returns_state_mismatch() {
1017        let mut backend = MockBackend::new_with_account("acc1");
1018        backend.add_account("acc2");
1019        let args = json!({
1020            "accountId": "acc1",
1021            "fromAccountId": "acc2",
1022            "ifFromInState": "stale-source-state",
1023            "create": {}
1024        });
1025        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1026        let err = result.expect_err("must reject stale ifFromInState");
1027        assert_eq!(err.error_type.to_string(), "stateMismatch");
1028    }
1029
1030    /// Oracle: RFC 8620 §5.4 — `ifInState` mismatch on the destination
1031    /// account returns `stateMismatch`.
1032    #[tokio::test]
1033    async fn copy_if_in_state_mismatch_returns_state_mismatch() {
1034        let mut backend = MockBackend::new_with_account("acc1");
1035        backend.add_account("acc2");
1036        let args = json!({
1037            "accountId": "acc1",
1038            "fromAccountId": "acc2",
1039            "ifInState": "stale-destination-state",
1040            "create": {}
1041        });
1042        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1043        let err = result.expect_err("must reject stale ifInState");
1044        assert_eq!(err.error_type.to_string(), "stateMismatch");
1045    }
1046
1047    /// Oracle: RFC 8620 §5.4 — a create entry without an `id` property must
1048    /// produce a per-entry `invalidProperties` SetError naming `id`. The
1049    /// previous handler silently substituted a "placeholder" id, masking
1050    /// this hard requirement.
1051    #[tokio::test]
1052    async fn copy_create_entry_without_id_returns_invalid_properties() {
1053        let mut backend = MockBackend::new_with_account("acc1");
1054        backend.add_account("acc2");
1055        let args = json!({
1056            "accountId": "acc1",
1057            "fromAccountId": "acc2",
1058            "create": { "c1": {} }
1059        });
1060        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1061            .await
1062            .expect("top-level call must succeed");
1063        let nc = resp["notCreated"].as_object().expect("notCreated present");
1064        let err = nc.get("c1").expect("c1 in notCreated");
1065        assert_eq!(err["type"], "invalidProperties");
1066        assert_eq!(err["properties"][0], "id");
1067    }
1068
1069    /// Oracle: RFC 8620 §5.4 — when the source id does not resolve to a
1070    /// Task in `fromAccountId`, the per-entry result is `notFound`.
1071    #[tokio::test]
1072    async fn copy_unknown_source_id_returns_not_found() {
1073        let mut backend = MockBackend::new_with_account("acc1");
1074        backend.add_account("acc2");
1075        let args = json!({
1076            "accountId": "acc1",
1077            "fromAccountId": "acc2",
1078            "create": { "c1": { "id": "no-such-task" } }
1079        });
1080        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1081            .await
1082            .expect("top-level call must succeed");
1083        let nc = resp["notCreated"].as_object().expect("notCreated present");
1084        assert_eq!(nc["c1"]["type"], "notFound");
1085    }
1086
1087    /// Oracle: RFC 8620 §5.4 — the create entry's `id` selects WHAT to copy;
1088    /// client-supplied properties OTHER than `id` overlay the source values.
1089    /// Verify the handler actually round-trips through the source: seed a
1090    /// Task into `from_account`, request a copy that overrides `title`, and
1091    /// confirm the response carries the override.
1092    #[tokio::test]
1093    async fn copy_fetches_source_and_overlays_client_overrides() {
1094        let mut backend = MockBackend::new_with_account("acc1");
1095        backend.add_account("acc2");
1096        backend.seed_task("acc2", "src1", true); // source task in acc2
1097
1098        let args = json!({
1099            "accountId": "acc1",
1100            "fromAccountId": "acc2",
1101            "create": {
1102                "c1": { "id": "src1", "title": "Overridden title" }
1103            }
1104        });
1105        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1106            .await
1107            .expect("top-level call must succeed");
1108
1109        // Source was fetched and the override applied: the created entry
1110        // carries the new title, not the source value (which had none).
1111        let created = resp["created"].as_object().expect("created present");
1112        let c1 = created.get("c1").expect("c1 in created");
1113        assert_eq!(
1114            c1["title"], "Overridden title",
1115            "client-supplied title must override source value: {resp}"
1116        );
1117    }
1118
1119    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is true, the
1120    /// server emits a single implicit Task/set call against fromAccountId
1121    /// destroying each successfully copied source. The synthesized response
1122    /// appears in the extra Vec<Invocation> with the same callId as the
1123    /// triggering Task/copy. Mirrors canonical jmap-mail-server
1124    /// email.rs:2432-2575.
1125    #[tokio::test]
1126    async fn copy_on_success_destroy_original_emits_implicit_task_set() {
1127        let mut backend = MockBackend::new_with_account("acc1");
1128        backend.add_account("acc2");
1129        backend.seed_task("acc2", "src1", true);
1130
1131        let args = json!({
1132            "accountId": "acc1",
1133            "fromAccountId": "acc2",
1134            "onSuccessDestroyOriginal": true,
1135            "create": {
1136                "c1": { "id": "src1" }
1137            }
1138        });
1139        let HandlerOutput {
1140            extra_invocations: extra,
1141            ..
1142        } = handle_task_copy(&backend, &(), args, "c0", &[])
1143            .await
1144            .expect("top-level call must succeed");
1145
1146        // Exactly one synthesized invocation: ("Task/set", response, "c0").
1147        assert_eq!(extra.len(), 1, "must emit one implicit Task/set: {extra:?}");
1148        let Invocation {
1149            name: method,
1150            arguments: val,
1151            call_id: ci,
1152        } = &extra[0];
1153        assert_eq!(method, "Task/set");
1154        assert_eq!(ci, "c0");
1155        assert_eq!(val["accountId"], "acc2", "implicit set targets fromAccount");
1156        let destroyed = val["destroyed"]
1157            .as_array()
1158            .expect("destroyed must be array");
1159        assert_eq!(destroyed.len(), 1);
1160        assert_eq!(destroyed[0], "src1");
1161        // Both state fields are present on the synthesized response. Their
1162        // bump semantics depend on the underlying backend's get_state — the
1163        // MockBackend here always returns "0" so we only assert presence;
1164        // state-advance semantics are covered by stateful integration tests.
1165        assert!(val.get("oldState").is_some(), "oldState must be present");
1166        assert!(val.get("newState").is_some(), "newState must be present");
1167    }
1168
1169    /// Oracle: RFC 8620 §5.4 — `destroyFromIfInState` mismatch on the implicit
1170    /// Task/set call yields a `stateMismatch` error response in place of the
1171    /// normal Task/set body. The destroy MUST NOT proceed.
1172    #[tokio::test]
1173    async fn copy_destroy_from_if_in_state_mismatch_aborts_destroy() {
1174        let mut backend = MockBackend::new_with_account("acc1");
1175        backend.add_account("acc2");
1176        backend.seed_task("acc2", "src1", true);
1177
1178        let args = json!({
1179            "accountId": "acc1",
1180            "fromAccountId": "acc2",
1181            "onSuccessDestroyOriginal": true,
1182            "destroyFromIfInState": "stale-source-state",
1183            "create": {
1184                "c1": { "id": "src1" }
1185            }
1186        });
1187        let HandlerOutput {
1188            extra_invocations: extra,
1189            ..
1190        } = handle_task_copy(&backend, &(), args, "c0", &[])
1191            .await
1192            .expect("top-level call must succeed");
1193
1194        assert_eq!(extra.len(), 1);
1195        let Invocation { arguments: val, .. } = &extra[0];
1196        assert_eq!(val["type"], "stateMismatch");
1197    }
1198
1199    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is false (or
1200    /// absent), no implicit Task/set call is synthesized.
1201    #[tokio::test]
1202    async fn copy_without_on_success_emits_no_extra_invocations() {
1203        let mut backend = MockBackend::new_with_account("acc1");
1204        backend.add_account("acc2");
1205        backend.seed_task("acc2", "src1", true);
1206
1207        let args = json!({
1208            "accountId": "acc1",
1209            "fromAccountId": "acc2",
1210            "create": {
1211                "c1": { "id": "src1" }
1212            }
1213        });
1214        let HandlerOutput {
1215            extra_invocations: extra,
1216            ..
1217        } = handle_task_copy(&backend, &(), args, "c0", &[])
1218            .await
1219            .expect("top-level call must succeed");
1220        assert!(
1221            extra.is_empty(),
1222            "no extra invocations without onSuccessDestroyOriginal: {extra:?}"
1223        );
1224    }
1225
1226    /// Oracle: Task/set empty destroy returns valid response.
1227    #[tokio::test]
1228    async fn set_empty_destroy_returns_valid_response() {
1229        let backend = MockBackend::new_with_account("acc1");
1230        let args = json!({ "accountId": "acc1", "destroy": [] });
1231        let HandlerOutput { primary: resp, .. } =
1232            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1233                .await
1234                .expect("must not return top-level error");
1235        assert_eq!(resp["accountId"], "acc1");
1236    }
1237
1238    // ── isDraft immutability enforcement (draft-tasks-06 §4 (isDraft paragraph)) ─
1239
1240    /// Oracle: draft-tasks-06 §4 — "Once set to false, the value [isDraft]
1241    /// cannot be updated to true."
1242    /// A patch of {"isDraft": true} on a task that already has isDraft=false
1243    /// MUST be rejected with invalidProperties. The handler does no isDraft
1244    /// check, so this exercises the backend rejection reaching `notUpdated`.
1245    #[tokio::test]
1246    async fn set_is_draft_revert_rejected_when_current_is_false() {
1247        let mut backend = MockBackend::new_with_account("acc1");
1248        // Pre-seed a published (isDraft=false) task.
1249        backend.seed_task("acc1", "t1", false);
1250
1251        let args = json!({
1252            "accountId": "acc1",
1253            "update": {
1254                "t1": { "isDraft": true }
1255            }
1256        });
1257        let HandlerOutput { primary: resp, .. } =
1258            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1259                .await
1260                .expect("must not return a top-level error");
1261
1262        let not_updated = resp["notUpdated"]
1263            .as_object()
1264            .expect("notUpdated must be an object");
1265        assert!(
1266            not_updated.contains_key("t1"),
1267            "t1 must appear in notUpdated: {resp}"
1268        );
1269        assert_eq!(
1270            not_updated["t1"]["type"].as_str(),
1271            Some("invalidProperties"),
1272            "error type must be invalidProperties"
1273        );
1274        assert_eq!(
1275            not_updated["t1"]["properties"][0].as_str(),
1276            Some("isDraft"),
1277            "properties must list isDraft"
1278        );
1279    }
1280
1281    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": true} on a task that
1282    /// is already a draft (isDraft=true) is allowed (no state transition).
1283    #[tokio::test]
1284    async fn set_is_draft_true_on_draft_task_passes_to_backend() {
1285        let mut backend = MockBackend::new_with_account("acc1");
1286        // Pre-seed a draft task (isDraft=true).
1287        backend.seed_task("acc1", "t2", true);
1288
1289        let args = json!({
1290            "accountId": "acc1",
1291            "update": {
1292                "t2": { "isDraft": true }
1293            }
1294        });
1295        let HandlerOutput { primary: resp, .. } =
1296            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1297                .await
1298                .expect("must not return a top-level error");
1299
1300        // The handler passes the patch to the backend (which returns Forbidden
1301        // in the mock). The important thing is it is NOT pre-rejected here —
1302        // it must NOT appear in notUpdated with type=="invalidProperties".
1303        if let Some(not_updated) = resp["notUpdated"].as_object()
1304            && let Some(err) = not_updated.get("t2")
1305        {
1306            assert_ne!(
1307                err["type"].as_str(),
1308                Some("invalidProperties"),
1309                "isDraft:true on an existing draft must not produce invalidProperties"
1310            );
1311        }
1312    }
1313
1314    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": false} is always allowed
1315    /// (moving from draft to published is a one-way door going the right way).
1316    #[tokio::test]
1317    async fn set_is_draft_false_passes_to_backend() {
1318        let mut backend = MockBackend::new_with_account("acc1");
1319        backend.seed_task("acc1", "t3", true);
1320
1321        let args = json!({
1322            "accountId": "acc1",
1323            "update": {
1324                "t3": { "isDraft": false }
1325            }
1326        });
1327        let HandlerOutput { primary: resp, .. } =
1328            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1329                .await
1330                .expect("must not return a top-level error");
1331
1332        // Like above: the patch must NOT be pre-rejected with invalidProperties.
1333        if let Some(not_updated) = resp["notUpdated"].as_object()
1334            && let Some(err) = not_updated.get("t3")
1335        {
1336            assert_ne!(
1337                err["type"].as_str(),
1338                Some("invalidProperties"),
1339                "isDraft:false must never produce invalidProperties"
1340            );
1341        }
1342    }
1343
1344    // ── compute_utc_times / utcStart wiring (draft-tasks-06 §4 (utcStart/utcDue paragraphs)) ─
1345
1346    /// Oracle: draft-tasks-06 §4 — utcStart is not returned unless explicitly
1347    /// requested in `properties`.  The default impl returns None so it must be
1348    /// absent from the response when not requested.
1349    #[tokio::test]
1350    async fn get_without_utc_properties_omits_utc_fields() {
1351        let backend = MockBackend::new_with_account("acc1");
1352        let args = json!({
1353            "accountId": "acc1",
1354            "ids": null,
1355            "properties": ["id", "title"]  // utcStart and utcDue NOT listed
1356        });
1357        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
1358            .await
1359            .expect("must succeed");
1360        // The list is empty (no tasks seeded), but the response itself must be valid.
1361        assert_eq!(resp["accountId"], "acc1");
1362        // No utcStart or utcDue should appear in response items (list is empty so
1363        // this is vacuously satisfied, but the path is exercised without error).
1364        let list = resp["list"].as_array().expect("list must be an array");
1365        for item in list {
1366            assert!(
1367                item.get("utcStart").is_none(),
1368                "utcStart must not appear when not in properties"
1369            );
1370        }
1371    }
1372
1373    /// Oracle: draft-tasks-06 §4 — when utcStart is in properties, the handler
1374    /// calls compute_utc_times. The default impl returns (None, None) so
1375    /// no utcStart key is injected, but no error is raised either.
1376    #[tokio::test]
1377    async fn get_with_utc_start_in_properties_does_not_error() {
1378        let backend = MockBackend::new_with_account("acc1");
1379        let args = json!({
1380            "accountId": "acc1",
1381            "ids": null,
1382            "properties": ["id", "utcStart", "utcDue"]
1383        });
1384        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
1385            .await
1386            .expect("must succeed with utcStart in properties");
1387        assert_eq!(resp["accountId"], "acc1");
1388    }
1389
1390    // ── per-user property routing (draft-tasks-06 §4.5.1) ──────────────────
1391    //
1392    // Routing is observable via MockBackend::per_user_calls — a counter that
1393    // increments inside `update_task_per_user` and stays at 0 for paths that
1394    // go to `update_object`. The earlier shape of these tests only asserted
1395    // that no `invalidProperties` error came back, which would pass even if
1396    // routing were inverted; tightened here to inspect the counter directly.
1397
1398    /// Oracle: draft-tasks-06 §4.5.1 — a patch with only per-user properties
1399    /// (bare keys, no JSON Pointer sub-paths) must route to update_task_per_user.
1400    #[tokio::test]
1401    async fn set_per_user_only_patch_routes_to_per_user_update() {
1402        use std::sync::atomic::Ordering;
1403        let backend = MockBackend::new_with_account("acc1");
1404        // color is a per-user property (§4.5.1).
1405        let args = json!({
1406            "accountId": "acc1",
1407            "update": { "t1": { "color": "#ff0000" } }
1408        });
1409        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1410            .await
1411            .expect("must not return top-level error");
1412        assert_eq!(
1413            backend.per_user_calls.load(Ordering::Relaxed),
1414            1,
1415            "per-user-only patch must route to update_task_per_user"
1416        );
1417    }
1418
1419    /// Oracle: draft-tasks-06 §4.5.1 + RFC 8620 §5.3 — JSON-pointer patches on
1420    /// per-user properties (e.g. `keywords/done: true` to toggle a single
1421    /// keyword, `alerts/0/offset: null` to clear an alert sub-field) must still
1422    /// route to update_task_per_user. The first pointer segment is the
1423    /// property name; the implementation MUST classify on that segment, not
1424    /// on the whole key.
1425    #[tokio::test]
1426    async fn set_per_user_json_pointer_patch_routes_to_per_user_update() {
1427        use std::sync::atomic::Ordering;
1428        let backend = MockBackend::new_with_account("acc1");
1429        let args = json!({
1430            "accountId": "acc1",
1431            "update": {
1432                "t1": {
1433                    "keywords/done": true,
1434                    "alerts/0/offset": null
1435                }
1436            }
1437        });
1438        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1439            .await
1440            .expect("must not return top-level error");
1441        assert_eq!(
1442            backend.per_user_calls.load(Ordering::Relaxed),
1443            1,
1444            "JSON-pointer patch on per-user properties must route to update_task_per_user"
1445        );
1446    }
1447
1448    /// Oracle: draft-tasks-06 §4.5.1 — a patch on a shared property (title)
1449    /// must route to update_object.
1450    #[tokio::test]
1451    async fn set_shared_property_patch_routes_to_update_object() {
1452        use std::sync::atomic::Ordering;
1453        let backend = MockBackend::new_with_account("acc1");
1454        let args = json!({
1455            "accountId": "acc1",
1456            "update": { "t1": { "title": "New title" } }
1457        });
1458        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1459            .await
1460            .expect("must not return top-level error");
1461        assert_eq!(
1462            backend.per_user_calls.load(Ordering::Relaxed),
1463            0,
1464            "shared-property patch must NOT route to update_task_per_user"
1465        );
1466    }
1467
1468    /// Oracle: RFC 7396 / RFC 8620 §5.3 — `{"title": null}` is a delete-shared-
1469    /// property mutation, NOT a per-user mutation. The previous routing
1470    /// short-circuited on null values, misclassifying this as per-user-only.
1471    #[tokio::test]
1472    async fn set_shared_property_null_patch_routes_to_update_object() {
1473        use std::sync::atomic::Ordering;
1474        let backend = MockBackend::new_with_account("acc1");
1475        let args = json!({
1476            "accountId": "acc1",
1477            "update": { "t1": { "title": null } }
1478        });
1479        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1480            .await
1481            .expect("must not return top-level error");
1482        assert_eq!(
1483            backend.per_user_calls.load(Ordering::Relaxed),
1484            0,
1485            "delete-shared-property patch must NOT route to update_task_per_user"
1486        );
1487    }
1488
1489    /// Oracle: draft-tasks-06 §4.5.1 — a mixed patch (per-user + shared)
1490    /// routes to update_object, never update_task_per_user.
1491    #[tokio::test]
1492    async fn set_mixed_patch_routes_to_update_object() {
1493        use std::sync::atomic::Ordering;
1494        let backend = MockBackend::new_with_account("acc1");
1495        let args = json!({
1496            "accountId": "acc1",
1497            "update": { "t1": { "color": "#ff0000", "title": "New" } }
1498        });
1499        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1500            .await
1501            .expect("must not return top-level error");
1502        assert_eq!(
1503            backend.per_user_calls.load(Ordering::Relaxed),
1504            0,
1505            "mixed patch must route to update_object"
1506        );
1507    }
1508
1509    /// Oracle: RFC 8620 §5.3 — an empty PatchObject is a no-op, not a per-user
1510    /// mutation. The previous routing classified it as per-user-only via
1511    /// vacuous-truth on `iter().all`.
1512    #[tokio::test]
1513    async fn set_empty_patch_routes_to_update_object() {
1514        use std::sync::atomic::Ordering;
1515        let backend = MockBackend::new_with_account("acc1");
1516        let args = json!({
1517            "accountId": "acc1",
1518            "update": { "t1": {} }
1519        });
1520        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1521            .await
1522            .expect("must not return top-level error");
1523        assert_eq!(
1524            backend.per_user_calls.load(Ordering::Relaxed),
1525            0,
1526            "empty patch must NOT route to update_task_per_user"
1527        );
1528    }
1529
1530    /// RFC 8620 §5.3 types `destroy` as "Id[]|null", so an object element
1531    /// is "invalidArguments: One of the arguments is of the wrong type"
1532    /// (§3.6.2). The description names only the JSON type: §3.6.1 reserves
1533    /// it for "unstructured English text suitable for displaying to a
1534    /// developer", so the client-supplied value is never echoed
1535    /// (bd JMAP-zegc).
1536    #[tokio::test]
1537    async fn set_non_string_destroy_element_does_not_echo_value() {
1538        let backend = MockBackend::new_with_account("acc");
1539        let args = json!({ "accountId": "acc", "destroy": [{ "note": "CANARY-zegc" }] });
1540        let err = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1541            .await
1542            .expect_err("non-string destroy element must be a method error");
1543        assert_eq!(err.error_type.to_string(), "invalidArguments");
1544        let desc = err.description.as_deref().unwrap_or_default();
1545        assert!(desc.contains("got object"), "{desc}");
1546        assert!(!desc.contains("CANARY"), "{desc}");
1547    }
1548
1549    /// Oracle: RFC 8620 §5.3: for `invalidProperties` "the SetError object
1550    /// SHOULD also have a property called `properties` of type `String[]`
1551    /// that lists *all* the properties that were invalid". Each create below
1552    /// has exactly one hand-picked bad property.
1553    #[tokio::test]
1554    async fn set_create_typed_parse_failure_names_property() {
1555        let backend = MockBackend::new_with_account("acc1");
1556        let args = json!({
1557            "accountId": "acc1",
1558            "create": {
1559                "badTitle": { "title": 5 },
1560                "badSequence": { "sequence": "x" }
1561            }
1562        });
1563        let HandlerOutput { primary: resp, .. } =
1564            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1565                .await
1566                .expect("must not return top-level error");
1567        assert!(resp["created"].is_null(), "nothing may be created: {resp}");
1568        for (cid, prop) in [("badTitle", "title"), ("badSequence", "sequence")] {
1569            let err = &resp["notCreated"][cid];
1570            assert_eq!(err["type"], "invalidProperties", "{cid}: {resp}");
1571            assert_eq!(err["properties"], json!([prop]), "{cid}: {resp}");
1572        }
1573    }
1574
1575    /// Oracle: RFC 8620 §5.3: for `invalidProperties` "the SetError object
1576    /// SHOULD also have a property called `properties` of type `String[]`
1577    /// that lists *all* the properties that were invalid". Each create below
1578    /// has exactly one hand-picked bad property override.
1579    #[tokio::test]
1580    async fn copy_typed_parse_failure_names_property() {
1581        let mut backend = MockBackend::new_with_account("acc1");
1582        backend.add_account("acc2");
1583        backend.seed_task("acc2", "src1", true);
1584        let args = json!({
1585            "accountId": "acc1",
1586            "fromAccountId": "acc2",
1587            "create": {
1588                "badTitle": { "id": "src1", "title": 5 }
1589            }
1590        });
1591        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1592            .await
1593            .expect("must not return top-level error");
1594        assert!(resp["created"].is_null(), "nothing may be created: {resp}");
1595        let err = &resp["notCreated"]["badTitle"];
1596        assert_eq!(err["type"], "invalidProperties", "{resp}");
1597        assert_eq!(err["properties"], json!(["title"]), "{resp}");
1598    }
1599}