jmap-chat-server 0.6.1

JMAP Chat extension method handlers — backend-agnostic, plugs into jmap-server Dispatcher
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! `SpaceInvite`/* method handlers (draft-atwood-jmap-chat-00 §`SpaceInvite`).
//!
//! Methods: get, changes, set only (no query, no queryChanges per spec).
//! Updates are forbidden — the spec treats [`SpaceInvite`] as write-once.
//!
//! # Wire-shape contract
//!
//! Every `handle_*` function in this module conforms to the canonical JMAP
//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
//! Object whose fields match the corresponding RFC 8620 §5 method shape
//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3), with the
//! type-specific arguments defined by draft-atwood-jmap-chat-00
//! §`SpaceInvite`. The returned `Value` is the corresponding
//! method-response object per the same section refs.
//!
//! The returned `HandlerOutput::extra_invocations` carries any invocations
//! that this handler injected into the request stream (RFC 8620 §6.3);
//! for the handlers in this module the vector is **always empty**.
//!
//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
//! §3.6.2 and §5):
//!
//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
//!   `maxObjectsInSet`;
//! - `/set`: `stateMismatch`;
//! - `/changes`: `cannotCalculateChanges`.
//!
//! Per-target failures inside `/set` (including the write-once `forbidden`
//! update rejection) surface in the `notCreated` / `notUpdated` /
//! `notDestroyed` maps within `Ok((Value, ...))`, not as `Err`.

use std::collections::{BTreeMap, HashSet};

use jmap_chat_types::{Space, SpaceInvite};
use jmap_types::{Id, JmapError, State, UTCDate};
use serde_json::{Value, json};

use crate::ChatBackend;
use crate::helpers::resolved_create;
use crate::helpers::{PropType, mistyped_create_props};
use crate::helpers::{
    SetAccumulators, enforce_max_objects_in_get, enforce_max_objects_in_set, extract_account_id,
    finalize_set_response, not_found_json, now_utc_string, serialize_value,
};
use jmap_server::{
    HandlerOutput, backend_set_error_value, reject_server_set, server_fail_from_backend,
    server_fail_value_from_backend,
};
use jmap_server::{SetError, SetErrorType};

// ---------------------------------------------------------------------------
// SpaceInvite/get
// ---------------------------------------------------------------------------

/// Handle a `SpaceInvite/get` method call (draft-atwood-jmap-chat-00 §`SpaceInvite`).
///
/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
/// `ids`, optional `properties`); the returned `Value` is the §5.1
/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
///
/// Each returned invite must pass [`SpacePolicy::may_get_space_invite`](crate::SpacePolicy::may_get_space_invite);
/// a hidden invite is reported exactly like a missing one.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
///   `ids` is not an Id array;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `requestTooLarge` when `ids` holds more than `maxObjectsInGet` ids;
/// - `serverFail` when the backend fails.
pub async fn handle_invite_get<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    let (account_id, mut args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }
    enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;

    let ids: Option<Vec<Id>> = match args.remove("ids") {
        None | Some(Value::Null) => None,
        Some(v) => Some(
            serde_json::from_value(v)
                .map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
        ),
    };

    let ids_slice = ids.as_deref();
    let (fetched, mut not_found) = backend
        .get_objects::<SpaceInvite>(caller, &account_id, ids_slice, None)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    // A hidden invite is indistinguishable from a missing one: a requested
    // id goes to notFound, and a full fetch (`ids: null`) drops it, since
    // RFC 8620 §5.1 notFound lists only requested ids.
    let mut list = Vec::with_capacity(fetched.len());
    for invite in fetched {
        if backend
            .may_get_space_invite(caller, &account_id, &invite)
            .await
            .map_err(|e| server_fail_from_backend(&e))?
        {
            list.push(invite);
        } else if ids_slice.is_some() {
            not_found.push(invite.id);
        }
    }

    let state = backend
        .get_state::<SpaceInvite>(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    let list_json: Vec<Value> = list
        .iter()
        .map(serialize_value)
        .collect::<Result<Vec<_>, _>>()?;

    Ok(HandlerOutput::new(json!({
        "accountId": account_id.as_ref(),
        "state": state.as_ref(),
        "list": list_json,
        "notFound": not_found_json(&not_found),
    })))
}

// ---------------------------------------------------------------------------
// SpaceInvite/changes
// ---------------------------------------------------------------------------

/// Handle a `SpaceInvite/changes` method call (draft-atwood-jmap-chat-00 §`SpaceInvite`).
///
/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
/// `sinceState`, optional `maxChanges`); the returned `Value` is the
/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
///
/// `created` and `updated` list only invites that still exist and pass
/// [`SpacePolicy::may_get_space_invite`](crate::SpacePolicy::may_get_space_invite); `destroyed` is not filtered.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id,
///   `sinceState` is missing, or `maxChanges` is not a positive integer;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `cannotCalculateChanges` when the backend cannot compute the changes
///   since `sinceState`;
/// - `serverFail` when the backend fails.
pub async fn handle_invite_changes<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    let (account_id, args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }

    let since_state: State = match args.get("sinceState").and_then(|v| v.as_str()) {
        Some(s) => State::from(s),
        None => return Err(JmapError::invalid_arguments("sinceState is required")),
    };

    let max_changes = jmap_server::parse_max_changes(args.get("maxChanges"))?;

    let result = backend
        .get_changes::<SpaceInvite>(
            caller,
            &account_id,
            jmap_server::ChangesParams::new(&since_state).max_changes(max_changes),
        )
        .await
        .map_err(jmap_server::changes_error_from_backend)?;

    // Keep only created/updated ids whose invite still resolves and passes
    // the SpaceInvite/get visibility gate.
    // ponytail: `destroyed` is passed through unfiltered because a destroyed
    // invite can no longer be evaluated, so its id leaks to callers who could
    // not see it. Closing that needs the backend's change log to record each
    // invite's visibility at destroy time.
    let changed: Vec<Id> = result
        .created
        .iter()
        .chain(&result.updated)
        .cloned()
        .collect();
    let mut visible: HashSet<Id> = HashSet::with_capacity(changed.len());
    if !changed.is_empty() {
        let (invites, _) = backend
            .get_objects::<SpaceInvite>(caller, &account_id, Some(&changed), None)
            .await
            .map_err(|e| server_fail_from_backend(&e))?;
        for invite in invites {
            if backend
                .may_get_space_invite(caller, &account_id, &invite)
                .await
                .map_err(|e| server_fail_from_backend(&e))?
            {
                visible.insert(invite.id);
            }
        }
    }
    let visible_ids = |ids: &[Id]| -> Vec<Value> {
        ids.iter()
            .filter(|id| visible.contains(*id))
            .map(|id| Value::from(id.as_ref()))
            .collect()
    };

    Ok(HandlerOutput::new(json!({
        "accountId": account_id.as_ref(),
        "oldState": since_state.as_ref(),
        "newState": result.new_state.as_ref(),
        "hasMoreChanges": result.has_more_changes,
        "updatedProperties": Value::Null,
        "created":   visible_ids(&result.created),
        "updated":   visible_ids(&result.updated),
        "destroyed": result.destroyed.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
    })))
}

// ---------------------------------------------------------------------------
// SpaceInvite/set
// ---------------------------------------------------------------------------

/// Handle a `SpaceInvite/set` method call (draft-atwood-jmap-chat-00 §`SpaceInvite`).
///
/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
/// `ifInState`, optional `create` / `update` / `destroy` maps); the
/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
/// `oldState`, `newState`, plus the per-operation `created` /
/// `notCreated` / `updated` / `notUpdated` / `destroyed` / `notDestroyed`
/// maps).
///
/// Per spec, [`SpaceInvite`] objects are write-once:
/// - create: accepted (`spaceId` required; server sets `code`, `createdBy`,
///   `uses`, `createdAt`).
/// - update: always rejected with `forbidden`.
/// - destroy: revokes the invite.
///
/// Create and destroy each consult [`SpacePolicy::may_set_space_invite`](crate::SpacePolicy::may_set_space_invite)
/// for the invite's Space.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
///
/// A `spaceId` or `defaultChannelId` that is a `#creationId` reference
/// names a record created earlier in the request and resolves against
/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
/// §5.3); an unknown reference is `invalidProperties` naming the property.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
///   an element of `destroy` is not a string;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `requestTooLarge` when `create`, `update` and `destroy` together hold
///   more than `maxObjectsInSet` objects;
/// - `stateMismatch` when `ifInState` is not the current state;
/// - `serverFail` when the backend fails.
///
/// A create or destroy that fails on its own, and every update, is a
/// [`SetError`] in the response, not an `Err`.
pub async fn handle_invite_set<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    created_ids: &BTreeMap<Id, Id>,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    let (account_id, mut args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-fo38).
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }

    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
    // unbounded /set batches before touching the storage layer.
    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;

    let old_state = backend
        .get_state::<SpaceInvite>(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
        && if_in_state != old_state.as_ref()
    {
        return Err(JmapError::state_mismatch());
    }

    let ctx = SetCtx {
        backend,
        caller,
        account_id: &account_id,
        created_ids,
    };
    let mut acc = SetAccumulators::default();
    let mut mutated = set_create(&ctx, &mut args, &mut acc).await?;
    // RFC 8620 §5.3: update keys and destroy ids may name this call's creates.
    jmap_server::resolve_set_id_refs(&mut args, created_ids, &acc.created);
    set_update(&mut args, &mut acc);
    mutated |= set_destroy(&ctx, &mut args, &mut acc).await?;

    finalize_set_response::<B, SpaceInvite>(backend, caller, &account_id, old_state, mutated, acc)
        .await
}

/// What every `SpaceInvite/set` sub-function needs from the request
/// (docs/design/set-handler-split.md).
struct SetCtx<'a, B: ChatBackend> {
    backend: &'a B,
    caller: &'a B::CallerCtx,
    account_id: &'a Id,
    /// The request-wide `#creationId` map (RFC 8620 §5.3).
    created_ids: &'a BTreeMap<Id, Id>,
}

/// The `create` part of `SpaceInvite/set`. Returns whether the backend was
/// written.
async fn set_create<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut serde_json::Map<String, Value>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
        for (create_id, obj_val) in create_map {
            mutated |= create_one(ctx, create_id, obj_val, acc).await?;
        }
    }
    Ok(mutated)
}

/// One `create` entry of `SpaceInvite/set`. Returns whether the backend was
/// written.
async fn create_one<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    create_id: &str,
    obj_val: &Value,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let (
        space_id,
        CreateOptions {
            default_channel_id,
            expires_at,
            max_uses,
        },
    ) = match create_request(ctx, obj_val).await {
        Ok(request) => request,
        Err(err) => {
            acc.not_created.insert(create_id.to_owned(), err);
            return Ok(false);
        }
    };

    let now_str = now_utc_string();
    let now: UTCDate = UTCDate::from(now_str.as_ref());

    // Delegate code generation to the backend. The trait contract
    // (`ChatSpaces::generate_invite_code`) requires a CSPRNG with
    // at least 128 bits of entropy and a fixed-length ASCII-safe
    // encoding; the reference `MemoryBackend` uses `getrandom::fill`
    // on a 16-byte buffer (bd:JMAP-sc1b.78, bd:JMAP-sc1b.93). The
    // handler does NOT re-validate the output shape — a backend
    // that fails the contract leaks the invite-code unguessability
    // bound.
    let code = match ctx
        .backend
        .generate_invite_code(ctx.caller, ctx.account_id)
        .await
    {
        Ok(code) => code,
        Err(e) => {
            acc.not_created
                .insert(create_id.to_owned(), server_fail_value_from_backend(&e));
            return Ok(false);
        }
    };

    // Security: createdBy MUST be set server-side, never accepted
    // from the client body. The creator is the owner, referenced by
    // the accountId (draft-atwood-jmap-chat-00 §Terminology,
    // §SpaceInvite.createdBy).
    if let Some(err) = invite_denied(ctx.backend, ctx.caller, ctx.account_id, &space_id, None).await
    {
        acc.not_created.insert(create_id.to_owned(), err);
        return Ok(false);
    }

    let invite = |id: &Id| {
        SpaceInvite::new(
            id.clone(),
            code,
            space_id,
            ctx.account_id.clone(),
            0,
            now,
            default_channel_id,
            expires_at,
            max_uses,
        )
    };
    match ctx
        .backend
        .create_object::<SpaceInvite, _>(ctx.caller, ctx.account_id, create_id, invite)
        .await
    {
        Ok((_server_id, created_obj)) => {
            acc.created.insert(
                create_id.to_owned(),
                jmap_server::serialize_value(&created_obj)?,
            );
            Ok(true)
        }
        Err(e) => {
            acc.not_created
                .insert(create_id.to_owned(), backend_set_error_value(e));
            Ok(false)
        }
    }
}

/// Resolve the `#creationId` references of one `SpaceInvite/set` create
/// object and check it: its `spaceId` ([`create_space_id`]), that the Space
/// is open ([`space_closed_error`]) and its options ([`create_options`]).
/// Returns the `spaceId` and the options, or the [`SetError`] value for
/// `notCreated`.
async fn create_request<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    obj_val: &Value,
) -> Result<(Id, CreateOptions), Value> {
    let resolved = resolved_create(obj_val, &["spaceId", "defaultChannelId"], ctx.created_ids)
        .map_err(|err| serde_json::Value::from(&*err))?;
    let space_id = create_space_id(&resolved)?;
    if let Some(err) = space_closed_error(ctx, &space_id).await {
        return Err(err);
    }
    let options = create_options(&resolved)?;
    Ok((space_id, options))
}

/// Check the server-set, wrongly-typed and `spaceId` properties of one
/// `SpaceInvite/set` create object (with `#creationId` references
/// resolved) and return its `spaceId`, or the [`SetError`] value for
/// `notCreated`.
fn create_space_id(obj_val: &Value) -> Result<Id, Value> {
    if let Some(err) = obj_val
        .as_object()
        .and_then(reject_server_set::<SpaceInvite>)
    {
        return Err(serde_json::Value::from(&err));
    }
    // Optional properties: a wrongly-typed value is invalidProperties
    // (RFC 8620 §5.3), not a silent absence.
    if let Some(err) = mistyped_create_props(
        obj_val,
        &[
            ("defaultChannelId", PropType::Str),
            ("expiresAt", PropType::Str),
            ("maxUses", PropType::UnsignedInt),
        ],
    ) {
        return Err(err);
    }
    // spaceId is required on create.
    match obj_val
        .get("spaceId")
        .and_then(|v| v.as_str())
        .and_then(|s| Id::new_validated(s).ok())
    {
        Some(id) => Ok(id),
        _ => Err(json!({ "type": "invalidProperties", "properties": ["spaceId"] })),
    }
}

/// The [`SetError`] value for a `SpaceInvite/set` create in a closed Space, or
/// `None` to go on.
///
/// draft-atwood-jmap-chat-00 §Space `closedAt`: "The server MUST also
/// reject ... `SpaceInvite/set` create for the Space with a `forbidden`
/// `SetError`".
async fn space_closed_error<B: ChatBackend>(ctx: &SetCtx<'_, B>, space_id: &Id) -> Option<Value> {
    match ctx
        .backend
        .get_objects::<Space>(
            ctx.caller,
            ctx.account_id,
            Some(std::slice::from_ref(space_id)),
            None,
        )
        .await
    {
        Ok((spaces, _)) if spaces.first().is_some_and(|s| s.closed_at.is_some()) => {
            Some(json!({ "type": "forbidden", "description": "the Space is closed" }))
        }
        Ok(_) => None,
        Err(e) => Some(server_fail_value_from_backend(&e)),
    }
}

/// The optional properties of a `SpaceInvite/set` create, checked.
struct CreateOptions {
    default_channel_id: Option<Id>,
    expires_at: Option<UTCDate>,
    max_uses: Option<u64>,
}

/// The optional `defaultChannelId`, `expiresAt` and `maxUses` of one
/// `SpaceInvite/set` create object, checked, or the [`SetError`] value for
/// `notCreated`.
fn create_options(obj_val: &Value) -> Result<CreateOptions, Value> {
    let default_channel_id: Option<Id> =
        match obj_val.get("defaultChannelId").and_then(|v| v.as_str()) {
            Some(s) => Some(
                jmap_server::parse_wire_id(s, "defaultChannelId")
                    .map_err(|err| serde_json::Value::from(&*err))?,
            ),
            None => None,
        };

    // expiresAt is a UTCDate per RFC 8620 §1.4. Validate the wire
    // shape via UTCDate::new_validated; a malformed value produces
    // invalidProperties rather than storing an unparseable string.
    let expires_at: Option<UTCDate> =
        if let Some(s) = obj_val.get("expiresAt").and_then(|v| v.as_str()) {
            let Ok(d) = UTCDate::new_validated(s) else {
                return Err(json!({
                    "type": "invalidProperties",
                    "properties": ["expiresAt"],
                }));
            };
            Some(d)
        } else {
            None
        };

    let max_uses: Option<u64> = obj_val.get("maxUses").and_then(|v| v.as_u64());
    if max_uses == Some(0) {
        return Err(json!({ "type": "invalidProperties", "properties": ["maxUses"] }));
    }
    Ok(CreateOptions {
        default_channel_id,
        expires_at,
        max_uses,
    })
}

/// The `update` part of `SpaceInvite/set`: forbidden, because [`SpaceInvite`]
/// objects are write-once per spec.
fn set_update(args: &mut serde_json::Map<String, Value>, acc: &mut SetAccumulators) {
    if let Some(Value::Object(update_map)) = args.remove("update") {
        for (id_str, _) in update_map {
            acc.not_updated.insert(
                id_str,
                serde_json::Value::from(&SetError::new(SetErrorType::Forbidden)),
            );
        }
    }
}

/// The `destroy` part of `SpaceInvite/set`. Returns whether the backend
/// was written.
async fn set_destroy<B: ChatBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut serde_json::Map<String, Value>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
        // Reject the whole request if any element is non-string rather than
        // silently skipping it, which would produce a misleading response.
        let id_strs: Vec<&str> = destroy_arr
            .iter()
            .map(|v| {
                v.as_str().ok_or_else(|| {
                    JmapError::invalid_arguments(format!(
                        "destroy: every element must be a string Id; got {}",
                        jmap_server::json_type_name(v)
                    ))
                })
            })
            .collect::<Result<_, _>>()?;
        for id_str in id_strs {
            let id = match jmap_server::parse_wire_id(id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    acc.not_destroyed
                        .insert(id_str.to_owned(), serde_json::Value::from(&*err));
                    continue;
                }
            };

            if let Some(err) =
                stored_invite_denied(ctx.backend, ctx.caller, ctx.account_id, &id).await
            {
                acc.not_destroyed.insert(id_str.to_owned(), err);
                continue;
            }

            match ctx
                .backend
                .destroy_object::<SpaceInvite>(ctx.caller, ctx.account_id, &id)
                .await
            {
                Ok(()) => {
                    mutated = true;
                    acc.destroyed.push(Value::String(id_str.to_owned()));
                }
                Err(e) => {
                    acc.not_destroyed
                        .insert(id_str.to_owned(), backend_set_error_value(e));
                }
            }
        }
    }

    Ok(mutated)
}

/// draft-atwood-jmap-chat-00 §SpaceInvite/set: create "Requires
/// `"manage_members"` permission"; destroy "Requires `"manage_members"`
/// permission or ownership of the invite"; the backend decides. Returns
/// the [`SetError`] value to report when the op is denied.
async fn invite_denied<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    space_id: &Id,
    created_by: Option<&Id>,
) -> Option<Value> {
    match backend
        .may_set_space_invite(caller, account_id, space_id, created_by)
        .await
    {
        Ok(Ok(())) => None,
        Ok(Err(set_err)) => Some(serde_json::Value::from(&set_err)),
        Err(e) => Some(server_fail_value_from_backend(&e)),
    }
}

/// [`invite_denied`] for the stored invite `id`. An invite that does not
/// resolve is not gated, so the backend surfaces `notFound`.
async fn stored_invite_denied<B: ChatBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
) -> Option<Value> {
    match backend
        .get_objects::<SpaceInvite>(caller, account_id, Some(std::slice::from_ref(id)), None)
        .await
    {
        Ok((invites, _)) => match invites.first() {
            Some(invite) => {
                invite_denied(
                    backend,
                    caller,
                    account_id,
                    &invite.space_id,
                    Some(&invite.created_by),
                )
                .await
            }
            None => None,
        },
        Err(e) => Some(server_fail_value_from_backend(&e)),
    }
}