jmap-scene-server 0.6.1

JMAP Scene method handlers (draft-atwood-jmap-scene-00 SceneAsset) — 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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! `SceneRegion/*` method handlers (draft-atwood-jmap-scene-00 §`SceneRegion`
//! Methods).
//!
//! `/get`, `/changes` and `/queryChanges` are the standard RFC 8620 §5.1,
//! §5.2 and §5.6 methods. `/set` applies §Creating a Region, §Updating a
//! Region, §Destroying a Region and §`SetError` Conditions: the required
//! `name` and `bounds`, `min <= max`, the `accessPolicy`, `spawnOrientation`
//! and binding rules, `mayCreateRegion`, the owner-or-admin rule on update
//! and the owner rule on destroy. `/query` supplies the "Default sort:
//! `createdAt` descending" and refuses an unknown `accessPolicy` filter
//! value with `invalidArguments`.

use std::collections::BTreeMap;

use jmap_scene_types::SceneRegionComparator;
use jmap_scene_types::{GeoAnchor, SceneRegion};
use jmap_types::{Id, JmapError, PatchObject};
use serde_json::{Map, Value, json};

use crate::helpers::resolve_refs;
use crate::helpers::{
    SetAccumulators, default_sort, enforce_max_objects_in_set, extract_account_id, fetch_one,
    finalize_set_response, forbidden, handle_get_visible, invalid, normalized_quaternion,
    not_found, numbers, orientation_ok, reject_unsupported_sort,
};
use crate::{BindingProperty, BindingTarget, SceneBackend};
use jmap_server::{
    HandlerOutput, SetError, SetErrorType, apply_patch_object, backend_set_error_value,
    now_utc_string, reject_read_only_patch, reject_server_set, server_fail_from_backend,
    server_fail_value_from_backend,
};

pub(crate) const JMAP_CHAT_URI: &str = "urn:ietf:params:jmap:chat";
const JMAP_VTC_URI: &str = "urn:ietf:params:jmap:vtc";

/// The binding properties and the companion capability each needs:
/// "present only when the corresponding companion capability is
/// advertised on the same account".
const BINDINGS: &[(BindingProperty, &str)] = &[
    (BindingProperty::ChatId, JMAP_CHAT_URI),
    (BindingProperty::SpaceId, JMAP_CHAT_URI),
    (BindingProperty::ChannelId, JMAP_CHAT_URI),
    (BindingProperty::ActiveCallId, JMAP_VTC_URI),
];

/// The `accessPolicy` values: "`accessPolicy` is not one of `\"public\"`,
/// `\"invite\"`, `\"space\"`" is `invalidProperties`.
const ACCESS_POLICIES: &[&str] = &["public", "invite", "space"];

/// Handle `SceneRegion/get` (draft-atwood-jmap-scene-00 §`SceneRegion/get`):
/// standard RFC 8620 §5.1 `/get`, with a region the caller has no access
/// to ([`SceneBackend::may_access_region`]) reported as `notFound`
/// (§Region Access). Of `invitedUserIds`, "The server returns the list
/// only to callers who may update the region; for every other caller, the
/// server returns `[]`" ([`SceneBackend::may_update_region`]).
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
///   when `ids` or `properties` is malformed;
/// - `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_scene_region_get<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    handle_get_visible::<SceneRegion, B>(backend, caller, args).await
}

/// Handle `SceneRegion/changes` (draft-atwood-jmap-scene-00
/// §`SceneRegion/changes`): standard RFC 8620 §5.2 `/changes`.
///
/// # 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_scene_region_changes<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_changes::<SceneRegion, B>(backend, caller, args, &[]).await
}

/// Handle `SceneRegion/query` (draft-atwood-jmap-scene-00
/// §`SceneRegion/query`).
///
/// Supplies the "Default sort: `createdAt` descending", refuses any other
/// sort property with `unsupportedSort` and an `accessPolicy` filter value
/// other than `"public"`, `"invite"` or `"space"` with `invalidArguments`;
/// an unknown filter property is `unsupportedFilter`. The backend
/// evaluates the filter; [`crate::query::region_matches`] and
/// [`crate::query::compare_regions`] implement it.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id, when
///   `filter`, `sort`, `position`, `anchor`, `anchorOffset` or `limit` is
///   malformed, or when a filter condition has an `accessPolicy` other than
///   `"public"`, `"invite"` or `"space"`, or a `worldStateEquals` that is not
///   an object of String, Number or Boolean values;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `unsupportedFilter` when the filter does not decode as a `SceneRegion` filter;
/// - `unsupportedSort` when `sort` names a property this server does not
///   define;
/// - `anchorNotFound` when `anchor` is not in the results;
/// - `serverFail` when the backend fails, or any other RFC 8620 §5.5 error
///   the backend returns.
pub async fn handle_scene_region_query<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_query::<SceneRegion, B>(backend, caller, prepare_query(args)?).await
}

/// Handle `SceneRegion/queryChanges` (draft-atwood-jmap-scene-00
/// §`SceneRegion/queryChanges`). RFC 8620 §5.6: the `filter` and `sort` are
/// those of the original query, so the `/query` rules apply here too.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id,
///   `sinceQueryState` is missing, or `filter`, `sort`, `maxChanges` or
///   `upToId` is malformed, or when a filter condition has an `accessPolicy`
///   other than `"public"`, `"invite"` or `"space"`, or a `worldStateEquals`
///   that is not an object of String, Number or Boolean values;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `unsupportedFilter` when the filter does not decode as a `SceneRegion` filter;
/// - `unsupportedSort` when `sort` names a property this server does not
///   define;
/// - `cannotCalculateChanges` when the backend cannot compute the changes
///   since `sinceQueryState`;
/// - `serverFail` when the backend fails, or any other RFC 8620 §5.6 error
///   the backend returns.
pub async fn handle_scene_region_query_changes<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_query_changes::<SceneRegion, B>(backend, caller, prepare_query(args)?).await
}

fn prepare_query(mut args: Value) -> Result<Value, JmapError> {
    if let Value::Object(map) = &mut args {
        default_sort(
            map,
            json!([{ "property": "createdAt", "isAscending": false }]),
        );
    }
    reject_unsupported_sort::<SceneRegionComparator>(args.get("sort"))?;
    if let Some(filter) = args.get("filter") {
        check_filter_values(filter)?;
    }
    Ok(args)
}

/// "If a client provides an invalid value for `accessPolicy` (not one of
/// the defined values), the server MUST return `invalidArguments`" and
/// "If `worldStateEquals` is not an object, or one of its values is not a
/// String, Number, or Boolean, the server MUST return `invalidArguments`"
/// (jmap-chat-spec 93f2258), in every condition of a `FilterOperator` tree.
fn check_filter_values(filter: &Value) -> Result<(), JmapError> {
    if let Some(Value::Array(conditions)) = filter.get("conditions") {
        return conditions.iter().try_for_each(check_filter_values);
    }
    if let Some(v) = filter.get("worldStateEquals") {
        let scalar = |v: &Value| v.is_string() || v.is_number() || v.is_boolean();
        if !v.as_object().is_some_and(|m| m.values().all(scalar)) {
            return Err(JmapError::invalid_arguments(
                "filter worldStateEquals must be an object of String, Number or Boolean values",
            ));
        }
    }
    match filter.get("accessPolicy") {
        Some(v) if !v.as_str().is_some_and(|p| ACCESS_POLICIES.contains(&p)) => {
            Err(JmapError::invalid_arguments(format!(
                "filter accessPolicy must be \"public\", \"invite\" or \"space\"; got {}",
                jmap_server::json_type_name(v)
            )))
        }
        _ => Ok(()),
    }
}

/// The `SceneRegion` properties that hold the id of another record, which a
/// client may set to a `#creationId` reference (RFC 8620 §5.3).
const REGION_ID_PROPERTIES: &[&str] = &["chatId", "spaceId", "channelId", "activeCallId"];

/// Handle `SceneRegion/set` (draft-atwood-jmap-scene-00 §`SceneRegion/set`).
///
/// Create requires `mayCreateRegion`, validates the region and its
/// bindings ([`SceneBackend::has_capability`],
/// [`SceneBackend::region_binding`]) and hands it to
/// [`SceneBackend::create_object`], which applies `maxRegionsPerAccount`.
/// Update and destroy of a region the caller has no access to
/// ([`SceneBackend::may_access_region`]) are `notFound`, never
/// `forbidden`. Update requires [`SceneBackend::may_update_region`] and
/// validates the patched region as a create; destroy requires
/// [`SceneBackend::may_destroy_region`], and the backend removes the
/// contained objects and avatars.
///
/// A `chatId`, `spaceId`, `channelId` or `activeCallId` 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, update or destroy that fails on its own is a [`SetError`] in
/// the response, not an `Err`.
pub async fn handle_scene_region_set<B: SceneBackend>(
    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: an unknown accountId is `accountNotFound`.
    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_set(&args, backend.max_objects_in_set(caller, &account_id))?;

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

    if let Some(if_in_state) = args.get("ifInState").and_then(Value::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);
    mutated |= set_update(&ctx, &mut args, &mut acc).await?;
    mutated |= set_destroy(&ctx, &mut args, &mut acc).await?;

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

/// What every `SceneRegion/set` sub-function needs from the request
/// (docs/design/set-handler-split.md).
struct SetCtx<'a, B: SceneBackend> {
    backend: &'a B,
    caller: &'a B::CallerCtx,
    account_id: &'a Id,
    /// The request's creation ids, for `#creationId` references in
    /// [`REGION_ID_PROPERTIES`].
    created_ids: &'a BTreeMap<Id, Id>,
}

/// The `create` part of `SceneRegion/set`. Returns whether the backend was
/// written.
async fn set_create<B: SceneBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut Map<String, Value>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    if let Some(Value::Object(create_map)) = args.remove("create") {
        for (create_id, mut obj) in create_map {
            if let Err(err) = resolve_refs(&mut obj, REGION_ID_PROPERTIES, ctx.created_ids) {
                acc.not_created
                    .insert(create_id, serde_json::Value::from(&*err));
                continue;
            }
            match create_region(ctx.backend, ctx.caller, ctx.account_id, &create_id, obj).await {
                Ok(created) => {
                    mutated = true;
                    acc.created.insert(create_id, created);
                }
                Err(e) => {
                    acc.not_created.insert(create_id, e);
                }
            }
        }
    }
    Ok(mutated)
}

/// The `update` part of `SceneRegion/set`. Returns whether the backend was
/// written.
async fn set_update<B: SceneBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut Map<String, Value>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    if let Some(Value::Object(update_map)) = args.remove("update") {
        for (id_str, mut patch) in update_map {
            let id = match jmap_server::parse_wire_id(&id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    acc.not_updated
                        .insert(id_str, serde_json::Value::from(&*err));
                    continue;
                }
            };
            if let Err(err) = resolve_refs(&mut patch, REGION_ID_PROPERTIES, ctx.created_ids) {
                acc.not_updated
                    .insert(id_str, serde_json::Value::from(&*err));
                continue;
            }
            match update_region(ctx.backend, ctx.caller, ctx.account_id, &id, patch).await {
                Ok(echo) => {
                    mutated = true;
                    acc.updated.insert(id_str, echo);
                }
                Err(e) => {
                    acc.not_updated.insert(id_str, e);
                }
            }
        }
    }
    Ok(mutated)
}

/// The `destroy` part of `SceneRegion/set`, including the whole-request
/// `invalidArguments` for a non-string element. Returns whether the
/// backend was written.
async fn set_destroy<B: SceneBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut Map<String, Value>,
    acc: &mut SetAccumulators,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
        // RFC 8620 §5.3: every element of `destroy` is an Id.
        let ids: Vec<&str> = destroy_arr
            .iter()
            .map(|v| v.as_str().ok_or(v))
            .collect::<Result<_, _>>()
            .map_err(|bad| {
                JmapError::invalid_arguments(format!(
                    "destroy: every element must be a string Id; got {}",
                    jmap_server::json_type_name(bad)
                ))
            })?;
        for id_str in ids {
            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;
                }
            };
            match destroy_region(ctx.backend, 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(), e);
                }
            }
        }
    }
    Ok(mutated)
}

/// `SceneBounds`: `min` and `max` are "a 3-element numeric array" and
/// "Each component of `min` MUST be less than or equal to the
/// corresponding component of `max`."
fn bounds_ok(v: &Value) -> bool {
    match (
        v.get("min").and_then(|m| numbers(m, 3)),
        v.get("max").and_then(|m| numbers(m, 3)),
    ) {
        (Some(min), Some(max)) => min.iter().zip(&max).all(|(lo, hi)| lo <= hi),
        _ => false,
    }
}

/// The properties of region `m` that break a §Create Errors
/// `invalidProperties` row that needs no backend fact: `name` "missing or
/// empty", `bounds` missing or malformed or `min > max`, an unknown
/// `accessPolicy`, a `spawnPosition` that is not 3 Numbers, a
/// `spawnOrientation` that is not a unit quaternion, "`invitedUserIds` is
/// not an array of Strings", and a property of the wrong JSON type.
fn malformed(m: &Map<String, Value>) -> Vec<&'static str> {
    let mut bad = Vec::new();
    let mut check = |key: &'static str, ok: bool| {
        if !ok {
            bad.push(key);
        }
    };
    let optional = |key: &str, ok: fn(&Value) -> bool| m.get(key).is_none_or(ok);

    check(
        "name",
        m.get("name")
            .and_then(Value::as_str)
            .is_some_and(|s| !s.is_empty()),
    );
    check("bounds", m.get("bounds").is_some_and(bounds_ok));
    // draft-atwood-jmap-updates-00 §7.1: the endpoint URIs are opaque in
    // meaning but SHOULD be RFC 3986 URIs.
    for key in ["simulationUri", "inputUri"] {
        check(
            key,
            optional(key, |v| {
                v.is_null()
                    || v.as_str()
                        .is_some_and(|s| jmap_types::uri::check_uri(s).is_ok())
            }),
        );
    }
    for key in [
        "description",
        "viewHint",
        "chatId",
        "spaceId",
        "channelId",
        "activeCallId",
    ] {
        check(key, optional(key, |v| v.is_null() || v.is_string()));
    }
    for key in ["environment", "worldState"] {
        check(key, optional(key, |v| v.is_null() || v.is_object()));
    }
    check(
        "geoAnchor",
        optional("geoAnchor", |v| {
            v.is_null() || serde_json::from_value::<GeoAnchor>(v.clone()).is_ok()
        }),
    );
    check(
        "spawnPosition",
        optional("spawnPosition", |v| numbers(v, 3).is_some()),
    );
    check(
        "spawnOrientation",
        optional("spawnOrientation", orientation_ok),
    );
    check(
        "accessPolicy",
        optional("accessPolicy", |v| {
            v.as_str().is_some_and(|p| ACCESS_POLICIES.contains(&p))
        }),
    );
    check(
        "invitedUserIds",
        optional("invitedUserIds", |v| {
            v.as_array().is_some_and(|a| a.iter().all(Value::is_string))
        }),
    );
    // jmap-chat-spec 93f2258: "`allowObservers` (Boolean)".
    check(
        "allowObservers",
        optional("allowObservers", Value::is_boolean),
    );
    bad
}

/// `allowObservers` on a server without `supportsObserve`
/// ([`SceneBackend::supports_observe`]): the property is "Present only
/// when the server advertises `supportsObserve`" (jmap-chat-spec 93f2258),
/// so it is refused rather than kept as an extension property.
fn observers_unsupported<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    touched: bool,
) -> Result<(), Value> {
    if touched && !backend.supports_observe(caller) {
        return Err(invalid(
            &["allowObservers"],
            "allowObservers needs supportsObserve",
        ));
    }
    Ok(())
}

/// The capability-dependent §Create Errors of region `m`: a non-null
/// binding in `touched` without its companion capability, and
/// "`accessPolicy` is `\"space\"` but `urn:ietf:params:jmap:chat` is not in
/// the server's capabilities" (naming `accessPolicy`) or "but `spaceId` is
/// null" (naming `spaceId`, as in §Updating a Region: "an update that sets
/// `spaceId` to `null` while `accessPolicy` is `\"space\"` fails with
/// `invalidProperties` naming `spaceId`").
fn capability_errors<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    m: &Map<String, Value>,
    touched: &impl Fn(&str) -> bool,
) -> Vec<&'static str> {
    let has = |uri| backend.has_capability(caller, account_id, uri);
    let mut bad: Vec<&'static str> = BINDINGS
        .iter()
        .map(|(p, uri)| (p.as_str(), uri))
        .filter(|(key, uri)| touched(key) && m.get(*key).is_some_and(|v| !v.is_null()) && !has(uri))
        .map(|(key, _)| key)
        .collect();
    if m.get("accessPolicy").and_then(Value::as_str) == Some("space") {
        if !has(JMAP_CHAT_URI) {
            bad.push("accessPolicy");
        } else if m.get("spaceId").is_none_or(Value::is_null) {
            bad.push("spaceId");
        }
    }
    bad
}

/// Ask [`SceneBackend::region_binding`] about each non-null binding in
/// `touched` and map the answer to the draft's `SetError`: `invalidProperties`
/// naming the property, except `forbidden` for an `activeCallId` the
/// caller lacks access to. Then ask [`SceneBackend::channel_in_space`]
/// whether a non-null `channelId` "is a channel of the Space named by
/// `spaceId`", naming `channelId` if not.
async fn check_bindings<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    m: &Map<String, Value>,
    touched: &impl Fn(&str) -> bool,
) -> Result<(), Value> {
    for (property, _) in BINDINGS.iter().filter(|(p, _)| touched(p.as_str())) {
        let key = property.as_str();
        let Some(id) = m.get(key).and_then(Value::as_str) else {
            continue;
        };
        let target = backend
            .region_binding(
                caller,
                account_id,
                *property,
                &Id::new_validated(id).map_err(|e| invalid(&[key], &e.to_string()))?,
            )
            .await
            .map_err(|e| server_fail_value_from_backend(&e))?;
        match (target, property) {
            (BindingTarget::Inaccessible, BindingProperty::ActiveCallId) => {
                return Err(forbidden(
                    "the caller is not a participant in or moderator of the VTCCall",
                ));
            }
            (BindingTarget::Missing | BindingTarget::Inaccessible, _) => {
                return Err(invalid(
                    &[key],
                    "the referenced object does not exist, is not accessible, or is an ended call",
                ));
            }
            _ => {}
        }
    }
    if (touched("channelId") || touched("spaceId"))
        && let (Some(channel), Some(space)) = (
            m.get("channelId").and_then(Value::as_str),
            m.get("spaceId").and_then(Value::as_str),
        )
    {
        let in_space = backend
            .channel_in_space(
                caller,
                account_id,
                &Id::new_validated(channel).map_err(|e| invalid(&["channelId"], &e.to_string()))?,
                &Id::new_validated(space).map_err(|e| invalid(&["spaceId"], &e.to_string()))?,
            )
            .await
            .map_err(|e| server_fail_value_from_backend(&e))?;
        if !in_space {
            return Err(invalid(
                &["channelId"],
                "channelId is not a channel of the Space named by spaceId",
            ));
        }
    }
    Ok(())
}

/// Every validation shared by create and update, on the whole region `m`.
async fn validate<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    m: &Map<String, Value>,
    touched: &impl Fn(&str) -> bool,
) -> Result<(), Value> {
    let mut bad = malformed(m);
    if bad.is_empty() {
        bad = capability_errors(backend, caller, account_id, m, touched);
    }
    if !bad.is_empty() {
        bad.sort_unstable();
        bad.dedup();
        return Err(invalid(
            &bad,
            "name and bounds are required, bounds.min <= bounds.max, spawnOrientation a unit \
             quaternion, accessPolicy public, invite or space (space needs \
             urn:ietf:params:jmap:chat and spaceId), bindings need their companion capability",
        ));
    }
    check_bindings(backend, caller, account_id, m, touched).await
}

/// One §Creating a Region. The `Ok` value is the `created` entry: the
/// server-set `id`, `accountId`, `ownerId` (from
/// [`SceneBackend::caller_user_id`]), `activeAvatarCount`, `createdAt` and
/// `updatedAt`, plus `spawnOrientation` when normalizing changed it (RFC
/// 8620 §5.3: "any properties that were omitted or not set to the
/// requested value by the server").
async fn create_region<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    create_id: &str,
    obj: Value,
) -> Result<Value, Value> {
    let Value::Object(mut m) = obj else {
        return Err(invalid(&[], "a SceneRegion create must be a JSON object"));
    };

    let cap = backend
        .scene_capability(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;
    if !cap.may_create_region {
        return Err(forbidden("mayCreateRegion is false"));
    }

    // "The server sets `id`, `accountId`, `ownerId` (to the caller's
    // userId), `activeAvatarCount` (to `0`), `createdAt`, and
    // `updatedAt`." `activeCallId` is a binding `update` supports; `create`
    // does not list it.
    if let Some(e) = reject_server_set::<SceneRegion>(&m) {
        return Err(serde_json::Value::from(
            &e.with_description("these properties are set by the server"),
        ));
    }
    if m.contains_key("activeCallId") {
        return Err(invalid(
            &["activeCallId"],
            "activeCallId cannot be set on create",
        ));
    }

    observers_unsupported(backend, caller, m.contains_key("allowObservers"))?;
    validate(backend, caller, account_id, &m, &|_| true).await?;
    // "The server sets ... when the region has the observer properties,
    // `observerCount` (to `0`)"; `allowObservers` "Default: `true`".
    let observers = backend.supports_observe(caller);
    let default_allow = observers && !m.contains_key("allowObservers");
    if observers {
        m.entry("allowObservers").or_insert(json!(true));
        m.insert("observerCount".to_owned(), json!(0));
    }
    let owner_id = backend
        .caller_user_id(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;

    for (property, uri) in BINDINGS {
        if backend.has_capability(caller, account_id, uri) {
            m.entry(property.as_str()).or_insert(Value::Null);
        }
    }
    let normalized = normalized_quaternion(&m, "spawnOrientation");
    if let Some(q) = &normalized {
        m.insert("spawnOrientation".to_owned(), q.clone());
    }
    let now = now_utc_string();
    // `id` is required by the type, so the parse uses
    // `jmap_server::CREATE_ID_PLACEHOLDER`; the
    // `create_object` builder overwrites it with the minted id.
    m.insert("id".to_owned(), json!(jmap_server::CREATE_ID_PLACEHOLDER));
    m.insert("accountId".to_owned(), json!(account_id));
    m.insert("ownerId".to_owned(), json!(owner_id));
    m.insert("activeAvatarCount".to_owned(), json!(0));
    m.insert("createdAt".to_owned(), json!(now));
    m.insert("updatedAt".to_owned(), json!(now));
    let mut region: SceneRegion = serde_json::from_value(Value::Object(m))
        .map_err(|e| invalid(&[], &format!("invalid SceneRegion: {e}")))?;
    let (id, stored) = backend
        .create_object(caller, account_id, create_id, move |id: &Id| {
            region.id = id.clone();
            region
        })
        .await
        .map_err(backend_set_error_value)?;
    let mut created = json!({
        "id": id,
        "accountId": stored.account_id,
        "ownerId": stored.owner_id,
        "activeAvatarCount": stored.active_avatar_count,
        "createdAt": stored.created_at,
        "updatedAt": stored.updated_at,
    });
    if normalized.is_some() {
        created["spawnOrientation"] = json!(stored.spawn_orientation);
    }
    if let Some(count) = stored.observer_count {
        created["observerCount"] = json!(count);
    }
    if default_allow {
        created["allowObservers"] = json!(stored.allow_observers);
    }
    Ok(created)
}

/// One §Updating a Region. `Ok` is the `updated` echo: the server-set
/// `updatedAt` and a normalized `spawnOrientation` (RFC 8620 §5.3: "any
/// properties that changed in a way not explicitly requested by the
/// `PatchObject`").
/// Vendor extension properties stay patchable and the spec-defined immutable
/// or server-set ones do not (§Extension Properties in Updates,
/// jmap-chat-spec 77c3474 L736: "MAY also accept patches to them";
/// "Patches to a property this document defines as immutable or server-set
/// are rejected as {{RFC8620}} Section 5.3 describes").
async fn update_region<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
    patch: Value,
) -> Result<Value, Value> {
    let mut patch: PatchObject = serde_json::from_value(patch).map_err(|e| {
        serde_json::Value::from(
            &SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
        )
    })?;
    let region = fetch_accessible(backend, caller, account_id, id).await?;
    if !backend
        .may_update_region(caller, account_id, &region)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        return Err(forbidden(
            "only the region owner or an admin may modify this region",
        ));
    }

    let top = |k: &str| k.split('/').next().unwrap_or(k).to_owned();
    let patched: Vec<String> = patch.as_map().keys().map(|k| top(k)).collect();

    // "Same field-level validations as create apply", to the region as
    // the patch leaves it.
    let Value::Object(mut result) = jmap_server::serialize_value(&region)
        .map_err(|e| jmap_server::server_fail_value_from_backend(&e))?
    else {
        unreachable!("a SceneRegion serializes as a JSON object")
    };
    // The server-set properties may repeat only their stored value (RFC
    // 8620 §5.3).
    if let Some(e) = reject_read_only_patch::<SceneRegion>(patch.as_map(), Some(&result)) {
        return Err(serde_json::Value::from(
            &e.with_description("these properties are set by the server"),
        ));
    }
    apply_patch_object(&mut result, patch.as_map()).map_err(|e| {
        serde_json::Value::from(
            &SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
        )
    })?;
    let touched = |k: &str| patched.iter().any(|p| p == k);
    observers_unsupported(backend, caller, touched("allowObservers"))?;
    validate(backend, caller, account_id, &result, &touched).await?;

    let now = now_utc_string();
    let mut echo = Map::new();
    echo.insert("updatedAt".to_owned(), json!(now));
    let map = patch.as_map_mut();
    if touched("spawnOrientation")
        && let Some(q) = normalized_quaternion(&result, "spawnOrientation")
    {
        map.retain(|k, _| top(k) != "spawnOrientation");
        map.insert("spawnOrientation".to_owned(), q.clone());
        echo.insert("spawnOrientation".to_owned(), q);
    }
    map.insert("updatedAt".to_owned(), json!(now));
    match backend
        .update_object::<SceneRegion>(caller, account_id, id, patch)
        .await
        .map_err(backend_set_error_value)?
    {
        Some(region) => Ok(jmap_server::serialize_value(region)
            .map_err(|e| jmap_server::server_fail_value_from_backend(&e))?),
        None => Ok(Value::Object(echo)),
    }
}

/// The region `id` that update or destroy acts on: `notFound` when "The
/// region id does not exist or the caller lacks access"
/// ([`SceneBackend::may_access_region`]), "the server returns `notFound`
/// rather than `forbidden` to prevent probing" (§Update Errors, §Destroy
/// Errors).
async fn fetch_accessible<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
) -> Result<SceneRegion, Value> {
    let region: SceneRegion = fetch_one(backend, caller, account_id, id)
        .await?
        .ok_or_else(not_found)?;
    if backend
        .may_access_region(caller, account_id, &region.id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        Ok(region)
    } else {
        Err(not_found())
    }
}

/// One §Destroying a Region: "The server SHOULD return `forbidden` when
/// the caller is not the region owner and does not have
/// deployment-defined administrative privileges."
async fn destroy_region<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
) -> Result<(), Value> {
    let region = fetch_accessible(backend, caller, account_id, id).await?;
    if !backend
        .may_destroy_region(caller, account_id, &region)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        return Err(forbidden(
            "only the region owner or an admin may destroy this region",
        ));
    }
    backend
        .destroy_object::<SceneRegion>(caller, account_id, id)
        .await
        .map_err(backend_set_error_value)
}