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
//! `SceneObject/*` method handlers (draft-atwood-jmap-scene-00 §`SceneObject`
//! Methods).
//!
//! `/get`, `/changes` and `/queryChanges` are the standard RFC 8620 §5.1,
//! §5.2 and §5.6 methods. `/set` applies §Creating an Object, §Updating an
//! Object, §Destroying an Object and §`SetError` Conditions: `mayCreateObject`,
//! the required `regionId` and `position`, the coordinate, `physicsMode`
//! and `visualRef`/`visualType` rules, the region-scoped, acyclic,
//! depth-limited scene graph, the immutable `regionId` and the
//! owner/region-owner/admin rule on update and destroy. `/query` supplies
//! the "Default sort: `createdAt` ascending" and the §Filter Validation
//! `invalidArguments` checks.

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

use jmap_scene_types::SceneObjectComparator;
use jmap_scene_types::{IDENTITY_ORIENTATION, SceneObject, SceneRegion};
use jmap_types::{Id, JmapError, PatchObject};
use serde_json::{Map, Value, json};

use crate::SceneBackend;
use crate::asset::GLTF_BINARY;
use crate::helpers::{
    SetAccumulators, check_region_filter, default_sort, enforce_max_objects_in_set,
    extract_account_id, fetch_one, finalize_set_response, finite3, forbidden, handle_get_visible,
    invalid, is_visible, normalized_quaternion, not_found, orientation_ok, reject_unsupported_sort,
};
use crate::helpers::{parents_first, resolve_refs};
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,
};

/// "`physicsMode` is not one of `\"static\"`, `\"dynamic\"`,
/// `\"kinematic\"`, `\"none\"`" is `invalidProperties` in `/set` and
/// `invalidArguments` in a `/query` filter.
const PHYSICS_MODES: &[&str] = &["static", "dynamic", "kinematic", "none"];

/// ponytail: "Servers MAY impose a maximum hierarchy depth"; this one is
/// fixed at the 16 levels the implementer guide calls "generous for any
/// practical scene graph" (jmap-scene-implementer-guide L339-342). A root
/// object is at depth 1. A deployment that wants another limit registers
/// its own `SceneObject/set`.
const MAX_DEPTH: usize = 16;

/// Handle `SceneObject/get` (draft-atwood-jmap-scene-00 §`SceneObject/get`):
/// standard RFC 8620 §5.1 `/get`, with an object in a region the caller
/// has no access to ([`SceneBackend::may_access_region`]) or outside its
/// visibility set ([`SceneBackend::is_object_visible`]) reported as
/// `notFound` (§Visibility Contract, §Region Access).
///
/// # 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_object_get<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    handle_get_visible::<SceneObject, B>(backend, caller, args).await
}

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

/// Handle `SceneObject/query` (draft-atwood-jmap-scene-00
/// §`SceneObject/query`).
///
/// Supplies the "Default sort: `createdAt` ascending" and refuses any
/// other sort property with `unsupportedSort`. Returns `invalidArguments`
/// when `regionId` is absent, when `physicsMode` is outside the defined
/// set, when `withinRadius.radius` is zero or negative, and when a
/// `withinBounds.max` component is below `min`. An unknown filter
/// property is `unsupportedFilter`. The backend evaluates the filter;
/// [`crate::query::object_matches`], [`crate::query::region_local_position`]
/// and [`crate::query::compare_objects`] 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 `filter` is absent or a condition of it (every one, in
///   a `FilterOperator` tree) lacks `regionId`, has a `physicsMode` outside the
///   defined set, a `withinRadius.radius` that is zero or negative, or a
///   `withinBounds.max` component below `min`;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `unsupportedFilter` when the filter does not decode as a `SceneObject` 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_object_query<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_query::<SceneObject, B>(backend, caller, prepare_query(args)?).await
}

/// Handle `SceneObject/queryChanges` (draft-atwood-jmap-scene-00
/// §`SceneObject/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 `filter` is absent or a condition of it
///   (every one, in a `FilterOperator` tree) lacks `regionId`, has a
///   `physicsMode` outside the defined set, a `withinRadius.radius` that is
///   zero or negative, or a `withinBounds.max` component below `min`;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `unsupportedFilter` when the filter does not decode as a `SceneObject` 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_object_query_changes<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_query_changes::<SceneObject, 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": true }]),
        );
    }
    reject_unsupported_sort::<SceneObjectComparator>(args.get("sort"))?;
    match args.get("filter") {
        None | Some(Value::Null) => {
            Err(JmapError::invalid_arguments("filter.regionId is required"))
        }
        Some(filter) => check_filter(filter),
    }?;
    Ok(args)
}

/// §Filter Validation: the shared region-scoped and spatial checks of
/// [`check_region_filter`], and "If `physicsMode` contains a value not in
/// the defined set, the server MUST return `invalidArguments`."
fn check_filter(filter: &Value) -> Result<(), JmapError> {
    check_region_filter(filter, &|c| match c.get("physicsMode") {
        Some(m) if !m.as_str().is_some_and(|m| PHYSICS_MODES.contains(&m)) => {
            Err(JmapError::invalid_arguments(format!(
                "filter physicsMode must be \"static\", \"dynamic\", \"kinematic\" or \"none\"; got {m}"
            )))
        }
        _ => Ok(()),
    })
}

/// The `SceneObject` properties that hold the id of another record, which a
/// client may set to a `#creationId` reference (RFC 8620 §5.3).
const OBJECT_ID_PROPERTIES: &[&str] = &["regionId", "parentId"];

/// Handle `SceneObject/set` (draft-atwood-jmap-scene-00 §`SceneObject/set`).
///
/// Create requires `mayCreateObject`, validates the object, its region,
/// its `visualRef` blob ([`SceneBackend::blob_size`]) and its parent, and
/// hands it to [`SceneBackend::create_object`], which sets `ownerId` and
/// applies `maxObjectsPerRegion`. Update and destroy require
/// [`SceneBackend::may_modify_object`]; update validates the patched
/// object as a create, and on destroy the backend removes the object's
/// descendants.
///
/// A `regionId` or `parentId` that is a `#creationId` reference names a
/// record created earlier in the request and resolves against
/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]) or
/// against a create of this call, which runs parents first (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_object_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::<SceneObject>(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,
    };
    let mut acc = SetAccumulators::default();
    // RFC 8620 §5.3: creates of this call join the request-wide map so
    // later creates and updates in this call can reference them.
    let mut created_ids = created_ids.clone();
    let mut mutated = set_create(&ctx, &mut args, &mut acc, &mut created_ids).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, &created_ids).await?;
    mutated |= set_destroy(&ctx, &mut args, &mut acc).await?;

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

/// What every `SceneObject/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 `create` part of `SceneObject/set`, parents first. Each created
/// object joins `created_ids`. Returns whether the backend was written.
async fn set_create<B: SceneBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut Map<String, Value>,
    acc: &mut SetAccumulators,
    created_ids: &mut BTreeMap<Id, Id>,
) -> Result<bool, JmapError> {
    let mut mutated = false;
    if let Some(Value::Object(create_map)) = args.remove("create") {
        for (create_id, mut obj) in parents_first(create_map, "parentId") {
            if let Err(err) = resolve_refs(&mut obj, OBJECT_ID_PROPERTIES, created_ids) {
                acc.not_created
                    .insert(create_id, serde_json::Value::from(&*err));
                continue;
            }
            match create_scene_object(ctx.backend, ctx.caller, ctx.account_id, &create_id, obj)
                .await
            {
                Ok(created) => {
                    mutated = true;
                    if let Some(id) = created.get("id").and_then(Value::as_str) {
                        created_ids.insert(Id::from(create_id.as_str()), Id::from(id));
                    }
                    acc.created.insert(create_id, created);
                }
                Err(e) => {
                    acc.not_created.insert(create_id, e);
                }
            }
        }
    }
    Ok(mutated)
}

/// The `update` part of `SceneObject/set`. Returns whether the backend was
/// written.
async fn set_update<B: SceneBackend>(
    ctx: &SetCtx<'_, B>,
    args: &mut Map<String, Value>,
    acc: &mut SetAccumulators,
    created_ids: &BTreeMap<Id, Id>,
) -> 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, OBJECT_ID_PROPERTIES, created_ids) {
                acc.not_updated
                    .insert(id_str, serde_json::Value::from(&*err));
                continue;
            }
            match update_scene_object(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 `SceneObject/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_scene_object(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)
}

/// The properties of object `m` that break a §Create Errors
/// `invalidProperties` row that needs no backend fact: `regionId` or
/// `position` missing, a non-finite `position` or `scale`, an
/// `orientation` that is not a unit quaternion, an unknown `physicsMode`,
/// `visualRef` without `visualType` or the reverse, 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("regionId", m.get("regionId").is_some_and(Value::is_string));
    check("position", m.get("position").is_some_and(finite3));
    check("orientation", optional("orientation", orientation_ok));
    check("scale", optional("scale", finite3));
    check(
        "physicsMode",
        optional("physicsMode", |v| {
            v.as_str().is_some_and(|p| PHYSICS_MODES.contains(&p))
        }),
    );
    for key in ["parentId", "name", "visualRef", "visualType"] {
        check(key, optional(key, |v| v.is_null() || v.is_string()));
    }
    // draft-atwood-jmap-updates-00 §7.1: an RFC 3986 URI.
    check(
        "assetUri",
        optional("assetUri", |v| {
            v.is_null()
                || v.as_str()
                    .is_some_and(|s| jmap_types::uri::check_uri(s).is_ok())
        }),
    );
    for key in ["interactable", "visible"] {
        check(key, optional(key, Value::is_boolean));
    }
    check(
        "worldState",
        optional("worldState", |v| v.is_null() || v.is_object()),
    );
    // "Both MUST be present together or both absent"; `null` is absent
    // ("`visualType` ... MUST be null when `visualRef` is null").
    let present = |key: &str| m.get(key).is_some_and(|v| !v.is_null());
    if present("visualRef") != present("visualType") {
        bad.extend(["visualRef", "visualType"]);
    }
    bad
}

/// "The server MUST return `invalidProperties` naming `visualType` when
/// `visualType` is not in `supportedVisualTypes`." `model/gltf-binary` is
/// always accepted, as in `SceneAsset/set`: §Preferred Asset Format makes
/// it mandatory to implement.
async fn check_visual_type<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    visual_type: &str,
) -> Result<(), Value> {
    let cap = backend
        .scene_capability(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;
    if visual_type == GLTF_BINARY || cap.supported_visual_types.iter().any(|t| t == visual_type) {
        Ok(())
    } else {
        Err(invalid(
            &["visualType"],
            "visualType is not in supportedVisualTypes",
        ))
    }
}

/// "`visualRef` does not reference a valid blob": `invalidProperties`
/// naming `visualRef`.
async fn check_visual_ref<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    visual_ref: &str,
) -> Result<(), Value> {
    backend
        .blob_size(
            caller,
            account_id,
            &Id::new_validated(visual_ref).map_err(|e| invalid(&["visualRef"], &e.to_string()))?,
        )
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
        .map(|_| ())
        .ok_or_else(|| {
            invalid(
                &["visualRef"],
                "visualRef does not reference an uploaded blob",
            )
        })
}

/// Check `parent_id` as the parent of an object in `region_id` whose own
/// subtree is `height` levels tall, walking the parent chain to the root.
///
/// `invalidProperties` naming `parentId` when "`parentId` does not
/// reference an existing `SceneObject`", for a parent "in a different
/// region", for a chain that reaches `self_id` ("the object is its own
/// ancestor (directly or transitively)") and for a chain that would put
/// any object deeper than [`MAX_DEPTH`].
async fn check_parent<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    region_id: &Id,
    self_id: Option<&Id>,
    parent_id: &Id,
    height: usize,
) -> Result<(), Value> {
    let mut depth = 0;
    let mut next = Some(parent_id.clone());
    while let Some(id) = next {
        if self_id == Some(&id) {
            return Err(invalid(
                &["parentId"],
                "parentId would make the object its own ancestor",
            ));
        }
        depth += 1;
        if depth + height > MAX_DEPTH {
            return Err(invalid(
                &["parentId"],
                "parentId would make the scene graph deeper than 16 levels",
            ));
        }
        let Some(ancestor): Option<SceneObject> =
            fetch_one(backend, caller, account_id, &id).await?
        else {
            if depth == 1 {
                return Err(invalid(
                    &["parentId"],
                    "parentId does not reference an existing SceneObject",
                ));
            }
            break;
        };
        if ancestor.region_id != *region_id {
            return Err(invalid(
                &["parentId"],
                "parentId references a SceneObject in a different region",
            ));
        }
        next = ancestor.parent_id;
    }
    Ok(())
}

/// The number of levels in the subtree rooted at `id`: 1 for an object
/// without children.
///
/// ponytail: reads every `SceneObject` of the account to find the
/// descendants, O(objects) per re-parenting update. A backend with a
/// `parentId` index can serve a faster `SceneObject/set`. The walk stops
/// past [`MAX_DEPTH`] levels, so a corrupt cycle cannot loop.
async fn subtree_height<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
) -> Result<usize, Value> {
    let (all, _) = backend
        .get_objects::<SceneObject>(caller, account_id, None, None)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;
    let mut children: HashMap<&Id, Vec<&Id>> = HashMap::new();
    for o in &all {
        if let Some(p) = &o.parent_id {
            children.entry(p).or_default().push(&o.id);
        }
    }
    let mut level = vec![id];
    let mut height = 0;
    while !level.is_empty() && height <= MAX_DEPTH {
        height += 1;
        level = level
            .iter()
            .filter_map(|p| children.get(p))
            .flatten()
            .copied()
            .collect();
    }
    Ok(height)
}

/// Refuse `bad` (from [`malformed`]) with one `invalidProperties`.
fn refuse_malformed(mut bad: Vec<&'static str>) -> Result<(), Value> {
    if bad.is_empty() {
        return Ok(());
    }
    bad.sort_unstable();
    bad.dedup();
    Err(invalid(
        &bad,
        "regionId and position are required, position and scale finite, orientation a unit \
         quaternion, physicsMode static, dynamic, kinematic or none, visualRef and visualType \
         together",
    ))
}

/// One §Creating an Object. The `Ok` value is the `created` entry: the
/// server-set `id`, `ownerId`, `createdAt` and `updatedAt`, plus
/// `orientation` when it was omitted (defaulted to identity) or 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_scene_object<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 SceneObject 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_object {
        return Err(forbidden("mayCreateObject is false"));
    }

    // "The server sets `id`, `ownerId`, `createdAt`, and `updatedAt`."
    if let Some(e) = reject_server_set::<SceneObject>(&m) {
        return Err(serde_json::Value::from(
            &e.with_description("these properties are set by the server"),
        ));
    }
    refuse_malformed(malformed(&m))?;
    if let Some(t) = m.get("visualType").and_then(Value::as_str) {
        check_visual_type(backend, caller, account_id, t).await?;
    }

    // "The server MUST return `invalidProperties` naming `regionId` when
    // `regionId` does not exist, and SHOULD return the same error (not
    // `forbidden`) when the caller does not have access to the region".
    let region_id = Id::new_validated(m["regionId"].as_str().unwrap_or_default())
        .map_err(|e| invalid(&["regionId"], &e.to_string()))?;
    let inaccessible = || invalid(&["regionId"], "regionId is not an accessible SceneRegion");
    fetch_one::<SceneRegion, B>(backend, caller, account_id, &region_id)
        .await?
        .ok_or_else(inaccessible)?;
    if !backend
        .may_access_region(caller, account_id, &region_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        return Err(inaccessible());
    }
    if let Some(r) = m.get("visualRef").and_then(Value::as_str) {
        check_visual_ref(backend, caller, account_id, r).await?;
    }
    if let Some(p) = m.get("parentId").and_then(Value::as_str) {
        check_parent(
            backend,
            caller,
            account_id,
            &region_id,
            None,
            &Id::new_validated(p).map_err(|e| invalid(&["parentId"], &e.to_string()))?,
            1,
        )
        .await?;
    }

    // `orientation` is optional on create and has no stated default; an
    // absent one is "the identity orientation (no rotation)".
    let mut echo_orientation = !m.contains_key("orientation");
    m.entry("orientation")
        .or_insert_with(|| json!(IDENTITY_ORIENTATION));
    if let Some(q) = normalized_quaternion(&m, "orientation") {
        m.insert("orientation".to_owned(), q);
        echo_orientation = true;
    }
    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("ownerId".to_owned(), Value::Null);
    m.insert("createdAt".to_owned(), json!(now));
    m.insert("updatedAt".to_owned(), json!(now));
    let mut object: SceneObject = serde_json::from_value(Value::Object(m))
        .map_err(|e| invalid(&[], &format!("invalid SceneObject: {e}")))?;
    let (id, stored) = backend
        .create_object(caller, account_id, create_id, move |id: &Id| {
            object.id = id.clone();
            object
        })
        .await
        .map_err(backend_set_error_value)?;
    let mut created = json!({
        "id": id,
        "ownerId": stored.owner_id,
        "createdAt": stored.created_at,
        "updatedAt": stored.updated_at,
    });
    if echo_orientation {
        created["orientation"] = json!(stored.orientation);
    }
    Ok(created)
}

/// The stored object `id` if the caller may modify it
/// ([`SceneBackend::may_modify_object`]), else `forbidden`; `notFound` if
/// it is missing or hidden from the caller: "The server MUST NOT return
/// `forbidden`, as that would confirm the object still exists"
/// (§Visibility Contract).
async fn fetch_modifiable<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
) -> Result<SceneObject, Value> {
    let object: SceneObject = fetch_one(backend, caller, account_id, id)
        .await?
        .ok_or_else(not_found)?;
    if !is_visible(backend, caller, account_id, &object)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        return Err(not_found());
    }
    if backend
        .may_modify_object(caller, account_id, &object)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        Ok(object)
    } else {
        Err(forbidden(
            "Caller is not the object owner, region owner, or an administrator.",
        ))
    }
}

/// One §Updating an Object. `Ok` is the `updated` echo: the server-set
/// `updatedAt` and a normalized `orientation` (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_scene_object<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 object = fetch_modifiable(backend, caller, account_id, id).await?;

    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();

    let Value::Object(mut result) = jmap_server::serialize_value(&object)
        .map_err(|e| jmap_server::server_fail_value_from_backend(&e))?
    else {
        unreachable!("a SceneObject serializes as a JSON object")
    };
    // The server-set properties and "`regionId` is immutable and cannot be
    // changed via update"; each may repeat its stored value (RFC 8620 §5.3).
    if let Some(e) = reject_read_only_patch::<SceneObject>(patch.as_map(), Some(&result)) {
        return Err(serde_json::Value::from(&e.with_description(
            "these properties are set by the server or immutable",
        )));
    }
    apply_patch_object(&mut result, patch.as_map()).map_err(|e| {
        serde_json::Value::from(
            &SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
        )
    })?;
    // "Same field-level validations as create", on the object as the
    // patch leaves it.
    refuse_malformed(malformed(&result))?;
    let touched = |k: &str| patched.iter().any(|p| p == k);
    if touched("visualType")
        && let Some(t) = result.get("visualType").and_then(Value::as_str)
    {
        check_visual_type(backend, caller, account_id, t).await?;
    }
    if touched("visualRef")
        && let Some(r) = result.get("visualRef").and_then(Value::as_str)
    {
        check_visual_ref(backend, caller, account_id, r).await?;
    }
    if touched("parentId")
        && let Some(p) = result.get("parentId").and_then(Value::as_str)
    {
        let height = subtree_height(backend, caller, account_id, id).await?;
        check_parent(
            backend,
            caller,
            account_id,
            &object.region_id,
            Some(id),
            &Id::new_validated(p).map_err(|e| invalid(&["parentId"], &e.to_string()))?,
            height,
        )
        .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("orientation")
        && let Some(q) = normalized_quaternion(&result, "orientation")
    {
        map.retain(|k, _| top(k) != "orientation");
        map.insert("orientation".to_owned(), q.clone());
        echo.insert("orientation".to_owned(), q);
    }
    map.insert("updatedAt".to_owned(), json!(now));
    match backend
        .update_object::<SceneObject>(caller, account_id, id, patch)
        .await
        .map_err(backend_set_error_value)?
    {
        Some(object) => Ok(jmap_server::serialize_value(object)
            .map_err(|e| jmap_server::server_fail_value_from_backend(&e))?),
        None => Ok(Value::Object(echo)),
    }
}

/// One §Destroying an Object: forbidden unless
/// [`SceneBackend::may_modify_object`]; the backend removes the
/// descendants.
async fn destroy_scene_object<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
) -> Result<(), Value> {
    fetch_modifiable(backend, caller, account_id, id).await?;
    backend
        .destroy_object::<SceneObject>(caller, account_id, id)
        .await
        .map_err(backend_set_error_value)
}