Skip to main content

jmap_chat_server/
position.rs

1//! `ReadPosition`/* method handlers (draft-atwood-jmap-chat-00 §`ReadPosition`).
2//!
3//! [`ReadPosition`] tracks how far a user has read in a given Chat. There is at
4//! most one `ReadPosition` per (account, chat) pair. The records are managed
5//! by the server: `ReadPosition/set` supports only `update`; `create` and
6//! `destroy` return `forbidden`. The record itself is created on first
7//! message delivery by [`crate::message::handle_message_set`] or, for
8//! channel Chats, on [`crate::space::handle_space_join`], and is destroyed
9//! with its Chat by the backend.
10//!
11//! # Wire-shape contract
12//!
13//! Every `handle_*` function in this module conforms to the canonical JMAP
14//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
15//! Object whose fields match the corresponding RFC 8620 §5 method shape
16//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3), with the
17//! type-specific arguments defined by draft-atwood-jmap-chat-00
18//! §`ReadPosition`. The returned `Value` is the corresponding
19//! method-response object per the same section refs.
20//!
21//! The returned `HandlerOutput::extra_invocations` carries any invocations
22//! that this handler injected into the request stream (RFC 8620 §6.3);
23//! for the handlers in this module the vector is **always empty**.
24//!
25//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
26//! §3.6.2 and §5):
27//!
28//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
29//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
30//!   `maxObjectsInSet`;
31//! - `/set`: `stateMismatch`;
32//! - `/changes`: `cannotCalculateChanges`.
33//!
34//! Per-target failures inside `/set` (including the `forbidden` create/destroy
35//! rejections) surface in the `notCreated` / `notUpdated` / `notDestroyed` maps
36//! within `Ok((Value, ...))`, not as `Err`.
37
38use std::collections::BTreeMap;
39
40use jmap_chat_types::ReadPosition;
41use jmap_types::{Id, JmapError, PatchObject, State};
42use serde_json::{Value, json};
43
44use crate::ChatBackend;
45use crate::chat::record_unread_count_changes;
46use crate::helpers::check_read_only_patch;
47use crate::helpers::resolve_refs;
48use crate::helpers::{
49    SetAccumulators, enforce_max_objects_in_get, enforce_max_objects_in_set, extract_account_id,
50    finalize_set_response, not_found_json, now_utc_string, serialize_value,
51};
52use jmap_server::{HandlerOutput, backend_set_error_value, server_fail_from_backend};
53use jmap_server::{SetError, SetErrorType};
54
55// ---------------------------------------------------------------------------
56// ReadPosition/get
57// ---------------------------------------------------------------------------
58
59/// Handle a `ReadPosition/get` method call (draft-atwood-jmap-chat-00 §`ReadPosition`).
60///
61/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
62/// `ids`, optional `properties`); the returned `Value` is the §5.1
63/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
64///
65/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
66///
67/// # Errors
68///
69/// Returns a method-level [`JmapError`]:
70///
71/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
72///   `ids` is not an Id array;
73/// - `accountNotFound` when the backend does not know `accountId`;
74/// - `requestTooLarge` when `ids` holds more than `maxObjectsInGet` ids;
75/// - `serverFail` when the backend fails.
76pub async fn handle_position_get<B: ChatBackend>(
77    backend: &B,
78    caller: &B::CallerCtx,
79    args: Value,
80) -> Result<HandlerOutput, JmapError> {
81    let (account_id, mut args) = extract_account_id(args)?;
82
83    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
84    if !backend
85        .account_exists(caller, &account_id)
86        .await
87        .map_err(|e| server_fail_from_backend(&e))?
88    {
89        return Err(JmapError::account_not_found());
90    }
91    enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
92
93    let ids: Option<Vec<Id>> = match args.remove("ids") {
94        None | Some(Value::Null) => None,
95        Some(v) => Some(
96            serde_json::from_value(v)
97                .map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
98        ),
99    };
100
101    let ids_slice = ids.as_deref();
102    let (list, not_found) = backend
103        .get_objects::<ReadPosition>(caller, &account_id, ids_slice, None)
104        .await
105        .map_err(|e| server_fail_from_backend(&e))?;
106
107    let state = backend
108        .get_state::<ReadPosition>(caller, &account_id)
109        .await
110        .map_err(|e| server_fail_from_backend(&e))?;
111
112    let list_json: Vec<Value> = list
113        .iter()
114        .map(serialize_value)
115        .collect::<Result<Vec<_>, _>>()?;
116
117    Ok(HandlerOutput::new(json!({
118        "accountId": account_id.as_ref(),
119        "state": state.as_ref(),
120        "list": list_json,
121        "notFound": not_found_json(&not_found),
122    })))
123}
124
125// ---------------------------------------------------------------------------
126// ReadPosition/changes
127// ---------------------------------------------------------------------------
128
129/// Handle a `ReadPosition/changes` method call (draft-atwood-jmap-chat-00 §`ReadPosition`).
130///
131/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
132/// `sinceState`, optional `maxChanges`); the returned `Value` is the
133/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
134/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
135///
136/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
137///
138/// # Errors
139///
140/// Returns a method-level [`JmapError`]:
141///
142/// - `invalidArguments` when `accountId` is missing or not a valid Id,
143///   `sinceState` is missing, or `maxChanges` is not a positive integer;
144/// - `accountNotFound` when the backend does not know `accountId`;
145/// - `cannotCalculateChanges` when the backend cannot compute the changes
146///   since `sinceState`;
147/// - `serverFail` when the backend fails.
148pub async fn handle_position_changes<B: ChatBackend>(
149    backend: &B,
150    caller: &B::CallerCtx,
151    args: Value,
152) -> Result<HandlerOutput, JmapError> {
153    let (account_id, args) = extract_account_id(args)?;
154
155    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
156    if !backend
157        .account_exists(caller, &account_id)
158        .await
159        .map_err(|e| server_fail_from_backend(&e))?
160    {
161        return Err(JmapError::account_not_found());
162    }
163
164    let since_state: State = match args.get("sinceState").and_then(|v| v.as_str()) {
165        Some(s) => State::from(s),
166        None => return Err(JmapError::invalid_arguments("sinceState is required")),
167    };
168
169    let max_changes = jmap_server::parse_max_changes(args.get("maxChanges"))?;
170
171    let result = backend
172        .get_changes::<ReadPosition>(
173            caller,
174            &account_id,
175            jmap_server::ChangesParams::new(&since_state).max_changes(max_changes),
176        )
177        .await
178        .map_err(jmap_server::changes_error_from_backend)?;
179
180    Ok(HandlerOutput::new(json!({
181        "accountId": account_id.as_ref(),
182        "oldState": since_state.as_ref(),
183        "newState": result.new_state.as_ref(),
184        "hasMoreChanges": result.has_more_changes,
185        "updatedProperties": Value::Null,
186        "created":   result.created.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
187        "updated":   result.updated.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
188        "destroyed": result.destroyed.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
189    })))
190}
191
192// ---------------------------------------------------------------------------
193// ReadPosition/set
194// ---------------------------------------------------------------------------
195
196/// Handle a `ReadPosition/set` method call (draft-atwood-jmap-chat-00 §`ReadPosition`).
197///
198/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
199/// `ifInState`, optional `create` / `update` / `destroy` maps); the
200/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
201/// `oldState`, `newState`, plus the per-operation `created` /
202/// `notCreated` / `updated` / `notUpdated` / `destroyed` / `notDestroyed`
203/// maps).
204///
205/// Validation enforced here (not in the backend):
206/// - `create` and `destroy` are rejected with `forbidden`.
207/// - `id`, `chatId` and `lastReadAt` are server-set/immutable and
208///   rejected in updates unless identical to the stored value (RFC 8620 §5.3).
209/// - Every successful update sets `lastReadAt` to the current time,
210///   except an empty patch, which is a no-op success.
211///
212/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
213///
214/// A `lastReadMessageId` that is a `#creationId` reference names a record created earlier in the request and resolves against
215/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
216/// §5.3); an unknown reference is `invalidProperties` naming the property.
217///
218/// # Errors
219///
220/// Returns a method-level [`JmapError`]:
221///
222/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
223///   an element of `destroy` is not a string;
224/// - `accountNotFound` when the backend does not know `accountId`;
225/// - `requestTooLarge` when `create`, `update` and `destroy` together hold
226///   more than `maxObjectsInSet` objects;
227/// - `stateMismatch` when `ifInState` is not the current state;
228/// - `serverFail` when the backend fails.
229///
230/// An update that fails on its own, and every create and destroy, is a
231/// [`SetError`] in the response, not an `Err`.
232pub async fn handle_position_set<B: ChatBackend>(
233    backend: &B,
234    caller: &B::CallerCtx,
235    created_ids: &BTreeMap<Id, Id>,
236    args: Value,
237) -> Result<HandlerOutput, JmapError> {
238    let (account_id, mut args) = extract_account_id(args)?;
239
240    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-fo38).
241    if !backend
242        .account_exists(caller, &account_id)
243        .await
244        .map_err(|e| server_fail_from_backend(&e))?
245    {
246        return Err(JmapError::account_not_found());
247    }
248
249    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
250    // unbounded /set batches before touching the storage layer.
251    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
252
253    let old_state = backend
254        .get_state::<ReadPosition>(caller, &account_id)
255        .await
256        .map_err(|e| server_fail_from_backend(&e))?;
257
258    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
259        && if_in_state != old_state.as_ref()
260    {
261        return Err(JmapError::state_mismatch());
262    }
263
264    let ctx = SetCtx {
265        backend,
266        caller,
267        account_id: &account_id,
268        created_ids,
269    };
270    let mut acc = SetAccumulators::default();
271    set_create(&args, &mut acc);
272    let mutated = set_update(&ctx, &mut args, &mut acc).await?;
273    set_destroy(&args, &mut acc)?;
274
275    finalize_set_response::<B, ReadPosition>(backend, caller, &account_id, old_state, mutated, acc)
276        .await
277}
278
279/// What every `ReadPosition/set` sub-function needs from the request
280/// (docs/design/set-handler-split.md).
281struct SetCtx<'a, B: ChatBackend> {
282    backend: &'a B,
283    caller: &'a B::CallerCtx,
284    account_id: &'a Id,
285    /// The request-wide `#creationId` map (RFC 8620 §5.3).
286    created_ids: &'a BTreeMap<Id, Id>,
287}
288
289/// The `create` part of `ReadPosition/set`: forbidden.
290///
291/// §ReadPosition/set: "`create` and `destroy` are not supported; both
292/// MUST return a [`SetError`] of type `forbidden`. [`ReadPosition`] records are
293/// managed by the server." The server creates them on first message
294/// delivery (see `crate::message::handle_message_set`).
295fn set_create(args: &serde_json::Map<String, Value>, acc: &mut SetAccumulators) {
296    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
297        for create_id in create_map.keys() {
298            acc.not_created
299                .insert(create_id.clone(), forbidden_server_managed());
300        }
301    }
302}
303
304/// The `update` part of `ReadPosition/set`, then the `Chat.unreadCount`
305/// recompute for the updated positions. Returns whether the backend was
306/// written.
307async fn set_update<B: ChatBackend>(
308    ctx: &SetCtx<'_, B>,
309    args: &mut serde_json::Map<String, Value>,
310    acc: &mut SetAccumulators,
311) -> Result<bool, JmapError> {
312    let mut mutated = false;
313    let mut updated_ids: Vec<Id> = Vec::new();
314    if let Some(Value::Object(update_map)) = args.remove("update") {
315        for (id_str, patch_val) in update_map {
316            if let Some(id) = update_one(ctx, id_str, patch_val, acc).await? {
317                mutated = true;
318                updated_ids.push(id);
319            }
320        }
321    }
322
323    if !updated_ids.is_empty()
324        && let Ok((updated_positions, _)) = ctx
325            .backend
326            .get_objects::<ReadPosition>(ctx.caller, ctx.account_id, Some(&updated_ids), None)
327            .await
328    {
329        let chat_ids = updated_positions.into_iter().map(|p| p.chat_id).collect();
330        record_unread_count_changes(ctx.backend, ctx.caller, ctx.account_id, chat_ids).await;
331    }
332    Ok(mutated)
333}
334
335/// One `update` entry of `ReadPosition/set`. Returns the id when the
336/// backend was written.
337async fn update_one<B: ChatBackend>(
338    ctx: &SetCtx<'_, B>,
339    id_str: String,
340    mut patch_val: Value,
341    acc: &mut SetAccumulators,
342) -> Result<Option<Id>, JmapError> {
343    let id = match jmap_server::parse_wire_id(&id_str, "id") {
344        Ok(id) => id,
345        Err(err) => {
346            acc.not_updated
347                .insert(id_str, serde_json::Value::from(&*err));
348            return Ok(None);
349        }
350    };
351    if let Err(err) = resolve_refs(&mut patch_val, &["lastReadMessageId"], ctx.created_ids) {
352        acc.not_updated
353            .insert(id_str, serde_json::Value::from(&*err));
354        return Ok(None);
355    }
356
357    // §ReadPosition: `id` and `lastReadAt` are server-set, `chatId`
358    // is immutable.
359    match check_read_only_patch::<_, ReadPosition>(
360        ctx.backend,
361        ctx.caller,
362        ctx.account_id,
363        &id,
364        &mut patch_val,
365    )
366    .await
367    {
368        Ok(false) => {}
369        Ok(true) => {
370            acc.updated.insert(id_str, Value::Null);
371            return Ok(None);
372        }
373        Err(err) => {
374            acc.not_updated.insert(id_str, err);
375            return Ok(None);
376        }
377    }
378    // `lastReadMessageId` (String, optional). Checked here because
379    // the server-added `lastReadAt` below stops the backend's
380    // re-validation from naming the one offending property.
381    if patch_val
382        .get("lastReadMessageId")
383        .is_some_and(|v| !v.is_string() && !v.is_null())
384    {
385        acc.not_updated.insert(
386            id_str,
387            json!({ "type": "invalidProperties", "properties": ["lastReadMessageId"] }),
388        );
389        return Ok(None);
390    }
391
392    // Convert wire-format Value into a typed PatchObject. RFC 8620
393    // §5.3 mandates a PatchObject is a JSON Object; non-object
394    // values produce an `invalidPatch` SetError.
395    let mut patch = match serde_json::from_value::<PatchObject>(patch_val) {
396        Ok(p) => p,
397        Err(e) => {
398            acc.not_updated.insert(
399                id_str,
400                json!({ "type": "invalidPatch", "description": e.to_string() }),
401            );
402            return Ok(None);
403        }
404    };
405    // §ReadPosition/set: "The server sets `lastReadAt` to the
406    // current time and recomputes `Chat.unreadCount` for the
407    // affected Chat." The count is written to the Chat after the
408    // update loop (`record_unread_count_changes`).
409    patch.as_map_mut().insert(
410        "lastReadAt".to_owned(),
411        Value::String(now_utc_string().into_inner()),
412    );
413    match ctx
414        .backend
415        .update_object::<ReadPosition>(ctx.caller, ctx.account_id, &id, patch)
416        .await
417    {
418        Ok(Some(obj)) => {
419            acc.updated
420                .insert(id_str, jmap_server::serialize_value(&obj)?);
421            Ok(Some(id))
422        }
423        Ok(None) => {
424            acc.updated.insert(id_str, Value::Null);
425            Ok(Some(id))
426        }
427        Err(e) => {
428            acc.not_updated.insert(id_str, backend_set_error_value(e));
429            Ok(None)
430        }
431    }
432}
433
434/// The `destroy` part of `ReadPosition/set`: forbidden (see
435/// [`set_create`]).
436fn set_destroy(
437    args: &serde_json::Map<String, Value>,
438    acc: &mut SetAccumulators,
439) -> Result<(), JmapError> {
440    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
441        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
442        // Reject the whole request if any element is non-string rather than
443        // silently skipping it, which would produce a misleading response.
444        let id_strs: Vec<&str> = destroy_arr
445            .iter()
446            .map(|v| {
447                v.as_str().ok_or_else(|| {
448                    JmapError::invalid_arguments(format!(
449                        "destroy: every element must be a string Id; got {}",
450                        jmap_server::json_type_name(v)
451                    ))
452                })
453            })
454            .collect::<Result<_, _>>()?;
455        for id_str in id_strs {
456            acc.not_destroyed
457                .insert(id_str.to_owned(), forbidden_server_managed());
458        }
459    }
460    Ok(())
461}
462
463/// The `forbidden` [`SetError`] for a client `create` or `destroy` of a
464/// server-managed [`ReadPosition`] (draft-atwood-jmap-chat-00 §ReadPosition/set).
465fn forbidden_server_managed() -> Value {
466    serde_json::Value::from(
467        &SetError::new(SetErrorType::Forbidden)
468            .with_description("ReadPosition records are managed by the server"),
469    )
470}