Skip to main content

jmap_chat_server/
chat.rs

1//! Chat/* method handlers (draft-atwood-jmap-chat-00 §Chat).
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 §Chat. The returned
11//! `Value` is the corresponding method-response object per the same
12//! section refs. `Chat/typing` (draft §Chat) is a Chat-specific signal
13//! method with its own request/response shape.
14//!
15//! The returned `HandlerOutput::extra_invocations` carries any invocations
16//! that this handler injected into the request stream (RFC 8620 §6.3);
17//! for the handlers in this module the vector is **always empty**.
18//!
19//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
20//! §3.6.2 and §5):
21//!
22//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
23//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
24//!   `maxObjectsInSet`;
25//! - `/set`: `stateMismatch`;
26//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
27//! - `/queryChanges`: `tooManyChanges`;
28//! - `/query`, `/queryChanges`: `unsupportedFilter`;
29//! - `/query`: `unsupportedSort`, `anchorNotFound`.
30//!
31//! Per-target failures inside `/set` surface in the `notCreated` / `notUpdated`
32//! / `notDestroyed` maps within `Ok((Value, ...))`, not as `Err`.
33
34use std::collections::{BTreeMap, HashMap, HashSet};
35
36use jmap_chat_types::ChatComparator;
37use jmap_chat_types::SPEC_CHAT_MEMBER_ROLES;
38use jmap_chat_types::{Chat, ChatKind, ChatMember, ChatMemberRole, Message, ReadPosition};
39use jmap_types::{Id, JmapError, PatchObject, UTCDate};
40use serde::Deserialize;
41use serde_json::{Value, json};
42
43use crate::ChatBackend;
44use crate::helpers::{
45    MetadataMaps, PropType, check_metadata_entry, create_metadata, mistyped_create_props,
46};
47use crate::helpers::{
48    SetAccumulators, default_sort, enforce_max_objects_in_set, extract_account_id,
49    finalize_set_response, now_utc_string, refusal_value, reject_unsupported_sort,
50};
51use crate::helpers::{resolve_entry_refs, resolve_refs, resolved_create, strip_read_only_patch};
52use crate::outbound::{GroupUpdateAction, OutboundEvent};
53use jmap_server::{
54    HandlerOutput, backend_set_error_value, is_client_updatable, reject_server_set,
55    server_fail_from_backend, server_fail_value_from_backend,
56};
57use jmap_server::{SetError, SetErrorType};
58
59/// `Chat/set` update keys that change a group Chat's member list
60/// (draft-atwood-jmap-chat-00 §Chat/set "Updating a Chat").
61const MEMBER_PATCH_KEYS: &[&str] = &["addMembers", "removeMembers", "updateMemberRoles"];
62
63/// `Chat/set` update keys, beyond [`MEMBER_PATCH_KEYS`], that a closed
64/// group rejects (draft-atwood-jmap-chat-00 §Chat `closedAt`).
65const SHARED_GROUP_KEYS: &[&str] = &["name", "description", "avatarBlobId", "pinnedMessageIds"];
66
67/// `Chat/set` update keys only a group Chat's admins may change
68/// (draft-atwood-jmap-chat-00 §Chat/set "Updating a Chat": "For group
69/// chats, admins additionally may update: `name`, `description`,
70/// `avatarBlobId`.").
71const GROUP_ADMIN_KEYS: &[&str] = &["name", "description", "avatarBlobId"];
72
73/// Chat properties draft-atwood-jmap-chat-00 §Chat Object Fields scopes
74/// to one kind ("**Direct chats only.**", "**Group chats only.**",
75/// "**Channel Chats only.**"), with that kind. `name` is "**Group and
76/// channel Chats.**", and `Chat/set` never creates a channel, so a group
77/// is the only created kind that carries it. A `Chat/set` create of
78/// another kind that carries one is `invalidProperties` (RFC 8620 §5.3).
79const KIND_SCOPED_CREATE_PROPS: &[(&str, ChatKind)] = &[
80    ("contactId", ChatKind::Direct),
81    ("name", ChatKind::Group),
82    ("description", ChatKind::Group),
83    ("avatarBlobId", ChatKind::Group),
84    ("spaceId", ChatKind::Channel),
85];
86
87/// Whether `account_id` holds the `"admin"` role in `chat.members`.
88pub(crate) fn is_chat_admin(chat: &Chat, account_id: &Id) -> bool {
89    chat.members
90        .iter()
91        .flatten()
92        .any(|m| m.id == *account_id && m.role == ChatMemberRole::Admin)
93}
94
95/// One `addMembers` or `updateMemberRoles` entry.
96#[derive(Deserialize)]
97struct MemberRoleEntry {
98    id: Id,
99    role: Option<ChatMemberRole>,
100}
101
102/// Apply the member patch keys in `patch` to `chat.members` on behalf of
103/// `owner_id` and return the resulting member list, and whether the
104/// patch closes the group.
105///
106/// Per draft-atwood-jmap-chat-00 §Chat/set "Updating a Chat":
107/// - a malformed entry, or a `role` other than `"admin"` or `"member"`,
108///   is `invalidProperties` naming the key; an `updateMemberRoles` entry
109///   must carry a `role` and name a current member;
110/// - "all require admin role, except leaving the group": a non-admin may
111///   only send `removeMembers` listing just their own id, else
112///   `forbidden`. `owner_id` is the accountId, which references the owner
113///   (draft §Terminology), so a non-admin owner leaves with
114///   `removeMembers: [accountId]`; the keys apply to group chats only;
115/// - more members than `max_members` after `addMembers` is `overQuota`;
116/// - "If the owner is the last admin and other members remain, leaving
117///   closes the group": the caller was an admin, is removed, and members
118///   but no admin remain.
119///
120/// Per the implementer guide's "Deployments SHOULD avoid admin-less open
121/// groups by refusing to let the last admin demote themselves via
122/// `updateMemberRoles`", an `updateMemberRoles` patch that leaves members
123/// but no admin is `forbidden`.
124fn apply_member_patch_keys(
125    chat: &Chat,
126    owner_id: &Id,
127    patch: &serde_json::Map<String, Value>,
128    max_members: u32,
129) -> Result<(Vec<ChatMember>, bool), Box<SetError>> {
130    fn parse<T: serde::de::DeserializeOwned>(
131        patch: &serde_json::Map<String, Value>,
132        key: &str,
133    ) -> Result<Option<T>, Box<SetError>> {
134        patch
135            .get(key)
136            .map(|v| serde_json::from_value(v.clone()))
137            .transpose()
138            .map_err(|_| {
139                Box::new(SetError::new(SetErrorType::InvalidProperties).with_properties([key]))
140            })
141    }
142    let valid_role = |role: &ChatMemberRole| SPEC_CHAT_MEMBER_ROLES.contains(&role.as_str());
143    let invalid =
144        |key: &str| Box::new(SetError::new(SetErrorType::InvalidProperties).with_properties([key]));
145    let forbidden =
146        |desc: &str| Box::new(SetError::new(SetErrorType::Forbidden).with_description(desc));
147
148    let add: Option<Vec<MemberRoleEntry>> = parse(patch, "addMembers")?;
149    let remove: Option<Vec<Id>> = parse(patch, "removeMembers")?;
150    let update: Option<Vec<MemberRoleEntry>> = parse(patch, "updateMemberRoles")?;
151    if add
152        .iter()
153        .flatten()
154        .any(|e| e.role.as_ref().is_some_and(|r| !valid_role(r)))
155    {
156        return Err(invalid("addMembers"));
157    }
158    if update
159        .iter()
160        .flatten()
161        .any(|e| !e.role.as_ref().is_some_and(valid_role))
162    {
163        return Err(invalid("updateMemberRoles"));
164    }
165
166    if chat.kind != ChatKind::Group {
167        return Err(forbidden("member patch keys apply to group chats only"));
168    }
169    let is_admin = is_chat_admin(chat, owner_id);
170    let mut members = chat.members.clone().unwrap_or_default();
171    let self_leave = add.is_none()
172        && update.is_none()
173        && remove.as_deref() == Some(std::slice::from_ref(owner_id));
174    if !is_admin && !self_leave {
175        return Err(forbidden("only group chat admins may change members"));
176    }
177
178    if let Some(add) = &add {
179        let now = UTCDate::from(now_utc_string().as_ref());
180        for entry in add {
181            if members.iter().all(|m| m.id != entry.id) {
182                let role = entry.role.clone().unwrap_or(ChatMemberRole::Member);
183                let mut m = ChatMember::new(entry.id.clone(), role, now.clone());
184                m.invited_by = Some(owner_id.clone());
185                members.push(m);
186            }
187        }
188        if members.len() > max_members as usize {
189            return Err(Box::new(
190                SetError::new(SetErrorType::OverQuota)
191                    .with_description("group chat member limit exceeded"),
192            ));
193        }
194    }
195    if let Some(remove) = &remove {
196        members.retain(|m| !remove.contains(&m.id));
197    }
198    if let Some(update) = &update {
199        for entry in update {
200            let member = members
201                .iter_mut()
202                .find(|m| m.id == entry.id)
203                .ok_or_else(|| invalid("updateMemberRoles"))?;
204            member.role = entry.role.clone().expect("role checked above");
205        }
206        if !members.is_empty() && members.iter().all(|m| m.role != ChatMemberRole::Admin) {
207            return Err(forbidden("the last admin may not demote themselves"));
208        }
209    }
210    let closes = is_admin
211        && members.iter().all(|m| m.id != *owner_id)
212        && !members.is_empty()
213        && members.iter().all(|m| m.role != ChatMemberRole::Admin);
214    Ok((members, closes))
215}
216
217/// Whether a `ChatBan` in force bans any of `user_ids` from Chat `chat_id`
218/// (draft-atwood-jmap-chat-00 §`ChatBan`).
219///
220/// ponytail: loads every `ChatBan` of the account per call. A backend with
221/// many bans should index them by Chat.
222async fn banned_among<B: ChatBackend>(
223    backend: &B,
224    caller: &B::CallerCtx,
225    account_id: &Id,
226    chat_id: &Id,
227    user_ids: &[&Id],
228) -> Result<bool, B::Error> {
229    let (bans, _) = backend
230        .get_objects::<jmap_chat_types::ChatBan>(caller, account_id, None, None)
231        .await?;
232    let now = UTCDate::from(now_utc_string().as_ref());
233    Ok(bans.iter().any(|b| {
234        b.chat_id == *chat_id
235            && user_ids.contains(&&b.user_id)
236            && crate::chat_ban::chat_ban_is_active(b, &now)
237    }))
238}
239
240/// Ids of `members` other than the owner, who is referenced by the
241/// accountId (draft-atwood-jmap-chat-00 §Terminology).
242fn other_member_ids<'a>(
243    members: impl IntoIterator<Item = &'a ChatMember>,
244    owner_id: &Id,
245) -> Vec<Id> {
246    members
247        .into_iter()
248        .filter(|m| m.id != *owner_id)
249        .map(|m| m.id.clone())
250        .collect()
251}
252
253/// The `Peer/groupUpdate` events for a successful `Chat/set` update of
254/// the group `before`, in [`GroupUpdateAction`] order.
255///
256/// `after` is the member list the update stored (`None` when it did not
257/// touch members) and `closes` whether it closed the group;
258/// `metadata_changed` is whether it patched `name`, `description` or
259/// `avatarBlobId`. The member actions are the difference between the two
260/// lists, so a no-op entry (adding a current member, re-assigning a
261/// member's role) reports nothing. The owner's own removal is `"leave"`
262/// or `"close"`, not `"removeMembers"`
263/// (draft-atwood-jmap-chat-federation-00 §Peer/groupUpdate: `"leave"` "is
264/// equivalent to `"removeMembers"` with `removedMemberIds:
265/// [senderUserId]`"). Recipients follow draft-atwood-jmap-chat-00
266/// §Chat/set "Updating a Chat".
267fn group_update_events(
268    chat_id: &Id,
269    owner_id: &Id,
270    before: &[ChatMember],
271    after: Option<&[ChatMember]>,
272    closes: bool,
273    metadata_changed: bool,
274) -> Vec<OutboundEvent> {
275    let after = after.unwrap_or(before);
276    let find = |list: &[ChatMember], id: &Id| list.iter().find(|m| m.id == *id).cloned();
277    let everyone = other_member_ids(after, owner_id);
278    let mut actions = Vec::new();
279    if metadata_changed {
280        actions.push((GroupUpdateAction::UpdateMetadata, everyone.clone()));
281    }
282    let added: Vec<ChatMember> = after
283        .iter()
284        .filter(|m| find(before, &m.id).is_none())
285        .cloned()
286        .collect();
287    if !added.is_empty() {
288        actions.push((GroupUpdateAction::AddMembers { added }, everyone.clone()));
289    }
290    let removed_ids = other_member_ids(
291        before.iter().filter(|m| find(after, &m.id).is_none()),
292        owner_id,
293    );
294    if !removed_ids.is_empty() {
295        let mut recipients = everyone.clone();
296        recipients.extend(removed_ids.iter().cloned());
297        actions.push((GroupUpdateAction::RemoveMembers { removed_ids }, recipients));
298    }
299    let updated: Vec<ChatMember> = after
300        .iter()
301        .filter(|m| find(before, &m.id).is_some_and(|old| old.role != m.role))
302        .cloned()
303        .collect();
304    if !updated.is_empty() {
305        actions.push((GroupUpdateAction::UpdateRoles { updated }, everyone.clone()));
306    }
307    if find(before, owner_id).is_some() && find(after, owner_id).is_none() {
308        let action = if closes {
309            GroupUpdateAction::Close
310        } else {
311            GroupUpdateAction::Leave
312        };
313        actions.push((action, everyone));
314    }
315    actions
316        .into_iter()
317        .map(|(action, recipients)| OutboundEvent::GroupUpdate {
318            chat_id: chat_id.clone(),
319            action,
320            recipients,
321        })
322        .collect()
323}
324
325// ---------------------------------------------------------------------------
326// Chat/get
327// ---------------------------------------------------------------------------
328
329/// Handle a `Chat/get` method call (draft-atwood-jmap-chat-00 §Chat).
330///
331/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
332/// `ids`, optional `properties`); the returned `Value` is the §5.1
333/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
334///
335/// `unreadCount` is computed on every call (§Chat, jmap-chat-spec aa01dd7
336/// L635): "Candidates are the Messages whose `id` ULID is
337/// lexicographically greater than `ReadPosition.lastReadMessageId`, or
338/// all Messages in the Chat if `lastReadMessageId` is absent. Which
339/// candidates count is implementation-defined; for example, a server MAY
340/// exclude Messages the owner sent." This server does not count Messages
341/// the owner sent (`senderId` is the accountId), so a Chat with no
342/// [`ReadPosition`] counts every Message from others. A backend whose
343/// [`ChatSettings::maintains_unread_count`](crate::ChatSettings::maintains_unread_count) is `true` gets its stored
344/// value back instead.
345///
346/// `using` is the request's capability list (pass
347/// [`jmap_server::CallContext::using`]). When the backend lists Chat for
348/// draft-ietf-jmap-metadata-05 ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)),
349/// `metadata` is returned as an object, by default only with
350/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
351/// `properties` may hold `metadata/<namespace>` subselectors (-05 §2,
352/// §3.1); see [`jmap_server::handle_get_with_metadata`].
353///
354/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
355///
356/// # Errors
357///
358/// Returns a method-level [`JmapError`]: those of
359/// [`jmap_server::handle_get_with_metadata`], and `serverFail` when reading
360/// the Messages and `ReadPosition`s behind `unreadCount` fails.
361// NOTE: properties forwarded via handle_get
362pub async fn handle_chat_get<B: ChatBackend>(
363    backend: &B,
364    caller: &B::CallerCtx,
365    args: Value,
366    using: &[String],
367) -> Result<HandlerOutput, JmapError> {
368    let mut out =
369        jmap_server::handle_get_with_metadata::<Chat, B>(backend, caller, args, using).await?;
370    fill_unread_counts(backend, caller, &mut out.primary).await?;
371    Ok(out)
372}
373
374/// Overwrite `unreadCount` on each Chat in a `Chat/get` response `list`
375/// that carries the property (it is absent when `properties` leaves it
376/// out), unless the backend maintains the count itself
377/// ([`ChatSettings::maintains_unread_count`](crate::ChatSettings::maintains_unread_count)).
378// ponytail: scans every Message and ReadPosition in the account per call
379// (O(messages) per Chat/get); a backend with many messages keeps its own
380// count via ChatSettings::maintains_unread_count.
381async fn fill_unread_counts<B: ChatBackend>(
382    backend: &B,
383    caller: &B::CallerCtx,
384    response: &mut Value,
385) -> Result<(), JmapError> {
386    if backend.maintains_unread_count() {
387        return Ok(());
388    }
389    // Id::from: the accountId this handler already validated and echoed.
390    let account_id = Id::from(response["accountId"].as_str().unwrap_or_default());
391    let Some(list) = response["list"].as_array_mut() else {
392        return Ok(());
393    };
394    if !list.iter().any(|c| c.get("unreadCount").is_some()) {
395        return Ok(());
396    }
397    let (messages, positions) = messages_and_positions(backend, caller, &account_id).await?;
398    for chat in list.iter_mut() {
399        let Some(chat) = chat.as_object_mut() else {
400            continue;
401        };
402        if !chat.contains_key("unreadCount") {
403            continue;
404        }
405        let Some(chat_id) = chat.get("id").and_then(Value::as_str) else {
406            continue;
407        };
408        let unread = unread_count(&messages, &positions, &account_id, chat_id);
409        chat.insert("unreadCount".to_owned(), Value::from(unread));
410    }
411    Ok(())
412}
413
414async fn messages_and_positions<B: ChatBackend>(
415    backend: &B,
416    caller: &B::CallerCtx,
417    account_id: &Id,
418) -> Result<(Vec<Message>, Vec<ReadPosition>), JmapError> {
419    let (messages, _) = backend
420        .get_objects::<Message>(caller, account_id, None, None)
421        .await
422        .map_err(|e| server_fail_from_backend(&e))?;
423    let (positions, _) = backend
424        .get_objects::<ReadPosition>(caller, account_id, None, None)
425        .await
426        .map_err(|e| server_fail_from_backend(&e))?;
427    Ok((messages, positions))
428}
429
430/// §Chat `unreadCount` for `chat_id`: Messages in the Chat not sent by
431/// the owner (`senderId` is not `account_id`) whose `id` sorts after the
432/// owner's `lastReadMessageId`, or all of them when it is absent.
433/// jmap-chat-spec aa01dd7 L635: "Which candidates count is
434/// implementation-defined; for example, a server MAY exclude Messages the
435/// owner sent." The owner's own messages never count, so a sender does
436/// not see a message they just sent as unread.
437pub(crate) fn unread_count(
438    messages: &[Message],
439    positions: &[ReadPosition],
440    account_id: &Id,
441    chat_id: &str,
442) -> u64 {
443    let last_read = positions
444        .iter()
445        .find(|p| p.chat_id.as_ref() == chat_id)
446        .and_then(|p| p.last_read_message_id.as_ref());
447    messages
448        .iter()
449        .filter(|m| m.chat_id.as_ref() == chat_id && m.sender_id != *account_id)
450        .filter(|m| last_read.is_none_or(|l| m.id.as_ref() > l.as_ref()))
451        .count() as u64
452}
453
454/// Write the recomputed `unreadCount` to each Chat in `chat_ids` so the
455/// `Chat` state advances and `Chat/changes` reports the Chat as updated.
456///
457/// RFC 8620 §5.1: "If the data changes, this string MUST change", and
458/// §ReadPosition/set (jmap-chat-spec 33702a5 L1434) "updates
459/// `Chat.unreadCount` for the affected Chat, possibly later". `Chat/get`
460/// derives the count on every call, so a [`ReadPosition`] update or a Message
461/// create/destroy changes Chat data; this records that change through
462/// [`ChatStore::update_object`](crate::ChatStore::update_object), whose contract bumps the type state
463/// and logs the id as updated. Does nothing when the backend maintains
464/// the count itself ([`ChatSettings::maintains_unread_count`](crate::ChatSettings::maintains_unread_count)).
465///
466/// Best-effort, like [`crate::message::ensure_read_positions`]: the
467/// caller's own write already succeeded and its response must report
468/// it, so a failure here (including a Chat that no longer exists) is
469/// not surfaced.
470pub(crate) async fn record_unread_count_changes<B: ChatBackend>(
471    backend: &B,
472    caller: &B::CallerCtx,
473    account_id: &Id,
474    mut chat_ids: Vec<Id>,
475) {
476    if chat_ids.is_empty() || backend.maintains_unread_count() {
477        return;
478    }
479    let Ok((messages, positions)) = messages_and_positions(backend, caller, account_id).await
480    else {
481        return;
482    };
483    chat_ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
484    chat_ids.dedup();
485    for chat_id in chat_ids {
486        let unread = unread_count(&messages, &positions, account_id, chat_id.as_ref());
487        let mut patch = PatchObject::new();
488        patch
489            .as_map_mut()
490            .insert("unreadCount".to_owned(), Value::from(unread));
491        let _ = backend
492            .update_object::<Chat>(caller, account_id, &chat_id, patch)
493            .await;
494    }
495}
496
497// ---------------------------------------------------------------------------
498// Chat/changes
499// ---------------------------------------------------------------------------
500
501/// Handle a `Chat/changes` method call (draft-atwood-jmap-chat-00 §Chat).
502///
503/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
504/// `sinceState`, optional `maxChanges`); the returned `Value` is the
505/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
506/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
507///
508/// `using` is the request's capability list (pass
509/// [`jmap_server::CallContext::using`]); with
510/// `urn:ietf:params:jmap:metadata` the request may set
511/// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges`, and
512/// without it metadata-only changes are left out (-05 §3).
513///
514/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
515///
516/// # Errors
517///
518/// Returns a method-level [`JmapError`]:
519///
520/// - `invalidArguments` when `accountId` is missing or not a valid Id,
521///   `sinceState` is missing, `maxChanges` is not a positive integer, or
522///   `ignoreMetadataOnlyChanges` is not a boolean;
523/// - `accountNotFound` when the backend does not know `accountId`;
524/// - `cannotCalculateChanges` when the backend cannot compute the changes
525///   since `sinceState`;
526/// - `serverFail` when the backend fails.
527pub async fn handle_chat_changes<B: ChatBackend>(
528    backend: &B,
529    caller: &B::CallerCtx,
530    args: Value,
531    using: &[String],
532) -> Result<HandlerOutput, JmapError> {
533    jmap_server::handle_changes::<Chat, B>(backend, caller, args, using).await
534}
535
536// ---------------------------------------------------------------------------
537// Chat/query
538// ---------------------------------------------------------------------------
539
540/// Handle a `Chat/query` method call (draft-atwood-jmap-chat-00 §Chat).
541///
542/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`, optional
543/// `filter`, optional `sort`, optional `position` / `anchor` /
544/// `anchorOffset`, optional `limit`, optional `calculateTotal`); the
545/// returned `Value` is the §5.5 `/query` response shape (`accountId`,
546/// `queryState`, `canCalculateChanges`, `position`, `ids`, optional
547/// `total`, optional `limit`).
548///
549/// Unknown filter clauses and sort properties are refused with
550/// `unsupportedFilter` / `unsupportedSort` (RFC 8620 §5.5).
551///
552/// `using` is the request's capability list (pass
553/// [`jmap_server::CallContext::using`]); without
554/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
555/// filter condition is `unsupportedFilter` (-05 §3).
556///
557/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
558///
559/// # Errors
560///
561/// Returns a method-level [`JmapError`]:
562///
563/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
564///   when `filter`, `sort`, `position`, `anchor`, `anchorOffset` or `limit`
565///   is malformed;
566/// - `accountNotFound` when the backend does not know `accountId`;
567/// - `unsupportedFilter` when the filter does not decode as a Chat filter, or
568///   holds a draft-ietf-jmap-metadata-05 §3.6 condition without
569///   `urn:ietf:params:jmap:metadata` in `using`;
570/// - `unsupportedSort` when `sort` names a property this server does not
571///   define;
572/// - `anchorNotFound` when `anchor` is not in the results;
573/// - `serverFail` when the backend fails, or any other RFC 8620 §5.5 error
574///   the backend returns.
575pub async fn handle_chat_query<B: ChatBackend>(
576    backend: &B,
577    caller: &B::CallerCtx,
578    mut args: Value,
579    using: &[String],
580) -> Result<HandlerOutput, JmapError> {
581    jmap_server::reject_metadata_filter_arg(
582        &args,
583        jmap_chat_types::ChatFilterCondition::has_metadata_condition,
584        using,
585    )?;
586    // §Chat/query: "Default sort: `lastMessageAt` descending; chats
587    // without messages sort last."
588    if let Value::Object(map) = &mut args {
589        default_sort(
590            map,
591            json!([{ "property": "lastMessageAt", "isAscending": false }]),
592        );
593    }
594    reject_unsupported_sort::<ChatComparator>(args.get("sort"))?;
595    jmap_server::handle_query::<Chat, B>(backend, caller, args).await
596}
597
598// ---------------------------------------------------------------------------
599// Chat/queryChanges
600// ---------------------------------------------------------------------------
601
602/// Handle a `Chat/queryChanges` method call (draft-atwood-jmap-chat-00 §Chat).
603///
604/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
605/// optional `filter`, optional `sort`, `sinceQueryState`, optional
606/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
607/// returned `Value` is the §5.6 `/queryChanges` response shape
608/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
609/// `removed`, `added`).
610///
611/// `using` is the request's capability list (pass
612/// [`jmap_server::CallContext::using`]); without
613/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
614/// filter condition is `unsupportedFilter` (-05 §3).
615///
616/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
617///
618/// # Errors
619///
620/// Returns a method-level [`JmapError`]:
621///
622/// - `invalidArguments` when `accountId` is missing or not a valid Id,
623///   `sinceQueryState` is missing, or `filter`, `sort`, `maxChanges` or
624///   `upToId` is malformed;
625/// - `accountNotFound` when the backend does not know `accountId`;
626/// - `unsupportedFilter` when the filter does not decode as a Chat filter, or
627///   holds a draft-ietf-jmap-metadata-05 §3.6 condition without
628///   `urn:ietf:params:jmap:metadata` in `using`;
629/// - `unsupportedSort` when `sort` names a property this server does not
630///   define;
631/// - `cannotCalculateChanges` when the backend cannot compute the changes
632///   since `sinceQueryState`;
633/// - `serverFail` when the backend fails, or any other RFC 8620 §5.6 error
634///   the backend returns.
635pub async fn handle_chat_query_changes<B: ChatBackend>(
636    backend: &B,
637    caller: &B::CallerCtx,
638    mut args: Value,
639    using: &[String],
640) -> Result<HandlerOutput, JmapError> {
641    jmap_server::reject_metadata_filter_arg(
642        &args,
643        jmap_chat_types::ChatFilterCondition::has_metadata_condition,
644        using,
645    )?;
646    // RFC 8620 §5.6: the `filter` and `sort` are those of the original
647    // query, so the §Chat/query default sort applies here too.
648    if let Value::Object(map) = &mut args {
649        default_sort(
650            map,
651            json!([{ "property": "lastMessageAt", "isAscending": false }]),
652        );
653    }
654    reject_unsupported_sort::<ChatComparator>(args.get("sort"))?;
655    jmap_server::handle_query_changes::<Chat, B>(backend, caller, args).await
656}
657
658// ---------------------------------------------------------------------------
659// Chat/set
660// ---------------------------------------------------------------------------
661
662/// The Chat create and update properties that hold the id of another record, which a
663/// client may set to a `#creationId` reference (RFC 8620 §5.3).
664const CHAT_ID_PROPERTIES: &[&str] = &[
665    "contactId",
666    "memberIds",
667    "pinnedMessageIds",
668    "removeMembers",
669    KICK_MEMBERS_KEY,
670];
671
672/// The `Chat/set` update key draft-atwood-jmap-chat-mimi-00 §Moderation
673/// adds "for Chats bound to a room" (String\[], `ChatContact` ids).
674const KICK_MEMBERS_KEY: &str = "kickMembers";
675
676/// Remove [`KICK_MEMBERS_KEY`] from `patch` and return its ids, or `None`
677/// when the key is absent or lists no one (a kick of nobody is a no-op).
678///
679/// # Errors
680///
681/// A value that is not an array of strings, or an element that is not a
682/// valid Id (RFC 8620 §1.2), is `invalidProperties` naming the key.
683fn take_kick_members(
684    patch: &mut serde_json::Map<String, Value>,
685) -> Result<Option<Vec<Id>>, Box<SetError>> {
686    let Some(value) = patch.remove(KICK_MEMBERS_KEY) else {
687        return Ok(None);
688    };
689    let invalid = || {
690        Box::new(SetError::new(SetErrorType::InvalidProperties).with_properties([KICK_MEMBERS_KEY]))
691    };
692    let Value::Array(items) = value else {
693        return Err(invalid());
694    };
695    let ids = items
696        .iter()
697        .map(|v| {
698            v.as_str()
699                .and_then(|s| jmap_server::parse_wire_id(s, KICK_MEMBERS_KEY).ok())
700                .ok_or_else(invalid)
701        })
702        .collect::<Result<Vec<Id>, _>>()?;
703    Ok((!ids.is_empty()).then_some(ids))
704}
705
706/// The Chat update entry fields that hold a `ChatContact` id, as
707/// `(patch key, entry field, property named on failure)`: draft-atwood-jmap-chat-00
708/// §Chat/set "Updating a Chat" gives each `addMembers` and
709/// `updateMemberRoles` entry an `id`, a `ChatContact` id.
710const CHAT_ENTRY_ID_PROPERTIES: &[(&str, &str, &str)] = &[
711    ("addMembers", "id", "addMembers"),
712    ("updateMemberRoles", "id", "updateMemberRoles"),
713];
714
715/// Handle a `Chat/set` method call (draft-atwood-jmap-chat-00 §Chat).
716///
717/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
718/// `ifInState`, optional `create` / `update` / `destroy` maps); the
719/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
720/// `oldState`, `newState`, plus the per-operation `created` /
721/// `notCreated` / `updated` / `notUpdated` / `destroyed` / `notDestroyed`
722/// maps).
723///
724/// Validation enforced here (not in the backend):
725/// - `kind` is required on create.
726/// - `direct` chats require `contactId`.
727/// - `channel` chats are `forbidden` on create and destroy (managed via
728///   `Space/set` `addChannels` / `removeChannels`).
729/// - a group create whose membership exceeds
730///   [`ChatLimits::max_group_chat_members`](crate::ChatLimits::max_group_chat_members)
731///   is `overQuota`.
732/// - an update key outside §Chat/set "Updating a Chat" is
733///   `invalidProperties`; `name`, `description` and `avatarBlobId` updates
734///   are `forbidden` unless the Chat is a group and the caller is an admin.
735/// - `pinnedMessageIds` updates are gated by
736///   [`ChatAccessPolicy::may_set_pinned_messages`](crate::ChatAccessPolicy::may_set_pinned_messages).
737///
738/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
739///
740/// A `contactId`, a `memberIds`, `pinnedMessageIds` or `removeMembers`
741/// element, or the `id` of an `addMembers` or `updateMemberRoles` entry,
742/// that is a `#creationId` reference names a record created earlier in the request and resolves against
743/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
744/// §5.3); an unknown reference is `invalidProperties` naming the property.
745///
746/// `using` is the request's capability list (pass
747/// [`jmap_server::CallContext::using`]): a write to `metadata` or
748/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
749/// `invalidProperties` (draft-ietf-jmap-metadata-05 §3), as is `null` for
750/// either in a create (-05 §3.2). The backend validates the rest.
751///
752/// # Errors
753///
754/// Returns a method-level [`JmapError`]:
755///
756/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
757///   an element of `destroy` is not a string;
758/// - `accountNotFound` when the backend does not know `accountId`;
759/// - `requestTooLarge` when `create`, `update` and `destroy` together hold
760///   more than `maxObjectsInSet` objects;
761/// - `stateMismatch` when `ifInState` is not the current state;
762/// - `serverFail` when the backend fails.
763///
764/// A create, update or destroy that fails on its own is a [`SetError`] in
765/// the response, not an `Err`.
766pub async fn handle_chat_set<B: ChatBackend>(
767    backend: &B,
768    caller: &B::CallerCtx,
769    created_ids: &BTreeMap<Id, Id>,
770    mut args: Value,
771    using: &[String],
772) -> Result<HandlerOutput, JmapError> {
773    // A `#creationId` blob reference names a blob created earlier in the
774    // request (RFC 8620 §5.3; draft-ietf-jmap-blobext-03 §8); an unknown one
775    // is left for the Id checks below.
776    jmap_server::resolve_blob_refs(&mut args, &["avatarBlobId"], created_ids);
777    let (account_id, mut args) = extract_account_id(args)?;
778
779    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-fo38).
780    if !backend
781        .account_exists(caller, &account_id)
782        .await
783        .map_err(|e| server_fail_from_backend(&e))?
784    {
785        return Err(JmapError::account_not_found());
786    }
787
788    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
789    // unbounded /set batches before touching the storage layer.
790    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
791
792    let old_state = backend
793        .get_state::<Chat>(caller, &account_id)
794        .await
795        .map_err(|e| server_fail_from_backend(&e))?;
796
797    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
798        && if_in_state != old_state.as_ref()
799    {
800        return Err(JmapError::state_mismatch());
801    }
802
803    let ctx = SetCtx {
804        backend,
805        caller,
806        account_id: &account_id,
807        created_ids,
808        using,
809    };
810    let mut acc = SetAccumulators::default();
811    let mut mutated = set_create(&ctx, &mut args, &mut acc).await?;
812    // RFC 8620 §5.3: update keys and destroy ids may name this call's creates.
813    jmap_server::resolve_set_id_refs(&mut args, created_ids, &acc.created);
814    mutated |= set_update(&ctx, &mut args, &mut acc).await?;
815    mutated |= set_destroy(&ctx, &mut args, &mut acc).await?;
816
817    finalize_set_response::<B, Chat>(backend, caller, &account_id, old_state, mutated, acc).await
818}
819
820/// What every `Chat/set` sub-function needs from the request
821/// (docs/design/set-handler-split.md).
822struct SetCtx<'a, B: ChatBackend> {
823    backend: &'a B,
824    caller: &'a B::CallerCtx,
825    account_id: &'a Id,
826    /// The request-wide `#creationId` map (RFC 8620 §5.3).
827    created_ids: &'a BTreeMap<Id, Id>,
828    /// The request's `using` capabilities.
829    using: &'a [String],
830}
831
832/// What the `Chat/set` create loop carries from one entry to the next:
833/// the Direct-chat contact ids already taken.
834struct CreateRun {
835    /// The account's Chats, read once before the loop when the batch has
836    /// a Direct create; empty otherwise.
837    existing_chats: Vec<Chat>,
838    /// `contactId`s of the account's Direct chats, including those created
839    /// earlier in this batch.
840    known_direct_contact_ids: HashSet<String>,
841    /// Maps contactId -> assigned `new_id` for Direct chats successfully
842    /// created earlier in this batch. Used to resolve intra-batch
843    /// duplicates without a re-fetch (JMAP-63k.12).
844    batch_direct_ids: HashMap<String, Id>,
845}
846
847/// The `create` part of `Chat/set`. Returns whether the backend was
848/// written.
849async fn set_create<B: ChatBackend>(
850    ctx: &SetCtx<'_, B>,
851    args: &mut serde_json::Map<String, Value>,
852    acc: &mut SetAccumulators,
853) -> Result<bool, JmapError> {
854    let mut mutated = false;
855    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
856        let mut run = create_run(ctx, create_map).await?;
857        for (create_id, obj_val) in create_map {
858            mutated |= create_one(ctx, create_id, obj_val, acc, &mut run).await?;
859        }
860    }
861    Ok(mutated)
862}
863
864/// The [`CreateRun`] a `Chat/set` create batch starts with.
865async fn create_run<B: ChatBackend>(
866    ctx: &SetCtx<'_, B>,
867    create_map: &serde_json::Map<String, Value>,
868) -> Result<CreateRun, JmapError> {
869    // Only pay the cost of a full get_objects fetch when the batch contains
870    // at least one Direct create (JMAP-63k.4).
871    let has_direct_create = create_map.values().any(|v| {
872        v.get("kind")
873            .and_then(|k| k.as_str())
874            .is_some_and(|s| s.eq_ignore_ascii_case("direct"))
875    });
876
877    // Fetch all existing chats once before the loop. For a batch of N
878    // creates against an account with K existing chats this is O(K + N)
879    // reads (one full-account scan + a HashSet lookup per create) rather
880    // than the naive O(N * K) of one fetch per create. The per-batch fetch
881    // still scales linearly in the account's chat count K, so production
882    // backends serving accounts with large K should push the
883    // contact-id-uniqueness check into a typed query method on
884    // ChatBackend rather than rely on this hoisted scan (tracked by
885    // JMAP-63k.9). Skipped entirely for non-Direct batches.
886    let (existing_chats, known_direct_contact_ids): (Vec<Chat>, HashSet<String>) =
887        if has_direct_create {
888            let (chats, _) = ctx
889                .backend
890                .get_objects::<Chat>(ctx.caller, ctx.account_id, None, None)
891                .await
892                .map_err(|e| server_fail_from_backend(&e))?;
893            let known = chats
894                .iter()
895                .filter(|c| c.kind == ChatKind::Direct)
896                .filter_map(|c| c.contact_id.as_ref().map(|id| id.as_ref().to_owned()))
897                .collect();
898            (chats, known)
899        } else {
900            (Vec::new(), HashSet::new())
901        };
902    Ok(CreateRun {
903        existing_chats,
904        known_direct_contact_ids,
905        batch_direct_ids: HashMap::new(),
906    })
907}
908
909/// One `create` entry of `Chat/set`. Returns whether the backend was
910/// written.
911async fn create_one<B: ChatBackend>(
912    ctx: &SetCtx<'_, B>,
913    create_id: &str,
914    obj_val: &Value,
915    acc: &mut SetAccumulators,
916    run: &mut CreateRun,
917) -> Result<bool, JmapError> {
918    let resolved = match resolved_create(obj_val, CHAT_ID_PROPERTIES, ctx.created_ids) {
919        Ok(v) => v,
920        Err(err) => {
921            acc.not_created
922                .insert(create_id.to_owned(), serde_json::Value::from(&*err));
923            return Ok(false);
924        }
925    };
926    let obj_val = &resolved;
927    let checked =
928        check_create_props(obj_val, ctx.using).and_then(|maps| Ok((maps, create_kind(obj_val)?)));
929    let ((metadata, private_metadata), kind) = match checked {
930        Ok(checked) => checked,
931        Err(err) => {
932            acc.not_created.insert(create_id.to_owned(), err);
933            return Ok(false);
934        }
935    };
936    let direct_contact_id_str = match direct_contact_id(&kind, obj_val, run)? {
937        Ok(contact) => contact,
938        Err(err) => {
939            acc.not_created.insert(create_id.to_owned(), err);
940            return Ok(false);
941        }
942    };
943    let now_str = now_utc_string();
944    let now: UTCDate = UTCDate::from(now_str.as_ref());
945    let members = match create_members(ctx, &kind, obj_val, &now) {
946        Ok(members) => members,
947        Err(err) => {
948            acc.not_created.insert(create_id.to_owned(), err);
949            return Ok(false);
950        }
951    };
952
953    let opts = match create_optionals(obj_val) {
954        Ok(opts) => opts,
955        Err(err) => {
956            acc.not_created.insert(create_id.to_owned(), err);
957            return Ok(false);
958        }
959    };
960    let build = |id: &Id| {
961        let mut chat = Chat::new(
962            id.clone(),
963            kind,
964            now,
965            0,
966            vec![],
967            opts.muted,
968            opts.receive_typing_indicators,
969        );
970        chat.contact_id = opts.contact_id;
971        chat.name = opts.name;
972        chat.description = opts.description;
973        chat.avatar_blob_id = opts.avatar_blob_id;
974        chat.message_expiry_seconds = opts.message_expiry_seconds;
975        chat.members = members;
976        chat.metadata = metadata;
977        chat.private_metadata = private_metadata;
978        chat
979    };
980
981    match ctx
982        .backend
983        .create_object::<Chat, _>(ctx.caller, ctx.account_id, create_id, build)
984        .await
985    {
986        Ok((new_id, created_obj)) => {
987            // The create is committed; every branch below (including
988            // rollback and cleanup failure) has moved backend state,
989            // so newState must be re-read (RFC 8620 §5.3).
990            let direct = direct_contact_id_str.as_deref();
991            after_create(ctx, create_id, new_id, created_obj, direct, acc, run).await?;
992            Ok(true)
993        }
994        Err(e) => {
995            acc.not_created
996                .insert(create_id.to_owned(), backend_set_error_value(e));
997            Ok(false)
998        }
999    }
1000}
1001
1002/// Check the metadata and wrongly-typed properties of one `Chat/set`
1003/// create object and return its metadata maps, or the [`SetError`] value for
1004/// `notCreated`.
1005fn check_create_props(obj_val: &Value, using: &[String]) -> Result<MetadataMaps, Value> {
1006    if let Some(Err(err)) = obj_val
1007        .as_object()
1008        .map(|o| check_metadata_entry(o, true, using))
1009    {
1010        return Err(serde_json::Value::from(&*err));
1011    }
1012    // draft-ietf-jmap-metadata-05 §3.2: the create sets the
1013    // metadata properties; the backend validates them.
1014    let maps = create_metadata(obj_val)?;
1015    // Optional properties: a wrongly-typed value is invalidProperties
1016    // (RFC 8620 §5.3), not a silent absence.
1017    if let Some(err) = mistyped_create_props(
1018        obj_val,
1019        &[
1020            ("contactId", PropType::Str),
1021            ("name", PropType::Str),
1022            ("description", PropType::Str),
1023            ("avatarBlobId", PropType::Str),
1024            ("messageExpirySeconds", PropType::UnsignedInt),
1025            ("spaceId", PropType::Str),
1026            ("muted", PropType::Bool),
1027            ("receiveTypingIndicators", PropType::Bool),
1028        ],
1029    ) {
1030        return Err(err);
1031    }
1032    Ok(maps)
1033}
1034
1035/// The `kind` of one `Chat/set` create object, checked together with the
1036/// kind-scoped and server-set properties, or the [`SetError`] value for
1037/// `notCreated`.
1038fn create_kind(obj_val: &Value) -> Result<ChatKind, Value> {
1039    // kind is required.
1040    let Some(kind_str) = obj_val
1041        .get("kind")
1042        .and_then(|v| v.as_str())
1043        .map(str::to_owned)
1044    else {
1045        return Err(json!({ "type": "invalidProperties", "properties": ["kind"] }));
1046    };
1047
1048    // ChatKind::Other(_) is the deserialize-from-wire forward-compat
1049    // catch-all: it preserves round-trip fidelity when reading data
1050    // produced by a future server that knows a new spec variant. It
1051    // is NOT a legitimate value on /set create — a client supplying
1052    // an unrecognised kind must be rejected with invalidProperties,
1053    // otherwise junk Chats end up in storage and break every
1054    // downstream kind-dispatched invariant (kind-specific required
1055    // field checks, /get response shape, Message/set chatId
1056    // resolution, etc.).
1057    let kind = match serde_json::from_value::<ChatKind>(Value::String(kind_str)) {
1058        Ok(k) if !matches!(k, ChatKind::Other(_)) => k,
1059        _ => return Err(json!({ "type": "invalidProperties", "properties": ["kind"] })),
1060    };
1061
1062    // A channel create is `forbidden` below whatever it carries.
1063    // `null` is read as absent, as in `mistyped_create_props`.
1064    if kind != ChatKind::Channel {
1065        let foreign: Vec<&str> = KIND_SCOPED_CREATE_PROPS
1066            .iter()
1067            .filter(|(prop, scope)| {
1068                *scope != kind && obj_val.get(*prop).is_some_and(|v| !v.is_null())
1069            })
1070            .map(|(prop, _)| *prop)
1071            .collect();
1072        if !foreign.is_empty() {
1073            return Err(json!({ "type": "invalidProperties", "properties": foreign }));
1074        }
1075        if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Chat>) {
1076            return Err(serde_json::Value::from(&err));
1077        }
1078    }
1079    Ok(kind)
1080}
1081
1082/// The `contactId` of a Direct `Chat/set` create, checked against the
1083/// Direct chats already known to `run`; `None` for a group. The inner
1084/// `Err` is the [`SetError`] value for `notCreated`.
1085///
1086/// `Some(id)` for Direct chats and `None` for all other kinds — it
1087/// simultaneously encodes the "is direct" flag and the contact ID,
1088/// avoiding a bool+Option pair whose invariant (Some iff direct) would
1089/// otherwise be implicit.
1090fn direct_contact_id(
1091    kind: &ChatKind,
1092    obj_val: &Value,
1093    run: &CreateRun,
1094) -> Result<Result<Option<String>, Value>, JmapError> {
1095    match kind {
1096        ChatKind::Direct => {
1097            let Some(contact_id_str) = obj_val
1098                .get("contactId")
1099                .and_then(|v| v.as_str())
1100                .map(str::to_owned)
1101            else {
1102                return Ok(Err(
1103                    json!({ "type": "invalidProperties", "properties": ["contactId"] }),
1104                ));
1105            };
1106            let stored_direct = |c: &&Chat| {
1107                c.kind == ChatKind::Direct
1108                    && c.contact_id.as_ref().map(|id| id.as_ref()) == Some(contact_id_str.as_str())
1109            };
1110
1111            // Pre-check: reject if a direct chat with this contactId is
1112            // already known from the hoisted fetch.
1113            if let Some(dup) = run.existing_chats.iter().find(stored_direct) {
1114                return Ok(Err(serde_json::Value::from(
1115                    SetError::new(SetErrorType::AlreadyExists).with_existing_id(dup.id.clone()),
1116                )));
1117            }
1118            // Also check contactIds created earlier in this same batch.
1119            // Resolve the canonical id from the hoisted pre-fetch data or
1120            // from the batch map — no re-fetch required (JMAP-63k.12).
1121            if run.known_direct_contact_ids.contains(&contact_id_str) {
1122                // Try the pre-fetch snapshot first (pre-existing chat).
1123                let canonical_id = if let Some(c) = run.existing_chats.iter().find(stored_direct) {
1124                    c.id.clone()
1125                } else if let Some(id) = run.batch_direct_ids.get(&contact_id_str) {
1126                    // Created earlier in this batch.
1127                    id.clone()
1128                } else {
1129                    // Should not happen: known_direct_contact_ids is only
1130                    // populated from existing_chats and batch_direct_ids.
1131                    return Ok(Err(json!({
1132                        "type": "serverFail",
1133                        "description": "direct chat for contact not found after concurrent operation; retry"
1134                    })));
1135                };
1136                return Ok(Err(jmap_server::serialize_value(
1137                    SetError::new(SetErrorType::AlreadyExists).with_existing_id(canonical_id),
1138                )?));
1139            }
1140            Ok(Ok(Some(contact_id_str)))
1141        }
1142        // §Chat/set: "Creating a Chat with `kind: "channel"` via
1143        // `Chat/set` is not supported; the server MUST return a
1144        // SetError of type `forbidden`."
1145        ChatKind::Channel => Ok(Err(json!({ "type": "forbidden" }))),
1146        _ => Ok(Ok(None)),
1147    }
1148}
1149
1150/// The `memberIds` of a group `Chat/set` create (`None` for another
1151/// kind), or the [`SetError`] value for `notCreated`.
1152///
1153/// Group create: "`memberIds` (String[], required): ChatContact.ids
1154/// of additional initial members." Absent is tolerated for
1155/// backward compatibility; a non-String[] value is rejected.
1156fn create_member_ids(kind: &ChatKind, obj_val: &Value) -> Result<Option<Vec<Id>>, Value> {
1157    if *kind != ChatKind::Group {
1158        return Ok(None);
1159    }
1160    match obj_val.get("memberIds") {
1161        None => Ok(Some(Vec::new())),
1162        Some(v) => match serde_json::from_value::<Vec<String>>(v.clone()) {
1163            Ok(ids) => ids
1164                .iter()
1165                .map(|s| jmap_server::parse_wire_id(s, "memberIds"))
1166                .collect::<Result<Vec<Id>, _>>()
1167                .map(Some)
1168                .map_err(|err| serde_json::Value::from(&*err)),
1169            Err(_) => Err(json!({ "type": "invalidProperties", "properties": ["memberIds"] })),
1170        },
1171    }
1172}
1173
1174/// The initial `members` of a group `Chat/set` create (`None` for another
1175/// kind), or the [`SetError`] value for `notCreated`.
1176fn create_members<B: ChatBackend>(
1177    ctx: &SetCtx<'_, B>,
1178    kind: &ChatKind,
1179    obj_val: &Value,
1180    now: &UTCDate,
1181) -> Result<Option<Vec<ChatMember>>, Value> {
1182    let members = initial_members(create_member_ids(kind, obj_val)?, ctx.account_id, now);
1183
1184    // Group create `memberIds`: "If the resulting membership would
1185    // exceed a server-defined limit on the number of members per
1186    // group Chat, the server MUST return an `overQuota` SetError".
1187    let max_members = ctx
1188        .backend
1189        .limits(ctx.caller, ctx.account_id)
1190        .max_group_chat_members;
1191    if members
1192        .as_ref()
1193        .is_some_and(|m| m.len() > max_members as usize)
1194    {
1195        return Err(json!({
1196            "type": "overQuota",
1197            "description": "group chat member limit exceeded",
1198        }));
1199    }
1200    Ok(members)
1201}
1202
1203/// The initial `members` of a created group Chat, from its checked
1204/// `memberIds`.
1205///
1206/// "The server [...] adds the creator to `members` with at least
1207/// one role granting permissions sufficient to administer the
1208/// chat": the creator is `"admin"`, each distinct memberIds entry
1209/// is `"member"` invited by the creator. The creator is the owner,
1210/// referenced by the accountId (§Terminology).
1211fn initial_members(
1212    member_ids: Option<Vec<Id>>,
1213    account_id: &Id,
1214    now: &UTCDate,
1215) -> Option<Vec<ChatMember>> {
1216    member_ids.map(|ids| {
1217        let creator: Id = account_id.clone();
1218        let mut members = vec![ChatMember::new(
1219            creator.clone(),
1220            ChatMemberRole::Admin,
1221            now.clone(),
1222        )];
1223        for id in ids {
1224            if members.iter().all(|m| m.id != id) {
1225                let mut m = ChatMember::new(id, ChatMemberRole::Member, now.clone());
1226                m.invited_by = Some(creator.clone());
1227                members.push(m);
1228            }
1229        }
1230        members
1231    })
1232}
1233
1234/// The optional properties of a `Chat/set` create, checked.
1235struct CreateOptionals {
1236    contact_id: Option<Id>,
1237    name: Option<String>,
1238    description: Option<String>,
1239    muted: bool,
1240    receive_typing_indicators: bool,
1241    avatar_blob_id: Option<Id>,
1242    message_expiry_seconds: Option<u64>,
1243}
1244
1245/// The [`CreateOptionals`] of one `Chat/set` create object, or the
1246/// [`SetError`] value for `notCreated`.
1247fn create_optionals(obj_val: &Value) -> Result<CreateOptionals, Value> {
1248    let contact_id: Option<Id> = match obj_val.get("contactId").and_then(|v| v.as_str()) {
1249        Some(s) => Some(
1250            jmap_server::parse_wire_id(s, "contactId")
1251                .map_err(|err| serde_json::Value::from(&*err))?,
1252        ),
1253        None => None,
1254    };
1255    let name: Option<String> = obj_val
1256        .get("name")
1257        .and_then(|v| v.as_str())
1258        .map(str::to_owned);
1259    let description: Option<String> = obj_val
1260        .get("description")
1261        .and_then(|v| v.as_str())
1262        .map(str::to_owned);
1263    let muted: bool = obj_val
1264        .get("muted")
1265        .and_then(|v| v.as_bool())
1266        .unwrap_or(false);
1267    let receive_typing_indicators: bool = obj_val
1268        .get("receiveTypingIndicators")
1269        .and_then(|v| v.as_bool())
1270        .unwrap_or(true);
1271
1272    // "Optional at creation: `description` (String), `avatarBlobId`
1273    // (String), `messageExpirySeconds` (UnsignedInt)."
1274    let avatar_blob_id = match obj_val.get("avatarBlobId").and_then(Value::as_str) {
1275        Some(s) => Some(
1276            jmap_server::parse_wire_id(s, "avatarBlobId")
1277                .map_err(|err| serde_json::Value::from(&*err))?,
1278        ),
1279        None => None,
1280    };
1281    let message_expiry_seconds = obj_val.get("messageExpirySeconds").and_then(Value::as_u64);
1282    Ok(CreateOptionals {
1283        contact_id,
1284        name,
1285        description,
1286        muted,
1287        receive_typing_indicators,
1288        avatar_blob_id,
1289        message_expiry_seconds,
1290    })
1291}
1292
1293/// What follows a committed `Chat/set` create: the Direct-chat duplicate
1294/// re-check (which may roll the create back into `notCreated`), the group
1295/// `Peer/groupUpdate`, and the `created` entry.
1296async fn after_create<B: ChatBackend>(
1297    ctx: &SetCtx<'_, B>,
1298    create_id: &str,
1299    new_id: Id,
1300    created_obj: Chat,
1301    direct_contact_id_str: Option<&str>,
1302    acc: &mut SetAccumulators,
1303    run: &mut CreateRun,
1304) -> Result<(), JmapError> {
1305    if let Some(contact_id_str) = direct_contact_id_str {
1306        if let Some(err) = direct_race_error(ctx, &new_id, contact_id_str).await {
1307            acc.not_created.insert(create_id.to_owned(), err);
1308            return Ok(());
1309        }
1310        // Exactly one (or we won): record contactId as known so
1311        // subsequent creates in this batch are pre-checked.
1312        run.known_direct_contact_ids
1313            .insert(contact_id_str.to_owned());
1314        run.batch_direct_ids
1315            .insert(contact_id_str.to_owned(), new_id.clone());
1316    }
1317    // §Creating a Chat: the server "MUST send
1318    // `Peer/groupUpdate` to each initial member".
1319    if created_obj.kind == ChatKind::Group {
1320        let event = OutboundEvent::GroupUpdate {
1321            chat_id: new_id.clone(),
1322            action: GroupUpdateAction::Create,
1323            recipients: other_member_ids(created_obj.members.iter().flatten(), ctx.account_id),
1324        };
1325        ctx.backend
1326            .on_outbound_event(ctx.caller, ctx.account_id, &event)
1327            .await;
1328    }
1329    acc.created.insert(
1330        create_id.to_owned(),
1331        jmap_server::serialize_value(&created_obj)?,
1332    );
1333    Ok(())
1334}
1335
1336/// Re-check a committed Direct-chat create `new_id` for a concurrent
1337/// duplicate with the same `contactId`, and roll it back when it lost.
1338/// Returns the [`SetError`] value for `notCreated`, or `None` when the create
1339/// stands.
1340///
1341/// Optimistic create-then-validate, required for JMAP-0c9. We fetch all
1342/// chats because the backend does not currently expose a filter-by-kind
1343/// query; a tighter fetch (Direct only) would be preferable but requires
1344/// backend support (JMAP-63k.9).
1345async fn direct_race_error<B: ChatBackend>(
1346    ctx: &SetCtx<'_, B>,
1347    new_id: &Id,
1348    contact_id_str: &str,
1349) -> Option<Value> {
1350    let current_chats = match ctx
1351        .backend
1352        .get_objects::<Chat>(ctx.caller, ctx.account_id, None, None)
1353        .await
1354    {
1355        Ok((chats, _)) => chats,
1356        Err(read_err) => {
1357            // The Chat (and earlier creates in this
1358            // batch) are already committed, so a
1359            // method-level serverFail would break
1360            // RFC 8620 §3.6.2 ("The method call made
1361            // no changes to the server's state").
1362            // Without the re-check the draft's
1363            // alreadyExists rule cannot be enforced,
1364            // so roll this create back and fail it
1365            // per id; the batch continues.
1366            let value = match ctx
1367                .backend
1368                .destroy_object::<Chat>(ctx.caller, ctx.account_id, new_id)
1369                .await
1370            {
1371                Ok(()) => server_fail_value_from_backend(&read_err),
1372                Err(e) => server_fail_value_from_backend(&e),
1373            };
1374            return Some(value);
1375        }
1376    };
1377    let duplicates: Vec<&Chat> = current_chats
1378        .iter()
1379        .filter(|c| {
1380            c.kind == ChatKind::Direct
1381                && c.contact_id.as_ref().map(|id| id.as_ref()) == Some(contact_id_str)
1382        })
1383        .collect();
1384    if duplicates.len() > 1 {
1385        // Race occurred: pick lexicographically smallest id
1386        // as the canonical winner.
1387        let canonical_id: Id = duplicates
1388            .iter()
1389            .map(|c| c.id.as_ref())
1390            .min()
1391            .map(Id::from)
1392            .unwrap_or_else(|| new_id.clone());
1393        if *new_id != canonical_id {
1394            // We lost the race: destroy our copy.
1395            if let Err(e) = ctx
1396                .backend
1397                .destroy_object::<Chat>(ctx.caller, ctx.account_id, new_id)
1398                .await
1399            {
1400                // Cleanup failed — the duplicate is still
1401                // live. Return a retryable server error
1402                // rather than alreadyExists with a
1403                // potentially inconsistent state.
1404                //
1405                // Route through server_fail_value_from_backend
1406                // to redact backend Display text from the
1407                // wire description per workspace redaction
1408                // discipline.
1409                return Some(server_fail_value_from_backend(&e));
1410            }
1411            // Cleanup succeeded: report alreadyExists
1412            // pointing to the canonical winner.
1413            return Some(
1414                serde_json::to_value(
1415                    SetError::new(SetErrorType::AlreadyExists).with_existing_id(canonical_id),
1416                )
1417                .unwrap_or_else(|e| server_fail_value_from_backend(&e)),
1418            );
1419        }
1420        // We won the race (our id is canonical): fall through
1421        // to success path below.
1422    }
1423    None
1424}
1425
1426/// The `update` part of `Chat/set`. Returns whether the backend was
1427/// written.
1428async fn set_update<B: ChatBackend>(
1429    ctx: &SetCtx<'_, B>,
1430    args: &mut serde_json::Map<String, Value>,
1431    acc: &mut SetAccumulators,
1432) -> Result<bool, JmapError> {
1433    let mut mutated = false;
1434    if let Some(Value::Object(update_map)) = args.remove("update") {
1435        for (id_str, patch_val) in update_map {
1436            mutated |= update_one(ctx, id_str, patch_val, acc).await?;
1437        }
1438    }
1439    Ok(mutated)
1440}
1441
1442/// One `update` entry of `Chat/set`. Returns whether the backend was
1443/// written.
1444async fn update_one<B: ChatBackend>(
1445    ctx: &SetCtx<'_, B>,
1446    id_str: String,
1447    patch_val: Value,
1448    acc: &mut SetAccumulators,
1449) -> Result<bool, JmapError> {
1450    let id = match jmap_server::parse_wire_id(&id_str, "id") {
1451        Ok(id) => id,
1452        Err(err) => {
1453            acc.not_updated
1454                .insert(id_str, serde_json::Value::from(&*err));
1455            return Ok(false);
1456        }
1457    };
1458    let mut patch = match update_patch(patch_val, ctx.created_ids, ctx.using) {
1459        Ok(patch) => patch,
1460        Err(err) => {
1461            acc.not_updated.insert(id_str, err);
1462            return Ok(false);
1463        }
1464    };
1465    let chat = match update_target(ctx, &id, &patch).await {
1466        Ok(chat) => chat,
1467        Err(err) => {
1468            acc.not_updated.insert(id_str, err);
1469            return Ok(false);
1470        }
1471    };
1472
1473    // Existence and permission come before shape (DECISIONS.md 44):
1474    // a changed read-only value and an undefined key are held in
1475    // `shape_err` and reported only after the `forbidden` checks
1476    // below, which look at patch keys alone.
1477    let shape_err = update_shape_error(&mut patch, &chat);
1478    let (kick, group_before) = match update_gates(ctx, &chat, &mut patch).await {
1479        Ok(gates) => gates,
1480        Err(err) => {
1481            acc.not_updated.insert(id_str, err);
1482            return Ok(false);
1483        }
1484    };
1485
1486    // Nothing left once identical values are dropped (or a literal
1487    // `{}`): a no-op success with no write (RFC 8620 §5.3).
1488    if patch.is_empty() && kick.is_none() {
1489        acc.updated.insert(id_str, Value::Null);
1490        return Ok(false);
1491    }
1492
1493    let member_change = match apply_member_keys(ctx, &chat, &mut patch)? {
1494        Ok(change) => change,
1495        Err(err) => {
1496            acc.not_updated.insert(id_str, err);
1497            return Ok(false);
1498        }
1499    };
1500    if let Some(err) = update_policy_error(ctx, &id, &chat, &patch, member_change.as_ref()).await {
1501        acc.not_updated.insert(id_str, err);
1502        return Ok(false);
1503    }
1504
1505    // Every `forbidden` check that needs no write has run: report a
1506    // held shape error now (DECISIONS.md 44).
1507    if let Some(err) = shape_err {
1508        acc.not_updated.insert(id_str, err);
1509        return Ok(false);
1510    }
1511    if let Some(err) = pinned_ids_error(ctx, &id, &chat, &patch).await {
1512        acc.not_updated.insert(id_str, err);
1513        return Ok(false);
1514    }
1515
1516    // draft-atwood-jmap-chat-mimi-00 §Moderation: `kickMembers`
1517    // "removes the listed users' clients from the group but keeps
1518    // them in the participant list". `members` is not touched; the
1519    // backend decides whether the Chat is bound to a room and the
1520    // caller may kick (`canKick`).
1521    // ponytail: the kick and the rest of the patch are two backend
1522    // calls; a failed write after a kick leaves the kick applied.
1523    if let Some(user_ids) = &kick {
1524        let outcome = ctx
1525            .backend
1526            .kick_chat_members(ctx.caller, ctx.account_id, &chat, user_ids)
1527            .await;
1528        if let Some(err) = refusal_value(outcome) {
1529            acc.not_updated.insert(id_str, err);
1530            return Ok(false);
1531        }
1532        // Nothing else to write: the Chat record is unchanged.
1533        if patch.is_empty() {
1534            acc.updated.insert(id_str, Value::Null);
1535            return Ok(false);
1536        }
1537    }
1538
1539    write_update(ctx, id_str, &id, patch, group_before, member_change, acc).await
1540}
1541
1542/// Resolve the `#creationId` references of one `Chat/set` update patch and
1543/// convert it into a typed [`PatchObject`], or return the [`SetError`] value for
1544/// `notUpdated`.
1545fn update_patch(
1546    mut patch_val: Value,
1547    created_ids: &BTreeMap<Id, Id>,
1548    using: &[String],
1549) -> Result<PatchObject, Value> {
1550    if let Err(err) = resolve_refs(&mut patch_val, CHAT_ID_PROPERTIES, created_ids)
1551        .and_then(|()| resolve_entry_refs(&mut patch_val, CHAT_ENTRY_ID_PROPERTIES, created_ids))
1552    {
1553        return Err(serde_json::Value::from(&*err));
1554    }
1555
1556    // draft-ietf-jmap-metadata-05 §3.2: patch errors "that can be
1557    // determined from the request alone ... MUST be reported with
1558    // "invalidPatch"" before `notFound`.
1559    if let Some(Err(err)) = patch_val
1560        .as_object()
1561        .map(|o| check_metadata_entry(o, false, using))
1562    {
1563        return Err(serde_json::Value::from(&*err));
1564    }
1565    if let Some(Err(e)) = patch_val.as_object().map(jmap_server::check_patch_paths) {
1566        return Err(json!({ "type": "invalidPatch", "description": e.to_string() }));
1567    }
1568
1569    // Convert wire-format Value into a typed PatchObject. RFC 8620
1570    // §5.3 mandates a PatchObject is a JSON Object; non-object
1571    // values produce an `invalidPatch` SetError.
1572    serde_json::from_value::<PatchObject>(patch_val)
1573        .map_err(|e| json!({ "type": "invalidPatch", "description": e.to_string() }))
1574}
1575
1576/// The stored Chat `id` a `Chat/set` update targets, read once for every
1577/// check, or the [`SetError`] value for `notUpdated`.
1578async fn update_target<B: ChatBackend>(
1579    ctx: &SetCtx<'_, B>,
1580    id: &Id,
1581    patch: &PatchObject,
1582) -> Result<Chat, Value> {
1583    let stored = match ctx
1584        .backend
1585        .get_objects::<Chat>(
1586            ctx.caller,
1587            ctx.account_id,
1588            Some(std::slice::from_ref(id)),
1589            None,
1590        )
1591        .await
1592    {
1593        Ok((chats, _)) => chats.into_iter().next(),
1594        Err(e) => return Err(server_fail_value_from_backend(&e)),
1595    };
1596    let Some(mut chat) = stored else {
1597        return Err(Value::from(&SetError::new(SetErrorType::NotFound)));
1598    };
1599
1600    // `unreadCount` is server-set, and when the backend does not
1601    // maintain it the "current server value" a client can echo is
1602    // the one Chat/get computes (fill_unread_counts), not the stored
1603    // field, so compare against that (bd:JMAP-t8ej.32 item 3).
1604    if patch.as_map().contains_key("unreadCount") && !ctx.backend.maintains_unread_count() {
1605        let (messages, positions) = messages_and_positions(ctx.backend, ctx.caller, ctx.account_id)
1606            .await
1607            .map_err(|e| server_fail_value_from_backend(&e))?;
1608        chat.unread_count = unread_count(&messages, &positions, ctx.account_id, chat.id.as_ref());
1609    }
1610    Ok(chat)
1611}
1612
1613/// Whether `k` is a `Chat/set` update key §Chat/set "Updating a Chat"
1614/// defines: the client-settable Chat properties that are not immutable,
1615/// and [`MEMBER_PATCH_KEYS`], plus the mimi draft's [`KICK_MEMBERS_KEY`]
1616/// (whole key only). JSON Pointer paths count by their first segment.
1617fn is_defined_update_key(k: &str) -> bool {
1618    let top = k.split('/').next().unwrap_or(k);
1619    is_client_updatable::<Chat>(top) || MEMBER_PATCH_KEYS.contains(&top) || k == KICK_MEMBERS_KEY
1620}
1621
1622/// Drop the read-only values of a `Chat/set` update patch that are
1623/// identical to `chat`, and return the shape error the patch still has:
1624/// a changed read-only value, or an undefined key (`invalidProperties`).
1625///
1626/// RFC 8620 §5.3: "Any server-set properties MAY be included in
1627/// the patch if their value is identical to the current server
1628/// value ... Otherwise, the update MUST be rejected with an
1629/// "invalidProperties" `SetError`." Identical values are dropped
1630/// here, so the checks below see only the client changes.
1631fn update_shape_error(patch: &mut PatchObject, chat: &Chat) -> Option<Value> {
1632    let shape_err = strip_read_only_patch::<Chat>(patch.as_map_mut(), chat).err();
1633    if shape_err.is_some() {
1634        return shape_err;
1635    }
1636    // Only the keys §Chat/set "Updating a Chat" defines may be
1637    // patched (`is_defined_update_key`). Any other key is
1638    // `invalidProperties`.
1639    let bad_props: Vec<&str> = patch
1640        .as_map()
1641        .keys()
1642        .map(String::as_str)
1643        .filter(|k| !is_defined_update_key(k))
1644        .collect();
1645    (!bad_props.is_empty()).then(|| json!({ "type": "invalidProperties", "properties": bad_props }))
1646}
1647
1648/// The `forbidden` gates of a `Chat/set` update that look at patch keys
1649/// alone: `ChatRestrictions::may_update_chat`, the `kickMembers` shape,
1650/// a closed group, and the group admin keys. Takes `kickMembers` out of
1651/// `patch` and returns its ids and, for a group update that touches
1652/// members or shared settings, the stored member list for
1653/// `group_update_events`. `Err` is the [`SetError`] value for `notUpdated`.
1654async fn update_gates<B: ChatBackend>(
1655    ctx: &SetCtx<'_, B>,
1656    chat: &Chat,
1657    patch: &mut PatchObject,
1658) -> Result<(Option<Vec<Id>>, Option<Vec<ChatMember>>), Value> {
1659    // Per-Chat restrictions of extension-bound Chats; see
1660    // `ChatRestrictions::may_update_chat`. It sees only the keys
1661    // the update may change.
1662    let patch_keys: Vec<&str> = patch
1663        .as_map()
1664        .keys()
1665        .map(String::as_str)
1666        .filter(|k| is_defined_update_key(k))
1667        .collect();
1668    let outcome = ctx
1669        .backend
1670        .may_update_chat(ctx.caller, ctx.account_id, chat, &patch_keys)
1671        .await;
1672    if let Some(err) = refusal_value(outcome) {
1673        return Err(err);
1674    }
1675
1676    // draft-atwood-jmap-chat-mimi-00 §Moderation `kickMembers`: an
1677    // operation, not a property, taken out of the patch here and
1678    // handed to `ChatModeration::kick_chat_members` before the write.
1679    let kick =
1680        take_kick_members(patch.as_map_mut()).map_err(|err| serde_json::Value::from(&*err))?;
1681
1682    // draft-atwood-jmap-chat-00 §Chat `closedAt`: "After it is
1683    // set, the server MUST reject with a `forbidden` SetError ...
1684    // every `Chat/set` update that changes membership ... or
1685    // shared group settings". Pointer paths beneath them count.
1686    // The stored group and the member list the update stores, for
1687    // `group_update_events` once the update succeeds.
1688    let mut group_before: Option<Vec<ChatMember>> = None;
1689    let touches_closed_keys = patch.as_map().keys().any(|k| {
1690        let top = k.split('/').next().unwrap_or(k);
1691        MEMBER_PATCH_KEYS.contains(&top) || SHARED_GROUP_KEYS.contains(&top)
1692    });
1693    if touches_closed_keys {
1694        if chat.closed_at.is_some() {
1695            return Err(json!({ "type": "forbidden", "description": "the group is closed" }));
1696        }
1697        // "For group chats, admins additionally may update:
1698        // `name`, `description`, `avatarBlobId`."
1699        let touches_admin_keys = patch
1700            .as_map()
1701            .keys()
1702            .any(|k| GROUP_ADMIN_KEYS.contains(&k.split('/').next().unwrap_or(k)));
1703        if touches_admin_keys
1704            && !(chat.kind == ChatKind::Group && is_chat_admin(chat, ctx.account_id))
1705        {
1706            return Err(json!({
1707                "type": "forbidden",
1708                "description": "only group chat admins may update name, description and avatarBlobId",
1709            }));
1710        }
1711        if chat.kind == ChatKind::Group {
1712            group_before = Some(chat.members.clone().unwrap_or_default());
1713        }
1714    }
1715    Ok((kick, group_before))
1716}
1717
1718/// The member list a `Chat/set` update stores, and whether it closes the
1719/// group.
1720type MemberChange = (Vec<ChatMember>, bool);
1721
1722/// Apply the member patch keys of a `Chat/set` update to the stored list
1723/// and replace them in `patch` by the resulting `members` (and
1724/// `closedAt` when the change closes the group). Returns that member list
1725/// and whether it closes the group, or `None` when the patch has no
1726/// member key. The inner `Err` is the [`SetError`] value for `notUpdated`.
1727///
1728/// draft-atwood-jmap-chat-00 §Chat/set "Updating a Chat": the
1729/// member patch keys are operations on `members`, not
1730/// properties. They are applied to the stored list here and
1731/// replaced by the resulting `members`, so the backend never
1732/// stores them.
1733/// ponytail: check-then-update is not atomic; two concurrent
1734/// member patches can lose one. A backend needing strictness
1735/// re-checks inside its update transaction.
1736fn apply_member_keys<B: ChatBackend>(
1737    ctx: &SetCtx<'_, B>,
1738    chat: &Chat,
1739    patch: &mut PatchObject,
1740) -> Result<Result<Option<MemberChange>, Value>, JmapError> {
1741    if !MEMBER_PATCH_KEYS
1742        .iter()
1743        .any(|k| patch.as_map().contains_key(*k))
1744    {
1745        return Ok(Ok(None));
1746    }
1747    let max_members = ctx
1748        .backend
1749        .limits(ctx.caller, ctx.account_id)
1750        .max_group_chat_members;
1751    match apply_member_patch_keys(chat, ctx.account_id, patch.as_map(), max_members) {
1752        Ok((members, closes)) => {
1753            let member_change = Some((members.clone(), closes));
1754            let map = patch.as_map_mut();
1755            for key in MEMBER_PATCH_KEYS {
1756                map.remove(*key);
1757            }
1758            map.insert("members".to_owned(), jmap_server::serialize_value(members)?);
1759            // "the server MUST set `closedAt` ({{chat}}) in
1760            // the same operation".
1761            if closes {
1762                map.insert("closedAt".to_owned(), json!(now_utc_string()));
1763            }
1764            Ok(Ok(member_change))
1765        }
1766        Err(set_err) => Ok(Err(serde_json::Value::from(&*set_err))),
1767    }
1768}
1769
1770/// The `forbidden` checks of a `Chat/set` update that read backend state:
1771/// a banned user among the added members, and the `pinnedMessageIds`
1772/// policy. Returns the [`SetError`] value for `notUpdated`, or `None`.
1773async fn update_policy_error<B: ChatBackend>(
1774    ctx: &SetCtx<'_, B>,
1775    id: &Id,
1776    chat: &Chat,
1777    patch: &PatchObject,
1778    member_change: Option<&MemberChange>,
1779) -> Option<Value> {
1780    // draft-atwood-jmap-chat-00 §ChatBan/set: "while the ban lasts
1781    // the server MUST reject adding the user with an `addMembers`
1782    // entry, returning a `forbidden` SetError." Only users the
1783    // update adds count; a ban whose `expiresAt` has passed is not
1784    // in force.
1785    if let Some((members, _)) = member_change {
1786        let added: Vec<&Id> = members
1787            .iter()
1788            .filter(|m| chat.members.iter().flatten().all(|old| old.id != m.id))
1789            .map(|m| &m.id)
1790            .collect();
1791        if !added.is_empty() {
1792            match banned_among(ctx.backend, ctx.caller, ctx.account_id, id, &added).await {
1793                Ok(false) => {}
1794                Ok(true) => {
1795                    return Some(json!({
1796                        "type": "forbidden",
1797                        "description": "addMembers names a user banned from this chat",
1798                    }));
1799                }
1800                Err(e) => return Some(server_fail_value_from_backend(&e)),
1801            }
1802        }
1803    }
1804
1805    // draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: who may
1806    // modify the list depends on the chat kind; the backend decides.
1807    // Pointer paths beneath the property are gated too.
1808    let touches_pins = patch
1809        .as_map()
1810        .keys()
1811        .any(|k| k == "pinnedMessageIds" || k.starts_with("pinnedMessageIds/"));
1812    if touches_pins {
1813        let outcome = ctx
1814            .backend
1815            .may_set_pinned_messages(ctx.caller, ctx.account_id, id)
1816            .await;
1817        return refusal_value(outcome);
1818    }
1819    None
1820}
1821
1822/// The [`SetError`] value when a `Chat/set` update's `pinnedMessageIds` would
1823/// add an id that does not name a Message in this Chat, or `None`.
1824///
1825/// draft-atwood-jmap-chat-00 §Chat `pinnedMessageIds`: an update
1826/// that would add an id not naming a Message in this Chat is
1827/// `invalidProperties`. RFC 8620 §5.3 forbids pointers into
1828/// arrays (`update_object` rejects them as invalidPatch), so only
1829/// the whole-property key can add ids, and its value is the
1830/// post-patch list. Only ids absent from the stored list count
1831/// as added; see `ChatAccessPolicy::validate_pinned_message_ids`.
1832/// ponytail: check-then-update is not atomic; a Message
1833/// hard-deleted between the two leaves a stale pin. A backend
1834/// needing strictness re-checks inside its update transaction.
1835async fn pinned_ids_error<B: ChatBackend>(
1836    ctx: &SetCtx<'_, B>,
1837    id: &Id,
1838    chat: &Chat,
1839    patch: &PatchObject,
1840) -> Option<Value> {
1841    let Some(Value::Array(new_pins)) = patch.as_map().get("pinnedMessageIds") else {
1842        return None;
1843    };
1844    let pins = match new_pins
1845        .iter()
1846        .filter_map(Value::as_str)
1847        .map(|s| jmap_server::parse_wire_id(s, "pinnedMessageIds"))
1848        .collect::<Result<Vec<Id>, _>>()
1849    {
1850        Ok(pins) => pins,
1851        Err(err) => return Some(serde_json::Value::from(&*err)),
1852    };
1853    let added: Vec<Id> = pins
1854        .into_iter()
1855        .filter(|pin| !chat.pinned_message_ids.contains(pin))
1856        .collect();
1857    if added.is_empty() {
1858        return None;
1859    }
1860    let outcome = ctx
1861        .backend
1862        .validate_pinned_message_ids(ctx.caller, ctx.account_id, id, &added)
1863        .await;
1864    refusal_value(outcome)
1865}
1866
1867/// Write one checked `Chat/set` update and send the group's
1868/// `Peer/groupUpdate` events once it succeeded. Returns whether the
1869/// backend was written.
1870async fn write_update<B: ChatBackend>(
1871    ctx: &SetCtx<'_, B>,
1872    id_str: String,
1873    id: &Id,
1874    patch: PatchObject,
1875    group_before: Option<Vec<ChatMember>>,
1876    member_change: Option<MemberChange>,
1877    acc: &mut SetAccumulators,
1878) -> Result<bool, JmapError> {
1879    let metadata_changed = patch
1880        .as_map()
1881        .keys()
1882        .any(|k| GROUP_ADMIN_KEYS.contains(&k.split('/').next().unwrap_or(k)));
1883    let outcome = ctx
1884        .backend
1885        .update_object::<Chat>(ctx.caller, ctx.account_id, id, patch)
1886        .await;
1887    if let (Ok(_), Some(before)) = (&outcome, &group_before) {
1888        let (after, closes) = match &member_change {
1889            Some((members, closes)) => (Some(members.as_slice()), *closes),
1890            None => (None, false),
1891        };
1892        for event in
1893            group_update_events(id, ctx.account_id, before, after, closes, metadata_changed)
1894        {
1895            ctx.backend
1896                .on_outbound_event(ctx.caller, ctx.account_id, &event)
1897                .await;
1898        }
1899    }
1900    match outcome {
1901        Ok(Some(obj)) => {
1902            acc.updated
1903                .insert(id_str, jmap_server::serialize_value(&obj)?);
1904            Ok(true)
1905        }
1906        Ok(None) => {
1907            acc.updated.insert(id_str, Value::Null);
1908            Ok(true)
1909        }
1910        Err(e) => {
1911            acc.not_updated.insert(id_str, backend_set_error_value(e));
1912            Ok(false)
1913        }
1914    }
1915}
1916
1917/// The `destroy` part of `Chat/set`. Returns whether the backend was
1918/// written.
1919async fn set_destroy<B: ChatBackend>(
1920    ctx: &SetCtx<'_, B>,
1921    args: &mut serde_json::Map<String, Value>,
1922    acc: &mut SetAccumulators,
1923) -> Result<bool, JmapError> {
1924    let mut mutated = false;
1925    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
1926        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
1927        // Reject the whole request if any element is non-string rather than
1928        // silently skipping it, which would produce a misleading response.
1929        let id_strs: Vec<&str> = destroy_arr
1930            .iter()
1931            .map(|v| {
1932                v.as_str().ok_or_else(|| {
1933                    JmapError::invalid_arguments(format!(
1934                        "destroy: every element must be a string Id; got {}",
1935                        jmap_server::json_type_name(v)
1936                    ))
1937                })
1938            })
1939            .collect::<Result<_, _>>()?;
1940        // §Destroying a Chat: "For channel Chats, destroy via `Chat/set` is
1941        // not supported; the server MUST return a SetError of type
1942        // `forbidden`." An id that does not resolve is left for
1943        // destroy_object to surface `notFound`.
1944        let mut ids: Vec<Id> = Vec::new();
1945        for raw in id_strs {
1946            match jmap_server::parse_wire_id(raw, "id") {
1947                Ok(id) => ids.push(id),
1948                Err(err) => {
1949                    acc.not_destroyed
1950                        .insert(raw.to_owned(), serde_json::Value::from(&*err));
1951                }
1952            }
1953        }
1954        // A failed read is per-id `serverFail`, not a method error: the
1955        // creates and updates above are already committed, and a method
1956        // `serverFail` means "The method call made no changes to the
1957        // server's state" (RFC 8620 §3.6.2). Without the kinds no id can
1958        // be checked, so none is destroyed.
1959        let channel_ids: HashSet<Id> = if ids.is_empty() {
1960            HashSet::new()
1961        } else {
1962            match ctx
1963                .backend
1964                .get_objects::<Chat>(ctx.caller, ctx.account_id, Some(&ids), None)
1965                .await
1966            {
1967                Ok((chats, _)) => chats
1968                    .into_iter()
1969                    .filter(|c| c.kind == ChatKind::Channel)
1970                    .map(|c| c.id)
1971                    .collect(),
1972                Err(e) => {
1973                    let err = server_fail_value_from_backend(&e);
1974                    for id in ids.drain(..) {
1975                        acc.not_destroyed
1976                            .insert(id.as_ref().to_owned(), err.clone());
1977                    }
1978                    HashSet::new()
1979                }
1980            }
1981        };
1982        for id in ids {
1983            let id_str = id.as_ref();
1984            if channel_ids.contains(&id) {
1985                acc.not_destroyed.insert(
1986                    id_str.to_owned(),
1987                    json!({
1988                        "type": "forbidden",
1989                        "description": "channel Chats are removed via Space/set removeChannels",
1990                    }),
1991                );
1992                continue;
1993            }
1994
1995            match ctx
1996                .backend
1997                .destroy_object::<Chat>(ctx.caller, ctx.account_id, &id)
1998                .await
1999            {
2000                Ok(()) => {
2001                    mutated = true;
2002                    acc.destroyed.push(Value::String(id_str.to_owned()));
2003                    ctx.backend
2004                        .on_chat_destroyed(ctx.caller, ctx.account_id, &id)
2005                        .await;
2006                }
2007                Err(e) => {
2008                    acc.not_destroyed
2009                        .insert(id_str.to_owned(), backend_set_error_value(e));
2010                }
2011            }
2012        }
2013    }
2014    Ok(mutated)
2015}
2016
2017// ---------------------------------------------------------------------------
2018// Chat/typing
2019// ---------------------------------------------------------------------------
2020
2021/// Handle a `Chat/typing` method call (draft-atwood-jmap-chat-00 §Chat).
2022///
2023/// `args` is the draft §Chat `Chat/typing` request shape (`accountId`,
2024/// `chatId`); the returned `Value` is the §Chat response shape
2025/// (`accountId` echo). No persistent state is changed.
2026///
2027/// This method is ephemeral — it signals the user is typing in a chat.
2028/// No state is persisted. In a full implementation, the server would
2029/// fan out a typing event to chat participants; this handler validates
2030/// and returns. An unknown `chatId` and a Chat the account does not
2031/// participate in both yield the same `invalidArguments` error. The
2032/// sender identity is always derived server-side from `accountId` —
2033/// clients MUST NOT supply a `senderId` field.
2034///
2035/// # Blocked-sender suppression
2036///
2037/// Per draft-atwood-jmap-chat-00 commit `d68b4e3` ("close blocked-sender
2038/// suppression gaps for typing/presence"): when the requesting account
2039/// corresponds to a [`ChatContact`] whose `blocked` is `true` on the
2040/// recipient's contact list, the server MUST silently suppress the
2041/// typing event for that recipient. The sender is NOT informed.
2042///
2043/// [`ChatContact`]: jmap_chat_types::ChatContact
2044///
2045/// This handler does not call [`ChatAccessPolicy::is_contact_blocked`](crate::ChatAccessPolicy::is_contact_blocked): that
2046/// check reads the recipient's contact list, and the request names only
2047/// the sender's `accountId`. The transport that fans the event out knows
2048/// each recipient's account and MUST call [`crate::should_deliver_typing`]
2049/// per recipient, which applies this check and the
2050/// `receiveTypingIndicators` and membership checks.
2051/// The wire response (echo `accountId`) is the same either way.
2052///
2053/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
2054///
2055/// # Errors
2056///
2057/// Returns a method-level [`JmapError`]:
2058///
2059/// - `invalidArguments` when `accountId` is missing or not a valid Id,
2060///   `chatId` is missing or not a valid Id, `typing` is missing or not a
2061///   boolean, or `chatId` names no Chat the account participates in;
2062/// - `accountNotFound` when the backend does not know `accountId`;
2063/// - `serverFail` when the backend fails.
2064pub async fn handle_chat_typing<B: ChatBackend>(
2065    backend: &B,
2066    caller: &B::CallerCtx,
2067    args: Value,
2068) -> Result<HandlerOutput, JmapError> {
2069    let (account_id, args) = extract_account_id(args)?;
2070
2071    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
2072    if !backend
2073        .account_exists(caller, &account_id)
2074        .await
2075        .map_err(|e| server_fail_from_backend(&e))?
2076    {
2077        return Err(JmapError::account_not_found());
2078    }
2079
2080    let chat_id: Id = match args.get("chatId").and_then(|v| v.as_str()) {
2081        Some(s) => Id::new_validated(s)
2082            .map_err(|e| JmapError::invalid_arguments(format!("chatId: {e}")))?,
2083        None => return Err(JmapError::invalid_arguments("chatId is required")),
2084    };
2085
2086    let typing: bool = match args.get("typing") {
2087        Some(Value::Bool(b)) => *b,
2088        None => return Err(JmapError::invalid_arguments("typing is required")),
2089        Some(_) => return Err(JmapError::invalid_arguments("typing must be a boolean")),
2090    };
2091
2092    // draft-atwood-jmap-chat-00 §Chat/typing `chatId` (jmap-chat-spec
2093    // 77c3474 L1164): "The server SHOULD return an `invalidArguments`
2094    // method error if `chatId` does not exist or the account is not a
2095    // participant in that Chat, and SHOULD NOT distinguish the two cases."
2096    // This crate performs the recommended behaviour by choice. A group chat's participants are its
2097    // `members`, where the owner is referenced by the accountId
2098    // (§Terminology).
2099    let (found, _not_found) = backend
2100        .get_objects::<Chat>(
2101            caller,
2102            &account_id,
2103            Some(std::slice::from_ref(&chat_id)),
2104            None,
2105        )
2106        .await
2107        .map_err(|e| server_fail_from_backend(&e))?;
2108    found
2109        .into_iter()
2110        .next()
2111        .filter(|c| {
2112            c.kind != ChatKind::Group || c.members.iter().flatten().any(|m| m.id == account_id)
2113        })
2114        .ok_or_else(|| {
2115            JmapError::invalid_arguments("chatId is not a Chat the account participates in")
2116        })?;
2117
2118    // §Chat/typing Server Behavior: deliver a `typing` push event to the
2119    // other local participants and, "For federated Chats, the server SHOULD
2120    // invoke `Peer/typing`". The backend does both from this event.
2121    backend
2122        .on_outbound_event(
2123            caller,
2124            &account_id,
2125            &OutboundEvent::Typing { chat_id, typing },
2126        )
2127        .await;
2128
2129    Ok(HandlerOutput::new(json!({
2130        "accountId": account_id.as_ref(),
2131    })))
2132}