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