Skip to main content

jmap_chat_server/
testkit.rs

1//! Backend conformance suite for [`ChatBackend`] implementations.
2//!
3//! Gated behind `feature = "testkit"`. Each test is a `pub async fn`
4//! generic over [`ConformanceBackend`], drives the backend through this
5//! crate's method handlers, and states its oracle (draft or RFC text) in
6//! its rustdoc. A backend crate runs the whole suite with one
7//! [`ConformanceBackend`] impl and one macro line in an integration test:
8//!
9//! ```rust,ignore
10//! // tests/backend_conformance.rs
11//! jmap_chat_server::chat_backend_conformance!(MyBackend::new_for_test);
12//! ```
13//!
14//! [`chat_backend_conformance!`](crate::chat_backend_conformance) emits
15//! one `#[test]` per suite test, each calling the given constructor for a
16//! fresh, empty backend and running the test through [`run`], so the
17//! calling crate needs no tokio macros.
18//!
19//! # What the suite assumes
20//!
21//! Every test runs in one account, `a1`, which it registers with
22//! [`ConformanceBackend::add_account`]; a few register further accounts.
23//! Requests act as the owner of the account
24//! ([`ConformanceBackend::caller`]). Fixtures are hand-written JSON
25//! stored with [`ConformanceBackend::seed`].
26//!
27//! # Capability-gated tests
28//!
29//! A test whose assertion holds only for some backend configurations
30//! returns early, and so passes, when the backend does not have that
31//! configuration:
32//!
33//! - The `replyCount` / `unreadReplyCount` tests check
34//!   [`ChatLimits::supports_threads`](crate::ChatLimits::supports_threads)
35//!   from [`ChatSettings::limits`](crate::ChatSettings::limits); one test runs only when it is `false`,
36//!   the others only when it is `true`. Run the macro once per
37//!   configuration to cover both.
38//! - The exact `Chat.unreadCount` tests run only when
39//!   [`ChatSettings::maintains_unread_count`](crate::ChatSettings::maintains_unread_count) is `false`, where this crate
40//!   keeps the count exact. draft-atwood-jmap-chat-00 §Chat `unreadCount`
41//!   lets a backend that keeps the count itself update it "some time after
42//!   the change that affects it" and "report a server-defined maximum".
43//! - The outbound-event test runs only when
44//!   [`ConformanceBackend::take_outbound_events`] returns `Some`.
45
46use std::future::Future;
47
48use jmap_types::Id;
49use serde_json::{Value, json};
50
51use crate::{ChatBackend, OutboundEvent};
52
53/// The account every suite test runs in.
54const ACCOUNT_ID: &str = "a1";
55
56/// The `ownerUserId` the suite registers its accounts with.
57const OWNER_USER_ID: &str = "owner@example.org";
58
59/// The test seam a [`ChatBackend`] implements to run the conformance
60/// suite.
61///
62/// The methods stand in for what a deployment does outside the JMAP
63/// methods: provisioning an account, authenticating its owner, and
64/// storing objects that arrived by federation or were created
65/// server-side.
66pub trait ConformanceBackend: ChatBackend {
67    /// The caller context of a request made by the owner of
68    /// `account_id`.
69    ///
70    /// The [`ChatStore::create_object`](crate::ChatStore::create_object) authorisation contract applies:
71    /// the backend must let this caller act as the owner of `account_id`.
72    fn caller(&self, account_id: &Id) -> Self::CallerCtx;
73
74    /// Provision `account_id`, owned by `owner_user_id` (the `ownerUserId`
75    /// Session field, as returned by [`ChatSettings::owner_user_id`](crate::ChatSettings::owner_user_id)), so
76    /// [`JmapAccounts::account_exists`](jmap_server::JmapAccounts::account_exists)
77    /// reports it and it holds no objects.
78    fn add_account(&self, account_id: &Id, owner_user_id: &str) -> impl Future<Output = ()> + Send;
79
80    /// Store `object`, the wire JSON of a `type_name` object (for example
81    /// `"Message"`), in `account_id` exactly as given, under the id in its
82    /// `id` member, replacing any object stored under that id.
83    ///
84    /// Fixtures use this for objects no client method creates (received
85    /// Messages, ChatContacts, PresenceStatus) and for fields no client
86    /// may set. The suite reads state before and after the writes it
87    /// tests, so whether seeding advances the state does not matter.
88    /// Objects may omit properties that have a default.
89    fn seed(
90        &self,
91        account_id: &Id,
92        type_name: &'static str,
93        object: Value,
94    ) -> impl Future<Output = ()> + Send;
95
96    /// Drain the [`OutboundEvent`]s the backend has enqueued since the
97    /// last call, oldest first.
98    ///
99    /// Return `None` when the backend cannot observe its own outbound
100    /// queue; the tests that check events then pass without running.
101    fn take_outbound_events(&self) -> Option<Vec<OutboundEvent>>;
102}
103
104/// Run `test` to completion on a fresh multi-thread tokio runtime with
105/// four workers, so the concurrency tests race on real threads.
106///
107/// # Panics
108///
109/// If the runtime cannot be built, and whenever `test` panics.
110pub fn run<F: Future>(test: F) -> F::Output {
111    tokio::runtime::Builder::new_multi_thread()
112        .worker_threads(4)
113        .build()
114        .expect("build the tokio runtime")
115        .block_on(test)
116}
117
118/// Emit one `#[test]` per conformance test, each running it on a fresh
119/// backend from `$make`.
120///
121/// `$make` is any expression callable with no arguments that returns a
122/// [`ConformanceBackend`](crate::testkit::ConformanceBackend), such as a
123/// constructor path or a closure. Invoke it at most once per module.
124///
125/// ```rust,ignore
126/// jmap_chat_server::chat_backend_conformance!(MyBackend::new_for_test);
127/// ```
128#[macro_export]
129macro_rules! chat_backend_conformance {
130    (@tests ($make:expr) $($name:ident),* $(,)?) => {
131        $(
132            #[test]
133            fn $name() {
134                $crate::testkit::run($crate::testkit::$name(($make)()));
135            }
136        )*
137    };
138    ($make:expr $(,)?) => {
139        $crate::chat_backend_conformance!(@tests ($make)
140            state_advances_after_create,
141            create_then_get,
142            is_contact_blocked_reads_chat_contact_blocked_field,
143            is_contact_blocked_reads_only_the_owner_list,
144            path_key_updates_nested_member,
145            top_level_object_value_replaces_property,
146            path_through_absent_parent_is_invalid_patch,
147            prefix_conflict_is_invalid_patch,
148            path_depth_counts_toward_nesting_cap,
149            chat_muted_null_resets_to_false,
150            chat_pinned_message_ids_null_resets_to_empty,
151            chat_receive_typing_indicators_null_resets_to_true,
152            chat_receipt_sharing_null_removes_override,
153            contact_blocked_null_resets_to_false,
154            presence_null_resets_to_online,
155            presence_receipt_sharing_null_resets_to_true,
156            message_mentions_null_resets_to_empty,
157            message_actions_null_resets_to_empty,
158            message_reactions_null_resets_to_empty,
159            message_broadcast_mentions_null_resets_to_empty,
160            chat_query_filters_kind_and_muted,
161            chat_query_applies_filter_operators,
162            contact_query_filters_blocked_and_presence,
163            message_query_filters_topic_id,
164            message_query_filters_has_attachment_both_ways,
165            message_query_has_mention_false_excludes_mentions,
166            message_query_changes_refuses_text_filter,
167            message_query_changes_requires_chat_id_or_has_mention,
168            space_query_filters_name_substring,
169            emoji_query_filters_space_id,
170            emoji_query_changes_applies_space_id_filter,
171            space_query_sort_descending_reverses_order,
172            space_query_sort_ascending_orders_by_property,
173            contact_query_sort_last_active_at_absent_sorts_last,
174            anchor_with_positive_offset_starts_after_anchor,
175            anchor_with_negative_offset_starts_before_anchor,
176            anchor_without_offset_starts_at_anchor,
177            anchor_offset_before_start_clamps_to_zero,
178            anchor_absent_from_results_is_anchor_not_found,
179            anchor_overrides_position,
180            anchor_offset_without_anchor_is_ignored,
181            anchor_arguments_of_wrong_type_are_invalid_arguments,
182            emoji_query_wrongly_typed_args_do_not_echo_value,
183            extreme_position_and_limit_saturate,
184            largest_position_is_empty_page_not_error,
185            join_adds_member_and_counts_use_together,
186            exhausted_invite_is_refused_without_any_write,
187            concurrent_redemptions_increment_exactly_once,
188            invalid_read_at_patch_is_rejected_without_burning,
189            create_message_stores_and_reports_one_new_message,
190            contact_create_by_identity_assigns_id,
191            contact_create_existing_identity_already_exists,
192            contact_create_without_identity_invalid_properties,
193            contact_create_other_properties_invalid_properties,
194            contact_query_identity_filter_matches_octet_for_octet,
195            reply_counts_match_fixture,
196            unread_reply_count_without_read_position,
197            counts_absent_without_supports_threads,
198            reply_create_lists_parent_updated,
199            reply_destroy_lists_parent_updated,
200            read_position_update_lists_thread_root_updated,
201            sender_expires_at_hard_deletes_at_deadline,
202            message_expiry_seconds_deletes_messages_older_than_policy,
203            expires_after_read_seconds_counts_from_read_at,
204            read_burn_on_read_message_is_deleted,
205            read_rules_spare_the_senders_own_copy,
206            mute_until_clears_muted_and_mute_until,
207            presence_expires_at_resets_status,
208            expiry_records_chat_unread_count_change,
209            absent_last_read_counts_every_message,
210            compliance_11_1_unread_count_from_read_position,
211            compliance_11_1_with_assigned_ids,
212            unread_count_in_full_get,
213            read_position_set_updates_last_read_at,
214            client_last_read_at_is_rejected,
215            chat_destroy_destroys_its_read_position,
216            space_join_creates_read_positions_for_its_channels,
217            remove_channels_destroys_their_read_positions,
218            space_destroy_destroys_channel_read_positions,
219            read_position_set_advances_chat_state,
220            message_destroy_advances_chat_state,
221        );
222    };
223}
224
225pub use backend_basics::*;
226pub use contact_identity::*;
227pub use expiry::*;
228pub use message_atomic::*;
229pub use patch_null::*;
230pub use patch_paths::*;
231pub use query_anchor::*;
232pub use query_filters::*;
233pub use query_sort::*;
234pub use read_position::*;
235pub use space_join::*;
236pub use threads::*;
237
238// ---------------------------------------------------------------------------
239// Shared helpers and fixture builders
240// ---------------------------------------------------------------------------
241
242/// The caller acting as the owner of [`ACCOUNT_ID`].
243fn owner<B: ConformanceBackend>(backend: &B) -> B::CallerCtx {
244    backend.caller(&Id::from(ACCOUNT_ID))
245}
246
247/// Provision [`ACCOUNT_ID`].
248async fn setup<B: ConformanceBackend>(backend: &B) {
249    backend
250        .add_account(&Id::from(ACCOUNT_ID), OWNER_USER_ID)
251        .await;
252}
253
254/// Store `object` in [`ACCOUNT_ID`] as given.
255async fn seed<B: ConformanceBackend>(backend: &B, type_name: &'static str, object: Value) {
256    backend.seed(&Id::from(ACCOUNT_ID), type_name, object).await;
257}
258
259/// Whether the backend reports `supportsThreads` for [`ACCOUNT_ID`].
260fn supports_threads<B: ConformanceBackend>(backend: &B) -> bool {
261    let account_id = Id::from(ACCOUNT_ID);
262    backend
263        .limits(&owner(backend), &account_id)
264        .supports_threads
265}
266
267/// Whether this crate keeps `Chat.unreadCount` exact for the backend
268/// (see the module docs).
269fn exact_unread_count<B: ConformanceBackend>(backend: &B) -> bool {
270    !backend.maintains_unread_count()
271}
272
273/// Store a group Chat with the given `id` in [`ACCOUNT_ID`], with the
274/// account as its admin member, so a `Message/set` create naming that
275/// `chatId` passes the draft-atwood-jmap-chat-00 §Input Validation
276/// `chatId` check. Overwrites any Chat already stored under `id`.
277async fn seed_group_chat<B: ConformanceBackend>(backend: &B, id: &str) {
278    seed(
279        backend,
280        "Chat",
281        json!({
282            "id": id,
283            "kind": "group",
284            "name": "G",
285            "createdAt": "2026-01-01T00:00:00Z",
286            "unreadCount": 0,
287            "pinnedMessageIds": [],
288            "members": [{ "id": ACCOUNT_ID, "role": "admin", "joinedAt": "2026-01-01T00:00:00Z" }],
289        }),
290    )
291    .await;
292}
293
294/// Re-store Message `id` with `senderId` set to `"bob"`, so it is a copy
295/// received from another participant. draft-atwood-jmap-chat-00
296/// §Message `burnOnRead`: "Applies only to the receiving mailbox; the
297/// sender's own copy is not affected."
298async fn make_received<B: ConformanceBackend>(backend: &B, id: &str) {
299    let jmap_server::HandlerOutput { primary: get, .. } = crate::message::handle_message_get(
300        backend,
301        &owner(backend),
302        json!({ "accountId": ACCOUNT_ID, "ids": [id] }),
303        &[],
304    )
305    .await
306    .expect("Message/get");
307    let mut msg = get["list"][0].clone();
308    assert!(msg.is_object(), "message {id} not found: {get}");
309    msg["senderId"] = json!("bob");
310    seed(backend, "Message", msg).await;
311}
312
313/// Create a Chat with `kind: "group"` and the given name in
314/// [`ACCOUNT_ID`] through `Chat/set` and return its server-assigned id.
315async fn make_chat_group<B: ConformanceBackend>(backend: &B, name: &str) -> String {
316    let jmap_server::HandlerOutput { primary: resp, .. } = crate::handle_chat_set(
317        backend,
318        &owner(backend),
319        &std::collections::BTreeMap::new(),
320        json!({
321            "accountId": ACCOUNT_ID,
322            "create": { "c0": { "kind": "group", "name": name } }
323        }),
324        &[],
325    )
326    .await
327    .expect("make_chat_group: handle_chat_set");
328    resp["created"]["c0"]["id"]
329        .as_str()
330        .expect("make_chat_group: server-assigned id")
331        .to_owned()
332}
333
334/// Create a Space with the given name in [`ACCOUNT_ID`] through
335/// `Space/set` and return its server-assigned id.
336async fn make_space<B: ConformanceBackend>(backend: &B, name: &str) -> String {
337    let jmap_server::HandlerOutput { primary: resp, .. } = crate::handle_space_set(
338        backend,
339        &owner(backend),
340        &std::collections::BTreeMap::new(),
341        json!({
342            "accountId": ACCOUNT_ID,
343            "create": { "s0": { "name": name } }
344        }),
345        &[],
346    )
347    .await
348    .expect("make_space: handle_space_set");
349    resp["created"]["s0"]["id"]
350        .as_str()
351        .expect("make_space: server-assigned id")
352        .to_owned()
353}
354
355// ---------------------------------------------------------------------------
356// Backend basics: state, create, get, is_contact_blocked
357// ---------------------------------------------------------------------------
358
359mod backend_basics {
360    use jmap_chat_types::{Chat, ChatKind};
361    use jmap_types::{Id, UTCDate};
362    use serde_json::json;
363
364    use super::{ACCOUNT_ID, ConformanceBackend, OWNER_USER_ID, seed, setup};
365
366    /// Oracle: state advances after a successful create_object call.
367    pub async fn state_advances_after_create<B: ConformanceBackend>(backend: B) {
368        let account_id = Id::from("account1");
369        backend.add_account(&account_id, OWNER_USER_ID).await;
370        let caller = backend.caller(&account_id);
371
372        let state_before = backend
373            .get_state::<Chat>(&caller, &account_id)
374            .await
375            .expect("get_state");
376
377        let chat = |id: &Id| {
378            Chat::new(
379                id.clone(),
380                ChatKind::Group,
381                UTCDate::from("2026-01-01T00:00:00Z"),
382                0,
383                vec![],
384                false,
385                true,
386            )
387        };
388        backend
389            .create_object::<Chat, _>(&caller, &account_id, "c0", chat)
390            .await
391            .expect("create_object");
392
393        let state_after = backend
394            .get_state::<Chat>(&caller, &account_id)
395            .await
396            .expect("get_state");
397        assert_ne!(
398            state_before, state_after,
399            "state must change after create_object"
400        );
401    }
402
403    /// Oracle: created objects are retrievable by id.
404    pub async fn create_then_get<B: ConformanceBackend>(backend: B) {
405        let account_id = Id::from("account1");
406        backend.add_account(&account_id, OWNER_USER_ID).await;
407        let caller = backend.caller(&account_id);
408
409        let chat = |id: &Id| {
410            Chat::new(
411                id.clone(),
412                ChatKind::Group,
413                UTCDate::from("2026-01-01T00:00:00Z"),
414                0,
415                vec![],
416                false,
417                true,
418            )
419        };
420        let (server_id, _) = backend
421            .create_object::<Chat, _>(&caller, &account_id, "c0", chat)
422            .await
423            .expect("create_object");
424
425        let (found, not_found) = backend
426            .get_objects::<Chat>(
427                &caller,
428                &account_id,
429                Some(std::slice::from_ref(&server_id)),
430                None,
431            )
432            .await
433            .expect("get_objects");
434
435        assert_eq!(found.len(), 1);
436        assert!(not_found.is_empty());
437        assert_eq!(found[0].id, server_id);
438    }
439
440    /// Oracle: `is_contact_blocked` reads `ChatContact.blocked` from the
441    /// store. The backend's predicate is exercised directly, mirroring the
442    /// way a consumer's transport layer would consult it before a fan-out.
443    pub async fn is_contact_blocked_reads_chat_contact_blocked_field<B: ConformanceBackend>(
444        backend: B,
445    ) {
446        setup(&backend).await;
447        let account_id = Id::from(ACCOUNT_ID);
448        let caller = backend.caller(&account_id);
449        let blocked_id = Id::from("blocked-user");
450        let allowed_id = Id::from("allowed-user");
451
452        seed(
453            &backend,
454            "ChatContact",
455            json!({
456                "id": "blocked-user",
457                "identity": "b@example.org",
458                "login": "b@example.org",
459                "firstSeenAt": "2024-01-01T00:00:00Z",
460                "lastSeenAt": "2024-01-02T00:00:00Z",
461                "blocked": true
462            }),
463        )
464        .await;
465        seed(
466            &backend,
467            "ChatContact",
468            json!({
469                "id": "allowed-user",
470                "identity": "a@example.org",
471                "login": "a@example.org",
472                "firstSeenAt": "2024-01-01T00:00:00Z",
473                "lastSeenAt": "2024-01-02T00:00:00Z",
474                "blocked": false
475            }),
476        )
477        .await;
478
479        assert!(
480            backend
481                .is_contact_blocked(&caller, &account_id, &blocked_id)
482                .await
483                .expect("is_contact_blocked"),
484            "blocked: true contact must report blocked"
485        );
486        assert!(
487            !backend
488                .is_contact_blocked(&caller, &account_id, &allowed_id)
489                .await
490                .expect("is_contact_blocked"),
491            "blocked: false contact must report not-blocked"
492        );
493
494        // Unknown contact id → not blocked (open-by-default for an
495        // unrecognised principal).
496        let unknown = Id::from("never-seen");
497        assert!(
498            !backend
499                .is_contact_blocked(&caller, &account_id, &unknown)
500                .await
501                .expect("is_contact_blocked"),
502            "unknown contact id must report not-blocked"
503        );
504    }
505
506    /// Oracle: draft-atwood-jmap-chat-00 §Blocked Contacts (L1698): "Typing and
507    /// presence push events whose sending or referenced ChatContact has
508    /// `blocked: true` on the receiving owner's contact list are similarly
509    /// dropped", and §ChatContact `id` (L426): "It identifies the ChatContact
510    /// only on this server". Two accounts each hold a ChatContact for the
511    /// other; only the recipient's own list decides, and a contact id is never
512    /// resolved in another account's list.
513    pub async fn is_contact_blocked_reads_only_the_owner_list<B: ConformanceBackend>(backend: B) {
514        let recipient = Id::from("acct-recipient");
515        let sender = Id::from("acct-sender");
516        backend.add_account(&recipient, OWNER_USER_ID).await;
517        backend.add_account(&sender, "sender@example.org").await;
518
519        backend
520            .seed(
521                &recipient,
522                "ChatContact",
523                json!({
524                    "id": "c-sender",
525                    "identity": "sender@example.org",
526                    "login": "sender@example.org",
527                    "firstSeenAt": "2024-01-01T00:00:00Z",
528                    "lastSeenAt": "2024-01-02T00:00:00Z",
529                    "blocked": true
530                }),
531            )
532            .await;
533        backend
534            .seed(
535                &sender,
536                "ChatContact",
537                json!({
538                    "id": "c-recipient",
539                    "identity": "recipient@example.org",
540                    "login": "recipient@example.org",
541                    "firstSeenAt": "2024-01-01T00:00:00Z",
542                    "lastSeenAt": "2024-01-02T00:00:00Z",
543                    "blocked": false
544                }),
545            )
546            .await;
547
548        let blocked = |account: &Id, contact: &str| {
549            let backend = &backend;
550            let account = account.clone();
551            let contact = Id::from(contact);
552            async move {
553                backend
554                    .is_contact_blocked(&backend.caller(&account), &account, &contact)
555                    .await
556                    .expect("is_contact_blocked")
557            }
558        };
559
560        assert!(
561            blocked(&recipient, "c-sender").await,
562            "the recipient blocked the sender on the recipient's own list"
563        );
564        assert!(
565            !blocked(&sender, "c-recipient").await,
566            "the sender's list does not block the recipient"
567        );
568        assert!(
569            !blocked(&sender, "c-sender").await,
570            "c-sender is held only by the recipient's account"
571        );
572    }
573}
574
575// ---------------------------------------------------------------------------
576// `/set update` PatchObject paths (RFC 8620 §5.3, bd:JMAP-cr0z)
577//
578// These tests drive the backend's `update_object` against the Message
579// `deliveryReceipts` map, a real object-of-objects property.
580// draft-atwood-jmap-chat-00 §Message marks it "`deliveryReceipts`
581// (Object, optional, server-set)", so `Message/set` rejects client
582// patches to it; the server's own delivery-receipt writes reach the
583// backend through this path.
584// ---------------------------------------------------------------------------
585
586mod patch_paths {
587    use jmap_chat_types::Message;
588    use jmap_server::HandlerOutput;
589    use jmap_server::{BackendSetError, SetErrorType};
590    use jmap_types::{Id, PatchObject};
591    use serde_json::{Value, json};
592
593    use super::{ACCOUNT_ID, ConformanceBackend, owner, seed_group_chat, setup};
594    use crate::message::{handle_message_get, handle_message_set};
595
596    /// Create a Message and return its server id.
597    async fn create_message<B: ConformanceBackend>(backend: &B) -> String {
598        seed_group_chat(backend, "c1").await;
599        let HandlerOutput { primary: resp, .. } = handle_message_set(
600            backend,
601            &owner(backend),
602            &std::collections::BTreeMap::new(),
603            json!({
604                "accountId": ACCOUNT_ID,
605                "create": { "m0": { "chatId": "c1", "body": "hi", "sentAt": "2024-01-01T00:00:00Z" } }
606            }),
607            &[],
608        )
609        .await
610        .expect("create");
611        resp["created"]["m0"]["id"]
612            .as_str()
613            .expect("created id")
614            .to_owned()
615    }
616
617    /// Apply `patch` to message `id` in the backend, returning the SetError
618    /// type on rejection.
619    async fn update<B: ConformanceBackend>(
620        backend: &B,
621        id: &str,
622        patch: Value,
623    ) -> Result<(), SetErrorType> {
624        let patch: PatchObject = serde_json::from_value(patch).expect("patch is a JSON object");
625        match backend
626            .update_object::<Message>(&owner(backend), &Id::from(ACCOUNT_ID), &Id::from(id), patch)
627            .await
628        {
629            Ok(_) => Ok(()),
630            Err(BackendSetError::SetError(e)) => Err(e.error_type),
631            Err(e) => panic!("backend error: {e:?}"),
632        }
633    }
634
635    /// Fetch message `id` as its wire JSON.
636    async fn get<B: ConformanceBackend>(backend: &B, id: &str) -> Value {
637        let HandlerOutput { primary: resp, .. } = handle_message_get(
638            backend,
639            &owner(backend),
640            json!({ "accountId": ACCOUNT_ID, "ids": [id] }),
641            &[],
642        )
643        .await
644        .expect("get");
645        resp["list"][0].clone()
646    }
647
648    /// Create a Message whose `deliveryReceipts` holds a single entry `u1`.
649    async fn message_with_receipt<B: ConformanceBackend>(backend: &B) -> String {
650        let id = create_message(backend).await;
651        let resp = update(
652            backend,
653            &id,
654            json!({ "deliveryReceipts": { "u1": { "deliveredAt": "2024-01-01T00:00:01Z" } } }),
655        )
656        .await;
657        assert_eq!(resp, Ok(()));
658        id
659    }
660
661    /// Oracle: RFC 8620 §5.3: "The keys are a path in JSON Pointer format
662    /// \[RFC6901\], with an implicit leading "/"". The key
663    /// `deliveryReceipts/u2` therefore adds member `u2` of the
664    /// `deliveryReceipts` object, keeping `u1`, rather than creating a
665    /// property literally named `deliveryReceipts/u2`.
666    pub async fn path_key_updates_nested_member<B: ConformanceBackend>(backend: B) {
667        setup(&backend).await;
668        let id = message_with_receipt(&backend).await;
669
670        let resp = update(
671            &backend,
672            &id,
673            json!({ "deliveryReceipts/u2": { "readAt": "2024-01-01T00:00:02Z" } }),
674        )
675        .await;
676        assert_eq!(resp, Ok(()));
677
678        let msg = get(&backend, &id).await;
679        assert!(msg.get("deliveryReceipts/u2").is_none(), "{msg:?}");
680        assert_eq!(
681            msg["deliveryReceipts"],
682            json!({
683                "u1": { "deliveredAt": "2024-01-01T00:00:01Z" },
684                "u2": { "readAt": "2024-01-01T00:00:02Z" },
685            })
686        );
687    }
688
689    /// Oracle: RFC 8620 §5.3: "Anything else: The value to set for this
690    /// property (this may be a replacement or addition to the object being
691    /// patched)." A top-level `deliveryReceipts` value replaces the whole
692    /// property; the existing `u1` entry is not merged into it.
693    pub async fn top_level_object_value_replaces_property<B: ConformanceBackend>(backend: B) {
694        setup(&backend).await;
695        let id = message_with_receipt(&backend).await;
696
697        let resp = update(
698            &backend,
699            &id,
700            json!({ "deliveryReceipts": { "u2": { "readAt": "2024-01-01T00:00:02Z" } } }),
701        )
702        .await;
703        assert_eq!(resp, Ok(()));
704
705        let msg = get(&backend, &id).await;
706        assert_eq!(
707            msg["deliveryReceipts"],
708            json!({ "u2": { "readAt": "2024-01-01T00:00:02Z" } })
709        );
710    }
711
712    /// Oracle: RFC 8620 §5.3: "All parts prior to the last (i.e., the value
713    /// after the final slash) MUST already exist on the object being
714    /// patched." and "if there is any violation, the update MUST be
715    /// rejected with an "invalidPatch" error". A fresh Message has no
716    /// `deliveryReceipts`, so `deliveryReceipts/u1` is rejected and the
717    /// stored Message is unchanged.
718    pub async fn path_through_absent_parent_is_invalid_patch<B: ConformanceBackend>(backend: B) {
719        setup(&backend).await;
720        let id = create_message(&backend).await;
721        let before = get(&backend, &id).await;
722        assert!(before.get("deliveryReceipts").is_none(), "{before:?}");
723
724        let resp = update(
725            &backend,
726            &id,
727            json!({ "deliveryReceipts/u1": { "readAt": "2024-01-01T00:00:02Z" } }),
728        )
729        .await;
730        assert_eq!(resp, Err(SetErrorType::InvalidPatch));
731        assert_eq!(get(&backend, &id).await, before);
732    }
733
734    /// Oracle: RFC 8620 §5.3: "There MUST NOT be two patches in the
735    /// PatchObject where the pointer of one is the prefix of the pointer of
736    /// the other, e.g., "alerts/1/offset" and "alerts"." and "if there is
737    /// any violation, the update MUST be rejected with an "invalidPatch"
738    /// error". The stored Message is unchanged.
739    pub async fn prefix_conflict_is_invalid_patch<B: ConformanceBackend>(backend: B) {
740        setup(&backend).await;
741        let id = message_with_receipt(&backend).await;
742        let before = get(&backend, &id).await;
743
744        let resp = update(
745            &backend,
746            &id,
747            json!({
748                "deliveryReceipts": { "u2": { "readAt": "2024-01-01T00:00:02Z" } },
749                "deliveryReceipts/u1/readAt": "2024-01-01T00:00:03Z",
750            }),
751        )
752        .await;
753        assert_eq!(resp, Err(SetErrorType::InvalidPatch));
754        assert_eq!(get(&backend, &id).await, before);
755    }
756
757    /// `{"k": {"k": ... {}}}` with `levels` object levels.
758    fn nested(levels: usize) -> Value {
759        (1..levels).fold(json!({}), |inner, _| json!({ "k": inner }))
760    }
761
762    /// Oracle: bd:JMAP-wlip.1 caps `/set update` nesting at 32 levels and
763    /// rejects deeper patches as RFC 8620 §5.3 "invalidPatch", leaving the
764    /// record unchanged. Because §5.3 makes keys "a path in JSON Pointer
765    /// format", the path itself reaches into the object, so its segments
766    /// count toward the cap. Test vector: a 21-segment path into an
767    /// existing 21-level value, setting another 21-level value, would store
768    /// 43 levels; each repeat could add 21 more.
769    pub async fn path_depth_counts_toward_nesting_cap<B: ConformanceBackend>(backend: B) {
770        setup(&backend).await;
771        let id = create_message(&backend).await;
772        let resp = update(
773            &backend,
774            &id,
775            json!({ "deliveryReceipts": { "u1": nested(21) } }),
776        )
777        .await;
778        assert_eq!(resp, Ok(()));
779        let before = get(&backend, &id).await;
780
781        let path = format!("deliveryReceipts/u1{}", "/k".repeat(19));
782        let resp = update(&backend, &id, json!({ path: nested(21) })).await;
783        assert_eq!(resp, Err(SetErrorType::InvalidPatch));
784        assert_eq!(get(&backend, &id).await, before);
785    }
786}
787
788// ---------------------------------------------------------------------------
789// `/set update` with a `null` PatchObject value resets a property to its
790// spec default (RFC 8620 §5.3, bd:JMAP-sofk).
791//
792// RFC 8620 §5.3: "null: The value to set for this property is the default
793// value if specified for this property". A backend that removes the
794// member on `null` must deserialize each property below to its
795// draft-atwood-jmap-chat-00 default when absent; otherwise the following
796// `/get` fails as a whole.
797// ---------------------------------------------------------------------------
798
799mod patch_null {
800    use jmap_chat_types::Message;
801    use jmap_server::HandlerOutput;
802    use jmap_types::{Id, PatchObject};
803    use serde_json::{Map, Value, json};
804
805    use super::{
806        ACCOUNT_ID, ConformanceBackend, make_chat_group, owner, seed, seed_group_chat, setup,
807    };
808    use crate::message::{handle_message_get, handle_message_set};
809    use crate::{
810        handle_chat_get, handle_chat_set, handle_contact_get, handle_contact_set,
811        handle_presence_get, handle_presence_set,
812    };
813
814    /// Assert a `/set` response updated `id` without error.
815    fn assert_updated(resp: &Value, id: &str) {
816        assert_eq!(resp["notUpdated"], Value::Null, "{resp:?}");
817        assert!(
818            resp["updated"]
819                .as_object()
820                .is_some_and(|m| m.contains_key(id)),
821            "{resp:?}"
822        );
823    }
824
825    async fn chat_update<B: ConformanceBackend>(backend: &B, id: &str, patch: Value) {
826        let HandlerOutput { primary: resp, .. } = handle_chat_set(
827            backend,
828            &owner(backend),
829            &std::collections::BTreeMap::new(),
830            json!({ "accountId": ACCOUNT_ID, "update": { id: patch } }),
831            &[],
832        )
833        .await
834        .expect("Chat/set");
835        assert_updated(&resp, id);
836    }
837
838    async fn chat_get<B: ConformanceBackend>(backend: &B, id: &str) -> Value {
839        let HandlerOutput { primary: resp, .. } = handle_chat_get(
840            backend,
841            &owner(backend),
842            json!({ "accountId": ACCOUNT_ID, "ids": [id] }),
843            &[],
844        )
845        .await
846        .expect("Chat/get");
847        resp["list"][0].clone()
848    }
849
850    /// Oracle: draft-atwood-jmap-chat-00 Chat `muted`: "When `true`, push
851    /// notifications for this chat are suppressed. \[...\] Default: `false`."
852    pub async fn chat_muted_null_resets_to_false<B: ConformanceBackend>(backend: B) {
853        setup(&backend).await;
854        let id = make_chat_group(&backend, "g").await;
855        chat_update(&backend, &id, json!({ "muted": true })).await;
856
857        chat_update(&backend, &id, json!({ "muted": null })).await;
858
859        assert_eq!(chat_get(&backend, &id).await["muted"], json!(false));
860    }
861
862    /// Oracle: draft-atwood-jmap-chat-00 Chat `pinnedMessageIds`: "Ordered
863    /// list of pinned Message ids, most-recently-pinned first. \[...\] Empty by
864    /// default."
865    pub async fn chat_pinned_message_ids_null_resets_to_empty<B: ConformanceBackend>(backend: B) {
866        setup(&backend).await;
867        let id = make_chat_group(&backend, "g").await;
868
869        chat_update(&backend, &id, json!({ "pinnedMessageIds": null })).await;
870
871        assert_eq!(chat_get(&backend, &id).await["pinnedMessageIds"], json!([]));
872    }
873
874    /// Oracle: draft-atwood-jmap-chat-00 Chat `receiveTypingIndicators`:
875    /// "Default: `true`."
876    pub async fn chat_receive_typing_indicators_null_resets_to_true<B: ConformanceBackend>(
877        backend: B,
878    ) {
879        setup(&backend).await;
880        let id = make_chat_group(&backend, "g").await;
881        chat_update(&backend, &id, json!({ "receiveTypingIndicators": false })).await;
882
883        chat_update(&backend, &id, json!({ "receiveTypingIndicators": null })).await;
884
885        assert_eq!(
886            chat_get(&backend, &id).await["receiveTypingIndicators"],
887            json!(true)
888        );
889    }
890
891    /// Oracle: draft-atwood-jmap-chat-00 Chat `receiptSharing` (line 645-646
892    /// at spec 29e9a41): "(Boolean, optional) Per-Chat override of the
893    /// account-level `PresenceStatus.receiptSharing` preference ... When
894    /// absent, the account-level preference applies." The property has no
895    /// default, so `null` removes the override and `/get` omits it
896    /// (bd:JMAP-w9ox.2).
897    pub async fn chat_receipt_sharing_null_removes_override<B: ConformanceBackend>(backend: B) {
898        setup(&backend).await;
899        let id = make_chat_group(&backend, "g").await;
900        chat_update(&backend, &id, json!({ "receiptSharing": false })).await;
901        assert_eq!(
902            chat_get(&backend, &id).await["receiptSharing"],
903            json!(false)
904        );
905
906        chat_update(&backend, &id, json!({ "receiptSharing": null })).await;
907
908        let chat = chat_get(&backend, &id).await;
909        assert!(
910            chat.as_object()
911                .is_some_and(|m| !m.contains_key("receiptSharing")),
912            "{chat:?}"
913        );
914    }
915
916    /// Oracle: draft-atwood-jmap-chat-00 ChatContact `blocked`: "When
917    /// `true`, messages from this ChatContact are silently dropped by this
918    /// mailbox \[...\] Default: `false`."
919    pub async fn contact_blocked_null_resets_to_false<B: ConformanceBackend>(backend: B) {
920        setup(&backend).await;
921        // ChatContact objects are server-managed (create is forbidden).
922        seed(
923            &backend,
924            "ChatContact",
925            json!({
926                "id": "ct1",
927                "identity": "alice@example.com",
928                "login": "alice@example.com",
929                "firstSeenAt": "2024-01-01T00:00:00Z",
930                "lastSeenAt": "2024-01-01T00:00:00Z",
931                "blocked": true,
932            }),
933        )
934        .await;
935
936        let HandlerOutput { primary: resp, .. } = handle_contact_set(
937            &backend,
938            &owner(&backend),
939            json!({ "accountId": ACCOUNT_ID, "update": { "ct1": { "blocked": null } } }),
940        )
941        .await
942        .expect("ChatContact/set");
943        assert_updated(&resp, "ct1");
944
945        let HandlerOutput { primary: resp, .. } = handle_contact_get(
946            &backend,
947            &owner(&backend),
948            json!({ "accountId": ACCOUNT_ID, "ids": ["ct1"] }),
949        )
950        .await
951        .expect("ChatContact/get");
952        assert_eq!(resp["list"][0]["blocked"], json!(false), "{resp:?}");
953    }
954
955    /// Seed a PresenceStatus with non-default `presence` and `receiptSharing`.
956    async fn seed_presence<B: ConformanceBackend>(backend: &B) {
957        // PresenceStatus objects are server-managed (only update is permitted).
958        seed(
959            backend,
960            "PresenceStatus",
961            json!({
962                "id": "ps1",
963                "presence": "busy",
964                "receiptSharing": false,
965                "updatedAt": "2024-01-01T00:00:00Z",
966            }),
967        )
968        .await;
969    }
970
971    async fn presence_null_then_get<B: ConformanceBackend>(backend: &B, prop: &str) -> Value {
972        let HandlerOutput { primary: resp, .. } = handle_presence_set(
973            backend,
974            &owner(backend),
975            json!({ "accountId": ACCOUNT_ID, "update": { "ps1": { prop: null } } }),
976        )
977        .await
978        .expect("PresenceStatus/set");
979        assert_updated(&resp, "ps1");
980
981        let HandlerOutput { primary: resp, .. } = handle_presence_get(
982            backend,
983            &owner(backend),
984            json!({ "accountId": ACCOUNT_ID, "ids": ["ps1"] }),
985        )
986        .await
987        .expect("PresenceStatus/get");
988        resp["list"][0].clone()
989    }
990
991    /// Oracle: draft-atwood-jmap-chat-00 PresenceStatus `presence`: "One of
992    /// `"online"`, `"away"`, `"busy"`, `"invisible"`, or `"offline"`.
993    /// Default is `"online"`."
994    pub async fn presence_null_resets_to_online<B: ConformanceBackend>(backend: B) {
995        setup(&backend).await;
996        seed_presence(&backend).await;
997
998        let ps = presence_null_then_get(&backend, "presence").await;
999
1000        assert_eq!(ps["presence"], json!("online"), "{ps:?}");
1001    }
1002
1003    /// Oracle: draft-atwood-jmap-chat-00 PresenceStatus `receiptSharing`:
1004    /// "When `false`, this account does not send read receipts to peers.
1005    /// \[...\] Default: `true`."
1006    pub async fn presence_receipt_sharing_null_resets_to_true<B: ConformanceBackend>(backend: B) {
1007        setup(&backend).await;
1008        seed_presence(&backend).await;
1009
1010        let ps = presence_null_then_get(&backend, "receiptSharing").await;
1011
1012        assert_eq!(ps["receiptSharing"], json!(true), "{ps:?}");
1013    }
1014
1015    /// Create a Message, patch `prop` to null in the backend, and return the
1016    /// fetched Message.
1017    ///
1018    /// The patch goes to `update_object` directly rather than through
1019    /// `Message/set`: draft-atwood-jmap-chat-00 §Message/set admits only the
1020    /// Editing, Reactions (`reactions/<senderReactionId>`), Deleting and
1021    /// Marking as Read updates, so the handler rejects a whole-property
1022    /// `actions` or `reactions` patch. The default-on-absence contract under
1023    /// test belongs to the stored record, not to the handler.
1024    async fn message_null_then_get<B: ConformanceBackend>(backend: &B, prop: &str) -> Value {
1025        setup(backend).await;
1026        seed_group_chat(backend, "c1").await;
1027        let HandlerOutput { primary: resp, .. } = handle_message_set(
1028            backend,
1029            &owner(backend),
1030            &std::collections::BTreeMap::new(),
1031            json!({
1032                "accountId": ACCOUNT_ID,
1033                "create": { "m0": { "chatId": "c1", "body": "hi", "sentAt": "2024-01-01T00:00:00Z" } }
1034            }),
1035            &[],
1036        )
1037        .await
1038        .expect("Message/set create");
1039        let id = resp["created"]["m0"]["id"]
1040            .as_str()
1041            .expect("created id")
1042            .to_owned();
1043
1044        let patch = PatchObject::from(Map::from_iter([(prop.to_owned(), Value::Null)]));
1045        backend
1046            .update_object::<Message>(
1047                &owner(backend),
1048                &Id::from(ACCOUNT_ID),
1049                &Id::from(id.as_str()),
1050                patch,
1051            )
1052            .await
1053            .expect("update_object");
1054
1055        let HandlerOutput { primary: resp, .. } = handle_message_get(
1056            backend,
1057            &owner(backend),
1058            json!({ "accountId": ACCOUNT_ID, "ids": [&id] }),
1059            &[],
1060        )
1061        .await
1062        .expect("Message/get");
1063        resp["list"][0].clone()
1064    }
1065
1066    /// Oracle: draft-atwood-jmap-chat-00 Message `mentions`: "Structured
1067    /// per-user @mention annotations. Empty by default."
1068    pub async fn message_mentions_null_resets_to_empty<B: ConformanceBackend>(backend: B) {
1069        let msg = message_null_then_get(&backend, "mentions").await;
1070        assert_eq!(msg["mentions"], json!([]), "{msg:?}");
1071    }
1072
1073    /// Oracle: draft-atwood-jmap-chat-00 Message `actions`: "Out-of-band
1074    /// action invitations associated with this message. Empty by default."
1075    pub async fn message_actions_null_resets_to_empty<B: ConformanceBackend>(backend: B) {
1076        let msg = message_null_then_get(&backend, "actions").await;
1077        assert_eq!(msg["actions"], json!([]), "{msg:?}");
1078    }
1079
1080    /// Oracle: draft-atwood-jmap-chat-00 Message `reactions`: "Emoji
1081    /// reactions, keyed by `senderReactionId`. \[...\] Empty object by
1082    /// default."
1083    pub async fn message_reactions_null_resets_to_empty<B: ConformanceBackend>(backend: B) {
1084        let msg = message_null_then_get(&backend, "reactions").await;
1085        assert_eq!(msg["reactions"], json!({}), "{msg:?}");
1086    }
1087
1088    /// Oracle: draft-atwood-jmap-chat-00 Message `broadcastMentions`:
1089    /// "Structured broadcast-scope mention annotations \[...\]. Empty by
1090    /// default."
1091    pub async fn message_broadcast_mentions_null_resets_to_empty<B: ConformanceBackend>(
1092        backend: B,
1093    ) {
1094        let msg = message_null_then_get(&backend, "broadcastMentions").await;
1095        assert_eq!(msg["broadcastMentions"], json!([]), "{msg:?}");
1096    }
1097}
1098
1099// ---------------------------------------------------------------------------
1100// `/query` filters (bd:JMAP-vwr2)
1101//
1102// The backend applies every `/query` filter clause the draft defines,
1103// FilterOperators included, and `/queryChanges` applies the same filter.
1104//
1105// Oracles: draft-atwood-jmap-chat-00 (jmap-chat-spec 33702a5):
1106// - L1064 §ChatContact/query: "Filter properties: `blocked` (Boolean),
1107//   `presence` (String), `identity` (String; ...)."
1108// - L1139 §Chat/query: "Filter properties: `kind` (String), `muted`
1109//   (Boolean)."
1110// - L1279 §Message/query `text`: "Servers that do not support full-text
1111//   search MUST return `unsupportedFilter`."
1112// - L1285 `topicId`: "Return only messages whose `topicId` equals this
1113//   value."
1114// - L1288 `hasAttachment`: "Filter to messages with or without
1115//   attachments."
1116// - L1291 `hasMention`: "Filter to messages that mention the owner: the
1117//   accountId appears in `mentions`, OR ..."
1118// - L1389 §Space/query: "Filter properties: `name` (String, substring
1119//   match), `isPublic` (Boolean)."
1120// - L1482 §CustomEmoji/query: "Filter properties: `spaceId` (String,
1121//   optional — if absent returns all emoji accessible to the account
1122//   including server-global)."
1123// - RFC 8620 §5.5 FilterOperator: "AND: All of the conditions must match
1124//   for the filter to match. OR: At least one of the conditions must
1125//   match for the filter to match. NOT: None of the conditions must match
1126//   for the filter to match."
1127// - RFC 8620 §5.6: `/queryChanges` takes the "filter" "as given in the
1128//   query", and `added` lists every id "added to the results since the
1129//   old state".
1130//
1131// Objects are seeded as hand-written JSON.
1132// ---------------------------------------------------------------------------
1133
1134mod query_filters {
1135    use jmap_server::HandlerOutput;
1136    use jmap_types::JmapError;
1137    use serde_json::{Value, json};
1138
1139    use super::{ACCOUNT_ID, ConformanceBackend, owner, seed, setup};
1140    use crate::message::{handle_message_query, handle_message_query_changes};
1141    use crate::{
1142        handle_chat_query, handle_contact_query, handle_emoji_query, handle_emoji_query_changes,
1143        handle_emoji_set, handle_space_query,
1144    };
1145
1146    fn sorted_ids(resp: &Value) -> Vec<String> {
1147        let mut ids: Vec<String> = resp["ids"]
1148            .as_array()
1149            .expect("ids")
1150            .iter()
1151            .map(|id| id.as_str().expect("id").to_owned())
1152            .collect();
1153        ids.sort();
1154        ids
1155    }
1156
1157    async fn seeded<B: ConformanceBackend>(
1158        backend: &B,
1159        type_name: &'static str,
1160        objects: &[(&str, Value)],
1161    ) {
1162        setup(backend).await;
1163        for (id, obj) in objects {
1164            let mut obj = obj.clone();
1165            obj["id"] = json!(id);
1166            seed(backend, type_name, obj).await;
1167        }
1168    }
1169
1170    async fn chat_backend<B: ConformanceBackend>(backend: &B) {
1171        seeded(
1172            backend,
1173            "Chat",
1174            &[
1175                ("g-muted", json!({ "kind": "group", "muted": true })),
1176                ("g-loud", json!({ "kind": "group", "muted": false })),
1177                ("d-loud", json!({ "kind": "direct", "muted": false })),
1178            ],
1179        )
1180        .await;
1181    }
1182
1183    async fn chat_query<B: ConformanceBackend>(backend: &B, filter: Value) -> Vec<String> {
1184        let HandlerOutput { primary: resp, .. } = handle_chat_query(
1185            backend,
1186            &owner(backend),
1187            json!({ "accountId": ACCOUNT_ID, "filter": filter }),
1188            &[],
1189        )
1190        .await
1191        .expect("Chat/query");
1192        sorted_ids(&resp)
1193    }
1194
1195    /// L1139 (jmap-chat-spec 33702a5) §Chat/query: "Filter properties:
1196    /// `kind` (String), `muted` (Boolean)."
1197    ///
1198    /// L1139: `kind` and `muted` each restrict the result; together both must
1199    /// hold.
1200    pub async fn chat_query_filters_kind_and_muted<B: ConformanceBackend>(backend: B) {
1201        chat_backend(&backend).await;
1202        assert_eq!(
1203            chat_query(&backend, json!({ "kind": "group" })).await,
1204            ["g-loud", "g-muted"]
1205        );
1206        assert_eq!(
1207            chat_query(&backend, json!({ "muted": true })).await,
1208            ["g-muted"]
1209        );
1210        assert_eq!(
1211            chat_query(&backend, json!({ "kind": "group", "muted": false })).await,
1212            ["g-loud"]
1213        );
1214    }
1215
1216    /// RFC 8620 §5.5 FilterOperator: "AND: All of the conditions must match
1217    /// for the filter to match. OR: At least one of the conditions must
1218    /// match for the filter to match. NOT: None of the conditions must match
1219    /// for the filter to match."
1220    ///
1221    /// RFC 8620 §5.5 OR and NOT over §Chat/query conditions.
1222    pub async fn chat_query_applies_filter_operators<B: ConformanceBackend>(backend: B) {
1223        chat_backend(&backend).await;
1224        let or = json!({ "operator": "OR", "conditions": [
1225            { "kind": "direct" }, { "muted": true },
1226        ] });
1227        assert_eq!(chat_query(&backend, or).await, ["d-loud", "g-muted"]);
1228        let not = json!({ "operator": "NOT", "conditions": [{ "kind": "direct" }] });
1229        assert_eq!(chat_query(&backend, not).await, ["g-loud", "g-muted"]);
1230        let and = json!({ "operator": "AND", "conditions": [
1231            { "kind": "group" }, { "muted": false },
1232        ] });
1233        assert_eq!(chat_query(&backend, and).await, ["g-loud"]);
1234    }
1235
1236    /// L1064 (jmap-chat-spec 33702a5) §ChatContact/query: "Filter
1237    /// properties: `blocked` (Boolean), `presence` (String), `identity`
1238    /// (String; ...)."
1239    ///
1240    /// L1064: `blocked` and `presence` each restrict `ChatContact/query`.
1241    pub async fn contact_query_filters_blocked_and_presence<B: ConformanceBackend>(backend: B) {
1242        seeded(
1243            &backend,
1244            "ChatContact",
1245            &[
1246                (
1247                    "blocked-online",
1248                    json!({ "identity": "a", "blocked": true, "presence": "online" }),
1249                ),
1250                (
1251                    "open-online",
1252                    json!({ "identity": "b", "blocked": false, "presence": "online" }),
1253                ),
1254                (
1255                    "open-away",
1256                    json!({ "identity": "c", "blocked": false, "presence": "away" }),
1257                ),
1258            ],
1259        )
1260        .await;
1261        let query = |filter: Value| {
1262            let backend = &backend;
1263            async move {
1264                let HandlerOutput { primary: resp, .. } = handle_contact_query(
1265                    backend,
1266                    &owner(backend),
1267                    json!({ "accountId": ACCOUNT_ID, "filter": filter }),
1268                )
1269                .await
1270                .expect("ChatContact/query");
1271                sorted_ids(&resp)
1272            }
1273        };
1274        assert_eq!(
1275            query(json!({ "blocked": false })).await,
1276            ["open-away", "open-online"]
1277        );
1278        assert_eq!(
1279            query(json!({ "presence": "online" })).await,
1280            ["blocked-online", "open-online"]
1281        );
1282        assert_eq!(
1283            query(json!({ "blocked": false, "presence": "online" })).await,
1284            ["open-online"]
1285        );
1286    }
1287
1288    async fn message_backend<B: ConformanceBackend>(backend: &B) {
1289        let msg = |extra: Value| {
1290            let mut m = json!({ "chatId": "chat1", "receivedAt": "2026-01-01T00:00:00Z" });
1291            for (k, v) in extra.as_object().expect("object") {
1292                m[k] = v.clone();
1293            }
1294            m
1295        };
1296        seeded(
1297            backend,
1298            "Message",
1299            &[
1300                (
1301                    "topic-a",
1302                    msg(json!({ "topicId": "a", "subject": "Topic A" })),
1303                ),
1304                (
1305                    "topic-b",
1306                    msg(json!({ "topicId": "b", "subject": "Topic B" })),
1307                ),
1308                (
1309                    "with-file",
1310                    msg(json!({ "attachments": [{ "blobId": "b1", "type": "text/plain" }] })),
1311                ),
1312                (
1313                    "mentions-me",
1314                    msg(json!({ "mentions": [{ "id": ACCOUNT_ID }] })),
1315                ),
1316            ],
1317        )
1318        .await;
1319        seed(backend, "Chat", json!({ "id": "chat1", "kind": "group" })).await;
1320    }
1321
1322    async fn message_query<B: ConformanceBackend>(backend: &B, extra: Value) -> Vec<String> {
1323        let mut filter = json!({ "chatId": "chat1" });
1324        for (k, v) in extra.as_object().expect("object") {
1325            filter[k] = v.clone();
1326        }
1327        let HandlerOutput { primary: resp, .. } = handle_message_query(
1328            backend,
1329            &owner(backend),
1330            json!({ "accountId": ACCOUNT_ID, "filter": filter }),
1331            &[],
1332        )
1333        .await
1334        .expect("Message/query");
1335        sorted_ids(&resp)
1336    }
1337
1338    /// L1285 (jmap-chat-spec 33702a5) `topicId`: "Return only messages
1339    /// whose `topicId` equals this value."
1340    ///
1341    /// L1285: `topicId` matches equal values only.
1342    pub async fn message_query_filters_topic_id<B: ConformanceBackend>(backend: B) {
1343        message_backend(&backend).await;
1344        assert_eq!(
1345            message_query(&backend, json!({ "topicId": "a" })).await,
1346            ["topic-a"]
1347        );
1348    }
1349
1350    /// L1288 (jmap-chat-spec 33702a5) `hasAttachment`: "Filter to messages
1351    /// with or without attachments."
1352    ///
1353    /// L1288: `hasAttachment` selects messages "with or without attachments".
1354    pub async fn message_query_filters_has_attachment_both_ways<B: ConformanceBackend>(backend: B) {
1355        message_backend(&backend).await;
1356        assert_eq!(
1357            message_query(&backend, json!({ "hasAttachment": true })).await,
1358            ["with-file"]
1359        );
1360        assert_eq!(
1361            message_query(&backend, json!({ "hasAttachment": false })).await,
1362            ["mentions-me", "topic-a", "topic-b"]
1363        );
1364    }
1365
1366    /// L1291 (jmap-chat-spec 33702a5) `hasMention`: "Filter to messages that
1367    /// mention the owner: the accountId appears in `mentions`, OR ..."
1368    ///
1369    /// L1291: `hasMention` is a Boolean filter, so `false` selects the
1370    /// messages that do not mention the owner.
1371    pub async fn message_query_has_mention_false_excludes_mentions<B: ConformanceBackend>(
1372        backend: B,
1373    ) {
1374        message_backend(&backend).await;
1375        assert_eq!(
1376            message_query(&backend, json!({ "hasMention": false })).await,
1377            ["topic-a", "topic-b", "with-file"]
1378        );
1379    }
1380
1381    /// L1279 (jmap-chat-spec 33702a5) §Message/query `text`: "Servers that
1382    /// do not support full-text search MUST return `unsupportedFilter`."
1383    ///
1384    /// L1279 and RFC 8620 §5.6 (the filter "as given in the query"): a
1385    /// `text` filter the server cannot run is `unsupportedFilter` on
1386    /// `Message/queryChanges` as on `Message/query`.
1387    pub async fn message_query_changes_refuses_text_filter<B: ConformanceBackend>(backend: B) {
1388        message_backend(&backend).await;
1389        let err = handle_message_query_changes(
1390            &backend,
1391            &owner(&backend),
1392            json!({
1393                "accountId": ACCOUNT_ID,
1394                "filter": { "chatId": "chat1", "text": "hello" },
1395                "sinceQueryState": "0",
1396            }),
1397            &[],
1398        )
1399        .await
1400        .expect_err("text filter");
1401        assert_eq!(err.error_type, JmapError::unsupported_filter().error_type);
1402        assert!(err.description.is_some(), "the refusal names its rule");
1403    }
1404
1405    /// L1269: "Servers MUST return an `unsupportedFilter` error for any
1406    /// request that omits `chatId` without also including `hasMention:
1407    /// true`" applies to `Message/queryChanges` too.
1408    pub async fn message_query_changes_requires_chat_id_or_has_mention<B: ConformanceBackend>(
1409        backend: B,
1410    ) {
1411        message_backend(&backend).await;
1412        let err = handle_message_query_changes(
1413            &backend,
1414            &owner(&backend),
1415            json!({
1416                "accountId": ACCOUNT_ID,
1417                "filter": { "topicId": "a" },
1418                "sinceQueryState": "0",
1419            }),
1420            &[],
1421        )
1422        .await
1423        .expect_err("no chatId");
1424        assert_eq!(err.error_type, JmapError::unsupported_filter().error_type);
1425        assert!(err.description.is_some(), "the refusal names its rule");
1426    }
1427
1428    /// L1389 (jmap-chat-spec 33702a5) §Space/query: "Filter properties:
1429    /// `name` (String, substring match), `isPublic` (Boolean)."
1430    ///
1431    /// L1389: `name` is a substring match.
1432    pub async fn space_query_filters_name_substring<B: ConformanceBackend>(backend: B) {
1433        let member = json!([{ "id": ACCOUNT_ID }]);
1434        seeded(
1435            &backend,
1436            "Space",
1437            &[
1438                ("rust", json!({ "name": "rustaceans", "members": member })),
1439                ("go", json!({ "name": "gophers", "members": member })),
1440            ],
1441        )
1442        .await;
1443        let HandlerOutput { primary: resp, .. } = handle_space_query(
1444            &backend,
1445            &owner(&backend),
1446            json!({ "accountId": ACCOUNT_ID, "filter": { "name": "stace" } }),
1447            &[],
1448        )
1449        .await
1450        .expect("Space/query");
1451        assert_eq!(sorted_ids(&resp), ["rust"]);
1452    }
1453
1454    async fn emoji_set<B: ConformanceBackend>(backend: &B, create: Value) -> Value {
1455        handle_emoji_set(
1456            backend,
1457            &owner(backend),
1458            &std::collections::BTreeMap::new(),
1459            json!({ "accountId": ACCOUNT_ID, "create": create }),
1460        )
1461        .await
1462        .expect("CustomEmoji/set")
1463        .primary
1464    }
1465
1466    /// L1482 (jmap-chat-spec 33702a5) §CustomEmoji/query: "Filter
1467    /// properties: `spaceId` (String, optional — if absent returns all
1468    /// emoji accessible to the account including server-global)."
1469    ///
1470    /// L1482: `spaceId` restricts the result to that Space's emoji; absent,
1471    /// server-global emoji are included.
1472    pub async fn emoji_query_filters_space_id<B: ConformanceBackend>(backend: B) {
1473        setup(&backend).await;
1474        let resp = emoji_set(
1475            &backend,
1476            json!({
1477                "global": { "name": "wave", "blobId": "b1" },
1478                "local": { "name": "crab", "blobId": "b2", "spaceId": "space1" },
1479            }),
1480        )
1481        .await;
1482        let local = resp["created"]["local"]["id"].as_str().expect("id");
1483        let global = resp["created"]["global"]["id"].as_str().expect("id");
1484
1485        let query = |filter: Value| {
1486            let backend = &backend;
1487            async move {
1488                let HandlerOutput { primary: resp, .. } = handle_emoji_query(
1489                    backend,
1490                    &owner(backend),
1491                    json!({ "accountId": ACCOUNT_ID, "filter": filter }),
1492                )
1493                .await
1494                .expect("CustomEmoji/query");
1495                sorted_ids(&resp)
1496            }
1497        };
1498        assert_eq!(query(json!({ "spaceId": "space1" })).await, [local]);
1499        let mut all = vec![local.to_owned(), global.to_owned()];
1500        all.sort();
1501        assert_eq!(query(json!({})).await, all);
1502    }
1503
1504    /// RFC 8620 §5.6: `CustomEmoji/queryChanges` with the query's `spaceId`
1505    /// filter adds only emoji that the query matches.
1506    pub async fn emoji_query_changes_applies_space_id_filter<B: ConformanceBackend>(backend: B) {
1507        setup(&backend).await;
1508        let filter = json!({ "spaceId": "space1" });
1509        let HandlerOutput {
1510            primary: before, ..
1511        } = handle_emoji_query(
1512            &backend,
1513            &owner(&backend),
1514            json!({ "accountId": ACCOUNT_ID, "filter": filter }),
1515        )
1516        .await
1517        .expect("CustomEmoji/query");
1518
1519        let resp = emoji_set(
1520            &backend,
1521            json!({
1522                "global": { "name": "wave", "blobId": "b1" },
1523                "local": { "name": "crab", "blobId": "b2", "spaceId": "space1" },
1524            }),
1525        )
1526        .await;
1527        let local = resp["created"]["local"]["id"].as_str().expect("id");
1528
1529        let HandlerOutput {
1530            primary: changes, ..
1531        } = handle_emoji_query_changes(
1532            &backend,
1533            &owner(&backend),
1534            json!({
1535                "accountId": ACCOUNT_ID,
1536                "filter": filter,
1537                "sinceQueryState": before["queryState"],
1538            }),
1539        )
1540        .await
1541        .expect("CustomEmoji/queryChanges");
1542        assert_eq!(changes["added"], json!([{ "id": local, "index": 0 }]));
1543    }
1544}
1545
1546// ---------------------------------------------------------------------------
1547// `/query` honours the request's `sort` (bd:JMAP-yt1w.1).
1548//
1549// Oracles: draft-atwood-jmap-chat-00 §Space/query "Standard JMAP
1550// `/query`." and §ChatContact/query "Sort properties: `lastSeenAt`,
1551// `login`, `lastActiveAt`. When sorting by `lastActiveAt`, ChatContacts
1552// for which the field is absent sort last."; RFC 8620 §5.5 Comparator
1553// `isAscending`: "If true, sort in ascending order. If false, reverse the
1554// comparator's results to sort in descending order."
1555// ---------------------------------------------------------------------------
1556
1557mod query_sort {
1558    use jmap_server::HandlerOutput;
1559    use serde_json::{Value, json};
1560
1561    use super::{ACCOUNT_ID, ConformanceBackend, make_space, owner, seed, setup};
1562    use crate::{handle_contact_query, handle_space_get, handle_space_query};
1563
1564    /// `ids` of a `/query` response.
1565    fn ids(resp: &Value) -> Vec<String> {
1566        resp["ids"]
1567            .as_array()
1568            .expect("ids")
1569            .iter()
1570            .map(|id| id.as_str().expect("id").to_owned())
1571            .collect()
1572    }
1573
1574    /// Names of the Spaces in `space_ids`, in that order.
1575    async fn space_names<B: ConformanceBackend>(backend: &B, space_ids: &[String]) -> Vec<String> {
1576        let HandlerOutput { primary: resp, .. } = handle_space_get(
1577            backend,
1578            &owner(backend),
1579            json!({ "accountId": ACCOUNT_ID, "ids": space_ids }),
1580            &[],
1581        )
1582        .await
1583        .expect("Space/get");
1584        space_ids
1585            .iter()
1586            .map(|id| {
1587                resp["list"]
1588                    .as_array()
1589                    .expect("list")
1590                    .iter()
1591                    .find(|s| s["id"] == id.as_str())
1592                    .and_then(|s| s["name"].as_str())
1593                    .expect("space name")
1594                    .to_owned()
1595            })
1596            .collect()
1597    }
1598
1599    /// `Space/query` sorted by `name` with the given direction.
1600    async fn query_spaces_by_name<B: ConformanceBackend>(
1601        backend: &B,
1602        is_ascending: bool,
1603    ) -> Vec<String> {
1604        let HandlerOutput { primary: resp, .. } = handle_space_query(
1605            backend,
1606            &owner(backend),
1607            json!({
1608                "accountId": ACCOUNT_ID,
1609                "sort": [{ "property": "name", "isAscending": is_ascending }],
1610            }),
1611            &[],
1612        )
1613        .await
1614        .expect("Space/query");
1615        space_names(backend, &ids(&resp)).await
1616    }
1617
1618    /// RFC 8620 §5.5 Comparator `isAscending`: "If false, reverse the
1619    /// comparator's results to sort in descending order."
1620    pub async fn space_query_sort_descending_reverses_order<B: ConformanceBackend>(backend: B) {
1621        setup(&backend).await;
1622        for name in ["Alpha", "Bravo", "Charlie"] {
1623            make_space(&backend, name).await;
1624        }
1625        assert_eq!(
1626            query_spaces_by_name(&backend, false).await,
1627            ["Charlie", "Bravo", "Alpha"]
1628        );
1629    }
1630
1631    /// RFC 8620 §5.5 Comparator `isAscending`: "If true, sort in ascending
1632    /// order." The Spaces are created out of name order so creation order
1633    /// cannot satisfy the assertion.
1634    pub async fn space_query_sort_ascending_orders_by_property<B: ConformanceBackend>(backend: B) {
1635        setup(&backend).await;
1636        for name in ["Charlie", "Alpha", "Bravo"] {
1637            make_space(&backend, name).await;
1638        }
1639        assert_eq!(
1640            query_spaces_by_name(&backend, true).await,
1641            ["Alpha", "Bravo", "Charlie"]
1642        );
1643    }
1644
1645    /// draft-atwood-jmap-chat-00 §ChatContact/query: "When sorting by
1646    /// `lastActiveAt`, ChatContacts for which the field is absent sort
1647    /// last." in both directions.
1648    pub async fn contact_query_sort_last_active_at_absent_sorts_last<B: ConformanceBackend>(
1649        backend: B,
1650    ) {
1651        setup(&backend).await;
1652        for (id, last_active_at) in [
1653            ("c1", None),
1654            ("c2", Some("2026-01-01T00:00:00Z")),
1655            ("c3", Some("2026-03-01T00:00:00Z")),
1656        ] {
1657            let mut contact = json!({ "id": id, "login": id });
1658            if let Some(at) = last_active_at {
1659                contact["lastActiveAt"] = json!(at);
1660            }
1661            seed(&backend, "ChatContact", contact).await;
1662        }
1663
1664        for (is_ascending, expected) in [(true, ["c2", "c3", "c1"]), (false, ["c3", "c2", "c1"])] {
1665            let HandlerOutput { primary: resp, .. } = handle_contact_query(
1666                &backend,
1667                &owner(&backend),
1668                json!({
1669                    "accountId": ACCOUNT_ID,
1670                    "sort": [{ "property": "lastActiveAt", "isAscending": is_ascending }],
1671                }),
1672            )
1673            .await
1674            .expect("ChatContact/query");
1675            assert_eq!(ids(&resp), expected, "isAscending: {is_ascending}");
1676        }
1677    }
1678}
1679
1680// ---------------------------------------------------------------------------
1681// `/query` honours `anchor` and `anchorOffset` (bd:JMAP-yt1w.22) and
1682// saturates extreme `position` / `limit` values (bd:JMAP-uqhn.2).
1683//
1684// Exercised through `Chat/query`, which delegates to the generic
1685// `jmap_server::handle_query`. With no `sort` the results are in id
1686// order, so five Chats `c1`..`c5` sit at indexes 0..4.
1687//
1688// Oracle: RFC 8620 §5.5 (https://www.rfc-editor.org/rfc/rfc8620.txt,
1689// Section 5.5 "/query").
1690// ---------------------------------------------------------------------------
1691
1692mod query_anchor {
1693    use jmap_server::HandlerOutput;
1694    use serde_json::{Value, json};
1695
1696    use super::{ACCOUNT_ID, ConformanceBackend, owner, seed, setup};
1697    use crate::{handle_chat_query, handle_emoji_query};
1698
1699    /// Store Chats `c1`..`c5` in account `a1`.
1700    async fn seeded_backend<B: ConformanceBackend>(backend: &B) {
1701        setup(backend).await;
1702        for id in ["c1", "c2", "c3", "c4", "c5"] {
1703            seed(backend, "Chat", json!({ "id": id })).await;
1704        }
1705    }
1706
1707    /// Run `Chat/query` with `extra` merged into `{ "accountId": ACCOUNT_ID }`.
1708    async fn query<B: ConformanceBackend>(backend: &B, extra: Value) -> Result<Value, Value> {
1709        let mut args = json!({ "accountId": ACCOUNT_ID });
1710        for (k, v) in extra.as_object().expect("extra must be an object") {
1711            args[k] = v.clone();
1712        }
1713        handle_chat_query(backend, &owner(backend), args, &[])
1714            .await
1715            .map(|HandlerOutput { primary: resp, .. }| resp)
1716            .map_err(|e| serde_json::to_value(&e).expect("JmapError must serialize"))
1717    }
1718
1719    /// `ids` of a `/query` response.
1720    fn ids(resp: &Value) -> Vec<&str> {
1721        resp["ids"]
1722            .as_array()
1723            .expect("ids")
1724            .iter()
1725            .map(|id| id.as_str().expect("id"))
1726            .collect()
1727    }
1728
1729    /// RFC 8620 §5.5: "If an "anchor" argument is given, the anchor is looked
1730    /// for in the results after filtering and sorting.  If found, the
1731    /// "anchorOffset" is then added to its index. ... This index is now used
1732    /// exactly as though it were supplied as the "position" argument."
1733    ///
1734    /// Anchor `c3` is index 2; offset +1 gives start index 3.
1735    pub async fn anchor_with_positive_offset_starts_after_anchor<B: ConformanceBackend>(
1736        backend: B,
1737    ) {
1738        seeded_backend(&backend).await;
1739        let resp = query(
1740            &backend,
1741            json!({ "anchor": "c3", "anchorOffset": 1, "limit": 2 }),
1742        )
1743        .await
1744        .expect("Chat/query");
1745        assert_eq!(ids(&resp), ["c4", "c5"]);
1746        assert_eq!(resp["position"], 3);
1747    }
1748
1749    /// RFC 8620 §5.5 anchorOffset: "This MAY be negative.  For example, "-1"
1750    /// means the Foo immediately preceding the anchor is the first result in
1751    /// the list returned".
1752    pub async fn anchor_with_negative_offset_starts_before_anchor<B: ConformanceBackend>(
1753        backend: B,
1754    ) {
1755        seeded_backend(&backend).await;
1756        let resp = query(
1757            &backend,
1758            json!({ "anchor": "c3", "anchorOffset": -1, "limit": 2 }),
1759        )
1760        .await
1761        .expect("Chat/query");
1762        assert_eq!(ids(&resp), ["c2", "c3"]);
1763        assert_eq!(resp["position"], 1);
1764    }
1765
1766    /// RFC 8620 §5.5 anchorOffset: "(default: 0)". Without an offset the
1767    /// anchor itself is the first result.
1768    pub async fn anchor_without_offset_starts_at_anchor<B: ConformanceBackend>(backend: B) {
1769        seeded_backend(&backend).await;
1770        let resp = query(&backend, json!({ "anchor": "c4" }))
1771            .await
1772            .expect("Chat/query");
1773        assert_eq!(ids(&resp), ["c4", "c5"]);
1774        assert_eq!(resp["position"], 3);
1775    }
1776
1777    /// RFC 8620 §5.5: "If the resulting index is now negative, it is clamped
1778    /// to 0."
1779    ///
1780    /// Anchor `c2` is index 1; offset -3 gives -2, clamped to 0. The ignored
1781    /// `position` keeps the expected page distinct from the `position` page.
1782    pub async fn anchor_offset_before_start_clamps_to_zero<B: ConformanceBackend>(backend: B) {
1783        seeded_backend(&backend).await;
1784        let resp = query(
1785            &backend,
1786            json!({ "position": 3, "anchor": "c2", "anchorOffset": -3, "limit": 2 }),
1787        )
1788        .await
1789        .expect("Chat/query");
1790        assert_eq!(ids(&resp), ["c1", "c2"]);
1791        assert_eq!(resp["position"], 0);
1792    }
1793
1794    /// RFC 8620 §5.5: "If the anchor is not found, the call is rejected with
1795    /// an "anchorNotFound" error."
1796    pub async fn anchor_absent_from_results_is_anchor_not_found<B: ConformanceBackend>(backend: B) {
1797        seeded_backend(&backend).await;
1798        let err = query(&backend, json!({ "anchor": "nope" }))
1799            .await
1800            .expect_err("an anchor absent from the results must be rejected");
1801        assert_eq!(err["type"], "anchorNotFound");
1802    }
1803
1804    /// RFC 8620 §5.5: "If an "anchor" is specified, any position argument
1805    /// supplied by the client MUST be ignored."
1806    pub async fn anchor_overrides_position<B: ConformanceBackend>(backend: B) {
1807        seeded_backend(&backend).await;
1808        let resp = query(
1809            &backend,
1810            json!({ "position": 4, "anchor": "c2", "limit": 2 }),
1811        )
1812        .await
1813        .expect("Chat/query");
1814        assert_eq!(ids(&resp), ["c2", "c3"]);
1815        assert_eq!(resp["position"], 1);
1816    }
1817
1818    /// RFC 8620 §5.5: "If no "anchor" is supplied, any "anchorOffset"
1819    /// argument MUST be ignored."
1820    ///
1821    /// Guards the fix against applying `anchorOffset` to `position`.
1822    pub async fn anchor_offset_without_anchor_is_ignored<B: ConformanceBackend>(backend: B) {
1823        seeded_backend(&backend).await;
1824        let resp = query(
1825            &backend,
1826            json!({ "position": 1, "anchorOffset": 2, "limit": 2 }),
1827        )
1828        .await
1829        .expect("Chat/query");
1830        assert_eq!(ids(&resp), ["c2", "c3"]);
1831        assert_eq!(resp["position"], 1);
1832    }
1833
1834    /// RFC 8620 §5.5 argument types: "anchor: "Id|null"" and
1835    /// "anchorOffset: "Int" (default: 0)"; RFC 8620 §3.6.2 ""invalidArguments":
1836    /// One of the arguments is of the wrong type or is otherwise invalid".
1837    pub async fn anchor_arguments_of_wrong_type_are_invalid_arguments<B: ConformanceBackend>(
1838        backend: B,
1839    ) {
1840        seeded_backend(&backend).await;
1841        for extra in [
1842            json!({ "anchor": 7 }),
1843            json!({ "anchor": "c2", "anchorOffset": "1" }),
1844        ] {
1845            let err = query(&backend, extra.clone())
1846                .await
1847                .expect_err("wrongly typed anchor arguments must be rejected");
1848            assert_eq!(err["type"], "invalidArguments", "args: {extra}");
1849        }
1850    }
1851
1852    /// RFC 8620 §5.5 types `limit` as "UnsignedInt|null" and `position` as
1853    /// "Int"; wrong types are `invalidArguments` (§3.6.2). The description
1854    /// names only the JSON type: §3.6.1 reserves it for "unstructured English
1855    /// text suitable for displaying to a developer", so the client-supplied
1856    /// value is never echoed (bd JMAP-zegc). `CustomEmoji/query` parses these
1857    /// arguments itself rather than through `jmap_server::handle_query`.
1858    pub async fn emoji_query_wrongly_typed_args_do_not_echo_value<B: ConformanceBackend>(
1859        backend: B,
1860    ) {
1861        seeded_backend(&backend).await;
1862        for name in ["limit", "position"] {
1863            let mut args = json!({ "accountId": ACCOUNT_ID });
1864            args[name] = json!({ "note": "CANARY-zegc" });
1865            let err = handle_emoji_query(&backend, &owner(&backend), args)
1866                .await
1867                .expect_err("wrongly typed argument must be rejected");
1868            assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
1869            let desc = err.description.as_deref().unwrap_or_default();
1870            assert!(desc.starts_with(name), "{desc}");
1871            assert!(desc.contains("got object"), "{desc}");
1872            assert!(!desc.contains("CANARY"), "{desc}");
1873        }
1874    }
1875
1876    /// RFC 8620 §1.3 bounds `Int` to "-2^53+1 <= value <= 2^53-1" and
1877    /// `UnsignedInt` to "0 <= value <= 2^53-1". §5.5 position: "the negative
1878    /// value MUST be added to the total number of results given the filter,
1879    /// and if still negative, it's clamped to "0"", so the most negative
1880    /// legal `position` starts at index 0, and the largest legal `limit`
1881    /// returns all five results (bd:JMAP-uqhn.2).
1882    pub async fn extreme_position_and_limit_saturate<B: ConformanceBackend>(backend: B) {
1883        seeded_backend(&backend).await;
1884        let resp = query(
1885            &backend,
1886            json!({ "position": -9_007_199_254_740_991_i64, "limit": 9_007_199_254_740_991_u64 }),
1887        )
1888        .await
1889        .expect("Chat/query");
1890        assert_eq!(ids(&resp), ["c1", "c2", "c3", "c4", "c5"]);
1891        assert_eq!(resp["position"], 0);
1892    }
1893
1894    /// RFC 8620 §5.5 position: "If the index is greater than or equal to the
1895    /// total number of objects in the results list, then the "ids" array in
1896    /// the response will be empty, but this is not an error."
1897    pub async fn largest_position_is_empty_page_not_error<B: ConformanceBackend>(backend: B) {
1898        seeded_backend(&backend).await;
1899        let resp = query(&backend, json!({ "position": 9_007_199_254_740_991_i64 }))
1900            .await
1901            .expect("Chat/query");
1902        assert!(ids(&resp).is_empty());
1903    }
1904}
1905
1906// ---------------------------------------------------------------------------
1907// `Space/join` by invite code redeems the invite atomically through
1908// `ChatSpaces::join_space_with_invite` (bd:JMAP-x2gd.2).
1909//
1910// Oracle: draft-atwood-jmap-chat-00 §Space/join (jmap-chat-spec 77c3474
1911// L1416): "The `uses` increment and membership insertion SHOULD be
1912// performed within a single atomic operation so that concurrent
1913// redemptions cannot exceed `maxUses`." This crate requires the
1914// recommended atomicity of every backend by choice.
1915//
1916// The joining member is always the account's owner, so two distinct
1917// joiners racing for the last use cannot be modelled here. These tests
1918// pin the properties that can be: both effects land together, the
1919// backend re-checks `maxUses` itself, a refusal writes nothing, and
1920// concurrent redemptions neither lose nor double the increment.
1921// ---------------------------------------------------------------------------
1922
1923mod space_join {
1924    use std::sync::Arc;
1925
1926    use jmap_chat_types::{Space, SpaceInvite};
1927    use jmap_types::{Id, UTCDate};
1928    use serde_json::json;
1929
1930    use super::{ACCOUNT_ID, ConformanceBackend, owner, seed, setup};
1931    use crate::{InviteJoinRefusal, handle_space_join};
1932
1933    const SPACE_ID: &str = "s1";
1934    const INVITE_ID: &str = "inv1";
1935    const CODE: &str = "0123456789abcdef0123456789abcdef";
1936
1937    /// An empty Space and one invite for it at `uses`.
1938    async fn seeded<B: ConformanceBackend>(backend: &B, uses: u64, max_uses: u64) {
1939        setup(backend).await;
1940        seed(
1941            backend,
1942            "Space",
1943            json!({
1944                "id": SPACE_ID,
1945                "name": "Test Space",
1946                "createdAt": "2026-01-01T00:00:00Z",
1947                "memberCount": 0,
1948                "categories": [],
1949                "uncategorizedChannelIds": [],
1950                "isPublic": false,
1951                "isPubliclyPreviewable": false,
1952                "roles": [],
1953                "members": [],
1954            }),
1955        )
1956        .await;
1957        seed(
1958            backend,
1959            "SpaceInvite",
1960            json!({
1961                "id": INVITE_ID,
1962                "code": CODE,
1963                "spaceId": SPACE_ID,
1964                "createdBy": ACCOUNT_ID,
1965                "uses": uses,
1966                "maxUses": max_uses,
1967                "createdAt": "2026-01-01T00:00:00Z",
1968            }),
1969        )
1970        .await;
1971    }
1972
1973    /// `(member ids, invite uses, Space state, SpaceInvite state)`.
1974    async fn snapshot<B: ConformanceBackend>(backend: &B) -> (Vec<String>, u64, String, String) {
1975        let acct = Id::from(ACCOUNT_ID);
1976        let (spaces, _) = backend
1977            .get_objects::<Space>(&owner(backend), &acct, Some(&[Id::from(SPACE_ID)]), None)
1978            .await
1979            .unwrap();
1980        let (invites, _) = backend
1981            .get_objects::<SpaceInvite>(&owner(backend), &acct, Some(&[Id::from(INVITE_ID)]), None)
1982            .await
1983            .unwrap();
1984        let members = spaces[0]
1985            .members
1986            .iter()
1987            .map(|m| m.id.as_ref().to_owned())
1988            .collect();
1989        let space_state = backend
1990            .get_state::<Space>(&owner(backend), &acct)
1991            .await
1992            .unwrap();
1993        let invite_state = backend
1994            .get_state::<SpaceInvite>(&owner(backend), &acct)
1995            .await
1996            .unwrap();
1997        (
1998            members,
1999            invites[0].uses,
2000            space_state.as_ref().to_owned(),
2001            invite_state.as_ref().to_owned(),
2002        )
2003    }
2004
2005    /// draft-atwood-jmap-chat-00 §Space/join: "... atomically increment
2006    /// `uses` and add the caller to the Space's member list": one join
2007    /// produces both effects, each recorded as a change.
2008    pub async fn join_adds_member_and_counts_use_together<B: ConformanceBackend>(backend: B) {
2009        seeded(&backend, 0, 2).await;
2010        let (_, _, space_before, invite_before) = snapshot(&backend).await;
2011
2012        handle_space_join(
2013            &backend,
2014            &owner(&backend),
2015            json!({ "accountId": ACCOUNT_ID, "inviteCode": CODE }),
2016        )
2017        .await
2018        .expect("Space/join");
2019
2020        let (members, uses, space_after, invite_after) = snapshot(&backend).await;
2021        assert_eq!(members, vec![ACCOUNT_ID.to_owned()]);
2022        assert_eq!(uses, 1);
2023        assert_ne!(space_after, space_before, "Space change not recorded");
2024        assert_ne!(
2025            invite_after, invite_before,
2026            "SpaceInvite change not recorded"
2027        );
2028    }
2029
2030    /// draft-atwood-jmap-chat-00 §Space/join: "... so that concurrent
2031    /// redemptions cannot exceed `maxUses`": the backend re-checks
2032    /// `maxUses` itself rather than trusting the handler's earlier read,
2033    /// and the refusal writes nothing.
2034    pub async fn exhausted_invite_is_refused_without_any_write<B: ConformanceBackend>(backend: B) {
2035        seeded(&backend, 1, 1).await;
2036        let before = snapshot(&backend).await;
2037
2038        let refusal = backend
2039            .join_space_with_invite(
2040                &owner(&backend),
2041                &Id::from(ACCOUNT_ID),
2042                &Id::from(INVITE_ID),
2043                &UTCDate::from("2026-01-02T00:00:00Z"),
2044            )
2045            .await
2046            .unwrap();
2047
2048        assert_eq!(refusal, Err(InviteJoinRefusal::Exhausted));
2049        assert_eq!(snapshot(&backend).await, before);
2050    }
2051
2052    /// draft-atwood-jmap-chat-00 §Space/join (jmap-chat-spec 77c3474 L1416):
2053    /// "The `uses` increment and membership insertion SHOULD be performed
2054    /// within a single atomic operation", which this crate requires by
2055    /// choice. Concurrent redemptions are serialized: exactly one
2056    /// succeeds, `uses` is incremented exactly once and the member appears
2057    /// exactly once.
2058    ///
2059    /// Spawns tokio tasks, so it must run on a multi-thread tokio runtime
2060    /// such as [`run`](super::run)'s.
2061    pub async fn concurrent_redemptions_increment_exactly_once<B: ConformanceBackend>(backend: B) {
2062        const RACERS: usize = 32;
2063        seeded(&backend, 0, 100).await;
2064        let backend = Arc::new(backend);
2065
2066        let tasks: Vec<_> = (0..RACERS)
2067            .map(|_| {
2068                let backend = Arc::clone(&backend);
2069                tokio::spawn(async move {
2070                    backend
2071                        .join_space_with_invite(
2072                            &owner(&*backend),
2073                            &Id::from(ACCOUNT_ID),
2074                            &Id::from(INVITE_ID),
2075                            &UTCDate::from("2026-01-02T00:00:00Z"),
2076                        )
2077                        .await
2078                        .unwrap()
2079                })
2080            })
2081            .collect();
2082        let mut outcomes = Vec::with_capacity(RACERS);
2083        for t in tasks {
2084            outcomes.push(t.await.unwrap());
2085        }
2086
2087        assert_eq!(outcomes.iter().filter(|o| o.is_ok()).count(), 1);
2088        assert!(
2089            outcomes
2090                .iter()
2091                .all(|o| *o == Ok(()) || *o == Err(InviteJoinRefusal::AlreadyMember))
2092        );
2093        let (members, uses, _, _) = snapshot(&*backend).await;
2094        assert_eq!(members, vec![ACCOUNT_ID.to_owned()]);
2095        assert_eq!(uses, 1);
2096    }
2097}
2098
2099// ---------------------------------------------------------------------------
2100// Message writes that must be atomic: burn-on-read (bd:JMAP-x2gd.6) and
2101// `create_message` (bd:JMAP-z4z0.5)
2102// ---------------------------------------------------------------------------
2103
2104mod message_atomic {
2105    use jmap_server::HandlerOutput;
2106    use jmap_types::{Id, State};
2107    use serde_json::{Value, json};
2108
2109    use super::{ACCOUNT_ID, ConformanceBackend, make_received, owner, seed_group_chat, setup};
2110    use crate::OutboundEvent;
2111    use crate::message::{handle_message_changes, handle_message_get, handle_message_set};
2112
2113    /// Store one `burnOnRead` message; returns its id.
2114    async fn seeded_burn<B: ConformanceBackend>(backend: &B) -> String {
2115        setup(backend).await;
2116        seed_group_chat(backend, "c1").await;
2117        let HandlerOutput { primary: resp, .. } = handle_message_set(
2118            backend,
2119            &owner(backend),
2120            &std::collections::BTreeMap::new(),
2121            json!({
2122                "accountId": ACCOUNT_ID,
2123                "create": {
2124                    "m0": {
2125                        "chatId": "c1",
2126                        "body": "burn me",
2127                        "sentAt": "2024-01-01T00:00:00Z",
2128                        "burnOnRead": true
2129                    }
2130                }
2131            }),
2132            &[],
2133        )
2134        .await
2135        .expect("create");
2136        let id = resp["created"]["m0"]["id"]
2137            .as_str()
2138            .expect("created id")
2139            .to_owned();
2140        make_received(backend, &id).await;
2141        id
2142    }
2143
2144    async fn set_update<B: ConformanceBackend>(backend: &B, id: &str, patch: Value) -> Value {
2145        handle_message_set(
2146            backend,
2147            &owner(backend),
2148            &std::collections::BTreeMap::new(),
2149            json!({ "accountId": ACCOUNT_ID, "update": { id: patch } }),
2150            &[],
2151        )
2152        .await
2153        .expect("Message/set")
2154        .primary
2155    }
2156
2157    async fn get<B: ConformanceBackend>(backend: &B, id: &str) -> Value {
2158        handle_message_get(
2159            backend,
2160            &owner(backend),
2161            json!({ "accountId": ACCOUNT_ID, "ids": [id] }),
2162            &[],
2163        )
2164        .await
2165        .expect("Message/get")
2166        .primary
2167    }
2168
2169    async fn burn_state<B: ConformanceBackend>(backend: &B, id: &str) -> String {
2170        get(backend, id).await["state"]
2171            .as_str()
2172            .expect("state")
2173            .to_owned()
2174    }
2175
2176    /// Oracle: draft-atwood-jmap-chat-00 (jmap-chat-spec 77c3474 L750)
2177    /// §Message `burnOnRead`: "When `true`, the receiving server SHOULD
2178    /// permanently hard-delete this message (row removal, not tombstone)
2179    /// immediately after setting `readAt`." This crate performs the
2180    /// recommended deletion, so the `readAt` write is never stored without
2181    /// it.
2182    ///
2183    /// A `readAt` patch the backend cannot store is rejected and burns
2184    /// nothing. RFC 8620 §5.3: "invalidProperties: The record given is
2185    /// invalid in some way." `readAt` is a UTCDate, so a number is invalid.
2186    pub async fn invalid_read_at_patch_is_rejected_without_burning<B: ConformanceBackend>(
2187        backend: B,
2188    ) {
2189        let id = seeded_burn(&backend).await;
2190        let before = burn_state(&backend, &id).await;
2191
2192        let resp = set_update(&backend, &id, json!({ "readAt": 42 })).await;
2193        assert_eq!(
2194            resp["notUpdated"][&id]["type"], "invalidProperties",
2195            "resp: {resp}"
2196        );
2197
2198        let still = get(&backend, &id).await;
2199        assert_eq!(still["list"][0]["id"], json!(id), "{still}");
2200        assert_eq!(still["list"][0]["readAt"], Value::Null, "{still}");
2201        assert_eq!(still["state"], json!(before), "no state change");
2202    }
2203
2204    async fn state<B: ConformanceBackend>(backend: &B) -> State {
2205        backend
2206            .get_state::<jmap_chat_types::Message>(&owner(backend), &Id::from(ACCOUNT_ID))
2207            .await
2208            .expect("Message state")
2209    }
2210
2211    async fn create<B: ConformanceBackend>(backend: &B) -> Value {
2212        let HandlerOutput { primary, .. } = handle_message_set(
2213            backend,
2214            &owner(backend),
2215            &std::collections::BTreeMap::new(),
2216            json!({
2217                "accountId": ACCOUNT_ID,
2218                "create": { "c": {
2219                    "chatId": "g1",
2220                    "body": "hi",
2221                    "bodyType": "text/plain",
2222                    "sentAt": "2026-01-02T00:00:00Z",
2223                } },
2224            }),
2225            &[],
2226        )
2227        .await
2228        .expect("Message/set");
2229        primary
2230    }
2231
2232    async fn stored_ids<B: ConformanceBackend>(backend: &B) -> Vec<Value> {
2233        let HandlerOutput { primary, .. } = handle_message_get(
2234            backend,
2235            &owner(backend),
2236            json!({ "accountId": ACCOUNT_ID, "ids": null, "properties": ["id"] }),
2237            &[],
2238        )
2239        .await
2240        .expect("Message/get");
2241        primary["list"]
2242            .as_array()
2243            .expect("list")
2244            .iter()
2245            .map(|m| m["id"].clone())
2246            .collect()
2247    }
2248
2249    /// Creates one Message and checks the stored Message, the state change
2250    /// and the single `NewMessage` event against the spec.
2251    ///
2252    /// Oracles:
2253    ///
2254    /// - draft-atwood-jmap-chat-00 at jmap-chat-spec b1cd625 L1222
2255    ///   (§Message/set): "The server sets `id`, `senderMsgId`, `senderId`,
2256    ///   `receivedAt`, `deliveryState`, and delivery timestamp fields, then
2257    ///   enqueues the message for outbound delivery."
2258    /// - draft-atwood-jmap-chat-00 §Message `senderMsgId`: "Equals `id` for
2259    ///   messages composed by the owner."
2260    ///
2261    /// Runs only when [`ConformanceBackend::take_outbound_events`] returns
2262    /// `Some`.
2263    pub async fn create_message_stores_and_reports_one_new_message<B: ConformanceBackend>(
2264        backend: B,
2265    ) {
2266        setup(&backend).await;
2267        seed_group_chat(&backend, "g1").await;
2268        if backend.take_outbound_events().is_none() {
2269            return;
2270        }
2271        let take_events = || {
2272            backend
2273                .take_outbound_events()
2274                .expect("take_outbound_events returned Some before")
2275        };
2276
2277        let before = state(&backend).await;
2278        let resp = create(&backend).await;
2279        let created = &resp["created"]["c"];
2280        let id = created["id"].as_str().expect("created id").to_owned();
2281        assert_eq!(created["senderMsgId"], json!(id), "{resp}");
2282        assert_eq!(resp["notCreated"], Value::Null, "{resp}");
2283        assert_eq!(stored_ids(&backend).await, vec![json!(id)]);
2284
2285        let HandlerOutput {
2286            primary: changes, ..
2287        } = handle_message_changes(
2288            &backend,
2289            &owner(&backend),
2290            json!({ "accountId": ACCOUNT_ID, "sinceState": before }),
2291            &[],
2292        )
2293        .await
2294        .expect("Message/changes");
2295        assert_eq!(changes["created"], json!([id]), "{changes}");
2296        assert_eq!(changes["updated"], json!([]), "{changes}");
2297        assert_eq!(changes["destroyed"], json!([]), "{changes}");
2298
2299        assert_eq!(
2300            take_events(),
2301            vec![OutboundEvent::NewMessage {
2302                chat_id: Id::from("g1"),
2303                message_id: Id::from(id.as_str()),
2304                sender_msg_id: Id::from(id.as_str()),
2305            }]
2306        );
2307    }
2308}
2309
2310// ---------------------------------------------------------------------------
2311// `ChatContact/set` create by `identity` and the `ChatContact/query`
2312// `identity` filter (bd:JMAP-405z.3).
2313//
2314// Oracle: draft-atwood-jmap-chat-00 (jmap-chat-spec cefc217)
2315// §ChatContact/set and §ChatContact/query, quoted on each test.
2316// ---------------------------------------------------------------------------
2317
2318mod contact_identity {
2319    use jmap_server::HandlerOutput;
2320    use serde_json::{Value, json};
2321
2322    use super::{ACCOUNT_ID, ConformanceBackend, owner, seed, setup};
2323    use crate::{handle_contact_get, handle_contact_query, handle_contact_set};
2324
2325    /// Store a ChatContact with the given `id` and `identity`.
2326    async fn insert_contact<B: ConformanceBackend>(backend: &B, id: &str, identity: &str) {
2327        seed(
2328            backend,
2329            "ChatContact",
2330            json!({
2331                "id": id,
2332                "identity": identity,
2333                "login": identity,
2334                "firstSeenAt": "2026-01-01T00:00:00Z",
2335                "lastSeenAt": "2026-01-01T00:00:00Z",
2336                "blocked": false
2337            }),
2338        )
2339        .await;
2340    }
2341
2342    /// `ChatContact/set` with the given `create` map.
2343    async fn create<B: ConformanceBackend>(backend: &B, create: Value) -> Value {
2344        let HandlerOutput { primary: resp, .. } = handle_contact_set(
2345            backend,
2346            &owner(backend),
2347            json!({ "accountId": ACCOUNT_ID, "create": create }),
2348        )
2349        .await
2350        .expect("ChatContact/set");
2351        resp
2352    }
2353
2354    /// The sorted `properties` of a SetError.
2355    fn error_properties(err: &Value) -> Vec<String> {
2356        let mut props: Vec<String> = err["properties"]
2357            .as_array()
2358            .unwrap_or_else(|| panic!("properties missing from {err}"))
2359            .iter()
2360            .map(|p| p.as_str().expect("property name").to_owned())
2361            .collect();
2362        props.sort();
2363        props
2364    }
2365
2366    /// draft-atwood-jmap-chat-00 §ChatContact/set: "`create` accepts only
2367    /// `identity`, which is required; the server assigns `id` and sets the
2368    /// other server-set properties."
2369    pub async fn contact_create_by_identity_assigns_id<B: ConformanceBackend>(backend: B) {
2370        setup(&backend).await;
2371        let resp = create(
2372            &backend,
2373            json!({ "k1": { "identity": "alice@example.com" } }),
2374        )
2375        .await;
2376
2377        assert!(
2378            resp["notCreated"].is_null(),
2379            "create with identity must succeed: {}",
2380            resp["notCreated"]
2381        );
2382        let id = resp["created"]["k1"]["id"]
2383            .as_str()
2384            .unwrap_or_else(|| panic!("created.k1.id missing: {resp}"))
2385            .to_owned();
2386
2387        let HandlerOutput { primary: get, .. } = handle_contact_get(
2388            &backend,
2389            &owner(&backend),
2390            json!({ "accountId": ACCOUNT_ID, "ids": [&id] }),
2391        )
2392        .await
2393        .expect("ChatContact/get");
2394        assert_eq!(get["list"][0]["id"], json!(id));
2395        assert_eq!(get["list"][0]["identity"], json!("alice@example.com"));
2396    }
2397
2398    /// draft-atwood-jmap-chat-00 §ChatContact/set: "If a ChatContact with
2399    /// that `identity` already exists, the server MUST reject the create with
2400    /// a SetError of type `alreadyExists`, including the existing
2401    /// ChatContact's id in the `existingId` field ({{RFC8620}} Section 5.3)."
2402    pub async fn contact_create_existing_identity_already_exists<B: ConformanceBackend>(
2403        backend: B,
2404    ) {
2405        setup(&backend).await;
2406        insert_contact(&backend, "ct1", "alice@example.com").await;
2407
2408        let resp = create(
2409            &backend,
2410            json!({ "k1": { "identity": "alice@example.com" } }),
2411        )
2412        .await;
2413
2414        assert!(resp["created"]["k1"].is_null(), "duplicate created: {resp}");
2415        assert_eq!(resp["notCreated"]["k1"]["type"], json!("alreadyExists"));
2416        assert_eq!(resp["notCreated"]["k1"]["existingId"], json!("ct1"));
2417    }
2418
2419    /// draft-atwood-jmap-chat-00 §ChatContact/set: "`create` accepts only
2420    /// `identity`, which is required". A create without `identity` is an
2421    /// invalid record (RFC 8620 §5.3 `invalidProperties`).
2422    pub async fn contact_create_without_identity_invalid_properties<B: ConformanceBackend>(
2423        backend: B,
2424    ) {
2425        setup(&backend).await;
2426        let resp = create(&backend, json!({ "k1": {} })).await;
2427
2428        assert!(
2429            resp["created"]["k1"].is_null(),
2430            "created without identity: {resp}"
2431        );
2432        assert_eq!(resp["notCreated"]["k1"]["type"], json!("invalidProperties"));
2433        assert_eq!(error_properties(&resp["notCreated"]["k1"]), ["identity"]);
2434    }
2435
2436    /// draft-atwood-jmap-chat-00 §ChatContact/set: "`create` accepts only
2437    /// `identity`". Any other property in a create is rejected with an RFC
2438    /// 8620 §5.3 `invalidProperties` SetError naming it, and no ChatContact
2439    /// is recorded.
2440    pub async fn contact_create_other_properties_invalid_properties<B: ConformanceBackend>(
2441        backend: B,
2442    ) {
2443        setup(&backend).await;
2444        let resp = create(
2445            &backend,
2446            json!({
2447                "k1": {
2448                    "identity": "alice@example.com",
2449                    "login": "alice",
2450                    "blocked": true,
2451                    "displayName": "Alice"
2452                }
2453            }),
2454        )
2455        .await;
2456
2457        assert!(
2458            resp["created"]["k1"].is_null(),
2459            "created with extras: {resp}"
2460        );
2461        assert_eq!(resp["notCreated"]["k1"]["type"], json!("invalidProperties"));
2462        assert_eq!(
2463            error_properties(&resp["notCreated"]["k1"]),
2464            ["blocked", "displayName", "login"]
2465        );
2466
2467        // The rejected create recorded nothing, so the identity is still free.
2468        let retry = create(
2469            &backend,
2470            json!({ "k2": { "identity": "alice@example.com" } }),
2471        )
2472        .await;
2473        assert!(
2474            retry["created"]["k2"]["id"].is_string(),
2475            "identity must still be creatable: {retry}"
2476        );
2477    }
2478
2479    /// draft-atwood-jmap-chat-00 §ChatContact/query: "Filter properties:
2480    /// `blocked` (Boolean), `presence` (String), `identity` (String; matches
2481    /// the ChatContact whose `identity` equals the value octet for octet)."
2482    /// The case-variant contact shows the match is octet-exact.
2483    pub async fn contact_query_identity_filter_matches_octet_for_octet<B: ConformanceBackend>(
2484        backend: B,
2485    ) {
2486        setup(&backend).await;
2487        insert_contact(&backend, "ct1", "alice@example.com").await;
2488        insert_contact(&backend, "ct2", "Alice@example.com").await;
2489        insert_contact(&backend, "ct3", "bob@example.com").await;
2490
2491        let HandlerOutput { primary: resp, .. } = handle_contact_query(
2492            &backend,
2493            &owner(&backend),
2494            json!({
2495                "accountId": ACCOUNT_ID,
2496                "filter": { "identity": "alice@example.com" }
2497            }),
2498        )
2499        .await
2500        .expect("ChatContact/query");
2501
2502        assert_eq!(resp["ids"], json!(["ct1"]));
2503    }
2504}
2505
2506// ---------------------------------------------------------------------------
2507// Thread counts `replyCount` / `unreadReplyCount` (bd:JMAP-y3f2.3) and
2508// their `Message/changes` reporting (bd:JMAP-y3f2.15).
2509//
2510// Oracles, quoted from draft-atwood-jmap-chat-00.md at jmap-chat-spec
2511// 91672c9:
2512//
2513// - L638-639 `replyCount`: "Count of messages in this chat with
2514//   `replyTo` equal to this message's `id`. Present only when
2515//   `supportsThreads` is `true`."
2516// - L641-642 `unreadReplyCount`: "Count of replies to this message
2517//   received after the owner's `ReadPosition.lastReadMessageId` in this
2518//   Chat. Present only when `supportsThreads` is `true` and this message
2519//   is a thread root (`threadRootId` is absent)."
2520// - L591: "Message IDs are ULIDs, assigned by the **receiving** mailbox
2521//   at storage time. ULIDs are lexicographically ordered by time".
2522// - jmap-chat-spec aa01dd7 L732, `unreadReplyCount`: "Which of those
2523//   replies count is implementation-defined, as for `Chat.unreadCount`".
2524//   The fixture Messages come from `OTHER_SENDER`, so every server counts
2525//   them.
2526// ---------------------------------------------------------------------------
2527
2528mod threads {
2529    use jmap_server::HandlerOutput;
2530    use serde_json::{Value, json};
2531
2532    use super::{ACCOUNT_ID, ConformanceBackend, owner, seed, setup, supports_threads};
2533    use crate::handle_chat_set;
2534    use crate::handle_position_set;
2535    use crate::message::{handle_message_changes, handle_message_get, handle_message_set};
2536
2537    // Hand-picked ULIDs (Crockford base32, 26 chars) in ascending order.
2538    const ROOT: &str = "01J0000000000000000000000A";
2539    const A: &str = "01J0000000000000000000000B";
2540    const B: &str = "01J0000000000000000000000C";
2541    const C: &str = "01J0000000000000000000000D";
2542    const OTHER_CHAT_MSG: &str = "01J0000000000000000000000E";
2543
2544    /// A ChatContact other than the owner; the owner's own Messages carry the
2545    /// accountId as `senderId`.
2546    const OTHER_SENDER: &str = "contact-bob";
2547
2548    async fn create_group<K: ConformanceBackend>(backend: &K) -> String {
2549        let HandlerOutput { primary: resp, .. } = handle_chat_set(
2550            backend,
2551            &owner(backend),
2552            &std::collections::BTreeMap::new(),
2553            json!({
2554                "accountId": ACCOUNT_ID,
2555                "create": { "g": { "kind": "group", "name": "G", "memberIds": ["contact-bob"] } }
2556            }),
2557            &[],
2558        )
2559        .await
2560        .expect("Chat/set");
2561        resp["created"]["g"]["id"]
2562            .as_str()
2563            .unwrap_or_else(|| panic!("group not created: {resp}"))
2564            .to_owned()
2565    }
2566
2567    /// Seed one stored Message from `OTHER_SENDER` with a fixed id.
2568    async fn seed_message<K: ConformanceBackend>(
2569        backend: &K,
2570        id: &str,
2571        chat_id: &str,
2572        reply_to: Option<&str>,
2573        root: Option<&str>,
2574    ) {
2575        let mut msg = json!({
2576            "id": id,
2577            "senderMsgId": id,
2578            "senderId": OTHER_SENDER,
2579            "chatId": chat_id,
2580            "body": "x",
2581            "bodyType": "text/plain",
2582            "attachments": [],
2583            "sentAt": "2024-01-01T00:00:00Z",
2584            "receivedAt": "2024-01-01T00:00:00Z",
2585            "deliveryState": "delivered",
2586        });
2587        if let Some(r) = reply_to {
2588            msg["replyTo"] = json!(r);
2589        }
2590        if let Some(r) = root {
2591            msg["threadRootId"] = json!(r);
2592        }
2593        seed(backend, "Message", msg).await;
2594    }
2595
2596    /// Fixture thread in one Chat:
2597    ///
2598    /// ```text
2599    /// ROOT
2600    /// ├── A  (replyTo ROOT, threadRootId ROOT)
2601    /// │   └── B  (replyTo A, threadRootId ROOT)
2602    /// └── C  (replyTo ROOT, threadRootId ROOT)
2603    /// ```
2604    ///
2605    /// plus OTHER_CHAT_MSG in a second Chat, and a ReadPosition for the
2606    /// first Chat with `lastReadMessageId` = A.
2607    async fn fixture<K: ConformanceBackend>(backend: &K) -> (String, String) {
2608        setup(backend).await;
2609        let chat = create_group(backend).await;
2610        let other = create_group(backend).await;
2611        seed_message(backend, ROOT, &chat, None, None).await;
2612        seed_message(backend, A, &chat, Some(ROOT), Some(ROOT)).await;
2613        seed_message(backend, B, &chat, Some(A), Some(ROOT)).await;
2614        seed_message(backend, C, &chat, Some(ROOT), Some(ROOT)).await;
2615        seed_message(backend, OTHER_CHAT_MSG, &other, None, None).await;
2616        seed(
2617            backend,
2618            "ReadPosition",
2619            json!({
2620                "id": "rp1",
2621                "chatId": chat,
2622                "lastReadMessageId": A,
2623                "lastReadAt": "2024-01-01T00:00:00Z",
2624            }),
2625        )
2626        .await;
2627        (chat, other)
2628    }
2629
2630    async fn create<K: ConformanceBackend>(backend: &K, obj: Value) -> Value {
2631        let HandlerOutput { primary: resp, .. } = handle_message_set(
2632            backend,
2633            &owner(backend),
2634            &std::collections::BTreeMap::new(),
2635            json!({ "accountId": ACCOUNT_ID, "create": { "m": obj } }),
2636            &[],
2637        )
2638        .await
2639        .expect("Message/set");
2640        resp
2641    }
2642
2643    fn reply(chat: &str, reply_to: &str, root: Option<&str>) -> Value {
2644        let mut obj = json!({
2645            "chatId": chat,
2646            "body": "re",
2647            "bodyType": "text/plain",
2648            "sentAt": "2024-01-01T00:00:00Z",
2649            "replyTo": reply_to,
2650        });
2651        if let Some(r) = root {
2652            obj["threadRootId"] = json!(r);
2653        }
2654        obj
2655    }
2656
2657    async fn get<K: ConformanceBackend>(backend: &K, ids: &[&str]) -> Vec<Value> {
2658        let HandlerOutput { primary: resp, .. } = handle_message_get(
2659            backend,
2660            &owner(backend),
2661            json!({ "accountId": ACCOUNT_ID, "ids": ids }),
2662            &[],
2663        )
2664        .await
2665        .expect("Message/get");
2666        resp["list"].as_array().expect("list").clone()
2667    }
2668
2669    fn by_id<'a>(list: &'a [Value], id: &str) -> &'a Value {
2670        list.iter()
2671            .find(|m| m["id"] == id)
2672            .unwrap_or_else(|| panic!("{id} missing from {list:?}"))
2673    }
2674
2675    /// L638-642 (jmap-chat-spec 91672c9) against the fixture, counted by
2676    /// hand:
2677    ///
2678    /// - ROOT: replies A and C -> replyCount 2; of those only C sorts after
2679    ///   lastReadMessageId A (L591) -> unreadReplyCount 1.
2680    /// - A: reply B -> replyCount 1; A has a threadRootId, so it is not a
2681    ///   thread root and carries no unreadReplyCount.
2682    /// - B, C: no replies -> replyCount 0, no unreadReplyCount.
2683    ///
2684    /// Runs only when `supportsThreads` is `true`.
2685    pub async fn reply_counts_match_fixture<K: ConformanceBackend>(backend: K) {
2686        if !supports_threads(&backend) {
2687            return;
2688        }
2689        let _ = fixture(&backend).await;
2690        let list = get(&backend, &[ROOT, A, B, C]).await;
2691        let root = by_id(&list, ROOT);
2692        assert_eq!(root["replyCount"], 2, "{root}");
2693        assert_eq!(root["unreadReplyCount"], 1, "{root}");
2694        let a = by_id(&list, A);
2695        assert_eq!(a["replyCount"], 1, "{a}");
2696        assert!(a.get("unreadReplyCount").is_none(), "{a}");
2697        for id in [B, C] {
2698            let m = by_id(&list, id);
2699            assert_eq!(m["replyCount"], 0, "{m}");
2700            assert!(m.get("unreadReplyCount").is_none(), "{m}");
2701        }
2702    }
2703
2704    /// L641-642 (jmap-chat-spec 91672c9) with no `lastReadMessageId`: no
2705    /// reply has been read, so the unread count equals the reply count
2706    /// (ROOT: A and C -> 2).
2707    ///
2708    /// Runs only when `supportsThreads` is `true`.
2709    pub async fn unread_reply_count_without_read_position<K: ConformanceBackend>(backend: K) {
2710        if !supports_threads(&backend) {
2711            return;
2712        }
2713        let (chat, _) = fixture(&backend).await;
2714        seed(
2715            &backend,
2716            "ReadPosition",
2717            json!({ "id": "rp1", "chatId": chat }),
2718        )
2719        .await;
2720        let list = get(&backend, &[ROOT]).await;
2721        assert_eq!(list[0]["unreadReplyCount"], 2, "{list:?}");
2722    }
2723
2724    /// L639 / L642 (jmap-chat-spec 91672c9) "Present only when
2725    /// `supportsThreads` is `true`": with `supportsThreads: false` neither
2726    /// count is returned.
2727    ///
2728    /// Runs only when `supportsThreads` is `false`.
2729    pub async fn counts_absent_without_supports_threads<K: ConformanceBackend>(backend: K) {
2730        if supports_threads(&backend) {
2731            return;
2732        }
2733        let _ = fixture(&backend).await;
2734        let list = get(&backend, &[ROOT, A]).await;
2735        for m in &list {
2736            assert!(m.get("replyCount").is_none(), "{m}");
2737            assert!(m.get("unreadReplyCount").is_none(), "{m}");
2738        }
2739    }
2740
2741    // Count changes advance Message state (bd:JMAP-y3f2.15)
2742    //
2743    // RFC 8620 §5.1: "If the data changes, this string MUST change." §5.2
2744    // `updated`: "An array of Ids for records that have been updated since
2745    // the old state." `replyCount` and `unreadReplyCount` are Message data
2746    // (L638-642), so a write that changes them must list the Message.
2747
2748    async fn message_state<K: ConformanceBackend>(backend: &K) -> String {
2749        let HandlerOutput { primary: resp, .. } = handle_message_get(
2750            backend,
2751            &owner(backend),
2752            json!({ "accountId": ACCOUNT_ID, "ids": [] }),
2753            &[],
2754        )
2755        .await
2756        .expect("Message/get");
2757        resp["state"].as_str().expect("state").to_owned()
2758    }
2759
2760    async fn message_changes<K: ConformanceBackend>(backend: &K, since: &str) -> Value {
2761        let HandlerOutput { primary: resp, .. } = handle_message_changes(
2762            backend,
2763            &owner(backend),
2764            json!({ "accountId": ACCOUNT_ID, "sinceState": since }),
2765            &[],
2766        )
2767        .await
2768        .expect("Message/changes");
2769        resp
2770    }
2771
2772    /// RFC 8620 §5.1: "If the data changes, this string MUST change."
2773    /// Creating a reply to A raises A's `replyCount` from 1 to 2 (L638-639),
2774    /// so `Message/changes` lists A as updated and the reply as created.
2775    ///
2776    /// Runs only when `supportsThreads` is `true`.
2777    pub async fn reply_create_lists_parent_updated<K: ConformanceBackend>(backend: K) {
2778        if !supports_threads(&backend) {
2779            return;
2780        }
2781        let (chat, _) = fixture(&backend).await;
2782        let since = message_state(&backend).await;
2783        let resp = create(&backend, reply(&chat, A, None)).await;
2784        let new_id = resp["created"]["m"]["id"].clone();
2785        let changes = message_changes(&backend, &since).await;
2786        assert_eq!(changes["created"], json!([new_id]), "{changes}");
2787        assert_eq!(changes["updated"], json!([A]), "{changes}");
2788    }
2789
2790    /// RFC 8620 §5.1: "If the data changes, this string MUST change."
2791    /// Destroying B, the only reply to A, lowers A's `replyCount` from 1 to
2792    /// 0, so `Message/changes` lists A as updated and B as destroyed.
2793    ///
2794    /// Runs only when `supportsThreads` is `true`.
2795    pub async fn reply_destroy_lists_parent_updated<K: ConformanceBackend>(backend: K) {
2796        if !supports_threads(&backend) {
2797            return;
2798        }
2799        let _ = fixture(&backend).await;
2800        let since = message_state(&backend).await;
2801        let HandlerOutput { primary: resp, .. } = handle_message_set(
2802            &backend,
2803            &owner(&backend),
2804            &std::collections::BTreeMap::new(),
2805            json!({ "accountId": ACCOUNT_ID, "destroy": [B] }),
2806            &[],
2807        )
2808        .await
2809        .expect("Message/set");
2810        assert_eq!(resp["destroyed"], json!([B]), "{resp}");
2811        let changes = message_changes(&backend, &since).await;
2812        assert_eq!(changes["destroyed"], json!([B]), "{changes}");
2813        assert_eq!(changes["updated"], json!([A]), "{changes}");
2814    }
2815
2816    /// RFC 8620 §5.1: "If the data changes, this string MUST change."
2817    /// Moving `lastReadMessageId` from A to C (L641-642, ids ordered per
2818    /// L591) marks reply C to ROOT read, so ROOT's `unreadReplyCount` drops
2819    /// from 1 to 0 and ROOT is listed as updated. B also crosses the read
2820    /// mark, but its parent A has a `threadRootId`, carries no
2821    /// `unreadReplyCount`, and is not listed.
2822    ///
2823    /// Runs only when `supportsThreads` is `true`.
2824    pub async fn read_position_update_lists_thread_root_updated<K: ConformanceBackend>(backend: K) {
2825        if !supports_threads(&backend) {
2826            return;
2827        }
2828        let _ = fixture(&backend).await;
2829        let since = message_state(&backend).await;
2830        let HandlerOutput { primary: resp, .. } = handle_position_set(
2831            &backend,
2832            &owner(&backend),
2833            &std::collections::BTreeMap::new(),
2834            json!({
2835                "accountId": ACCOUNT_ID,
2836                "update": { "rp1": { "lastReadMessageId": C } },
2837            }),
2838        )
2839        .await
2840        .expect("ReadPosition/set");
2841        assert!(resp["updated"].get("rp1").is_some(), "{resp}");
2842        let changes = message_changes(&backend, &since).await;
2843        assert_eq!(changes["updated"], json!([ROOT]), "{changes}");
2844        assert_eq!(changes["created"], json!([]), "{changes}");
2845        assert_eq!(changes["destroyed"], json!([]), "{changes}");
2846    }
2847}
2848
2849// ---------------------------------------------------------------------------
2850// `sweep_expired` applies the draft's time-driven expiry rules against an
2851// injected clock (bd:JMAP-y3f2.6).
2852//
2853// Oracles, from jmap-chat-spec 91672c9, draft-atwood-jmap-chat-00.md,
2854// except the three hard-delete rules, which jmap-chat-spec 4ffb96e
2855// downgraded from MUST to SHOULD and are quoted from 77c3474. The
2856// deletions stay required here: this crate's `sweep_expired` performs
2857// them, its choice of the recommended behaviour.
2858//
2859// - L559, §Chat `muteUntil`: "Muting expires at this time. Servers SHOULD
2860//   clear `muted` and `muteUntil` automatically when the time passes."
2861// - L581, §Chat `messageExpirySeconds`: "When set and non-zero, messages
2862//   in this chat older than this many seconds are deleted by this
2863//   mailbox."
2864// - L654, §Message `receivedAt`: "Authoritative for ordering and expiry
2865//   calculations."
2866// - 77c3474 L747, §Message `senderExpiresAt`: "servers SHOULD
2867//   permanently delete this message — removing the row entirely, not
2868//   leaving a tombstone — at or before this time. A hard-deleted message
2869//   appears in the `destroyed` list of subsequent `Message/changes`
2870//   responses, not `updated`."
2871// - 77c3474 L750, §Message `burnOnRead`: "the receiving server SHOULD
2872//   permanently hard-delete this message (row removal, not tombstone)
2873//   immediately after setting `readAt`."
2874// - 77c3474 L753, §Message `expiresAfterReadSeconds`: "the receiving
2875//   server SHOULD permanently hard-delete this message (row removal, not
2876//   tombstone) this many seconds after setting `readAt`."
2877// - 77c3474 L750 and L753, both rules: "Applies only to the receiving
2878//   mailbox; the sender's own copy is not affected."
2879// - L941-942, §PresenceStatus `expiresAt`: "If set, the server SHOULD
2880//   clear `statusText` and `statusEmoji` (setting them to null) at this
2881//   time, and SHOULD reset `presence` to `"online"`."
2882//
2883// - jmap-chat-spec aa01dd7 L635, §Chat `unreadCount`: "Candidates are
2884//   the Messages whose `id` ULID is lexicographically greater than
2885//   `ReadPosition.lastReadMessageId`, or all Messages in the Chat if
2886//   `lastReadMessageId` is absent." An expired Message
2887//   lowers that count, and RFC 8620 §5.1 ("If the data changes, this
2888//   string MUST change") then requires the `Chat` state to move
2889//   (bd:JMAP-y3f2.18).
2890//
2891// Clock values are hand-computed: 2024-01-01T00:00:00Z is Unix time
2892// 1_704_067_200.
2893// ---------------------------------------------------------------------------
2894
2895mod expiry {
2896    use std::time::{Duration, SystemTime, UNIX_EPOCH};
2897
2898    use jmap_types::Id;
2899    use serde_json::{Value, json};
2900
2901    use super::{ACCOUNT_ID, ConformanceBackend, exact_unread_count, owner, seed, setup};
2902    use crate::message::{handle_message_changes, handle_message_get};
2903    use crate::{handle_chat_changes, handle_chat_get, handle_presence_get, sweep_expired};
2904
2905    /// 2024-01-01T00:00:00Z.
2906    const T0: u64 = 1_704_067_200;
2907    const T0_STR: &str = "2024-01-01T00:00:00Z";
2908
2909    fn at(offset_secs: u64) -> SystemTime {
2910        UNIX_EPOCH + Duration::from_secs(T0 + offset_secs)
2911    }
2912
2913    async fn seed_chat<B: ConformanceBackend>(b: &B, id: &str, extra: Value) {
2914        let mut chat = json!({
2915            "id": id,
2916            "kind": "direct",
2917            "contactId": "contact1",
2918            "createdAt": T0_STR,
2919            "unreadCount": 0,
2920            "pinnedMessageIds": [],
2921        });
2922        chat.as_object_mut()
2923            .expect("object literal")
2924            .extend(extra.as_object().expect("object literal").clone());
2925        seed(b, "Chat", chat).await;
2926    }
2927
2928    async fn seed_message<B: ConformanceBackend>(b: &B, id: &str, chat_id: &str, extra: Value) {
2929        let mut msg = json!({
2930            "id": id,
2931            "senderMsgId": id,
2932            "senderId": "other",
2933            "chatId": chat_id,
2934            "body": "x",
2935            "bodyType": "text/plain",
2936            "attachments": [],
2937            "sentAt": T0_STR,
2938            "receivedAt": T0_STR,
2939            "deliveryState": "delivered",
2940        });
2941        msg.as_object_mut()
2942            .expect("object literal")
2943            .extend(extra.as_object().expect("object literal").clone());
2944        seed(b, "Message", msg).await;
2945    }
2946
2947    async fn sweep<B: ConformanceBackend>(b: &B, now: SystemTime) {
2948        sweep_expired(b, &owner(b), &Id::from(ACCOUNT_ID), now)
2949            .await
2950            .expect("sweep");
2951    }
2952
2953    async fn message_exists<B: ConformanceBackend>(b: &B, id: &str) -> bool {
2954        let resp = handle_message_get(
2955            b,
2956            &owner(b),
2957            json!({ "accountId": ACCOUNT_ID, "ids": [id] }),
2958            &[],
2959        )
2960        .await
2961        .expect("Message/get")
2962        .primary;
2963        resp["list"].as_array().expect("list").len() == 1
2964    }
2965
2966    async fn chat<B: ConformanceBackend>(b: &B, id: &str) -> Value {
2967        let resp = handle_chat_get(
2968            b,
2969            &owner(b),
2970            json!({ "accountId": ACCOUNT_ID, "ids": [id] }),
2971            &[],
2972        )
2973        .await
2974        .expect("Chat/get")
2975        .primary;
2976        resp["list"][0].clone()
2977    }
2978
2979    /// L747 (jmap-chat-spec 77c3474), §Message `senderExpiresAt`: "servers
2980    /// SHOULD permanently delete this message — removing the row entirely,
2981    /// not leaving a tombstone — at or before this time. A hard-deleted
2982    /// message appears in the `destroyed` list of subsequent
2983    /// `Message/changes` responses, not `updated`."
2984    ///
2985    /// L747: deletion "at or before this time", and the id lands in
2986    /// `destroyed`, not `updated`.
2987    pub async fn sender_expires_at_hard_deletes_at_deadline<B: ConformanceBackend>(b: B) {
2988        setup(&b).await;
2989        seed_chat(&b, "c1", json!({})).await;
2990        seed_message(
2991            &b,
2992            "m1",
2993            "c1",
2994            json!({ "senderExpiresAt": "2024-01-01T00:00:10Z" }),
2995        )
2996        .await;
2997        let state = handle_message_get(
2998            &b,
2999            &owner(&b),
3000            json!({ "accountId": ACCOUNT_ID, "ids": [] }),
3001            &[],
3002        )
3003        .await
3004        .expect("Message/get")
3005        .primary["state"]
3006            .clone();
3007
3008        sweep(&b, at(9)).await;
3009        assert!(
3010            message_exists(&b, "m1").await,
3011            "deadline not reached at T+9"
3012        );
3013
3014        sweep(&b, at(10)).await;
3015        assert!(!message_exists(&b, "m1").await, "deleted at the deadline");
3016        let changes = handle_message_changes(
3017            &b,
3018            &owner(&b),
3019            json!({ "accountId": ACCOUNT_ID, "sinceState": state }),
3020            &[],
3021        )
3022        .await
3023        .expect("Message/changes")
3024        .primary;
3025        assert_eq!(changes["destroyed"], json!(["m1"]));
3026        assert_eq!(changes["updated"], json!([]));
3027    }
3028
3029    /// L581 (jmap-chat-spec 91672c9), §Chat `messageExpirySeconds`: "When
3030    /// set and non-zero, messages in this chat older than this many seconds
3031    /// are deleted by this mailbox." L654, §Message `receivedAt`:
3032    /// "Authoritative for ordering and expiry calculations."
3033    ///
3034    /// L581 + L654: "older than this many seconds", measured from
3035    /// `receivedAt`; a zero policy deletes nothing ("When set and non-zero").
3036    pub async fn message_expiry_seconds_deletes_messages_older_than_policy<
3037        B: ConformanceBackend,
3038    >(
3039        b: B,
3040    ) {
3041        setup(&b).await;
3042        seed_chat(&b, "c1", json!({ "messageExpirySeconds": 60 })).await;
3043        seed_chat(&b, "c0", json!({ "messageExpirySeconds": 0 })).await;
3044        seed_message(&b, "m1", "c1", json!({})).await;
3045        seed_message(&b, "m0", "c0", json!({})).await;
3046
3047        sweep(&b, at(60)).await;
3048        assert!(
3049            message_exists(&b, "m1").await,
3050            "exactly 60s old is not older than 60s"
3051        );
3052
3053        sweep(&b, at(61)).await;
3054        assert!(!message_exists(&b, "m1").await, "61s old is older than 60s");
3055        assert!(
3056            message_exists(&b, "m0").await,
3057            "zero policy deletes nothing"
3058        );
3059    }
3060
3061    /// L753 (jmap-chat-spec 77c3474), §Message `expiresAfterReadSeconds`:
3062    /// "the receiving server SHOULD permanently hard-delete this message (row
3063    /// removal, not tombstone) this many seconds after setting `readAt`."
3064    ///
3065    /// L753: deletion "this many seconds after setting `readAt`"; an unread
3066    /// message has no such deadline.
3067    pub async fn expires_after_read_seconds_counts_from_read_at<B: ConformanceBackend>(b: B) {
3068        setup(&b).await;
3069        seed_chat(&b, "c1", json!({})).await;
3070        seed_message(
3071            &b,
3072            "read",
3073            "c1",
3074            json!({ "expiresAfterReadSeconds": 30, "readAt": "2024-01-01T00:01:40Z" }),
3075        )
3076        .await;
3077        seed_message(&b, "unread", "c1", json!({ "expiresAfterReadSeconds": 30 })).await;
3078
3079        sweep(&b, at(129)).await;
3080        assert!(message_exists(&b, "read").await, "29s after readAt");
3081
3082        sweep(&b, at(130)).await;
3083        assert!(!message_exists(&b, "read").await, "30s after readAt");
3084        assert!(
3085            message_exists(&b, "unread").await,
3086            "never read, never expires"
3087        );
3088    }
3089
3090    /// L750 (jmap-chat-spec 77c3474), §Message `burnOnRead`: "the receiving
3091    /// server SHOULD permanently hard-delete this message (row removal, not
3092    /// tombstone) immediately after setting `readAt`."
3093    ///
3094    /// L750: a read `burnOnRead` message must not survive (this crate
3095    /// requires the recommended deletion); the sweep deletes
3096    /// one stored with `readAt` set.
3097    pub async fn read_burn_on_read_message_is_deleted<B: ConformanceBackend>(b: B) {
3098        setup(&b).await;
3099        seed_chat(&b, "c1", json!({})).await;
3100        seed_message(
3101            &b,
3102            "burn",
3103            "c1",
3104            json!({ "burnOnRead": true, "readAt": T0_STR }),
3105        )
3106        .await;
3107        seed_message(&b, "unread", "c1", json!({ "burnOnRead": true })).await;
3108
3109        sweep(&b, at(0)).await;
3110        assert!(!message_exists(&b, "burn").await);
3111        assert!(message_exists(&b, "unread").await, "not yet read");
3112    }
3113
3114    /// L660 and L663 (jmap-chat-spec 91672c9), both rules: "Applies only to
3115    /// the receiving mailbox; the sender's own copy is not affected."
3116    ///
3117    /// L660 + L663: "the sender's own copy is not affected", so an own-sent
3118    /// message (`senderId` is the account) survives with `readAt` set.
3119    pub async fn read_rules_spare_the_senders_own_copy<B: ConformanceBackend>(b: B) {
3120        setup(&b).await;
3121        seed_chat(&b, "c1", json!({})).await;
3122        seed_message(
3123            &b,
3124            "own-timed",
3125            "c1",
3126            json!({
3127                "senderId": ACCOUNT_ID,
3128                "expiresAfterReadSeconds": 30,
3129                "readAt": T0_STR,
3130            }),
3131        )
3132        .await;
3133        seed_message(
3134            &b,
3135            "own-burn",
3136            "c1",
3137            json!({ "senderId": ACCOUNT_ID, "burnOnRead": true, "readAt": T0_STR }),
3138        )
3139        .await;
3140
3141        sweep(&b, at(3600)).await;
3142        assert!(message_exists(&b, "own-timed").await, "own copy kept");
3143        assert!(message_exists(&b, "own-burn").await, "own copy kept");
3144    }
3145
3146    /// L559 (jmap-chat-spec 91672c9), §Chat `muteUntil`: "Muting expires at
3147    /// this time. Servers SHOULD clear `muted` and `muteUntil`
3148    /// automatically when the time passes."
3149    ///
3150    /// L559: `muted` and `muteUntil` are cleared once the time passes.
3151    pub async fn mute_until_clears_muted_and_mute_until<B: ConformanceBackend>(b: B) {
3152        setup(&b).await;
3153        seed_chat(
3154            &b,
3155            "c1",
3156            json!({ "muted": true, "muteUntil": "2024-01-01T00:00:05Z" }),
3157        )
3158        .await;
3159
3160        sweep(&b, at(4)).await;
3161        let before = chat(&b, "c1").await;
3162        assert_eq!(before["muted"], json!(true));
3163        assert_eq!(before["muteUntil"], json!("2024-01-01T00:00:05Z"));
3164
3165        sweep(&b, at(5)).await;
3166        let after = chat(&b, "c1").await;
3167        assert_eq!(after["muted"], json!(false));
3168        assert!(
3169            after.get("muteUntil").is_none_or(Value::is_null),
3170            "muteUntil cleared: {after}"
3171        );
3172    }
3173
3174    /// L941-942 (jmap-chat-spec 91672c9), §PresenceStatus `expiresAt`: "If
3175    /// set, the server SHOULD clear `statusText` and `statusEmoji` (setting
3176    /// them to null) at this time, and SHOULD reset `presence` to
3177    /// `"online"`."
3178    ///
3179    /// L941-942: at `expiresAt` the status text and emoji are nulled and
3180    /// presence resets to "online".
3181    pub async fn presence_expires_at_resets_status<B: ConformanceBackend>(b: B) {
3182        setup(&b).await;
3183        seed(
3184            &b,
3185            "PresenceStatus",
3186            json!({
3187                "id": "p1",
3188                "presence": "busy",
3189                "receiptSharing": true,
3190                "updatedAt": T0_STR,
3191                "statusText": "In a meeting",
3192                "statusEmoji": ":calendar:",
3193                "expiresAt": "2024-01-01T01:00:00Z",
3194            }),
3195        )
3196        .await;
3197        let get = || async {
3198            handle_presence_get(
3199                &b,
3200                &owner(&b),
3201                json!({ "accountId": ACCOUNT_ID, "ids": ["p1"] }),
3202            )
3203            .await
3204            .expect("PresenceStatus/get")
3205            .primary["list"][0]
3206                .clone()
3207        };
3208
3209        sweep(&b, at(3599)).await;
3210        let before = get().await;
3211        assert_eq!(before["presence"], json!("busy"));
3212        assert_eq!(before["statusText"], json!("In a meeting"));
3213
3214        sweep(&b, at(3600)).await;
3215        let after = get().await;
3216        assert_eq!(after["presence"], json!("online"));
3217        assert!(
3218            after.get("statusText").is_none_or(Value::is_null),
3219            "{after}"
3220        );
3221        assert!(
3222            after.get("statusEmoji").is_none_or(Value::is_null),
3223            "{after}"
3224        );
3225    }
3226
3227    async fn chat_state<B: ConformanceBackend>(b: &B) -> Value {
3228        handle_chat_get(
3229            b,
3230            &owner(b),
3231            json!({ "accountId": ACCOUNT_ID, "ids": [] }),
3232            &[],
3233        )
3234        .await
3235        .expect("Chat/get")
3236        .primary["state"]
3237            .clone()
3238    }
3239
3240    /// jmap-chat-spec aa01dd7 L635, §Chat `unreadCount`: "Candidates are
3241    /// the Messages whose `id` ULID is lexicographically greater than
3242    /// `ReadPosition.lastReadMessageId`, or all Messages in the Chat if
3243    /// `lastReadMessageId` is absent." An expired Message lowers that
3244    /// count, and RFC 8620 §5.1 ("If the data changes, this string MUST
3245    /// change") then requires the `Chat` state to move (bd:JMAP-y3f2.18).
3246    ///
3247    /// L547-548 with RFC 8620 §5.1/§5.2: expiring an unread Message lowers
3248    /// its Chat's `unreadCount`, so `Chat/changes` lists exactly that Chat;
3249    /// a re-run at the same time changes nothing.
3250    ///
3251    /// Runs only when `maintains_unread_count` is `false`.
3252    pub async fn expiry_records_chat_unread_count_change<B: ConformanceBackend>(b: B) {
3253        if !exact_unread_count(&b) {
3254            return;
3255        }
3256        setup(&b).await;
3257        seed_chat(&b, "c1", json!({})).await;
3258        seed_chat(&b, "c2", json!({})).await;
3259        seed_message(
3260            &b,
3261            "m1",
3262            "c1",
3263            json!({ "senderExpiresAt": "2024-01-01T00:00:10Z" }),
3264        )
3265        .await;
3266        seed_message(&b, "m2", "c2", json!({})).await;
3267        let since = chat_state(&b).await;
3268
3269        sweep(&b, at(10)).await;
3270
3271        assert_eq!(chat(&b, "c1").await["unreadCount"], json!(0));
3272        assert_eq!(chat(&b, "c2").await["unreadCount"], json!(1));
3273        let changes = handle_chat_changes(
3274            &b,
3275            &owner(&b),
3276            json!({ "accountId": ACCOUNT_ID, "sinceState": since }),
3277            &[],
3278        )
3279        .await
3280        .expect("Chat/changes")
3281        .primary;
3282        assert_eq!(changes["updated"], json!(["c1"]), "{changes}");
3283
3284        let after = chat_state(&b).await;
3285        sweep(&b, at(10)).await;
3286        assert_eq!(chat_state(&b).await, after, "re-run changes no state");
3287    }
3288}
3289
3290// ---------------------------------------------------------------------------
3291// `Chat.unreadCount` and the ReadPosition lifecycle (bd:JMAP-y3f2.4,
3292// bd:JMAP-0x0q.56).
3293//
3294// Oracles, from jmap-chat-spec 33702a5:
3295//
3296// - draft-atwood-jmap-chat-00.md L629 (aa01dd7 L635), §Chat
3297//   `unreadCount`: "The number of unread Messages in this Chat, derived
3298//   server-side from the owner's ReadPosition record. Candidates are the
3299//   Messages whose `id` ULID is lexicographically greater than
3300//   `ReadPosition.lastReadMessageId`, or all Messages in the Chat if
3301//   `lastReadMessageId` is absent. [...] The value is advisory [...] Servers
3302//   SHOULD keep it accurate, but MAY update it some time after the change
3303//   that affects it [...] Whenever the server changes the value, the
3304//   Chat's state changes as for any other property ({{RFC8620}} Section
3305//   5.1)." The exact-count tests run only where this crate keeps the
3306//   count exact (`maintains_unread_count` is `false`).
3307// - jmap-chat-compliance-tests.md §11.1: "Send 5 messages. Set
3308//   ReadPosition to message 3. Call `Chat/get`. Verify `unreadCount` is
3309//   2 (messages 4 and 5)."
3310// - L1434, §ReadPosition/set: "`update` supports: `lastReadMessageId`.
3311//   The server sets `lastReadAt` to the current time and updates
3312//   `Chat.unreadCount` for the affected Chat, possibly later ({{chat}})."
3313// - L993, §ReadPosition: "The server creates a ReadPosition record
3314//   automatically when a Chat first becomes visible to the owner, and
3315//   destroys it when the Chat is destroyed. [...] For channel Chats, a
3316//   ReadPosition is created when the owner joins the containing Space."
3317// - L1004, `lastReadAt` "(UTCDate, server-set)"; RFC 8620 §5.3 rejects a
3318//   client write of a server-set property with `invalidProperties`.
3319// - RFC 8620 §5.1: "If the data changes, this string MUST change", so
3320//   `ReadPosition/changes` reports the cascaded destroy, and a change
3321//   to the derived `unreadCount` advances the `Chat` state.
3322// - RFC 8620 §5.2: `updated` lists "the ids for records that have been
3323//   updated since the old state", so `Chat/changes` names the Chat
3324//   whose `unreadCount` moved.
3325// - jmap-chat-spec aa01dd7 L635, §Chat `unreadCount`: "Which candidates
3326//   count is implementation-defined; for example, a server MAY exclude
3327//   Messages the owner sent." The seeded Messages come from
3328//   `OTHER_SENDER`, so the L629 counts apply to every server.
3329// ---------------------------------------------------------------------------
3330
3331mod read_position {
3332    use jmap_chat_types::{DeliveryState, Message};
3333    use jmap_server::HandlerOutput;
3334    use jmap_types::{Id, UTCDate};
3335    use serde_json::{Value, json};
3336
3337    use super::{ACCOUNT_ID, ConformanceBackend, exact_unread_count, owner, seed, setup};
3338    use crate::message::{StoreOutcome, handle_message_set, store_server_message};
3339    use crate::{
3340        handle_chat_changes, handle_chat_get, handle_chat_set, handle_position_changes,
3341        handle_position_get, handle_position_set, handle_space_join, handle_space_set,
3342    };
3343
3344    // Hand-picked ULIDs (Crockford base32, 26 chars) in ascending order:
3345    // "ULIDs are lexicographically ordered by time" (draft L675).
3346    const M1: &str = "01J0000000000000000000000A";
3347    const M2: &str = "01J0000000000000000000000B";
3348    const M3: &str = "01J0000000000000000000000C";
3349    const M4: &str = "01J0000000000000000000000D";
3350    const M5: &str = "01J0000000000000000000000E";
3351    const OTHER_MSG: &str = "01J0000000000000000000000F";
3352
3353    /// A ChatContact other than the owner; the owner's own Messages carry the
3354    /// accountId as `senderId`.
3355    const OTHER_SENDER: &str = "contact-bob";
3356
3357    const SEEDED_READ_AT: &str = "2000-01-01T00:00:00Z";
3358    const SPACE_ID: &str = "s1";
3359    const OTHER_SPACE_ID: &str = "space2";
3360
3361    async fn seed_chat<B: ConformanceBackend>(backend: &B, id: &str, extra: Value) {
3362        let mut chat = json!({
3363            "id": id,
3364            "createdAt": "2026-01-01T00:00:00Z",
3365            "unreadCount": 0,
3366            "pinnedMessageIds": [],
3367        });
3368        let (Value::Object(chat_map), Value::Object(extra_map)) = (&mut chat, extra) else {
3369            unreachable!("both are object literals");
3370        };
3371        chat_map.extend(extra_map);
3372        seed(backend, "Chat", chat).await;
3373    }
3374
3375    async fn seed_group<B: ConformanceBackend>(backend: &B, id: &str) {
3376        seed_chat(
3377            backend,
3378            id,
3379            json!({
3380                "kind": "group",
3381                "name": "G",
3382                "members": [{ "id": ACCOUNT_ID, "role": "admin", "joinedAt": "2026-01-01T00:00:00Z" }],
3383            }),
3384        )
3385        .await;
3386    }
3387
3388    async fn seed_message<B: ConformanceBackend>(backend: &B, id: &str, chat_id: &str) {
3389        seed(
3390            backend,
3391            "Message",
3392            json!({
3393                "id": id,
3394                "senderMsgId": id,
3395                "senderId": OTHER_SENDER,
3396                "chatId": chat_id,
3397                "body": "x",
3398                "bodyType": "text/plain",
3399                "attachments": [],
3400                "sentAt": "2026-01-01T00:00:00Z",
3401                "receivedAt": "2026-01-01T00:00:00Z",
3402                "deliveryState": "delivered",
3403            }),
3404        )
3405        .await;
3406    }
3407
3408    async fn seed_position<B: ConformanceBackend>(backend: &B, id: &str, chat_id: &str) {
3409        seed(
3410            backend,
3411            "ReadPosition",
3412            json!({ "id": id, "chatId": chat_id, "lastReadAt": SEEDED_READ_AT }),
3413        )
3414        .await;
3415    }
3416
3417    /// Group Chat `g` with M1..M5 and its ReadPosition `rp-g` (no
3418    /// `lastReadMessageId`), plus group Chat `h` with OTHER_MSG.
3419    async fn seed_five<B: ConformanceBackend>(backend: &B) {
3420        setup(backend).await;
3421        seed_group(backend, "g").await;
3422        seed_group(backend, "h").await;
3423        for m in [M1, M2, M3, M4, M5] {
3424            seed_message(backend, m, "g").await;
3425        }
3426        seed_message(backend, OTHER_MSG, "h").await;
3427        seed_position(backend, "rp-g", "g").await;
3428    }
3429
3430    async fn unread_counts<B: ConformanceBackend>(backend: &B, args: Value) -> Vec<Value> {
3431        let HandlerOutput { primary: resp, .. } =
3432            handle_chat_get(backend, &owner(backend), args, &[])
3433                .await
3434                .expect("Chat/get");
3435        resp["list"].as_array().expect("list").clone()
3436    }
3437
3438    async fn unread_of<B: ConformanceBackend>(backend: &B, chat_id: &str) -> Value {
3439        let list = unread_counts(
3440            backend,
3441            json!({ "accountId": ACCOUNT_ID, "ids": [chat_id] }),
3442        )
3443        .await;
3444        assert_eq!(list.len(), 1, "{list:?}");
3445        list[0]["unreadCount"].clone()
3446    }
3447
3448    async fn set_last_read<B: ConformanceBackend>(backend: &B, rp: &str, patch: Value) -> Value {
3449        let HandlerOutput { primary: resp, .. } = handle_position_set(
3450            backend,
3451            &owner(backend),
3452            &std::collections::BTreeMap::new(),
3453            json!({ "accountId": ACCOUNT_ID, "update": { rp: patch } }),
3454        )
3455        .await
3456        .expect("ReadPosition/set");
3457        resp
3458    }
3459
3460    async fn positions<B: ConformanceBackend>(backend: &B) -> Vec<Value> {
3461        let HandlerOutput { primary: resp, .. } =
3462            handle_position_get(backend, &owner(backend), json!({ "accountId": ACCOUNT_ID }))
3463                .await
3464                .expect("ReadPosition/get");
3465        resp["list"].as_array().expect("list").clone()
3466    }
3467
3468    async fn position_chat_ids<B: ConformanceBackend>(backend: &B) -> Vec<String> {
3469        let mut ids: Vec<String> = positions(backend)
3470            .await
3471            .iter()
3472            .map(|p| p["chatId"].as_str().expect("chatId").to_owned())
3473            .collect();
3474        ids.sort();
3475        ids
3476    }
3477
3478    async fn position_state<B: ConformanceBackend>(backend: &B) -> String {
3479        let HandlerOutput { primary: resp, .. } = handle_position_get(
3480            backend,
3481            &owner(backend),
3482            json!({ "accountId": ACCOUNT_ID, "ids": [] }),
3483        )
3484        .await
3485        .expect("ReadPosition/get");
3486        resp["state"].as_str().expect("state").to_owned()
3487    }
3488
3489    async fn destroyed_positions_since<B: ConformanceBackend>(
3490        backend: &B,
3491        since: &str,
3492    ) -> Vec<Value> {
3493        let HandlerOutput { primary: resp, .. } = handle_position_changes(
3494            backend,
3495            &owner(backend),
3496            json!({ "accountId": ACCOUNT_ID, "sinceState": since }),
3497        )
3498        .await
3499        .expect("ReadPosition/changes");
3500        resp["destroyed"].as_array().expect("destroyed").clone()
3501    }
3502
3503    /// aa01dd7 L635: candidates are "all Messages in the Chat if
3504    /// `lastReadMessageId` is absent." Only Messages "in this Chat" count, so
3505    /// `h` has 1.
3506    ///
3507    /// Runs only when `maintains_unread_count` is `false`.
3508    pub async fn absent_last_read_counts_every_message<B: ConformanceBackend>(backend: B) {
3509        if !exact_unread_count(&backend) {
3510            return;
3511        }
3512        seed_five(&backend).await;
3513        assert_eq!(unread_of(&backend, "g").await, 5);
3514        assert_eq!(unread_of(&backend, "h").await, 1);
3515    }
3516
3517    /// Compliance §11.1: "Send 5 messages. Set ReadPosition to message 3.
3518    /// Call `Chat/get`. Verify `unreadCount` is 2 (messages 4 and 5)."
3519    ///
3520    /// Runs only when `maintains_unread_count` is `false`.
3521    pub async fn compliance_11_1_unread_count_from_read_position<B: ConformanceBackend>(
3522        backend: B,
3523    ) {
3524        if !exact_unread_count(&backend) {
3525            return;
3526        }
3527        seed_five(&backend).await;
3528
3529        let resp = set_last_read(&backend, "rp-g", json!({ "lastReadMessageId": M3 })).await;
3530        assert!(resp["updated"].get("rp-g").is_some(), "{resp}");
3531
3532        assert_eq!(unread_of(&backend, "g").await, 2);
3533        assert_eq!(unread_of(&backend, "h").await, 1, "other Chat unaffected");
3534
3535        // L1434: the count is recomputed on each ReadPosition/set.
3536        set_last_read(&backend, "rp-g", json!({ "lastReadMessageId": M5 })).await;
3537        assert_eq!(unread_of(&backend, "g").await, 0);
3538    }
3539
3540    /// Compliance §11.1 with server-assigned ids: "Send 5 messages. Set
3541    /// ReadPosition to message 3. Call `Chat/get`. Verify `unreadCount` is
3542    /// 2 (messages 4 and 5)." The count holds only if, per L675, "Message
3543    /// IDs are ULIDs \[...\] lexicographically ordered by time", including
3544    /// for messages sent within the same millisecond (bd:JMAP-nls1).
3545    ///
3546    /// Runs only when `maintains_unread_count` is `false`.
3547    pub async fn compliance_11_1_with_assigned_ids<B: ConformanceBackend>(backend: B) {
3548        // ULID spec: 26 chars of Crockford base32 (no I, L, O, U).
3549        const CROCKFORD: &str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
3550        if !exact_unread_count(&backend) {
3551            return;
3552        }
3553        setup(&backend).await;
3554        seed_group(&backend, "s").await;
3555        seed_position(&backend, "rp-s", "s").await;
3556
3557        // Received from OTHER_SENDER: the owner's own Messages are not counted
3558        // (implementation-defined, chat-00 aa01dd7 L635), and
3559        // `store_server_message` has the backend assign each id as
3560        // `Message/set` does.
3561        let mut sent = Vec::new();
3562        for n in 0..5 {
3563            let smid = Id::from(format!("smid-{n}"));
3564            let outcome = store_server_message(
3565                &backend,
3566                &owner(&backend),
3567                &Id::from(ACCOUNT_ID),
3568                &Id::from("s"),
3569                &smid,
3570                |id: &Id| {
3571                    Message::new(
3572                        id.clone(),
3573                        Id::from("unused"),
3574                        Id::from(OTHER_SENDER),
3575                        Id::from("unused"),
3576                        "hi",
3577                        "text/plain",
3578                        UTCDate::from("2026-01-01T00:00:00Z"),
3579                        UTCDate::from("2026-01-01T00:00:00Z"),
3580                        DeliveryState::Delivered,
3581                    )
3582                },
3583            )
3584            .await
3585            .expect("store_server_message");
3586            let StoreOutcome::Stored(id) = outcome else {
3587                panic!("message {n} reported as a duplicate");
3588            };
3589            let id = id.as_ref();
3590            assert_eq!(id.len(), 26, "{id}");
3591            assert!(id.chars().all(|c| CROCKFORD.contains(c)), "{id}");
3592            sent.push(id.to_owned());
3593        }
3594
3595        set_last_read(&backend, "rp-s", json!({ "lastReadMessageId": sent[2] })).await;
3596        assert_eq!(unread_of(&backend, "s").await, 2, "{sent:?}");
3597    }
3598
3599    /// aa01dd7 L635: `unreadCount` is computed for a full `Chat/get` (no
3600    /// `ids`) as well.
3601    ///
3602    /// Runs only when `maintains_unread_count` is `false`.
3603    pub async fn unread_count_in_full_get<B: ConformanceBackend>(backend: B) {
3604        if !exact_unread_count(&backend) {
3605            return;
3606        }
3607        seed_five(&backend).await;
3608        set_last_read(&backend, "rp-g", json!({ "lastReadMessageId": M4 })).await;
3609
3610        let list = unread_counts(&backend, json!({ "accountId": ACCOUNT_ID })).await;
3611        let count = |id: &str| {
3612            list.iter()
3613                .find(|c| c["id"] == id)
3614                .unwrap_or_else(|| panic!("{id} missing: {list:?}"))["unreadCount"]
3615                .clone()
3616        };
3617        assert_eq!(count("g"), 1);
3618        assert_eq!(count("h"), 1);
3619    }
3620
3621    /// L1434: "The server sets `lastReadAt` to the current time".
3622    pub async fn read_position_set_updates_last_read_at<B: ConformanceBackend>(backend: B) {
3623        seed_five(&backend).await;
3624
3625        set_last_read(&backend, "rp-g", json!({ "lastReadMessageId": M2 })).await;
3626        let list = positions(&backend).await;
3627        let rp = list.iter().find(|p| p["id"] == "rp-g").expect("rp-g");
3628        assert_eq!(rp["lastReadMessageId"], M2, "{rp}");
3629        let read_at = rp["lastReadAt"].as_str().expect("lastReadAt is a UTCDate");
3630        assert_ne!(read_at, SEEDED_READ_AT, "{rp}");
3631        assert!(
3632            read_at > "2026-01-01T00:00:00Z",
3633            "{read_at} is not the current time"
3634        );
3635    }
3636
3637    /// L1004 `lastReadAt` is server-set: a client write is `invalidProperties`
3638    /// (RFC 8620 §5.3) and the record is unchanged.
3639    pub async fn client_last_read_at_is_rejected<B: ConformanceBackend>(backend: B) {
3640        seed_five(&backend).await;
3641
3642        let resp = set_last_read(
3643            &backend,
3644            "rp-g",
3645            json!({ "lastReadMessageId": M2, "lastReadAt": "2030-01-01T00:00:00Z" }),
3646        )
3647        .await;
3648        assert_eq!(
3649            resp["notUpdated"]["rp-g"]["type"], "invalidProperties",
3650            "{resp}"
3651        );
3652        assert_eq!(
3653            resp["notUpdated"]["rp-g"]["properties"],
3654            json!(["lastReadAt"]),
3655            "{resp}"
3656        );
3657        let list = positions(&backend).await;
3658        assert_eq!(list[0]["lastReadAt"], SEEDED_READ_AT, "{list:?}");
3659        assert!(list[0].get("lastReadMessageId").is_none(), "{list:?}");
3660    }
3661
3662    /// L993: the server "destroys it when the Chat is destroyed"; RFC 8620
3663    /// §5.1 makes `ReadPosition/changes` report it.
3664    pub async fn chat_destroy_destroys_its_read_position<B: ConformanceBackend>(backend: B) {
3665        seed_five(&backend).await;
3666        seed_position(&backend, "rp-h", "h").await;
3667        let since = position_state(&backend).await;
3668
3669        let HandlerOutput { primary: resp, .. } = handle_chat_set(
3670            &backend,
3671            &owner(&backend),
3672            &std::collections::BTreeMap::new(),
3673            json!({ "accountId": ACCOUNT_ID, "destroy": ["g"] }),
3674            &[],
3675        )
3676        .await
3677        .expect("Chat/set");
3678        assert_eq!(resp["destroyed"], json!(["g"]), "{resp}");
3679
3680        assert_eq!(position_chat_ids(&backend).await, vec!["h"]);
3681        assert_eq!(
3682            destroyed_positions_since(&backend, &since).await,
3683            vec![json!("rp-g")]
3684        );
3685    }
3686
3687    /// A Space whose only member is `preseeded-admin`, holding channels
3688    /// `ch1` and `ch2`, plus channel `other` of `OTHER_SPACE_ID`.
3689    async fn seed_space_with_channels<B: ConformanceBackend>(
3690        backend: &B,
3691        is_public: bool,
3692        owner_member: bool,
3693    ) {
3694        setup(backend).await;
3695        let mut members = vec![json!({
3696            "id": "preseeded-admin", "roleIds": ["r-admin"], "joinedAt": "2026-01-01T00:00:00Z"
3697        })];
3698        if owner_member {
3699            members.push(json!({
3700                "id": ACCOUNT_ID, "roleIds": ["r-admin"], "joinedAt": "2026-01-01T00:00:00Z"
3701            }));
3702        }
3703        for space_id in [SPACE_ID, OTHER_SPACE_ID] {
3704            seed(
3705                backend,
3706                "Space",
3707                json!({
3708                    "id": space_id,
3709                    "name": "S",
3710                    "createdAt": "2026-01-01T00:00:00Z",
3711                    "memberCount": members.len(),
3712                    "categories": [],
3713                    "uncategorizedChannelIds": [],
3714                    "isPublic": is_public,
3715                    "isPubliclyPreviewable": false,
3716                    "roles": [{
3717                        "id": "r-admin",
3718                        "name": "Admin",
3719                        "permissions": ["manage_space", "manage_channels", "view"],
3720                        "position": 1
3721                    }],
3722                    "members": members,
3723                }),
3724            )
3725            .await;
3726        }
3727        seed_chat(
3728            backend,
3729            "ch1",
3730            json!({ "kind": "channel", "name": "a", "spaceId": SPACE_ID }),
3731        )
3732        .await;
3733        seed_chat(
3734            backend,
3735            "ch2",
3736            json!({ "kind": "channel", "name": "b", "spaceId": SPACE_ID }),
3737        )
3738        .await;
3739        seed_chat(
3740            backend,
3741            "other",
3742            json!({ "kind": "channel", "name": "c", "spaceId": OTHER_SPACE_ID }),
3743        )
3744        .await;
3745    }
3746
3747    /// L993: "For channel Chats, a ReadPosition is created when the owner
3748    /// joins the containing Space." Only that Space's channels get one.
3749    pub async fn space_join_creates_read_positions_for_its_channels<B: ConformanceBackend>(
3750        backend: B,
3751    ) {
3752        seed_space_with_channels(&backend, true, false).await;
3753        assert!(positions(&backend).await.is_empty());
3754
3755        handle_space_join(
3756            &backend,
3757            &owner(&backend),
3758            json!({ "accountId": ACCOUNT_ID, "spaceId": SPACE_ID }),
3759        )
3760        .await
3761        .expect("Space/join");
3762
3763        assert_eq!(position_chat_ids(&backend).await, vec!["ch1", "ch2"]);
3764        for p in positions(&backend).await {
3765            assert!(p.get("lastReadMessageId").is_none(), "{p}");
3766        }
3767    }
3768
3769    /// L993 "destroys it when the Chat is destroyed" holds for a channel
3770    /// removed by `Space/set` `removeChannels`.
3771    pub async fn remove_channels_destroys_their_read_positions<B: ConformanceBackend>(backend: B) {
3772        seed_space_with_channels(&backend, false, true).await;
3773        seed_position(&backend, "rp1", "ch1").await;
3774        seed_position(&backend, "rp2", "ch2").await;
3775        seed_position(&backend, "rp3", "other").await;
3776        let since = position_state(&backend).await;
3777
3778        let HandlerOutput { primary: resp, .. } = handle_space_set(
3779            &backend,
3780            &owner(&backend),
3781            &std::collections::BTreeMap::new(),
3782            json!({
3783                "accountId": ACCOUNT_ID,
3784                "update": { SPACE_ID: { "removeChannels": ["ch1"] } }
3785            }),
3786            &[],
3787        )
3788        .await
3789        .expect("Space/set");
3790        assert!(resp["updated"].get(SPACE_ID).is_some(), "{resp}");
3791
3792        assert_eq!(position_chat_ids(&backend).await, vec!["ch2", "other"]);
3793        assert_eq!(
3794            destroyed_positions_since(&backend, &since).await,
3795            vec![json!("rp1")]
3796        );
3797    }
3798
3799    /// Destroying a Space destroys its channel Chats (§Destroying a Space),
3800    /// so their ReadPositions go too (L993).
3801    pub async fn space_destroy_destroys_channel_read_positions<B: ConformanceBackend>(backend: B) {
3802        seed_space_with_channels(&backend, false, true).await;
3803        seed_position(&backend, "rp1", "ch1").await;
3804        seed_position(&backend, "rp2", "ch2").await;
3805        seed_position(&backend, "rp3", "other").await;
3806        let since = position_state(&backend).await;
3807
3808        let HandlerOutput { primary: resp, .. } = handle_space_set(
3809            &backend,
3810            &owner(&backend),
3811            &std::collections::BTreeMap::new(),
3812            json!({ "accountId": ACCOUNT_ID, "destroy": [SPACE_ID] }),
3813            &[],
3814        )
3815        .await
3816        .expect("Space/set");
3817        assert_eq!(resp["destroyed"], json!([SPACE_ID]), "{resp}");
3818
3819        assert_eq!(position_chat_ids(&backend).await, vec!["other"]);
3820        let mut destroyed = destroyed_positions_since(&backend, &since).await;
3821        destroyed.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
3822        assert_eq!(destroyed, vec![json!("rp1"), json!("rp2")]);
3823    }
3824
3825    async fn chat_state<B: ConformanceBackend>(backend: &B) -> String {
3826        let HandlerOutput { primary: resp, .. } = handle_chat_get(
3827            backend,
3828            &owner(backend),
3829            json!({ "accountId": ACCOUNT_ID, "ids": [] }),
3830            &[],
3831        )
3832        .await
3833        .expect("Chat/get");
3834        resp["state"].as_str().expect("state").to_owned()
3835    }
3836
3837    async fn chats_updated_since<B: ConformanceBackend>(backend: &B, since: &str) -> Vec<Value> {
3838        let HandlerOutput { primary: resp, .. } = handle_chat_changes(
3839            backend,
3840            &owner(backend),
3841            json!({ "accountId": ACCOUNT_ID, "sinceState": since }),
3842            &[],
3843        )
3844        .await
3845        .expect("Chat/changes");
3846        resp["updated"].as_array().expect("updated").clone()
3847    }
3848
3849    async fn message_set<B: ConformanceBackend>(backend: &B, args: Value) -> Value {
3850        let mut args = args;
3851        args["accountId"] = json!(ACCOUNT_ID);
3852        let HandlerOutput { primary: resp, .. } = handle_message_set(
3853            backend,
3854            &owner(backend),
3855            &std::collections::BTreeMap::new(),
3856            args,
3857            &[],
3858        )
3859        .await
3860        .expect("Message/set");
3861        resp
3862    }
3863
3864    /// L1434 "updates `Chat.unreadCount` for the affected Chat" changes
3865    /// Chat data, so (RFC 8620 §5.1) the Chat state moves and (§5.2)
3866    /// `Chat/changes` lists only the affected Chat.
3867    ///
3868    /// Runs only when `maintains_unread_count` is `false`.
3869    pub async fn read_position_set_advances_chat_state<B: ConformanceBackend>(backend: B) {
3870        if !exact_unread_count(&backend) {
3871            return;
3872        }
3873        seed_five(&backend).await;
3874        assert_eq!(unread_of(&backend, "g").await, 5);
3875        let since = chat_state(&backend).await;
3876
3877        set_last_read(&backend, "rp-g", json!({ "lastReadMessageId": M3 })).await;
3878
3879        assert_eq!(unread_of(&backend, "g").await, 2);
3880        assert_ne!(chat_state(&backend).await, since);
3881        assert_eq!(
3882            chats_updated_since(&backend, &since).await,
3883            vec![json!("g")]
3884        );
3885    }
3886
3887    /// Destroying an unread Message lowers the Chat's `unreadCount`
3888    /// (L629), so `Chat/changes` reports that Chat (RFC 8620 §5.2).
3889    ///
3890    /// Runs only when `maintains_unread_count` is `false`.
3891    pub async fn message_destroy_advances_chat_state<B: ConformanceBackend>(backend: B) {
3892        if !exact_unread_count(&backend) {
3893            return;
3894        }
3895        seed_five(&backend).await;
3896        let since = chat_state(&backend).await;
3897
3898        let resp = message_set(&backend, json!({ "destroy": [M5] })).await;
3899        assert_eq!(resp["destroyed"], json!([M5]), "{resp}");
3900
3901        assert_eq!(unread_of(&backend, "g").await, 4);
3902        assert_eq!(
3903            chats_updated_since(&backend, &since).await,
3904            vec![json!("g")]
3905        );
3906    }
3907}