Skip to main content

jmap_tasks_server/
task_notification.rs

1//! TaskNotification/* method handlers (draft-tasks-06 §5).
2//!
3//! TaskNotifications are server-created immutable records. Clients may only
4//! query and destroy them. Any attempt to create or update a TaskNotification
5//! via `/set` MUST be rejected with `forbidden` at the handler layer — the
6//! backend never sees create or update calls for this type.
7//!
8//! # Wire-shape contract
9//!
10//! Every `handle_*` function in this module conforms to the canonical JMAP
11//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
12//! Object whose fields match the corresponding RFC 8620 §5 method shape
13//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3,
14//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
15//! arguments defined by draft-tasks-06 §5. The returned `Value` is the
16//! corresponding method-response object per the same section refs.
17//!
18//! The returned `Vec<Invocation>` carries any back-reference invocations
19//! that this handler injected into the request stream (RFC 8620 §6.3);
20//! for the handlers in this module the vector is **always empty**.
21//!
22//! Each handler returns `Err(JmapError)` for method-level failures
23//! (`accountNotFound`, `invalidArguments`, `stateMismatch`, `serverFail`,
24//! `unsupportedFilter`, `unsupportedSort`, `cannotCalculateChanges` —
25//! per RFC 8620 §3.6 and §5). Per-target failures inside `/set` surface
26//! in the `notDestroyed` map within `Ok((Value, ...))`, not as `Err`.
27
28use jmap_tasks_types::TaskNotification;
29use jmap_types::{Id, Invocation, JmapError};
30use serde_json::Value;
31
32use crate::backend::{BackendSetError, SetError, SetErrorType, TasksBackend};
33use crate::helpers::{
34    enforce_max_objects_in_set, extract_account_id, finalize_set_response, set_error_value,
35    SetAccumulators,
36};
37use jmap_server::{server_fail_from_backend, server_fail_value_from_backend};
38
39// ---------------------------------------------------------------------------
40// TaskNotification/get
41// ---------------------------------------------------------------------------
42
43/// Handle a `TaskNotification/get` method call (draft-tasks-06 §5.2).
44///
45/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
46/// `ids`, optional `properties`); the returned `Value` is the §5.1
47/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
48///
49/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
50pub async fn handle_task_notification_get<B: TasksBackend>(
51    backend: &B,
52    caller: &B::CallerCtx,
53    args: Value,
54) -> Result<(Value, Vec<Invocation>), JmapError> {
55    jmap_server::handlers::handle_get::<TaskNotification, B>(backend, caller, args).await
56}
57
58// ---------------------------------------------------------------------------
59// TaskNotification/changes
60// ---------------------------------------------------------------------------
61
62/// Handle a `TaskNotification/changes` method call (draft-tasks-06 §5.3).
63///
64/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
65/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
66/// `/changes` response shape (`accountId`, `oldState`, `newState`,
67/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
68///
69/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
70pub async fn handle_task_notification_changes<B: TasksBackend>(
71    backend: &B,
72    caller: &B::CallerCtx,
73    args: Value,
74) -> Result<(Value, Vec<Invocation>), JmapError> {
75    jmap_server::handlers::handle_changes::<TaskNotification, B>(backend, caller, args).await
76}
77
78// ---------------------------------------------------------------------------
79// TaskNotification/set
80// ---------------------------------------------------------------------------
81
82/// Handle a `TaskNotification/set` method call (draft-tasks-06 §5.4).
83///
84/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
85/// `ifInState`, optional `create` / `update` / `destroy` maps); the
86/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
87/// `oldState`, `newState`, plus the per-operation result maps).
88///
89/// **Destroy-only enforcement**: draft-tasks-06 §5.4 states that only
90/// `destroy` is supported. Any entries in the `create` or `update` maps
91/// receive an immediate `forbidden` SetError without touching the backend.
92/// The `destroy` list is forwarded to the backend normally.
93///
94/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
95pub async fn handle_task_notification_set<B: TasksBackend>(
96    backend: &B,
97    caller: &B::CallerCtx,
98    args: Value,
99) -> Result<(Value, Vec<Invocation>), JmapError> {
100    let (account_id, mut args) = extract_account_id(args)?;
101
102    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
103    // error). Without this, a /set against an unknown accountId would silently
104    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
105    if !backend
106        .account_exists(caller, &account_id)
107        .await
108        .map_err(|e| server_fail_from_backend(&e))?
109    {
110        return Err(JmapError::account_not_found());
111    }
112
113    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
114    // unbounded /set batches before touching the storage layer.
115    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
116
117    let old_state = backend
118        .get_state::<TaskNotification>(caller, &account_id)
119        .await
120        .map_err(|e| server_fail_from_backend(&e))?;
121
122    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
123        if if_in_state != old_state.as_ref() {
124            return Err(JmapError::state_mismatch());
125        }
126    }
127
128    let created = serde_json::Map::new();
129    let mut not_created = serde_json::Map::new();
130    let updated = serde_json::Map::new();
131    let mut not_updated = serde_json::Map::new();
132    let mut destroyed_list: Vec<Value> = Vec::new();
133    let mut not_destroyed = serde_json::Map::new();
134    let mut mutated = false;
135
136    // -----------------------------------------------------------------------
137    // create — forbidden: TaskNotification is server-created only
138    // -----------------------------------------------------------------------
139    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
140        for create_id in create_map.keys() {
141            not_created.insert(
142                create_id.clone(),
143                set_error_value(&SetError::new(SetErrorType::Forbidden)),
144            );
145        }
146    }
147
148    // -----------------------------------------------------------------------
149    // update — forbidden: TaskNotification is immutable
150    // -----------------------------------------------------------------------
151    if let Some(update_map) = args.get("update").and_then(|v| v.as_object()) {
152        for id_str in update_map.keys() {
153            not_updated.insert(
154                id_str.clone(),
155                set_error_value(&SetError::new(SetErrorType::Forbidden)),
156            );
157        }
158    }
159
160    // -----------------------------------------------------------------------
161    // destroy — the only permitted operation (draft-tasks-06 §5.4)
162    // -----------------------------------------------------------------------
163    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
164        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
165        // Two-pass validation is intentional: this up-front loop fails the whole
166        // request loudly; the `None => continue` arm in the inner match below
167        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
168        // delete this pre-check on the reasoning that the inner match handles
169        // non-string elements — silent-skip is the wrong behaviour per the
170        // workspace "silent-drop is a data-integrity bug class" rule
171        // (JMAP-wlip.1).
172        if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
173            return Err(JmapError::invalid_arguments(format!(
174                "destroy: every element must be a string Id; got {bad}"
175            )));
176        }
177        for id_val in destroy_arr {
178            let id_str = match id_val.as_str() {
179                Some(s) => s.to_owned(),
180                None => continue, // unreachable: validated above
181            };
182            // Id::from: wire-boundary validation deferred to JMAP-k9va; backend rejects unknown IDs.
183            let id = Id::from(id_str.as_str());
184
185            match backend
186                .destroy_object::<TaskNotification>(caller, &account_id, &id)
187                .await
188            {
189                Ok(()) => {
190                    mutated = true;
191                    destroyed_list.push(Value::String(id_str));
192                }
193                Err(BackendSetError::SetError(set_err)) => {
194                    not_destroyed.insert(id_str, set_error_value(&set_err));
195                }
196                Err(BackendSetError::Other(e)) => {
197                    not_destroyed.insert(id_str, server_fail_value_from_backend(&e));
198                }
199                Err(other) => {
200                    not_destroyed.insert(id_str, server_fail_value_from_backend(&other));
201                }
202            }
203        }
204    }
205
206    finalize_set_response::<B, TaskNotification>(
207        backend,
208        caller,
209        &account_id,
210        old_state,
211        mutated,
212        SetAccumulators {
213            created,
214            updated,
215            destroyed: destroyed_list,
216            not_created,
217            not_updated,
218            not_destroyed,
219        },
220    )
221    .await
222}
223
224// ---------------------------------------------------------------------------
225// TaskNotification/query
226// ---------------------------------------------------------------------------
227
228/// Handle a `TaskNotification/query` method call (draft-tasks-06 §5.5).
229///
230/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
231/// optional `filter`, optional `sort`, optional `position`, optional
232/// `anchor`, optional `anchorOffset`, optional `limit`, optional
233/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
234/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
235/// `position`, `ids`, optional `total`).
236///
237/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
238pub async fn handle_task_notification_query<B: TasksBackend>(
239    backend: &B,
240    caller: &B::CallerCtx,
241    args: Value,
242) -> Result<(Value, Vec<Invocation>), JmapError> {
243    jmap_server::handlers::handle_query::<TaskNotification, B>(backend, caller, args).await
244}
245
246// ---------------------------------------------------------------------------
247// TaskNotification/queryChanges
248// ---------------------------------------------------------------------------
249
250/// Handle a `TaskNotification/queryChanges` method call (draft-tasks-06 §5.6).
251///
252/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
253/// optional `filter`, optional `sort`, `sinceQueryState`, optional
254/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
255/// returned `Value` is the §5.6 `/queryChanges` response shape
256/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
257/// `removed`, `added`).
258///
259/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
260pub async fn handle_task_notification_query_changes<B: TasksBackend>(
261    backend: &B,
262    caller: &B::CallerCtx,
263    args: Value,
264) -> Result<(Value, Vec<Invocation>), JmapError> {
265    jmap_server::handlers::handle_query_changes::<TaskNotification, B>(backend, caller, args).await
266}
267
268// ---------------------------------------------------------------------------
269// Tests
270// ---------------------------------------------------------------------------
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use serde_json::json;
276
277    use crate::test_support::MockBackend;
278
279    /// Oracle: TaskNotification/set create entries must produce `forbidden` in notCreated.
280    /// No backend call is made for create (pure handler-layer enforcement).
281    #[tokio::test]
282    async fn set_create_returns_forbidden_not_created() {
283        let backend = MockBackend::new_with_account("acc1");
284        let args = json!({
285            "accountId": "acc1",
286            "create": {
287                "c1": {
288                    "id": "ignored",
289                    "created": "2024-01-01T00:00:00Z",
290                    "changedBy": { "@type": "Person", "name": "Alice" },
291                    "type": "created",
292                    "taskId": "t1"
293                }
294            }
295        });
296        let (resp, _) = handle_task_notification_set(&backend, &(), args)
297            .await
298            .expect("must not return top-level error");
299
300        let not_created = &resp["notCreated"];
301        assert!(
302            not_created.is_object(),
303            "notCreated must be present for create attempts: {resp}"
304        );
305        assert_eq!(
306            not_created["c1"]["type"], "forbidden",
307            "c1 create must be forbidden: {resp}"
308        );
309        assert!(
310            resp["created"].is_null(),
311            "created must be null when all creates are forbidden: {resp}"
312        );
313    }
314
315    /// Oracle: TaskNotification/set update entries must produce `forbidden` in notUpdated.
316    #[tokio::test]
317    async fn set_update_returns_forbidden_not_updated() {
318        let backend = MockBackend::new_with_account("acc1");
319        let args = json!({
320            "accountId": "acc1",
321            "update": {
322                "notif1": { "comment": "new comment" }
323            }
324        });
325        let (resp, _) = handle_task_notification_set(&backend, &(), args)
326            .await
327            .expect("must not return top-level error");
328
329        let not_updated = &resp["notUpdated"];
330        assert!(
331            not_updated.is_object(),
332            "notUpdated must be present for update attempts: {resp}"
333        );
334        assert_eq!(not_updated["notif1"]["type"], "forbidden");
335    }
336
337    /// Oracle: destroy of a non-existent notification → notFound in notDestroyed.
338    #[tokio::test]
339    async fn set_destroy_nonexistent_returns_not_found() {
340        let backend = MockBackend::new_with_account("acc1");
341        let args = json!({
342            "accountId": "acc1",
343            "destroy": ["doesnotexist"]
344        });
345        let (resp, _) = handle_task_notification_set(&backend, &(), args)
346            .await
347            .expect("must not return top-level error");
348
349        let not_destroyed = &resp["notDestroyed"];
350        assert!(
351            not_destroyed.is_object(),
352            "notDestroyed must be present: {resp}"
353        );
354        assert_eq!(
355            not_destroyed["doesnotexist"]["type"], "notFound",
356            "missing id must produce notFound: {resp}"
357        );
358    }
359
360    /// Oracle: destroy of existing notification → appears in destroyed list.
361    #[tokio::test]
362    async fn set_destroy_existing_notification_succeeds() {
363        let mut backend = MockBackend::new_with_account("acc1");
364        backend.add_notification("acc1", "notif1");
365
366        let args = json!({
367            "accountId": "acc1",
368            "destroy": ["notif1"]
369        });
370        let (resp, _) = handle_task_notification_set(&backend, &(), args)
371            .await
372            .expect("must not return top-level error");
373
374        let destroyed = resp["destroyed"]
375            .as_array()
376            .expect("destroyed must be array");
377        assert_eq!(destroyed.len(), 1);
378        assert_eq!(destroyed[0], "notif1");
379    }
380}