jmap-tasks-server 0.5.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
//! TaskNotification/* method handlers (draft-tasks-06 §5).
//!
//! TaskNotifications are server-created immutable records. Clients may only
//! query and destroy them. Any attempt to create or update a TaskNotification
//! via `/set` MUST be rejected with `forbidden` at the handler layer — the
//! backend never sees create or update calls for this type.
//!
//! # Wire-shape contract
//!
//! Every `handle_*` function in this module conforms to the canonical JMAP
//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
//! Object whose fields match the corresponding RFC 8620 §5 method shape
//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3,
//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
//! arguments defined by draft-tasks-06 §5. The returned `Value` is the
//! corresponding method-response object per the same section refs.
//!
//! The returned `HandlerOutput::extra_invocations` carries any invocations
//! that this handler injected into the request stream (RFC 8620 §6.3);
//! for the handlers in this module the vector is **always empty**.
//!
//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
//! §3.6.2 and §5):
//!
//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
//!   `maxObjectsInSet`;
//! - `/set`: `stateMismatch`;
//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
//! - `/queryChanges`: `tooManyChanges`;
//! - `/query`, `/queryChanges`: `unsupportedFilter`;
//! - `/query`: `unsupportedSort`, `anchorNotFound`.
//!
//! Per-target failures inside `/set` surface in the `notDestroyed` map within
//! `Ok((Value, ...))`, not as `Err`.

use jmap_tasks_types::{TaskNotification, TaskNotificationComparator};
use jmap_types::JmapError;
use serde_json::Value;

use crate::TasksBackend;
use crate::helpers::{
    SetAccumulators, enforce_max_objects_in_set, extract_account_id, finalize_set_response,
    reject_unsupported_sort,
};
use jmap_server::{HandlerOutput, backend_set_error_value, server_fail_from_backend};
use jmap_server::{SetError, SetErrorType};

// ---------------------------------------------------------------------------
// TaskNotification/get
// ---------------------------------------------------------------------------

/// Handle a `TaskNotification/get` method call (draft-tasks-06 §5.2).
///
/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
/// `ids`, optional `properties`); the returned `Value` is the §5.1
/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_notification_get<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_get::<TaskNotification, B>(backend, caller, args).await
}

// ---------------------------------------------------------------------------
// TaskNotification/changes
// ---------------------------------------------------------------------------

/// Handle a `TaskNotification/changes` method call (draft-tasks-06 §5.3).
///
/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
/// `/changes` response shape (`accountId`, `oldState`, `newState`,
/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_notification_changes<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_changes::<TaskNotification, B>(backend, caller, args, &[]).await
}

// ---------------------------------------------------------------------------
// TaskNotification/set
// ---------------------------------------------------------------------------

/// Handle a `TaskNotification/set` method call (draft-tasks-06 §5.4).
///
/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
/// `ifInState`, optional `create` / `update` / `destroy` maps); the
/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
/// `oldState`, `newState`, plus the per-operation result maps).
///
/// **Destroy-only enforcement**: draft-tasks-06 §5.4 states that only
/// `destroy` is supported. Any entries in the `create` or `update` maps
/// receive an immediate `forbidden` SetError without touching the backend.
/// The `destroy` list is forwarded to the backend normally.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_notification_set<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    let (account_id, mut args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
    // error). Without this, a /set against an unknown accountId would silently
    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }

    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
    // unbounded /set batches before touching the storage layer.
    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;

    let old_state = backend
        .get_state::<TaskNotification>(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
        && if_in_state != old_state.as_ref()
    {
        return Err(JmapError::state_mismatch());
    }

    let created = serde_json::Map::new();
    let mut not_created = serde_json::Map::new();
    let updated = serde_json::Map::new();
    let mut not_updated = serde_json::Map::new();
    let mut destroyed_list: Vec<Value> = Vec::new();
    let mut not_destroyed = serde_json::Map::new();
    let mut mutated = false;

    // -----------------------------------------------------------------------
    // create — forbidden: TaskNotification is server-created only
    // -----------------------------------------------------------------------
    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
        for create_id in create_map.keys() {
            not_created.insert(
                create_id.clone(),
                serde_json::Value::from(&SetError::new(SetErrorType::Forbidden)),
            );
        }
    }

    // -----------------------------------------------------------------------
    // update — forbidden: TaskNotification is immutable
    // -----------------------------------------------------------------------
    if let Some(update_map) = args.get("update").and_then(|v| v.as_object()) {
        for id_str in update_map.keys() {
            not_updated.insert(
                id_str.clone(),
                serde_json::Value::from(&SetError::new(SetErrorType::Forbidden)),
            );
        }
    }

    // -----------------------------------------------------------------------
    // destroy — the only permitted operation (draft-tasks-06 §5.4)
    // -----------------------------------------------------------------------
    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
        // Two-pass validation is intentional: this up-front loop fails the whole
        // request loudly; the `None => continue` arm in the inner match below
        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
        // delete this pre-check on the reasoning that the inner match handles
        // non-string elements — silent-skip is the wrong behaviour per the
        // workspace "silent-drop is a data-integrity bug class" rule
        // (JMAP-wlip.1).
        let id_strs: Vec<&str> = destroy_arr
            .iter()
            .map(|v| {
                v.as_str().ok_or_else(|| {
                    JmapError::invalid_arguments(format!(
                        "destroy: every element must be a string Id; got {}",
                        jmap_server::json_type_name(v)
                    ))
                })
            })
            .collect::<Result<_, _>>()?;
        for id_str in id_strs {
            let id_str = id_str.to_owned();
            let id = match jmap_server::parse_wire_id(&id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    not_destroyed.insert(id_str, serde_json::Value::from(&*err));
                    continue;
                }
            };

            match backend
                .destroy_object::<TaskNotification>(caller, &account_id, &id)
                .await
            {
                Ok(()) => {
                    mutated = true;
                    destroyed_list.push(Value::String(id_str));
                }
                Err(e) => {
                    not_destroyed.insert(id_str, backend_set_error_value(e));
                }
            }
        }
    }

    finalize_set_response::<B, TaskNotification>(
        backend,
        caller,
        &account_id,
        old_state,
        mutated,
        SetAccumulators {
            created,
            updated,
            destroyed: destroyed_list,
            not_created,
            not_updated,
            not_destroyed,
        },
    )
    .await
}

// ---------------------------------------------------------------------------
// TaskNotification/query
// ---------------------------------------------------------------------------

/// Handle a `TaskNotification/query` method call (draft-tasks-06 §5.5).
///
/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
/// optional `filter`, optional `sort`, optional `position`, optional
/// `anchor`, optional `anchorOffset`, optional `limit`, optional
/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
/// `position`, `ids`, optional `total`).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_notification_query<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    reject_unsupported_sort::<TaskNotificationComparator>(args.get("sort"))?;
    jmap_server::handle_query::<TaskNotification, B>(backend, caller, args).await
}

// ---------------------------------------------------------------------------
// TaskNotification/queryChanges
// ---------------------------------------------------------------------------

/// Handle a `TaskNotification/queryChanges` method call (draft-tasks-06 §5.6).
///
/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
/// optional `filter`, optional `sort`, `sinceQueryState`, optional
/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
/// returned `Value` is the §5.6 `/queryChanges` response shape
/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
/// `removed`, `added`).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_notification_query_changes<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    reject_unsupported_sort::<TaskNotificationComparator>(args.get("sort"))?;
    jmap_server::handle_query_changes::<TaskNotification, B>(backend, caller, args).await
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    use crate::test_support::MockBackend;

    /// Oracle: RFC 8620 §5.5 `unsupportedSort`: "The sort is syntactically
    /// valid, but includes a property the server does not support sorting
    /// on". draft-ietf-jmap-tasks-06 §5.5.2: "The \"created\" property MUST be
    /// supported for sorting." and lists no other; `taskId` is not among them.
    #[tokio::test]
    async fn query_unlisted_sort_property_returns_unsupported_sort() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({ "accountId": "acc1", "sort": [{ "property": "taskId" }] });
        let err = handle_task_notification_query(&backend, &(), args)
            .await
            .expect_err("unlisted sort property must be rejected");
        assert_eq!(err.error_type.to_string(), "unsupportedSort");
    }

    /// Oracle: as above; `TaskNotification/queryChanges` carries the same `sort`
    /// (RFC 8620 §5.6).
    #[tokio::test]
    async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "sinceQueryState": "0",
            "sort": [{ "property": "created" }, { "property": "taskId" }]
        });
        let err = handle_task_notification_query_changes(&backend, &(), args)
            .await
            .expect_err("unlisted sort property must be rejected");
        assert_eq!(err.error_type.to_string(), "unsupportedSort");
    }

    /// Oracle: draft-ietf-jmap-tasks-06 §5.5.2: "The \"created\" property MUST be
    /// supported for sorting." and lists no other, so a `created` sort is accepted.
    #[tokio::test]
    async fn query_listed_sort_property_is_accepted() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({ "accountId": "acc1", "sort": [{ "property": "created" }] });
        handle_task_notification_query(&backend, &(), args)
            .await
            .expect("listed sort property must not be rejected");
    }

    /// Oracle: TaskNotification/set create entries must produce `forbidden` in notCreated.
    /// No backend call is made for create (pure handler-layer enforcement).
    #[tokio::test]
    async fn set_create_returns_forbidden_not_created() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "create": {
                "c1": {
                    "id": "ignored",
                    "created": "2024-01-01T00:00:00Z",
                    "changedBy": { "@type": "Person", "name": "Alice" },
                    "type": "created",
                    "taskId": "t1"
                }
            }
        });
        let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
            .await
            .expect("must not return top-level error");

        let not_created = &resp["notCreated"];
        assert!(
            not_created.is_object(),
            "notCreated must be present for create attempts: {resp}"
        );
        assert_eq!(
            not_created["c1"]["type"], "forbidden",
            "c1 create must be forbidden: {resp}"
        );
        assert!(
            resp["created"].is_null(),
            "created must be null when all creates are forbidden: {resp}"
        );
    }

    /// Oracle: TaskNotification/set update entries must produce `forbidden` in notUpdated.
    #[tokio::test]
    async fn set_update_returns_forbidden_not_updated() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "update": {
                "notif1": { "comment": "new comment" }
            }
        });
        let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
            .await
            .expect("must not return top-level error");

        let not_updated = &resp["notUpdated"];
        assert!(
            not_updated.is_object(),
            "notUpdated must be present for update attempts: {resp}"
        );
        assert_eq!(not_updated["notif1"]["type"], "forbidden");
    }

    /// Oracle: destroy of a non-existent notification → notFound in notDestroyed.
    #[tokio::test]
    async fn set_destroy_nonexistent_returns_not_found() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "destroy": ["doesnotexist"]
        });
        let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
            .await
            .expect("must not return top-level error");

        let not_destroyed = &resp["notDestroyed"];
        assert!(
            not_destroyed.is_object(),
            "notDestroyed must be present: {resp}"
        );
        assert_eq!(
            not_destroyed["doesnotexist"]["type"], "notFound",
            "missing id must produce notFound: {resp}"
        );
    }

    /// Oracle: destroy of existing notification → appears in destroyed list.
    #[tokio::test]
    async fn set_destroy_existing_notification_succeeds() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_notification("acc1", "notif1");

        let args = json!({
            "accountId": "acc1",
            "destroy": ["notif1"]
        });
        let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
            .await
            .expect("must not return top-level error");

        let destroyed = resp["destroyed"]
            .as_array()
            .expect("destroyed must be array");
        assert_eq!(destroyed.len(), 1);
        assert_eq!(destroyed[0], "notif1");
    }
}