jmap-tasks-server 0.6.0

JMAP Tasks method handlers — backend-agnostic, plugs into jmap-server Dispatcher
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! TasksBackend trait and supporting types for JMAP Tasks method handlers.
//!
//! Consumers implement [`TasksBackend`] for their storage system. The method
//! handlers in sibling modules call into the backend through this trait.
//!
//! The read-side operations (`get_objects`, `get_state`, `get_changes`,
//! `query_objects`, `query_changes`) are defined on the [`jmap_server::JmapBackend`]
//! supertrait. Only write operations and type-specific operations are here.

use jmap_server::{
    BackendQueryError, BackendSetError, JmapBackend, JmapObject, QueryParams, QueryResult,
    SetObject,
};
use jmap_types::PatchObject;

// ---------------------------------------------------------------------------
// TasksBackend trait
// ---------------------------------------------------------------------------

/// Storage backend for JMAP Tasks method handlers (draft-ietf-jmap-tasks-06).
///
/// Implementors provide the actual data access; the method handler modules
/// in this crate translate between JMAP wire protocol and backend calls.
///
/// Read-side operations (`get_objects`, `get_state`, `get_changes`,
/// `query_objects`, `query_changes`) are defined on the [`JmapBackend`]
/// supertrait. Only write operations and type introspection are here.
///
/// This trait is not object-safe by design (generic methods). Use
/// `Arc<impl TasksBackend>` when sharing across tasks.
pub trait TasksBackend: JmapBackend {
    /// Create a new object (TaskList or Task).
    ///
    /// # Authorisation contract
    ///
    /// This method is the canonical enforcement point for caller authorisation
    /// per workspace AGENTS.md "Caller identity (foundation seam)" and per-crate
    /// AGENTS.md "Permission enforcement: backend canonical". Implementors MUST
    /// verify that the principal identified by
    /// [`JmapAccounts::principal_id(caller)`](jmap_server::JmapAccounts::principal_id) has write
    /// access to the target account / TaskList / Task before performing the
    /// mutation, and MUST return
    /// [`BackendSetError::SetError`] carrying
    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. Handlers in this crate do NO
    /// permission checking; any handler-layer pre-check is defense-in-depth
    /// only and the backend MUST re-verify atomically with the mutation. A
    /// backend that trusts the handler is a bug. A backend whose
    /// `principal_id` returns `None` permits every write (fail-open,
    /// bd:JMAP-bghk) and CANNOT correctly implement TaskList ACLs or
    /// per-user scoping.
    ///
    /// ## `mayWriteOwn` and task owners
    ///
    /// For a Task, write access is the TaskList's `mayWriteAll` right, or
    /// its `mayWriteOwn` right when the caller is an owner of the task or
    /// the task has no owner (draft-ietf-jmap-tasks-06 §3 `mayWriteOwn`).
    /// Who the owner is follows JMAP Calendars (jmapio/jmap #461, PR #462;
    /// draft-ietf-jmap-calendars-34 §4), not -06's "participant"/"chair"
    /// text: decide it with [`jmap_tasks_types::is_task_owner`] and
    /// [`jmap_tasks_types::task_has_owner`], passing the `calendarAddress`
    /// of each of the caller's ParticipantIdentity objects in the account.
    /// A participant with the `"owner"` role whose `calendarAddress` is one
    /// of those makes the caller an owner; a task whose `participants` is
    /// null or omitted, or has no `"owner"` participant, has no owner.
    ///
    /// Check a create against the new task, and an update or destroy
    /// against the stored one: "This means the user may also transfer
    /// ownership by updating a task so they are no longer an owner" (-06
    /// §3), so the patched result need not leave the caller an owner.
    ///
    /// # Errors
    ///
    /// Reject a create that RFC 8620 §5.3 defines an error for with
    /// [`BackendSetError::SetError`] carrying the matching
    /// [`SetErrorType`](jmap_server::SetErrorType); the handler places it verbatim in `notCreated`.
    /// For create these are `forbidden`, `overQuota`, `tooLarge`,
    /// `rateLimit` and `invalidProperties`. An `invalidProperties` error
    /// SHOULD name in `properties` "*all* the properties that were
    /// invalid", for example `taskListId` when a Task names a TaskList that
    /// does not exist.
    ///
    /// Return [`BackendSetError::Other`] only for unexpected storage
    /// failures. The handler reports it as `serverFail` without the
    /// error's `Display` text, which tells the client to retry; a
    /// deterministic rejection returned as `Other` invites retries that
    /// cannot succeed.
    ///
    /// The `/set` handlers in this crate reject an unknown `account_id`
    /// with the method-level `accountNotFound` error before calling the
    /// backend.
    ///
    /// # State and change log
    ///
    /// RFC 8620 §5.1 defines the state string over "*all* the data of
    /// this type in the account": "If the data changes, this string MUST
    /// change." Every successful `create_object`,
    /// [`update_object`](Self::update_object) and
    /// [`destroy_object`](Self::destroy_object) MUST advance
    /// [`get_state`](jmap_server::JmapReads::get_state) for `O` in `account_id` and
    /// record the id as created, updated or destroyed so
    /// [`get_changes`](jmap_server::JmapReads::get_changes) reports it.
    ///
    /// The write, the state advance and the change record MUST be atomic
    /// with respect to other callers: the reference `MemoryBackend` does
    /// all three under one mutex acquisition, and a database backend uses
    /// one transaction. A call that returns `Err` MUST leave the stored
    /// data, the state and the change log unchanged.
    fn create_object<O, F>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        create_id: &str,
        build: F,
    ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
    + Send
    where
        O: SetObject + Send + Sync,
        F: FnOnce(&jmap_types::Id) -> O + Send;

    /// Store `obj`, a record read from `from_account_id`, as a new record in
    /// `to_account_id`, for `/copy` (RFC 8620 §5.4).
    ///
    /// Called by `Task/copy` after the handler fetched the Task from
    /// `from_account_id` and applied the request's overrides, including any
    /// `metadata` and `privateMetadata` it supplies
    /// (draft-ietf-jmap-metadata-05 §3.4). `create` is the request's create
    /// object for this copy (RFC 8620 §5.4). -05 §3.4 says its `metadata`
    /// and `privateMetadata` follow "the same rules as a create in
    /// Foo/set", so the backend validates them as
    /// [`create_object`](Self::create_object) does (-05 §3.2 rules 1 to 4,
    /// `maxDepth` only on these supplied values) and leaves the copied
    /// values unvalidated ("Copied values are not revalidated against the
    /// destination account"). Every other rule of
    /// [`create_object`](Self::create_object) applies to the copy. The
    /// backend assigns the new `id`, stores the record in `to_account_id`
    /// and records the create in the state and change log as
    /// [`create_object`](Self::create_object) does. Returns the new id and
    /// the stored record.
    ///
    /// # Authorisation contract
    ///
    /// Implementors MUST verify caller read access to `obj` in
    /// `from_account_id` and write access to `to_account_id` before storing the
    /// copy, and MUST return [`BackendSetError::SetError`] with
    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`] for
    /// the workspace-canonical rationale; the same rule applies here.
    ///
    /// # Errors
    ///
    /// As for [`create_object`](Self::create_object): a
    /// [`BackendSetError::SetError`] is reported for that copy.
    fn copy_object<O: SetObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        from_account_id: &jmap_types::Id,
        to_account_id: &jmap_types::Id,
        obj: O,
        create: &serde_json::Value,
    ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
    + Send;

    /// Apply a partial update (patch) to an existing object.
    ///
    /// Returns `Some(updated_object)` if the backend modified any properties
    /// beyond what the client requested (RFC 8620 §5.3 server-set field echo),
    /// or `None` if the patch was applied verbatim.
    ///
    /// # Authorisation contract
    ///
    /// Implementors MUST verify caller write-access to the target object before
    /// applying the patch and MUST return [`BackendSetError::SetError`] with
    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`] for
    /// the workspace-canonical rationale; the same rule applies here. For a
    /// Task, write access includes `mayWriteOwn` on a task the caller owns
    /// or that has no owner, judged on the stored task (see
    /// [`Self::create_object`], "`mayWriteOwn` and task owners").
    ///
    /// # Patch format
    ///
    /// `patch` is an RFC 8620 §5.3 PatchObject, not an RFC 7396 JSON
    /// Merge Patch: "The keys are a path in JSON Pointer format
    /// \[RFC6901\], with an implicit leading "/"". So `{"a/b": null}`
    /// removes member `b` of property `a`; it does not touch a top-level
    /// property literally named `a/b`. A `null` value sets the
    /// property's default if it has one, otherwise removes it. A pointer
    /// into an array, a pointer whose parent does not exist, or two keys
    /// where one pointer is a prefix of the other "MUST be rejected with
    /// an "invalidPatch" error".
    ///
    /// Implementors SHOULD apply `patch` with
    /// [`jmap_server::apply_patch_object`], which enforces these rules
    /// all-or-nothing, and map any [`jmap_server::PatchPathError`] to
    /// [`jmap_server::SetErrorType::InvalidPatch`], as the reference
    /// `MemoryBackend` does.
    ///
    /// # Errors
    ///
    /// As for [`create_object`](Self::create_object), plus these RFC 8620
    /// §5.3 rules for update:
    ///
    /// - "If an id given cannot be found, the update or destroy MUST be
    ///   rejected with a "notFound" set error."
    /// - A patch that breaks the rules under "Patch format" is
    ///   `invalidPatch`.
    /// - A patched record that is invalid is `invalidProperties`. That
    ///   includes changing a server-set property, though "it is not an
    ///   error to include a server-set property in an update as long as
    ///   the value is identical to the current value on the server."
    /// - A Task patch whose result has `isDraft: true` when the stored
    ///   value is not `true` (false, or absent after a `null` patch) is
    ///   `invalidProperties` naming `isDraft`: draft-tasks-06 §4 "This may
    ///   only be set to true upon creation." The `Task/set` handler does
    ///   not pre-check this; the backend is the only enforcement point, in
    ///   the same critical section that applies the patch.
    /// - A Task's `workflowStatus` and `progress` follow decision 42
    ///   ([`crate::workflow::apply_workflow_status`]): a status not in the
    ///   list's `workflowStatuses` is `invalidProperties` when the patch sets
    ///   it or moves the task; a progress value is mirrored into `progress`
    ///   (return the Task as `Some` to echo it); a conflicting `progress` is
    ///   `invalidProperties`. Run it in the same critical section, as
    ///   `create_object` does for a create.
    ///
    /// # Atomicity
    ///
    /// RFC 8620 §5.3: the server "MUST NOT only commit part of an update
    /// to a single record". Apply the whole patch and validate the result
    /// before writing it, so that on any error the stored record is
    /// unchanged. State and change log follow
    /// [`create_object`](Self::create_object) ("State and change log"); an
    /// `Ok(None)` return still advances the state.
    fn update_object<O: SetObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        id: &jmap_types::Id,
        patch: O::Patch,
    ) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;

    /// Destroy an object by id.
    ///
    /// # Authorisation contract
    ///
    /// Implementors MUST verify caller write-access to the target object before
    /// destroying it and MUST return [`BackendSetError::SetError`] with
    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`] for
    /// the workspace-canonical rationale; the same rule applies here. For a
    /// Task, write access includes `mayWriteOwn` on a task the caller owns
    /// or that has no owner (see [`Self::create_object`], "`mayWriteOwn`
    /// and task owners").
    ///
    /// # Errors
    ///
    /// As for [`create_object`](Self::create_object), plus these RFC 8620
    /// §5.3 rules for destroy: an unknown id, including one already
    /// destroyed, is `notFound`, and a destroy that "would violate an ACL
    /// or other permissions policy" is `forbidden`.
    ///
    /// # Cascades
    ///
    /// The handlers perform the cross-record effects the client chooses,
    /// through explicit backend calls, and the backend does not repeat
    /// them. `TaskList/set` `onDestroyRemoveTasks` destroys the list's
    /// Tasks through [`Self::destroy_object`] calls the handler makes.
    ///
    /// If the backend itself changes another record because of the
    /// destroy, it MUST advance that record type's state and record the
    /// change in the same atomic step, so `/changes` on that type sees it.
    /// State and change log for `O` follow
    /// [`create_object`](Self::create_object) ("State and change log").
    fn destroy_object<O: SetObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        id: &jmap_types::Id,
    ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;

    /// Returns `true` if this backend supports JMAP object type `O` for
    /// `account_id`, as seen by `caller`.
    ///
    /// # Per-account semantics
    ///
    /// Capabilities are per account (RFC 8620 §1.6.2, §2
    /// `accountCapabilities`), so the answer may vary with `caller` and
    /// `account_id`. Backends that support every type in this trait for
    /// every account can ignore both arguments and return `true`.
    fn supports_type<O: JmapObject>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
    ) -> bool;

    /// Returns true if the given task list contains at least one task.
    ///
    /// Called by `TaskList/set` destroy handler when `onDestroyRemoveTasks`
    /// is false: if this returns `Ok(true)`, the destroy is rejected with
    /// `taskListHasTask` (draft-ietf-jmap-tasks-06 §3.4).
    ///
    /// # Three-way result
    ///
    /// The return type is `Result<bool, Self::Error>` to distinguish
    /// three states that callers actually need to tell apart
    /// (mirrors [`CalendarsBackend::calendar_has_events`]):
    ///
    /// - `Ok(true)` — the task list is definitely non-empty. The
    ///   handler rejects the destroy with `taskListHasTask`.
    /// - `Ok(false)` — the task list is definitely empty. The handler
    ///   forwards to `destroy_object`.
    /// - `Err(_)` — connectivity/transient failure. The handler maps
    ///   this to `serverFail` so the client knows to retry. Returning
    ///   `Ok(false)` for a transient backend failure is a bug: the
    ///   destroy proceeds and any tasks that DID exist become silently
    ///   orphaned.
    ///
    /// [`CalendarsBackend::calendar_has_events`]: https://docs.rs/jmap-calendars-server/latest/jmap_calendars_server/trait.CalendarsBackend.html#tymethod.calendar_has_events
    ///
    /// # Authorisation contract
    ///
    /// This is a read-side probe that informs a destroy decision the caller is
    /// already authorised to attempt; implementors MAY assume the caller has at
    /// least read access to the target TaskList (the surrounding `/set` flow
    /// re-validates write access in [`Self::destroy_object`]). Backends that
    /// scope task visibility per-principal MUST filter by the caller's effective
    /// access — a counter that includes tasks the caller cannot see leaks
    /// existence information.
    fn task_list_has_tasks(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        task_list_id: &jmap_types::Id,
    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send;

    /// Apply a patch that contains only per-user Task properties
    /// (draft-tasks-06 §4.5.1 — `keywords`, `color`, `freeBusyStatus`,
    /// `useDefaultAlerts`, `alerts`).
    ///
    /// The handler routes here when every patch key's leading segment
    /// satisfies [`jmap_tasks_types::is_per_user_task_property`]; that
    /// classification is fixed by the spec and is not a backend hook.
    ///
    /// When only per-user properties are patched, the shared `updated`
    /// timestamp MUST NOT change (§4.5.1 (per-user updated paragraph)).
    /// There is no default: delegating to [`Self::update_object`] is correct
    /// only for a single-user backend whose `update_object` leaves `updated`
    /// alone. A backend serving multiple users stores the patch in a
    /// user-scoped path.
    ///
    /// # Authorisation contract
    ///
    /// Implementors MUST verify that the caller may modify per-user properties
    /// on the target Task and MUST return [`BackendSetError::SetError`] with
    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. That is the TaskList's
    /// `mayUpdatePrivate` right, which covers exactly the per-user properties
    /// of draft-ietf-jmap-tasks-06 §4.5.1
    /// ([`jmap_tasks_types::PER_USER_TASK_PROPERTIES`]), as jmapio/jmap
    /// #468 / PR #469 words it: "The user may modify the per-user properties
    /// (see the "Per-user properties" section) on all tasks in the task list,
    /// even if they would not otherwise have permission to modify that task."
    /// (-06 §3 says "the following properties" and gives no list.) The
    /// handler sends only patches whose every key is one of those here, so a
    /// patch that also touches a shared property goes to
    /// [`Self::update_object`] and needs write access. The write-access rule
    /// of [`Self::update_object`] does NOT apply here. See
    /// [`Self::create_object`] for the workspace-canonical rationale on
    /// backend-as-enforcement-point.
    fn update_task_per_user(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        id: &jmap_types::Id,
        patch: PatchObject,
    ) -> impl std::future::Future<
        Output = Result<Option<jmap_tasks_types::Task>, BackendSetError<Self::Error>>,
    > + Send;

    /// Compute `utcStart` and `utcDue` for a [`Task`](jmap_tasks_types::Task) by converting the task's
    /// `start`/`due` local-time fields and time zone into UTC (draft-tasks-06 §4,
    /// utcStart/utcDue paragraphs).
    ///
    /// Returns `(utc_start, utc_due)` as [`UTCDate`](jmap_types::UTCDate) values,
    /// or `None` for each if the corresponding field is absent or the time zone
    /// is unknown.
    ///
    /// `Task/get` sends `null` for a requested `utcStart` / `utcDue` when the
    /// task has no `start` / `due` (jmapio/jmap PR #464), whatever this
    /// returns; when the local time is set and this returns `None`, the key
    /// is left out, because `null` would say the local time is unset.
    ///
    /// The default implementation returns `(None, None)` — backends that do not
    /// support time-zone conversion can accept this behaviour, and `Task/get`
    /// then omits the two properties for tasks that have a `start` / `due`.
    /// Backends with full tz support should override this.
    ///
    /// # Parameters
    /// - `caller` — the caller context. The default implementation ignores it.
    /// - `account_id` — the target account. The default implementation ignores
    ///   it, but backends MAY use it to look up an account-scoped tz database.
    /// - `task` — the task whose `start` and `due` fields are to be converted.
    /// - `tz_hint` — the Task/get `timeZone` argument, `None` when the
    ///   request has none, which means `"Etc/UTC"` (the CalendarEvent/get
    ///   default, draft-ietf-jmap-calendars-34 §5.7). It applies only to a
    ///   floating task (a null `timeZone`): "Floating tasks will be
    ///   interpreted as per the time zone given as a Task/get argument"
    ///   (draft-tasks-06 §4). A task with a `timeZone` converts with its own
    ///   zone. The crate does not check the value against the IANA Time
    ///   Zone Database; an unknown zone converts to `None`.
    ///
    /// Naming and signature mirror the canonical
    /// [`CalendarsBackend::compute_utc_times`](https://docs.rs/jmap-calendars-server/latest/jmap_calendars_server/trait.CalendarsBackend.html#method.compute_utc_times)
    /// (bd:JMAP-ops7.25).
    fn compute_utc_times(
        &self,
        _caller: &Self::CallerCtx,
        _account_id: &jmap_types::Id,
        _task: &jmap_tasks_types::Task,
        _tz_hint: Option<&str>,
    ) -> impl std::future::Future<
        Output = (Option<jmap_types::UTCDate>, Option<jmap_types::UTCDate>),
    > + Send {
        // Default: no UTC conversion capability; callers omit utcStart/utcDue.
        async { (None, None) }
    }

    /// Run a `Task/query` request with its Task/query arguments
    /// (`expandRecurrences`, `timeZone`; jmapio/jmap #456, following
    /// CalendarEvent/query, draft-ietf-jmap-calendars-34 §5.11).
    ///
    /// `params` holds the RFC 8620 §5.5 arguments. `args.time_zone` (or
    /// `"Etc/UTC"` when `None`) is the zone for the `after` / `before`
    /// conditions and for the local times of floating tasks, both when
    /// filtering and when sorting; a `start` sort orders by absolute time.
    /// The conditions are documented on
    /// [`TaskFilterCondition`](jmap_tasks_types::TaskFilterCondition): `after`
    /// tests the task's `due` (or `start` when it has no `due`), `before` its
    /// `start` (or `due`).
    ///
    /// When `args.expand_recurrences` is `true`, return one id per
    /// instance of a recurring task inside the filter's `after` / `before`
    /// window; the handler has checked the filter is one FilterCondition
    /// with both. A synthetic instance id is opaque to the client and must
    /// resolve in `Task/get` and `Task/set` (calendars-34 §5.11). With
    /// `expand_recurrences` `false`, a recurring task is one id.
    ///
    /// There is no default: one that ignored `args` would answer an
    /// expansion request with unexpanded ids and read floating tasks in the
    /// wrong zone (workspace AGENTS.md, "Default bodies on spec-semantic
    /// backend methods"). A backend that cannot expand says so with
    /// `cannotCalculateOccurrences`.
    ///
    /// # Errors
    ///
    /// [`BackendQueryError::Method`](jmap_server::BackendQueryError::Method)
    /// is returned to the client unchanged:
    ///
    /// - `expandDurationTooLarge` (`JmapError::custom`) when expansion is
    ///   requested and `before - after` exceeds
    ///   [`TasksLimits::max_expanded_query_duration_seconds`] (the account's
    ///   `maxExpandedQueryDuration`, draft-tasks-06 §1.6.2). The handler
    ///   checks this first, but the backend is canonical and MUST check it
    ///   again (workspace AGENTS.md "Backend caps and limits").
    /// - `cannotCalculateOccurrences` when a recurrence needed for the
    ///   result cannot be expanded.
    /// - The RFC 8620 §5.5 errors (`unsupportedFilter`, `unsupportedSort`,
    ///   `anchorNotFound`, ...), as for
    ///   [`query_objects`](jmap_server::JmapReads::query_objects).
    ///
    /// [`BackendQueryError::Other`](jmap_server::BackendQueryError::Other)
    /// becomes a redacted `serverFail`.
    fn query_tasks(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        params: QueryParams<'_, jmap_tasks_types::Task>,
        args: &TaskQueryArgs,
    ) -> impl std::future::Future<Output = Result<QueryResult, BackendQueryError<Self::Error>>> + Send;

    /// Implementation-defined caps for `account_id` as seen by `caller`
    /// (workspace AGENTS.md "Backend caps and limits"). The default is
    /// [`TasksLimits::default`]; override it to vary caps per account.
    fn limits(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> TasksLimits {
        let _ = (caller, account_id);
        TasksLimits::default()
    }
}

/// Per-call `Task/query` arguments beyond RFC 8620 §5.5
/// (jmapio/jmap #456, following CalendarEvent/query,
/// draft-ietf-jmap-calendars-34 §5.11).
///
/// `#[non_exhaustive]` so a later revision can add arguments; build one
/// with [`TaskQueryArgs::default`] and the setters.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TaskQueryArgs {
    /// `expandRecurrences` (default `false`): return one id per instance
    /// of a recurring task. The handler has checked that the filter is one
    /// FilterCondition with both `before` and `after`.
    pub expand_recurrences: bool,
    /// `timeZone` (default `"Etc/UTC"` when `None`): the zone for the
    /// `after` / `before` conditions and for floating tasks when filtering
    /// and sorting. The crate does not check it against the IANA Time Zone
    /// Database; that is the backend's job.
    pub time_zone: Option<String>,
}

impl TaskQueryArgs {
    /// Set [`Self::expand_recurrences`].
    #[must_use]
    pub fn with_expand_recurrences(mut self, expand: bool) -> Self {
        self.expand_recurrences = expand;
        self
    }

    /// Set [`Self::time_zone`].
    #[must_use]
    pub fn with_time_zone(mut self, time_zone: Option<String>) -> Self {
        self.time_zone = time_zone;
        self
    }
}

/// Implementation-defined caps of a [`TasksBackend`], returned by
/// [`TasksBackend::limits`] (workspace AGENTS.md "Backend caps and limits";
/// mirrors `CalendarsLimits`).
///
/// | Field | Default | Rationale |
/// |---|---|---|
/// | `max_expanded_query_duration_seconds` | `31_536_000` (365 days) | As `CalendarsLimits`: a year is the range clients commonly ask for, and longer windows multiply recurrence expansion. |
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TasksLimits {
    /// Longest `before - after` window, in seconds, that `Task/query`
    /// expands recurrences over: the account's `maxExpandedQueryDuration`
    /// (draft-tasks-06 §1.6.2, "The maximum duration the user may query
    /// over when asking the server to expand recurrences"). A longer window
    /// is the `expandDurationTooLarge` method error.
    pub max_expanded_query_duration_seconds: u64,
}

impl Default for TasksLimits {
    fn default() -> Self {
        Self {
            max_expanded_query_duration_seconds: 31_536_000,
        }
    }
}

impl TasksLimits {
    /// Limits with the given [`Self::max_expanded_query_duration_seconds`].
    #[must_use]
    pub fn new(max_expanded_query_duration_seconds: u64) -> Self {
        Self {
            max_expanded_query_duration_seconds,
        }
    }
}