jmap_tasks_server/task_notification.rs
1//! [`TaskNotification`]/* method handlers (draft-tasks-06 §5).
2//!
3//! `TaskNotification`s 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 `HandlerOutput::extra_invocations` carries any 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 (RFC 8620
23//! §3.6.2 and §5):
24//!
25//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
26//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
27//! `maxObjectsInSet`;
28//! - `/set`: `stateMismatch`;
29//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
30//! - `/queryChanges`: `tooManyChanges`;
31//! - `/query`, `/queryChanges`: `unsupportedFilter`;
32//! - `/query`: `unsupportedSort`, `anchorNotFound`.
33//!
34//! Per-target failures inside `/set` surface in the `notDestroyed` map within
35//! `Ok((Value, ...))`, not as `Err`.
36
37use jmap_tasks_types::{TaskNotification, TaskNotificationComparator};
38use jmap_types::{Id, JmapError};
39use serde_json::Value;
40
41use crate::TasksBackend;
42use crate::helpers::{
43 SetAccumulators, enforce_max_objects_in_set, extract_account_id, finalize_set_response,
44 reject_unsupported_sort,
45};
46use jmap_server::{HandlerOutput, backend_set_error_value, server_fail_from_backend};
47use jmap_server::{SetError, SetErrorType};
48
49// ---------------------------------------------------------------------------
50// TaskNotification/get
51// ---------------------------------------------------------------------------
52
53/// Handle a `TaskNotification/get` method call (draft-tasks-06 §5.2).
54///
55/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
56/// `ids`, optional `properties`); the returned `Value` is the §5.1
57/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
58///
59/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
60///
61/// # Errors
62///
63/// Returns a method-level [`JmapError`]:
64///
65/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
66/// when `ids` or `properties` is malformed;
67/// - `accountNotFound` when the backend does not know `accountId`;
68/// - `requestTooLarge` when `ids` holds more than `maxObjectsInGet` ids;
69/// - `serverFail` when the backend fails.
70pub async fn handle_task_notification_get<B: TasksBackend>(
71 backend: &B,
72 caller: &B::CallerCtx,
73 args: Value,
74) -> Result<HandlerOutput, JmapError> {
75 jmap_server::handle_get::<TaskNotification, B>(backend, caller, args).await
76}
77
78// ---------------------------------------------------------------------------
79// TaskNotification/changes
80// ---------------------------------------------------------------------------
81
82/// Handle a `TaskNotification/changes` method call (draft-tasks-06 §5.3).
83///
84/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
85/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
86/// `/changes` response shape (`accountId`, `oldState`, `newState`,
87/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
88///
89/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
90///
91/// # Errors
92///
93/// Returns a method-level [`JmapError`]:
94///
95/// - `invalidArguments` when `accountId` is missing or not a valid Id,
96/// `sinceState` is missing, or `maxChanges` is not a positive integer;
97/// - `accountNotFound` when the backend does not know `accountId`;
98/// - `cannotCalculateChanges` when the backend cannot compute the changes
99/// since `sinceState`;
100/// - `serverFail` when the backend fails.
101pub async fn handle_task_notification_changes<B: TasksBackend>(
102 backend: &B,
103 caller: &B::CallerCtx,
104 args: Value,
105) -> Result<HandlerOutput, JmapError> {
106 jmap_server::handle_changes::<TaskNotification, B>(backend, caller, args, &[]).await
107}
108
109// ---------------------------------------------------------------------------
110// TaskNotification/set
111// ---------------------------------------------------------------------------
112
113/// Handle a `TaskNotification/set` method call (draft-tasks-06 §5.4).
114///
115/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
116/// `ifInState`, optional `create` / `update` / `destroy` maps); the
117/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
118/// `oldState`, `newState`, plus the per-operation result maps).
119///
120/// **Destroy-only enforcement**: draft-tasks-06 §5.4 states that only
121/// `destroy` is supported. Any entries in the `create` or `update` maps
122/// receive an immediate `forbidden` [`SetError`] without touching the backend.
123/// The `destroy` list is forwarded to the backend normally.
124///
125/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
126///
127/// # Errors
128///
129/// Returns a method-level [`JmapError`]:
130///
131/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
132/// when `destroy` is malformed;
133/// - `accountNotFound` when the backend does not know `accountId`;
134/// - `requestTooLarge` when `create`, `update` and `destroy` together hold
135/// more than `maxObjectsInSet` objects;
136/// - `stateMismatch` when `ifInState` is not the current state;
137/// - `serverFail` when the backend fails.
138///
139/// A create or update is a `forbidden` [`SetError`], and a destroy that
140/// fails on its own is a [`SetError`] in `notDestroyed`, not an `Err`.
141pub async fn handle_task_notification_set<B: TasksBackend>(
142 backend: &B,
143 caller: &B::CallerCtx,
144 args: Value,
145) -> Result<HandlerOutput, JmapError> {
146 let (account_id, mut args) = extract_account_id(args)?;
147
148 // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
149 // error). Without this, a /set against an unknown accountId would silently
150 // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
151 if !backend
152 .account_exists(caller, &account_id)
153 .await
154 .map_err(|e| server_fail_from_backend(&e))?
155 {
156 return Err(JmapError::account_not_found());
157 }
158
159 // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
160 // unbounded /set batches before touching the storage layer.
161 enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
162
163 let old_state = backend
164 .get_state::<TaskNotification>(caller, &account_id)
165 .await
166 .map_err(|e| server_fail_from_backend(&e))?;
167
168 if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
169 && if_in_state != old_state.as_ref()
170 {
171 return Err(JmapError::state_mismatch());
172 }
173
174 let ctx = SetCtx {
175 backend,
176 caller,
177 account_id: &account_id,
178 };
179 let mut acc = SetAccumulators::default();
180 set_create(&mut args, &mut acc);
181 set_update(&mut args, &mut acc);
182 let mutated = set_destroy(&ctx, &mut args, &mut acc).await?;
183
184 finalize_set_response::<B, TaskNotification>(
185 backend,
186 caller,
187 &account_id,
188 old_state,
189 mutated,
190 acc,
191 )
192 .await
193}
194
195/// What every `TaskNotification/set` sub-function needs from the request
196/// (docs/design/set-handler-split.md).
197struct SetCtx<'a, B: TasksBackend> {
198 backend: &'a B,
199 caller: &'a B::CallerCtx,
200 account_id: &'a Id,
201}
202
203/// The `create` part of `TaskNotification/set`: every entry is
204/// `forbidden`, since a [`TaskNotification`] is server-created only.
205fn set_create(args: &mut serde_json::Map<String, Value>, acc: &mut SetAccumulators) {
206 if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
207 for create_id in create_map.keys() {
208 acc.not_created.insert(
209 create_id.clone(),
210 serde_json::Value::from(&SetError::new(SetErrorType::Forbidden)),
211 );
212 }
213 }
214}
215
216/// The `update` part of `TaskNotification/set`: every entry is
217/// `forbidden`, since a [`TaskNotification`] is immutable.
218fn set_update(args: &mut serde_json::Map<String, Value>, acc: &mut SetAccumulators) {
219 if let Some(update_map) = args.get("update").and_then(|v| v.as_object()) {
220 for id_str in update_map.keys() {
221 acc.not_updated.insert(
222 id_str.clone(),
223 serde_json::Value::from(&SetError::new(SetErrorType::Forbidden)),
224 );
225 }
226 }
227}
228
229/// The `destroy` part of `TaskNotification/set`, the only permitted
230/// operation (draft-tasks-06 §5.4). Returns whether the backend was
231/// written.
232///
233/// # Errors
234///
235/// `invalidArguments` when an element of `destroy` is not a string.
236async fn set_destroy<B: TasksBackend>(
237 ctx: &SetCtx<'_, B>,
238 args: &mut serde_json::Map<String, Value>,
239 acc: &mut SetAccumulators,
240) -> Result<bool, JmapError> {
241 let mut mutated = false;
242 if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
243 // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
244 // Two-pass validation is intentional: this up-front loop fails the whole
245 // request loudly; the `None => continue` arm in the inner match below
246 // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
247 // delete this pre-check on the reasoning that the inner match handles
248 // non-string elements — silent-skip is the wrong behaviour per the
249 // workspace "silent-drop is a data-integrity bug class" rule
250 // (JMAP-wlip.1).
251 let id_strs: Vec<&str> = destroy_arr
252 .iter()
253 .map(|v| {
254 v.as_str().ok_or_else(|| {
255 JmapError::invalid_arguments(format!(
256 "destroy: every element must be a string Id; got {}",
257 jmap_server::json_type_name(v)
258 ))
259 })
260 })
261 .collect::<Result<_, _>>()?;
262 for id_str in id_strs {
263 let id_str = id_str.to_owned();
264 let id = match jmap_server::parse_wire_id(&id_str, "id") {
265 Ok(id) => id,
266 Err(err) => {
267 acc.not_destroyed
268 .insert(id_str, serde_json::Value::from(&*err));
269 continue;
270 }
271 };
272
273 match ctx
274 .backend
275 .destroy_object::<TaskNotification>(ctx.caller, ctx.account_id, &id)
276 .await
277 {
278 Ok(()) => {
279 mutated = true;
280 acc.destroyed.push(Value::String(id_str));
281 }
282 Err(e) => {
283 acc.not_destroyed.insert(id_str, backend_set_error_value(e));
284 }
285 }
286 }
287 }
288 Ok(mutated)
289}
290
291// ---------------------------------------------------------------------------
292// TaskNotification/query
293// ---------------------------------------------------------------------------
294
295/// Handle a `TaskNotification/query` method call (draft-tasks-06 §5.5).
296///
297/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
298/// optional `filter`, optional `sort`, optional `position`, optional
299/// `anchor`, optional `anchorOffset`, optional `limit`, optional
300/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
301/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
302/// `position`, `ids`, optional `total`).
303///
304/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
305///
306/// # Errors
307///
308/// Returns a method-level [`JmapError`]:
309///
310/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
311/// when `filter`, `sort`, `position`, `anchor`, `anchorOffset` or `limit`
312/// is malformed;
313/// - `accountNotFound` when the backend does not know `accountId`;
314/// - `unsupportedFilter` when the filter does not decode as a `TaskNotification` filter;
315/// - `unsupportedSort` when `sort` names a property that is not supported;
316/// - `serverFail` when the backend fails, or any other RFC 8620 §5.5 error
317/// the backend returns, such as `anchorNotFound`.
318pub async fn handle_task_notification_query<B: TasksBackend>(
319 backend: &B,
320 caller: &B::CallerCtx,
321 args: Value,
322) -> Result<HandlerOutput, JmapError> {
323 reject_unsupported_sort::<TaskNotificationComparator>(args.get("sort"))?;
324 jmap_server::handle_query::<TaskNotification, B>(backend, caller, args).await
325}
326
327// ---------------------------------------------------------------------------
328// TaskNotification/queryChanges
329// ---------------------------------------------------------------------------
330
331/// Handle a `TaskNotification/queryChanges` method call (draft-tasks-06 §5.6).
332///
333/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
334/// optional `filter`, optional `sort`, `sinceQueryState`, optional
335/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
336/// returned `Value` is the §5.6 `/queryChanges` response shape
337/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
338/// `removed`, `added`).
339///
340/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
341///
342/// # Errors
343///
344/// Returns a method-level [`JmapError`]:
345///
346/// - `invalidArguments` when `accountId` is missing or not a valid Id,
347/// `sinceQueryState` is missing, or `filter`, `sort`, `maxChanges` or
348/// `upToId` is malformed;
349/// - `accountNotFound` when the backend does not know `accountId`;
350/// - `unsupportedFilter` or `unsupportedSort` as for
351/// [`handle_task_notification_query`];
352/// - `cannotCalculateChanges` when `sinceQueryState` was computed in another
353/// language or the backend cannot compute the changes since it;
354/// - `tooManyChanges` when there are more changes than `maxChanges`;
355/// - `serverFail` when the backend fails.
356pub async fn handle_task_notification_query_changes<B: TasksBackend>(
357 backend: &B,
358 caller: &B::CallerCtx,
359 args: Value,
360) -> Result<HandlerOutput, JmapError> {
361 reject_unsupported_sort::<TaskNotificationComparator>(args.get("sort"))?;
362 jmap_server::handle_query_changes::<TaskNotification, B>(backend, caller, args).await
363}
364
365// ---------------------------------------------------------------------------
366// Tests
367// ---------------------------------------------------------------------------
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372 use serde_json::json;
373
374 use crate::test_support::MockBackend;
375
376 /// Oracle: RFC 8620 §5.5 `unsupportedSort`: "The sort is syntactically
377 /// valid, but includes a property the server does not support sorting
378 /// on". draft-ietf-jmap-tasks-06 §5.5.2: "The \"created\" property MUST be
379 /// supported for sorting." and lists no other; `taskId` is not among them.
380 #[tokio::test]
381 async fn query_unlisted_sort_property_returns_unsupported_sort() {
382 let backend = MockBackend::new_with_account("acc1");
383 let args = json!({ "accountId": "acc1", "sort": [{ "property": "taskId" }] });
384 let err = handle_task_notification_query(&backend, &(), args)
385 .await
386 .expect_err("unlisted sort property must be rejected");
387 assert_eq!(err.error_type.to_string(), "unsupportedSort");
388 }
389
390 /// Oracle: as above; `TaskNotification/queryChanges` carries the same `sort`
391 /// (RFC 8620 §5.6).
392 #[tokio::test]
393 async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
394 let backend = MockBackend::new_with_account("acc1");
395 let args = json!({
396 "accountId": "acc1",
397 "sinceQueryState": "0",
398 "sort": [{ "property": "created" }, { "property": "taskId" }]
399 });
400 let err = handle_task_notification_query_changes(&backend, &(), args)
401 .await
402 .expect_err("unlisted sort property must be rejected");
403 assert_eq!(err.error_type.to_string(), "unsupportedSort");
404 }
405
406 /// Oracle: draft-ietf-jmap-tasks-06 §5.5.2: "The \"created\" property MUST be
407 /// supported for sorting." and lists no other, so a `created` sort is accepted.
408 #[tokio::test]
409 async fn query_listed_sort_property_is_accepted() {
410 let backend = MockBackend::new_with_account("acc1");
411 let args = json!({ "accountId": "acc1", "sort": [{ "property": "created" }] });
412 handle_task_notification_query(&backend, &(), args)
413 .await
414 .expect("listed sort property must not be rejected");
415 }
416
417 /// Oracle: TaskNotification/set create entries must produce `forbidden` in notCreated.
418 /// No backend call is made for create (pure handler-layer enforcement).
419 #[tokio::test]
420 async fn set_create_returns_forbidden_not_created() {
421 let backend = MockBackend::new_with_account("acc1");
422 let args = json!({
423 "accountId": "acc1",
424 "create": {
425 "c1": {
426 "id": "ignored",
427 "created": "2024-01-01T00:00:00Z",
428 "changedBy": { "@type": "Person", "name": "Alice" },
429 "type": "created",
430 "taskId": "t1"
431 }
432 }
433 });
434 let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
435 .await
436 .expect("must not return top-level error");
437
438 let not_created = &resp["notCreated"];
439 assert!(
440 not_created.is_object(),
441 "notCreated must be present for create attempts: {resp}"
442 );
443 assert_eq!(
444 not_created["c1"]["type"], "forbidden",
445 "c1 create must be forbidden: {resp}"
446 );
447 assert!(
448 resp["created"].is_null(),
449 "created must be null when all creates are forbidden: {resp}"
450 );
451 }
452
453 /// Oracle: TaskNotification/set update entries must produce `forbidden` in notUpdated.
454 #[tokio::test]
455 async fn set_update_returns_forbidden_not_updated() {
456 let backend = MockBackend::new_with_account("acc1");
457 let args = json!({
458 "accountId": "acc1",
459 "update": {
460 "notif1": { "comment": "new comment" }
461 }
462 });
463 let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
464 .await
465 .expect("must not return top-level error");
466
467 let not_updated = &resp["notUpdated"];
468 assert!(
469 not_updated.is_object(),
470 "notUpdated must be present for update attempts: {resp}"
471 );
472 assert_eq!(not_updated["notif1"]["type"], "forbidden");
473 }
474
475 /// Oracle: destroy of a non-existent notification → notFound in notDestroyed.
476 #[tokio::test]
477 async fn set_destroy_nonexistent_returns_not_found() {
478 let backend = MockBackend::new_with_account("acc1");
479 let args = json!({
480 "accountId": "acc1",
481 "destroy": ["doesnotexist"]
482 });
483 let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
484 .await
485 .expect("must not return top-level error");
486
487 let not_destroyed = &resp["notDestroyed"];
488 assert!(
489 not_destroyed.is_object(),
490 "notDestroyed must be present: {resp}"
491 );
492 assert_eq!(
493 not_destroyed["doesnotexist"]["type"], "notFound",
494 "missing id must produce notFound: {resp}"
495 );
496 }
497
498 /// Oracle: destroy of existing notification → appears in destroyed list.
499 #[tokio::test]
500 async fn set_destroy_existing_notification_succeeds() {
501 let mut backend = MockBackend::new_with_account("acc1");
502 backend.add_notification("acc1", "notif1");
503
504 let args = json!({
505 "accountId": "acc1",
506 "destroy": ["notif1"]
507 });
508 let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
509 .await
510 .expect("must not return top-level error");
511
512 let destroyed = resp["destroyed"]
513 .as_array()
514 .expect("destroyed must be array");
515 assert_eq!(destroyed.len(), 1);
516 assert_eq!(destroyed[0], "notif1");
517 }
518}