Skip to main content

jmap_chat_server/
message.rs

1//! Message/* method handlers (draft-atwood-jmap-chat-00 §Message).
2//!
3//! # Wire-shape contract
4//!
5//! Every `handle_*` function in this module conforms to the canonical JMAP
6//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
7//! Object whose fields match the corresponding RFC 8620 §5 method shape
8//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3,
9//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
10//! arguments defined by draft-atwood-jmap-chat-00 §Message. The
11//! returned `Value` is the corresponding method-response object per the
12//! same section refs.
13//!
14//! The returned `Vec<Invocation>` carries any back-reference invocations
15//! that this handler injected into the request stream (RFC 8620 §6.3);
16//! for the handlers in this module the vector is **always empty**.
17//!
18//! Each handler returns `Err(JmapError)` for method-level failures
19//! (`accountNotFound`, `invalidArguments`, `stateMismatch`, `serverFail`,
20//! `unsupportedFilter`, `unsupportedSort`, `cannotCalculateChanges` —
21//! per RFC 8620 §3.6 and §5). Per-target failures inside `/set`
22//! (including the `slow_mode_check` `rateLimited` and reaction-patch
23//! `invalidPatch` paths) surface in the `notCreated` / `notUpdated` /
24//! `notDestroyed` maps within `Ok((Value, ...))`, not as `Err`.
25
26use jmap_chat_types::{DeliveryState, Message, SenderId};
27use jmap_types::{Id, Invocation, JmapError, PatchObject, State, UTCDate};
28use serde_json::{json, Value};
29
30use crate::backend::{BackendSetError, ChatBackend, SetError, SetErrorType};
31use std::collections::HashSet;
32
33use crate::helpers::{
34    enforce_max_objects_in_set, extract_account_id, filter_properties, finalize_set_response,
35    iso8601_before, not_found_json, now_utc_string, serialize_value, set_error_value,
36    SetAccumulators,
37};
38use jmap_server::{server_fail_from_backend, server_fail_value_from_backend};
39
40// ---------------------------------------------------------------------------
41// Message/get
42// ---------------------------------------------------------------------------
43
44/// Handle a `Message/get` method call (draft-atwood-jmap-chat-00 §Message).
45///
46/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
47/// `ids`, optional `properties`); the returned `Value` is the §5.1
48/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
49///
50/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
51pub async fn handle_message_get<B: ChatBackend>(
52    backend: &B,
53    caller: &B::CallerCtx,
54    args: Value,
55) -> Result<(Value, Vec<Invocation>), JmapError> {
56    let (account_id, mut args) = extract_account_id(args)?;
57
58    let ids: Option<Vec<Id>> = match args.remove("ids") {
59        None | Some(Value::Null) => None,
60        Some(v) => Some(
61            serde_json::from_value(v)
62                .map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
63        ),
64    };
65
66    // RFC 8620 §5.1: when `properties` is specified, return only those fields
67    // (plus `id` which is always included). `None` means return all fields.
68    let properties: Option<Vec<String>> = match args.remove("properties") {
69        None | Some(Value::Null) => None,
70        Some(v) => Some(
71            serde_json::from_value(v)
72                .map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
73        ),
74    };
75
76    let ids_slice = ids.as_deref();
77    let (mut list, not_found) = backend
78        .get_objects::<Message>(caller, &account_id, ids_slice, properties.as_deref())
79        .await
80        .map_err(|e| server_fail_from_backend(&e))?;
81
82    // Edit-history retention gate (draft-atwood-jmap-chat-00 commit
83    // `0783fc4` + §Message editHistory). When the backend does not
84    // retain edit history, the `editHistory` field MUST be omitted
85    // from every returned Message. Setting `edit_history = None`
86    // here causes serde's `skip_serializing_if = "Option::is_none"`
87    // to collapse it on the wire, satisfying the spec MUST.
88    //
89    // `Message/changes` per RFC 8620 §5.2 returns id arrays only
90    // (no Message objects), so the spec's "omit from /changes" has
91    // no wire-level effect — only `Message/get` needs this gate.
92    if !backend.retains_edit_history() {
93        for msg in list.iter_mut() {
94            msg.edit_history = None;
95        }
96    }
97
98    let state = backend
99        .get_state::<Message>(caller, &account_id)
100        .await
101        .map_err(|e| server_fail_from_backend(&e))?;
102
103    let list_json: Vec<Value> = if let Some(ref props) = properties {
104        let mut prop_set: HashSet<&str> = props.iter().map(|s| s.as_str()).collect();
105        prop_set.insert("id");
106        list.iter()
107            .map(|obj| {
108                let val = serialize_value(obj)?;
109                Ok(filter_properties(&val, &prop_set))
110            })
111            .collect::<Result<Vec<_>, JmapError>>()?
112    } else {
113        list.iter()
114            .map(serialize_value)
115            .collect::<Result<Vec<_>, _>>()?
116    };
117
118    Ok((
119        json!({
120            "accountId": account_id.as_ref(),
121            "state": state.as_ref(),
122            "list": list_json,
123            "notFound": not_found_json(&not_found),
124        }),
125        vec![],
126    ))
127}
128
129// ---------------------------------------------------------------------------
130// Message/changes
131// ---------------------------------------------------------------------------
132
133/// Handle a `Message/changes` method call (draft-atwood-jmap-chat-00 §Message).
134///
135/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
136/// `sinceState`, optional `maxChanges`); the returned `Value` is the
137/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
138/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
139///
140/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
141pub async fn handle_message_changes<B: ChatBackend>(
142    backend: &B,
143    caller: &B::CallerCtx,
144    args: Value,
145) -> Result<(Value, Vec<Invocation>), JmapError> {
146    jmap_server::handlers::handle_changes::<Message, B>(backend, caller, args).await
147}
148
149// ---------------------------------------------------------------------------
150// Message/query
151// ---------------------------------------------------------------------------
152
153/// Handle a `Message/query` method call (draft-atwood-jmap-chat-00 §Message).
154///
155/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`, optional
156/// `filter`, optional `sort`, optional `position` / `anchor` /
157/// `anchorOffset`, optional `limit`, optional `calculateTotal`); the
158/// returned `Value` is the §5.5 `/query` response shape (`accountId`,
159/// `queryState`, `canCalculateChanges`, `position`, `ids`, optional
160/// `total`, optional `limit`).
161///
162/// Filter and sort are passed through to the backend unchanged.
163///
164/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
165pub async fn handle_message_query<B: ChatBackend>(
166    backend: &B,
167    caller: &B::CallerCtx,
168    args: Value,
169) -> Result<(Value, Vec<Invocation>), JmapError> {
170    let (account_id, mut args) = extract_account_id(args)?;
171
172    let calculate_total: bool = args
173        .get("calculateTotal")
174        .and_then(|v| v.as_bool())
175        .unwrap_or(false);
176
177    let limit: Option<u64> = match args.remove("limit") {
178        None | Some(Value::Null) => None,
179        Some(v) => match v.as_u64() {
180            Some(n) => Some(n),
181            None => {
182                return Err(JmapError::invalid_arguments(format!(
183                    "limit: expected a non-negative integer, got {v}"
184                )))
185            }
186        },
187    };
188
189    let position: i64 = match args.remove("position") {
190        None | Some(Value::Null) => 0,
191        Some(v) => v.as_i64().ok_or_else(|| {
192            JmapError::invalid_arguments(format!("position: expected an integer, got {v}"))
193        })?,
194    };
195
196    let filter: Option<serde_json::Value> = match args.remove("filter") {
197        None | Some(Value::Null) => None,
198        Some(v) => Some(v),
199    };
200
201    // JMAP Chat spec §Message — chatId filter is required unless hasMention: true.
202    let has_chat_id = filter
203        .as_ref()
204        .and_then(|f| f.get("chatId"))
205        .map(|v| !v.is_null())
206        .unwrap_or(false);
207    let has_mention_true = filter
208        .as_ref()
209        .and_then(|f| f.get("hasMention"))
210        .and_then(|v| v.as_bool())
211        .unwrap_or(false);
212    if !has_chat_id && !has_mention_true {
213        return Err(JmapError::unsupported_filter());
214    }
215
216    let sort: Option<Vec<serde_json::Value>> = match args.remove("sort") {
217        None | Some(Value::Null) => None,
218        Some(v) => Some(
219            serde_json::from_value(v)
220                .map_err(|_| JmapError::invalid_arguments("sort must be an array"))?,
221        ),
222    };
223
224    let result = backend
225        .query_objects::<Message>(
226            caller,
227            &account_id,
228            filter.as_ref(),
229            sort.as_deref(),
230            limit,
231            position,
232        )
233        .await
234        .map_err(|e| server_fail_from_backend(&e))?;
235
236    let mut resp = json!({
237        "accountId": account_id.as_ref(),
238        "queryState": result.query_state.as_ref(),
239        "canCalculateChanges": result.can_calculate_changes,
240        "position": result.position,
241        "ids": result.ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
242    });
243    if calculate_total {
244        if let Some(t) = result.total {
245            resp["total"] = json!(t);
246        }
247    }
248
249    Ok((resp, vec![]))
250}
251
252// ---------------------------------------------------------------------------
253// Message/queryChanges
254// ---------------------------------------------------------------------------
255
256/// Handle a `Message/queryChanges` method call (draft-atwood-jmap-chat-00 §Message).
257///
258/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
259/// optional `filter`, optional `sort`, `sinceQueryState`, optional
260/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
261/// returned `Value` is the §5.6 `/queryChanges` response shape
262/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
263/// `removed`, `added`).
264///
265/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
266pub async fn handle_message_query_changes<B: ChatBackend>(
267    backend: &B,
268    caller: &B::CallerCtx,
269    args: Value,
270) -> Result<(Value, Vec<Invocation>), JmapError> {
271    let (account_id, args) = extract_account_id(args)?;
272
273    let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
274        Some(s) => State::from(s),
275        None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
276    };
277
278    let max_changes: Option<u64> = match args.get("maxChanges") {
279        None | Some(Value::Null) => None,
280        Some(v) => Some(v.as_u64().filter(|&n| n > 0).ok_or_else(|| {
281            JmapError::invalid_arguments("maxChanges must be a positive integer")
282        })?),
283    };
284
285    let up_to_id: Option<Id> = match args.get("upToId") {
286        None | Some(Value::Null) => None,
287        // Id::from: wire-boundary validation deferred to JMAP-k9va; backend rejects unknown IDs.
288        Some(Value::String(s)) => Some(Id::from(s.as_str())),
289        Some(_) => {
290            return Err(JmapError::invalid_arguments(
291                "upToId must be a string Id or null",
292            ))
293        }
294    };
295
296    let calculate_total: bool = args
297        .get("calculateTotal")
298        .and_then(|v| v.as_bool())
299        .unwrap_or(false);
300
301    let result = backend
302        .query_changes::<Message>(
303            caller,
304            &account_id,
305            &since_query_state,
306            None,
307            None,
308            max_changes,
309            up_to_id.as_ref(),
310            false,
311        )
312        .await
313        .map_err(JmapError::from)?;
314
315    let removed: Vec<&str> = result.removed.iter().map(|id| id.as_ref()).collect();
316    let added: Vec<Value> = result
317        .added
318        .iter()
319        .map(|item| {
320            json!({
321                "id": item.id.as_ref(),
322                "index": item.index,
323            })
324        })
325        .collect();
326
327    let mut resp = json!({
328        "accountId": account_id.as_ref(),
329        "oldQueryState": result.old_query_state.as_ref(),
330        "newQueryState": result.new_query_state.as_ref(),
331        "removed": removed,
332        "added": added,
333    });
334    if calculate_total {
335        if let Some(t) = result.total {
336            resp["total"] = json!(t);
337        }
338    }
339
340    Ok((resp, vec![]))
341}
342
343// ---------------------------------------------------------------------------
344// Message/set
345// ---------------------------------------------------------------------------
346
347/// Handle a `Message/set` method call (draft-atwood-jmap-chat-00 §Message).
348///
349/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
350/// `ifInState`, optional `create` / `update` / `destroy` maps); the
351/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
352/// `oldState`, `newState`, plus the per-operation `created` /
353/// `notCreated` / `updated` / `notUpdated` / `destroyed` / `notDestroyed`
354/// maps).
355///
356/// Validation enforced here (not in the backend):
357/// - `chatId` and `body` are required on create.
358/// - `id`, `senderMsgId`, `senderId`, `sentAt`, `receivedAt`, `deliveryState`
359///   are server-set and rejected in updates.
360///
361/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
362pub async fn handle_message_set<B: ChatBackend>(
363    backend: &B,
364    caller: &B::CallerCtx,
365    args: Value,
366) -> Result<(Value, Vec<Invocation>), JmapError> {
367    let (account_id, mut args) = extract_account_id(args)?;
368
369    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
370    // unbounded /set batches before touching the storage layer.
371    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
372
373    let old_state = backend
374        .get_state::<Message>(caller, &account_id)
375        .await
376        .map_err(|e| server_fail_from_backend(&e))?;
377
378    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
379        if if_in_state != old_state.as_ref() {
380            return Err(JmapError::state_mismatch());
381        }
382    }
383
384    let mut created = serde_json::Map::new();
385    let mut not_created = serde_json::Map::new();
386    let mut updated = serde_json::Map::new();
387    let mut not_updated = serde_json::Map::new();
388    let mut destroyed_list: Vec<Value> = Vec::new();
389    let mut not_destroyed = serde_json::Map::new();
390    let mut mutated = false;
391
392    // -----------------------------------------------------------------------
393    // create
394    // -----------------------------------------------------------------------
395    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
396        for (create_id, obj_val) in create_map {
397            let Some(chat_id_str) = obj_val.get("chatId").and_then(|v| v.as_str()) else {
398                not_created.insert(
399                    create_id.clone(),
400                    json!({ "type": "invalidProperties", "properties": ["chatId"] }),
401                );
402                continue;
403            };
404            let chat_id = Id::from(chat_id_str);
405
406            let Some(body) = obj_val
407                .get("body")
408                .and_then(|v| v.as_str())
409                .map(str::to_owned)
410            else {
411                not_created.insert(
412                    create_id.clone(),
413                    json!({ "type": "invalidProperties", "properties": ["body"] }),
414                );
415                continue;
416            };
417            if body.len() > 100_000 {
418                not_created.insert(
419                    create_id.clone(),
420                    json!({ "type": "invalidProperties", "properties": ["body"] }),
421                );
422                continue;
423            }
424
425            // sentAt is a UTCDate per RFC 8620 §1.4 (20-char
426            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
427            // UTCDate::new_validated; a malformed value produces
428            // invalidProperties rather than silently flowing through
429            // to storage where downstream lex-compares and slice ops
430            // (helpers::iso8601_before) assume a validated 20-byte
431            // ASCII shape.
432            let Some(sent_at_str) = obj_val.get("sentAt").and_then(|v| v.as_str()) else {
433                not_created.insert(
434                    create_id.clone(),
435                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
436                );
437                continue;
438            };
439            let Ok(sent_at) = UTCDate::new_validated(sent_at_str) else {
440                not_created.insert(
441                    create_id.clone(),
442                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
443                );
444                continue;
445            };
446
447            let body_type = obj_val
448                .get("bodyType")
449                .and_then(|v| v.as_str())
450                .unwrap_or("text/plain")
451                .to_owned();
452
453            let reply_to: Option<Id> = obj_val
454                .get("replyTo")
455                .and_then(|v| v.as_str())
456                .map(Id::from);
457
458            let thread_root_id: Option<Id> = obj_val
459                .get("threadRootId")
460                .and_then(|v| v.as_str())
461                .map(Id::from);
462
463            // senderExpiresAt is a UTCDate per RFC 8620 §1.4 (20-char
464            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
465            // UTCDate::new_validated; a malformed value produces
466            // invalidProperties rather than silently flowing through to
467            // a downstream string compare with undefined ordering.
468            let sender_expires_at: Option<UTCDate> =
469                if let Some(s) = obj_val.get("senderExpiresAt").and_then(|v| v.as_str()) {
470                    let Ok(d) = UTCDate::new_validated(s) else {
471                        not_created.insert(
472                            create_id.clone(),
473                            json!({
474                                "type": "invalidProperties",
475                                "properties": ["senderExpiresAt"],
476                            }),
477                        );
478                        continue;
479                    };
480                    Some(d)
481                } else {
482                    None
483                };
484
485            let burn_on_read: Option<bool> = obj_val.get("burnOnRead").and_then(|v| v.as_bool());
486
487            if let Some(ref expires_at) = sender_expires_at {
488                let now = now_utc_string();
489                if !iso8601_before(&now, expires_at) {
490                    not_created.insert(
491                        create_id.clone(),
492                        json!({ "type": "invalidProperties", "properties": ["senderExpiresAt"] }),
493                    );
494                    continue;
495                }
496            }
497
498            // Slow-mode rate-limit gate (draft-atwood-jmap-chat-00
499            // §Chat `slowModeSeconds` + spec commit `de60acb`).
500            //
501            // Runs AFTER wire-format validation so malformed requests
502            // don't consume rate-tracker slots, and BEFORE the
503            // `create_object` call so a throttled sender never sees the
504            // message touch storage. On a Throttled return the backend
505            // tells us when the caller may retry; we surface that
506            // verbatim as the `serverRetryAfter` extra field on the
507            // `rateLimited` SetError, built via the typed
508            // `SetError::with_extra` builder added in bd:JMAP-dha0.
509            // `serverRetryAfter` is the workspace convention paired
510            // with `rateLimited` (read by
511            // `jmap_chat_client::server_retry_after` on the client
512            // side); `SetErrorType::custom("rateLimited")` produces
513            // the spec wire string. The reference `MemoryBackend`
514            // never returns an Err here.
515            if let Err(slow_err) = backend.slow_mode_check(caller, &account_id, &chat_id).await {
516                let retry_after_str: String = slow_err.retry_after.as_ref().to_owned();
517                let set_err = SetError::new(SetErrorType::custom("rateLimited"))
518                    .with_description("Slow mode is active for this chat")
519                    .with_extra("serverRetryAfter", json!(retry_after_str));
520                not_created.insert(create_id.clone(), set_error_value(&set_err));
521                continue;
522            }
523
524            let now_str = now_utc_string();
525            let received_at: UTCDate = UTCDate::from(now_str.as_ref());
526
527            let mut msg = Message::new(
528                Id::from("placeholder"),
529                Id::from(create_id.as_str()),
530                SenderId::Owner,
531                chat_id,
532                body,
533                body_type,
534                sent_at,
535                received_at,
536                DeliveryState::Pending,
537            );
538
539            msg.reply_to = reply_to;
540            msg.thread_root_id = thread_root_id;
541            if let Some(d) = sender_expires_at {
542                msg.sender_expires_at = Some(d);
543            }
544            msg.burn_on_read = burn_on_read;
545
546            match backend
547                .create_object::<Message>(caller, &account_id, create_id, msg)
548                .await
549            {
550                Ok((_server_id, created_obj)) => {
551                    mutated = true;
552                    created.insert(
553                        create_id.clone(),
554                        serde_json::to_value(&created_obj)
555                            .expect("derive(Serialize) on plain data is infallible"),
556                    );
557                }
558                Err(BackendSetError::SetError(set_err)) => {
559                    not_created.insert(create_id.clone(), set_error_value(&set_err));
560                }
561                Err(BackendSetError::Other(e)) => {
562                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
563                }
564                Err(_) => {
565                    not_created.insert(
566                        create_id.clone(),
567                        json!({
568                            "type": "serverFail",
569                            "description": "unhandled backend error variant",
570                        }),
571                    );
572                }
573            }
574        }
575    }
576
577    // -----------------------------------------------------------------------
578    // update
579    // -----------------------------------------------------------------------
580    if let Some(Value::Object(update_map)) = args.remove("update") {
581        for (id_str, patch_val) in update_map {
582            let id = Id::from(id_str.as_str());
583
584            // Reject patches that include server-set fields.
585            // MAINTENANCE: when adding a server-set field to Message in
586            // jmap-chat-types, add its wire name here too.  A missing entry
587            // silently allows clients to overwrite server-managed state.
588            const MESSAGE_READONLY: &[&str] = &[
589                "id",
590                "senderMsgId",
591                "senderId",
592                "chatId",
593                "sentAt",
594                "receivedAt",
595                "deliveryState",
596            ];
597            let bad_props: Vec<&str> = MESSAGE_READONLY
598                .iter()
599                .copied()
600                .filter(|&field| patch_val.get(field).is_some())
601                .collect();
602            if !bad_props.is_empty() {
603                not_updated.insert(
604                    id_str,
605                    json!({ "type": "invalidProperties", "properties": bad_props }),
606                );
607                continue;
608            }
609
610            // Build augmented patch with server-side timestamps.
611            let mut augmented = patch_val;
612            if augmented.get("body").is_some() {
613                if let Some(obj) = augmented.as_object_mut() {
614                    obj.insert("editedAt".to_owned(), json!(now_utc_string()));
615                }
616            }
617            if augmented.get("deletedForAll").and_then(|v| v.as_bool()) == Some(true) {
618                if let Some(obj) = augmented.as_object_mut() {
619                    obj.insert("deletedAt".to_owned(), json!(now_utc_string()));
620                }
621            }
622            // Spec §557 + §1029: when readAt is set without readDisposition, default to "displayed".
623            if let Some(obj) = augmented.as_object_mut() {
624                if obj.contains_key("readAt") && !obj.contains_key("readDisposition") {
625                    obj.insert("readDisposition".to_owned(), json!("displayed"));
626                }
627            }
628
629            // Reaction patch processing
630            // (draft-atwood-jmap-chat-00 §Message/set, §Reaction).
631            //
632            // Reactions are added/removed by patching
633            // `reactions/{senderReactionId}` as RFC 8620 §5.3 JSON
634            // Pointer entries:
635            //
636            // - value is an object: add or modify the reaction
637            // - value is `null`: remove the reaction
638            //
639            // The backend's `json_merge_patch` is flat-key — it would
640            // store a literal top-level field named `"reactions/X"`
641            // rather than descending into the `reactions` map. So this
642            // handler must rewrite all `reactions/X` entries into a
643            // single nested `reactions` entry; RFC 7396 then merges
644            // that into the stored reactions map per spec.
645            //
646            // While rewriting, the handler:
647            //
648            // 1. Rejects `reactions/{id}` keys containing `/` or `~`
649            //    (RFC 6901 escape characters — the chat-client also
650            //    rejects them; this is defense-in-depth).
651            // 2. Rejects non-null non-object values as `invalidPatch`.
652            // 3. Pre-fetches the Message and rejects with `forbidden`
653            //    if the patched key targets an existing reaction whose
654            //    `senderId` is not `"self"` — per spec, only the
655            //    original sender may modify their own reactions.
656            // 4. Server-overrides `senderId` to `"self"` on every add
657            //    (spec MUST; defense-in-depth).
658            // 5. Server-injects `sentAt` to the current time on adds
659            //    that lack it, so the resulting `Reaction` round-trips
660            //    through the typed shape (which requires `sentAt`).
661            let reaction_pointer_keys: Vec<String> = augmented
662                .as_object()
663                .map(|obj| {
664                    obj.keys()
665                        .filter(|k| k.starts_with("reactions/"))
666                        .cloned()
667                        .collect()
668                })
669                .unwrap_or_default();
670
671            if !reaction_pointer_keys.is_empty() {
672                // Reject mixing top-level `reactions` with
673                // `reactions/{id}` — the two have incompatible
674                // semantics (wholesale replace vs per-key merge) and
675                // a single patch should not attempt both.
676                if augmented
677                    .as_object()
678                    .is_some_and(|obj| obj.contains_key("reactions"))
679                {
680                    not_updated.insert(
681                        id_str,
682                        json!({
683                            "type": "invalidPatch",
684                            "description":
685                                "patch must not combine top-level `reactions` with `reactions/{id}` entries",
686                        }),
687                    );
688                    continue;
689                }
690
691                // Validate each pointer key + value shape. The
692                // `.collect::<Result<Vec<_>, _>>()` form short-circuits
693                // on the first Err and is the idiomatic Rust expression
694                // of "validate-or-fail" over an iterator. A future
695                // contributor adding a new validation rule appends an
696                // `if ... { return Err(...) }` inside the closure; the
697                // short-circuit behavior is structural, not a hand-coded
698                // flag invariant.
699                let decoded: Result<Vec<(String, String)>, String> = reaction_pointer_keys
700                    .iter()
701                    .map(|raw_key| {
702                        let suffix = &raw_key["reactions/".len()..];
703                        if suffix.is_empty() || suffix.contains('/') || suffix.contains('~') {
704                            return Err(format!(
705                                "reactions/{{id}} pointer key {raw_key:?} has empty or forbidden suffix; '/' and '~' are reserved by RFC 6901",
706                            ));
707                        }
708                        let val = augmented.get(raw_key).unwrap_or(&Value::Null);
709                        if !val.is_null() {
710                            let ok = val.as_object().is_some_and(|m| {
711                                m.get("emoji")
712                                    .and_then(|v| v.as_str())
713                                    .is_some_and(|s| !s.is_empty())
714                            });
715                            if !ok {
716                                return Err(format!(
717                                    "reaction value for {raw_key:?} must be null or an object with a non-empty `emoji` string",
718                                ));
719                            }
720                        }
721                        Ok((raw_key.clone(), suffix.to_owned()))
722                    })
723                    .collect();
724                let decoded = match decoded {
725                    Ok(d) => d,
726                    Err(desc) => {
727                        not_updated.insert(
728                            id_str,
729                            json!({ "type": "invalidPatch", "description": desc }),
730                        );
731                        continue;
732                    }
733                };
734
735                // Pre-fetch the Message to inspect existing
736                // reactions. An update target that doesn't exist on
737                // the backend will surface a normal `notFound` from
738                // the subsequent `update_object` call — we don't
739                // short-circuit here. A backend storage error becomes
740                // `serverFail`.
741                let forbidden = match backend
742                    .get_objects::<Message>(
743                        caller,
744                        &account_id,
745                        Some(std::slice::from_ref(&id)),
746                        None,
747                    )
748                    .await
749                {
750                    Ok((found, _not_found)) => {
751                        let mut bad: Vec<String> = Vec::new();
752                        if let Some(msg) = found.first() {
753                            for (_, suffix) in &decoded {
754                                if let Some(existing) = msg.reactions.get(suffix) {
755                                    if existing.sender_id != SenderId::Owner {
756                                        bad.push(suffix.clone());
757                                    }
758                                }
759                            }
760                        }
761                        bad
762                    }
763                    Err(e) => {
764                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
765                        continue;
766                    }
767                };
768                if !forbidden.is_empty() {
769                    not_updated.insert(
770                        id_str,
771                        json!({
772                            "type": "forbidden",
773                            "description": format!(
774                                "cannot modify reactions authored by another sender: {}",
775                                forbidden.join(", "),
776                            ),
777                        }),
778                    );
779                    continue;
780                }
781
782                // Coalesce every `reactions/{key}` entry into a single
783                // nested `reactions` patch entry, server-overriding
784                // `senderId` and injecting `sentAt` where absent so
785                // the stored Reaction round-trips through the typed
786                // shape.
787                let now_str = now_utc_string();
788                if let Some(obj) = augmented.as_object_mut() {
789                    let mut sub = serde_json::Map::new();
790                    for (raw_key, suffix) in &decoded {
791                        let val = obj.remove(raw_key).unwrap_or(Value::Null);
792                        let final_val = match val {
793                            Value::Null => Value::Null,
794                            Value::Object(mut map) => {
795                                // Spec MUST: server overrides senderId
796                                // to "self" on every add, regardless
797                                // of what the client supplied.
798                                map.insert("senderId".to_owned(), json!("self"));
799                                if !map.contains_key("sentAt") {
800                                    map.insert("sentAt".to_owned(), json!(now_str));
801                                }
802                                Value::Object(map)
803                            }
804                            // Validation above rejects non-null
805                            // non-object; this arm is unreachable.
806                            other => other,
807                        };
808                        sub.insert(suffix.clone(), final_val);
809                    }
810                    obj.insert("reactions".to_owned(), Value::Object(sub));
811                }
812            }
813
814            // Detect a non-null readAt assignment in the patch. A
815            // `readAt: null` is a PatchObject clear (RFC 8620 §5.3), not a
816            // "mark as read" event, so it does not trigger burn-on-read.
817            // draft-atwood-jmap-chat-00 §Message `burnOnRead`: the
818            // receiving server MUST hard-delete immediately after setting
819            // readAt on a message whose `burnOnRead` is `true`.
820            let patch_sets_read_at = augmented.get("readAt").is_some_and(|v| !v.is_null());
821
822            // If the patch sets readAt, pre-fetch the message so we can
823            // decide whether it is burn-on-read. We deliberately consult
824            // the pre-patch state: a recipient setting readAt for the
825            // first time should fire the burn, regardless of whether the
826            // same patch attempts to also clear `burnOnRead` (which is a
827            // sender-set field and the spec does not authorize a
828            // recipient to flip).
829            let pre_patch_burn_on_read = if patch_sets_read_at {
830                match backend
831                    .get_objects::<Message>(
832                        caller,
833                        &account_id,
834                        Some(std::slice::from_ref(&id)),
835                        None,
836                    )
837                    .await
838                {
839                    Ok((found, _not_found)) => {
840                        found.first().and_then(|m| m.burn_on_read) == Some(true)
841                    }
842                    Err(_) => false,
843                }
844            } else {
845                false
846            };
847
848            // Convert the augmented wire-format Value into a typed
849            // PatchObject (RFC 8620 §5.3). Non-object values yield
850            // invalidPatch.
851            let patch = match serde_json::from_value::<PatchObject>(augmented) {
852                Ok(p) => p,
853                Err(e) => {
854                    not_updated.insert(
855                        id_str,
856                        json!({ "type": "invalidPatch", "description": e.to_string() }),
857                    );
858                    continue;
859                }
860            };
861            let update_outcome = backend
862                .update_object::<Message>(caller, &account_id, &id, patch)
863                .await;
864            let maybe_updated_obj = match update_outcome {
865                Ok(maybe_obj) => maybe_obj,
866                Err(BackendSetError::SetError(set_err)) => {
867                    not_updated.insert(id_str, set_error_value(&set_err));
868                    continue;
869                }
870                Err(BackendSetError::Other(e)) => {
871                    not_updated.insert(id_str, server_fail_value_from_backend(&e));
872                    continue;
873                }
874                Err(_) => {
875                    not_updated.insert(
876                        id_str,
877                        json!({
878                            "type": "serverFail",
879                            "description": "unhandled backend error variant",
880                        }),
881                    );
882                    continue;
883                }
884            };
885
886            // Burn-on-read fires AFTER the readAt patch has been applied.
887            // draft-atwood-jmap-chat-00 §Message `burnOnRead`: hard-delete
888            // immediately. The patch already succeeded above; the hard
889            // delete is its own backend call so that a production backend
890            // can either (a) leave the default no-op and override
891            // `update_object` for atomic write+delete, or (b) override
892            // this method for a separate two-step deletion. The reference
893            // `MemoryBackend` uses (b). Both are conforming.
894            if patch_sets_read_at && pre_patch_burn_on_read {
895                if let Err(burn_err) = backend.expire_message(caller, &account_id, &id).await {
896                    // The readAt patch already landed in storage but
897                    // the spec-mandated hard-delete failed. Surface
898                    // as serverFail; the recipient will retry, and
899                    // the next pre-fetch will still see
900                    // `burnOnRead: true` (a sender-set field a
901                    // recipient cannot flip), so the burn will be
902                    // attempted again. Production backends that
903                    // need atomic readAt-and-burn semantics SHOULD
904                    // override `update_object` to perform both
905                    // inside a single transaction; the reference
906                    // `MemoryBackend::expire_message` does not
907                    // surface failures and so this branch is
908                    // unreachable for it.
909                    //
910                    // Route through server_fail_value_from_backend to
911                    // redact backend Display text from the wire
912                    // description per workspace redaction discipline
913                    // (otherwise the backend error message leaks to
914                    // the JMAP client).
915                    not_updated.insert(id_str, server_fail_value_from_backend(&burn_err));
916                    // Bump mutated regardless, because the readAt
917                    // write is committed even though we report
918                    // notUpdated for the wire response. Callers
919                    // relying on `mutated` to decide whether to
920                    // rotate the state token will rotate, which
921                    // correctly reflects that something changed in
922                    // storage.
923                    mutated = true;
924                    continue;
925                }
926            }
927
928            // Update succeeded (and burn, if applicable, succeeded too).
929            mutated = true;
930            match maybe_updated_obj {
931                Some(obj) => {
932                    updated.insert(
933                        id_str,
934                        serde_json::to_value(&obj)
935                            .expect("derive(Serialize) on plain data is infallible"),
936                    );
937                }
938                None => {
939                    updated.insert(id_str, Value::Null);
940                }
941            }
942        }
943    }
944
945    // -----------------------------------------------------------------------
946    // destroy
947    // -----------------------------------------------------------------------
948    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
949        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
950        // Reject the whole request if any element is non-string rather than
951        // silently skipping it, which would produce a misleading response.
952        if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
953            return Err(JmapError::invalid_arguments(format!(
954                "destroy: every element must be a string Id; got {bad}"
955            )));
956        }
957        for id_val in destroy_arr {
958            let Some(id_str) = id_val.as_str() else {
959                continue; // unreachable: validated above
960            };
961            let id = Id::from(id_str);
962
963            match backend
964                .destroy_object::<Message>(caller, &account_id, &id)
965                .await
966            {
967                Ok(()) => {
968                    mutated = true;
969                    destroyed_list.push(Value::String(id_str.to_owned()));
970                }
971                Err(BackendSetError::SetError(set_err)) => {
972                    not_destroyed.insert(id_str.to_owned(), set_error_value(&set_err));
973                }
974                Err(BackendSetError::Other(e)) => {
975                    not_destroyed.insert(id_str.to_owned(), server_fail_value_from_backend(&e));
976                }
977                Err(_) => {
978                    not_destroyed.insert(
979                        id_str.to_owned(),
980                        json!({
981                            "type": "serverFail",
982                            "description": "unhandled backend error variant",
983                        }),
984                    );
985                }
986            }
987        }
988    }
989
990    finalize_set_response::<B, Message>(
991        backend,
992        caller,
993        &account_id,
994        old_state,
995        mutated,
996        SetAccumulators {
997            created,
998            updated,
999            destroyed: destroyed_list,
1000            not_created,
1001            not_updated,
1002            not_destroyed,
1003        },
1004    )
1005    .await
1006}