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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! `SceneAvatar/*` method handlers (draft-atwood-jmap-scene-00 §`SceneAvatar`
//! Methods).
//!
//! `/get`, `/changes` and `/queryChanges` are the standard RFC 8620 §5.1,
//! §5.2 and §5.6 methods. `/set` applies §Entering a Region, §Updating
//! Avatar State, §Leaving a Region, §Re-entering a Region and §`SetError`
//! Conditions: create enters a region, an update that sets `leftAt`
//! leaves it (or, by a region owner or administrator, ejects another
//! user), an update that clears `leftAt` re-enters it, and destroy is
//! always `forbidden`. The one-record-per-region, auto-eject,
//! `maxAvatarsPerRegion` and `activeAvatarCount` rules are applied
//! atomically by [`SceneBackend::create_object`] and
//! [`SceneBackend::update_object`]. `/query` supplies the "Default sort:
//! `joinedAt` ascending" and the §Filter Validation `invalidArguments`
//! checks.

use std::collections::BTreeMap;

use jmap_scene_types::SceneAvatarComparator;
use jmap_scene_types::{SceneAvatar, SceneRegion};
use jmap_types::{Id, JmapError, PatchObject, SetObject};
use serde_json::{Map, Value, json};

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, normalized_quaternion, not_found, orientation_ok, reject_unsupported_sort,
};
use crate::helpers::{avatar_view, resolve_refs};
use crate::{AvatarView, SceneBackend};
use jmap_server::{
    HandlerOutput, SetError, SetErrorType, apply_patch_object, backend_set_error_value,
    now_utc_string, reject_server_set, server_fail_from_backend, server_fail_value_from_backend,
    strip_read_only_patch,
};

/// "The server sets `id`, `userId` (to the caller's `userId`), `position`
/// (to the region's `spawnPosition`), `orientation` (to the region's
/// `spawnOrientation`), `joinedAt`, and `leftAt` (to `null`)." A client
/// "MUST omit any properties that may only be set by the server" (RFC 8620
/// §5.3). These are the ones an update may still change, so they are not in
/// [`SceneAvatar::SERVER_SET`].
const SET_BY_SERVER_ON_CREATE: &[&str] = &["position", "orientation", "leftAt"];

/// What a region owner or administrator may patch on another user's
/// avatar: "An eject update patches only `leftAt`"
/// (draft-atwood-jmap-scene-00 §Avatar Permissions).
const EJECT_PROPERTIES: &[&str] = &["leftAt"];

/// `regionState` (jmap-chat-spec 93f2258): changed only by the region
/// owner, administrators and the server, and the other property a region
/// owner or administrator may patch on another user's avatar.
const REGION_STATE: &str = "regionState";

/// Handle `SceneAvatar/get` (draft-atwood-jmap-scene-00 §`SceneAvatar/get`):
/// standard RFC 8620 §5.1 `/get`, with an avatar in a region the caller
/// has no access to ([`SceneBackend::may_access_region`]), of a user the
/// caller blocked ([`SceneBackend::is_user_blocked`]) or in a region whose
/// avatars the caller may not see ([`SceneBackend::may_see_region_avatars`],
/// a region bound to an E2EE call) reported as `notFound` (§Region Access,
/// §Blocked-Contact Spatial Presence, §Security Considerations). Another
/// user's avatar that [`SceneBackend::avatar_view`] hides is `notFound`
/// too, and one it redacts is returned with the withheld properties
/// replaced or left out (jmap-chat-spec 93f2258 §Avatar Visibility).
///
/// # 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_avatar_get<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    handle_get_visible::<SceneAvatar, B>(backend, caller, args).await
}

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

/// Handle `SceneAvatar/query` (draft-atwood-jmap-scene-00
/// §`SceneAvatar/query`).
///
/// Supplies the "Default sort: `joinedAt` ascending" and refuses any other
/// sort property with `unsupportedSort`. Returns `invalidArguments` when
/// `regionId` is absent, 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::avatar_matches`] and
/// [`crate::query::compare_avatars`] 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 `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 `SceneAvatar` 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_avatar_query<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_query::<SceneAvatar, B>(backend, caller, prepare_query(args)?).await
}

/// Handle `SceneAvatar/queryChanges` (draft-atwood-jmap-scene-00
/// §`SceneAvatar/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
///   `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 `SceneAvatar` 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_avatar_query_changes<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_query_changes::<SceneAvatar, 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": "joinedAt", "isAscending": true }]),
        );
    }
    reject_unsupported_sort::<SceneAvatarComparator>(args.get("sort"))?;
    match args.get("filter") {
        None | Some(Value::Null) => {
            Err(JmapError::invalid_arguments("filter.regionId is required"))
        }
        Some(filter) => check_region_filter(filter, &|_| Ok(())),
    }?;
    Ok(args)
}

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

/// Handle `SceneAvatar/set` (draft-atwood-jmap-scene-00 §`SceneAvatar/set`).
///
/// Create enters a region: it validates the request, requires an
/// existing region the caller has access to
/// ([`SceneBackend::may_access_region`], else `invalidProperties` naming
/// `regionId`) and [`SceneBackend::may_enter_region`], fills the server-set properties
/// and hands the avatar to [`SceneBackend::create_object`]. The `created`
/// entry is the stored avatar, as in the draft's example response. Update
/// of an avatar in a region the caller has no access to
/// ([`SceneBackend::may_access_region`]) is `notFound`; otherwise it is
/// limited to the caller's own avatar, except that
/// [`SceneBackend::may_eject_avatar`] lets a region owner or administrator
/// set `leftAt` on another's. An update that sets `leftAt` to `null` on a
/// departed avatar re-enters its region: [`SceneBackend::may_enter_region`]
/// `false` is `forbidden`, and the server sets `joinedAt`, `position` and
/// `orientation`. A create or update that sets a
/// `displayName` from [`SceneBackend::reserved_display_names`] is
/// `forbidden` (§Avatar Identity and Impersonation). Destroy is always
/// `forbidden`.
///
/// `regionState` (jmap-chat-spec 93f2258) exists only on an account whose
/// capability has `supportsAvatarRegionState`; elsewhere it is
/// `invalidProperties`. A create stores `null` unless it supplies one, and
/// a non-null one is `forbidden` unless the caller is the region owner or
/// an admin ([`SceneBackend::may_update_region`]). The same rule governs
/// an update that changes it, the avatar's own user included; a region
/// owner or admin may combine it with an eject on another user's avatar
/// and patch nothing else.
///
/// A `regionId` that is a `#creationId` reference names a `SceneRegion`
/// 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 `regionId`.
///
/// # 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 update that fails on its own, and every destroy, is a
/// [`SetError`] in the response, not an `Err`.
pub async fn handle_scene_avatar_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::<SceneAvatar>(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?;
    set_destroy(&mut args, &mut acc)?;

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

/// What every `SceneAvatar/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
    /// [`AVATAR_ID_PROPERTIES`].
    created_ids: &'a BTreeMap<Id, Id>,
}

/// The `create` part of `SceneAvatar/set`: each entry enters a region.
/// 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, AVATAR_ID_PROPERTIES, ctx.created_ids) {
                acc.not_created
                    .insert(create_id, serde_json::Value::from(&*err));
                continue;
            }
            match enter_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 `SceneAvatar/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, AVATAR_ID_PROPERTIES, ctx.created_ids) {
                acc.not_updated
                    .insert(id_str, serde_json::Value::from(&*err));
                continue;
            }
            match update_avatar(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 `SceneAvatar/set`: every id is `forbidden`, after
/// the whole-request `invalidArguments` for a non-string element. Never
/// touches the backend.
fn set_destroy(args: &mut Map<String, Value>, acc: &mut SetAccumulators) -> Result<(), JmapError> {
    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)
                ))
            })?;
        // "Servers MUST return `forbidden` for destroy operations on
        // SceneAvatar."
        for id_str in ids {
            acc.not_destroyed.insert(
                id_str.to_owned(),
                forbidden("SceneAvatar records are not destroyed; set leftAt to leave"),
            );
        }
    }
    Ok(())
}

/// `true` if `s` has the RFC 8620 §1.4 `UTCDate` shape
/// `YYYY-MM-DDTHH:MM:SS[.fraction]Z`. Field ranges are not checked.
fn utc_date_shaped(s: &str) -> bool {
    let b = s.as_bytes();
    let digits =
        |r: std::ops::Range<usize>| b.get(r).is_some_and(|d| d.iter().all(u8::is_ascii_digit));
    let at = |i: usize, c: u8| b.get(i) == Some(&c);
    let fraction = match b.get(19..b.len().saturating_sub(1)) {
        Some([]) => true,
        Some([b'.', rest @ ..]) => !rest.is_empty() && rest.iter().all(u8::is_ascii_digit),
        _ => false,
    };
    digits(0..4)
        && at(4, b'-')
        && digits(5..7)
        && at(7, b'-')
        && digits(8..10)
        && at(10, b'T')
        && digits(11..13)
        && at(13, b':')
        && digits(14..16)
        && at(16, b':')
        && digits(17..19)
        && fraction
        && s.ends_with('Z')
}

/// The properties of avatar `m` that break an `invalidProperties` row
/// that needs no backend fact: `regionId` missing, a non-finite
/// `position`, an `orientation` that is not a unit quaternion, `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", optional("position", finite3));
    check("orientation", optional("orientation", orientation_ok));
    check("displayName", optional("displayName", Value::is_string));
    for key in ["visualRef", "visualType"] {
        check(key, optional(key, |v| v.is_null() || v.is_string()));
    }
    for key in ["worldState", "regionState"] {
        check(key, optional(key, |v| v.is_null() || v.is_object()));
    }
    // "`visualRef` is present but `visualType` is absent (or vice versa)
    // | Both must be present together or both absent."
    let present = |key: &str| m.get(key).is_some_and(|v| !v.is_null());
    if present("visualRef") != present("visualType") {
        bad.extend(["visualRef", "visualType"]);
    }
    bad
}

/// 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 is required, position finite, orientation a unit quaternion, visualRef and \
         visualType together",
    ))
}

/// Refuse a `displayName` in `m` that the backend reserves
/// (draft-atwood-jmap-scene-00 §Avatar Identity and Impersonation,
/// jmap-chat-spec 77c3474 L2776): "The server MAY maintain a list of
/// reserved display names ... and MAY reject `SceneAvatar/set` operations
/// that attempt to use a reserved name with a `SetError` of type
/// `forbidden`." This crate rejects them by choice.
async fn refuse_reserved_name<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    m: &Map<String, Value>,
) -> Result<(), Value> {
    let Some(name) = m.get("displayName").and_then(Value::as_str) else {
        return Ok(());
    };
    let reserved = backend
        .reserved_display_names(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;
    if reserved.iter().any(|r| r == name) {
        return Err(forbidden("This displayName is reserved."));
    }
    Ok(())
}

/// Whether the account's capability has `supportsAvatarRegionState`.
/// `regionState` is "Present only when the account capability
/// `supportsAvatarRegionState` is `true`" (jmap-chat-spec 93f2258); without
/// it the handlers refuse the property with `invalidProperties` rather than
/// keep it as an extension property any user could write.
async fn region_state_supported<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
) -> Result<bool, Value> {
    Ok(backend
        .scene_capability(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
        .supports_avatar_region_state)
}

/// `true` if the caller may change `regionState` on avatars of `region`:
/// "Only the region owner, users with deployment-defined administrative
/// privileges, and the server itself change it" (jmap-chat-spec 93f2258
/// §Avatar Permissions), which is the owner-or-admin rule of
/// [`SceneBackend::may_update_region`].
async fn may_manage_region_state<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    region: &SceneRegion,
) -> Result<bool, Value> {
    backend
        .may_update_region(caller, account_id, region)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))
}

fn present_in<'a>(keys: impl Iterator<Item = &'a str>, set: &[&str]) -> Vec<&'a str> {
    let mut found: Vec<&str> = keys.filter(|k| set.contains(k)).collect();
    found.sort_unstable();
    found.dedup();
    found
}

/// One §Entering a Region. The `Ok` value is the `created` entry: the
/// stored avatar.
async fn enter_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 SceneAvatar create must be a JSON object"));
    };

    let user_id = backend
        .caller_user_id(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;
    reject_create_server_set(&mut m, &user_id)?;
    refuse_malformed(malformed(&m))?;
    let region_state = region_state_supported(backend, caller, account_id).await?;
    if m.contains_key("regionState") && !region_state {
        return Err(invalid(
            &["regionState"],
            "regionState needs supportsAvatarRegionState",
        ));
    }
    let region = region_to_enter(backend, caller, account_id, &m).await?;
    refuse_reserved_name(backend, caller, account_id, &m).await?;
    if region_state {
        // "Default: `null`."
        m.entry("regionState").or_insert(Value::Null);
    }

    if !m.contains_key("displayName") {
        let name = backend
            .avatar_display_name(caller, account_id, &user_id)
            .await
            .map_err(|e| server_fail_value_from_backend(&e))?;
        m.insert("displayName".to_owned(), json!(name));
    }
    fill_entry_fields(&mut m, &region, &user_id);
    let mut avatar: SceneAvatar = serde_json::from_value(Value::Object(m))
        .map_err(|e| invalid(&[], &format!("invalid SceneAvatar: {e}")))?;
    let (_, stored) = backend
        .create_object(caller, account_id, create_id, move |id: &Id| {
            avatar.id = id.clone();
            avatar
        })
        .await
        .map_err(backend_set_error_value)?;
    jmap_server::serialize_value(stored)
        .map_err(|e| jmap_server::server_fail_value_from_backend(&e))
}

/// Refuse a create that sets a property the server sets, and take out
/// the `userId` that matches the caller's `user_id`.
///
/// "Caller is creating an avatar record for a different user":
/// `forbidden`. A matching `userId` is the value the server sets, so only
/// the other server-set properties are refused.
fn reject_create_server_set(m: &mut Map<String, Value>, user_id: &str) -> Result<(), Value> {
    if m.get("userId").is_some_and(|u| u.as_str() != Some(user_id)) {
        return Err(forbidden("Users MUST only create their own avatar."));
    }
    m.remove("userId");
    if let Some(e) = reject_server_set::<SceneAvatar>(m) {
        return Err(serde_json::Value::from(
            &e.with_description("these properties are set by the server"),
        ));
    }
    let fixed = present_in(m.keys().map(String::as_str), SET_BY_SERVER_ON_CREATE);
    if !fixed.is_empty() {
        return Err(invalid(&fixed, "these properties are set by the server"));
    }
    Ok(())
}

/// The region a create's `regionId` names, once the caller may enter it
/// and, for a non-null `regionState`, set that.
///
/// "The server MUST return `invalidProperties` naming `regionId` when
/// `regionId` does not reference an existing `SceneRegion`. The server
/// SHOULD return the same error when the caller has no access to the
/// region under its `accessPolicy`".
async fn region_to_enter<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    m: &Map<String, Value>,
) -> Result<SceneRegion, Value> {
    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");
    let region: SceneRegion = fetch_one(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());
    }
    // "User is banned or ejected with a cooldown period still active":
    // `forbidden`.
    if !backend
        .may_enter_region(caller, account_id, &region)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        return Err(forbidden("The caller may not enter this region."));
    }
    // "Caller supplies a non-null `regionState` and is neither the region
    // owner nor an administrator": `forbidden` (jmap-chat-spec 93f2258).
    if m.get("regionState").is_some_and(|v| !v.is_null())
        && !may_manage_region_state(backend, caller, account_id, &region).await?
    {
        return Err(forbidden(
            "regionState is kept by the region; only its owner or an admin may set it",
        ));
    }
    Ok(region)
}

/// Fill the properties the server sets on an avatar that enters `region`
/// as `user_id`.
///
/// "The server sets ... `position` (to the region's `spawnPosition`),
/// `orientation` (to the region's `spawnOrientation`)".
fn fill_entry_fields(m: &mut Map<String, Value>, region: &SceneRegion, user_id: &str) {
    m.insert("position".to_owned(), json!(region.spawn_position));
    m.insert("orientation".to_owned(), json!(region.spawn_orientation));
    if let Some(q) = normalized_quaternion(m, "orientation") {
        m.insert("orientation".to_owned(), q);
    }
    for key in ["visualRef", "visualType", "worldState"] {
        m.entry(key).or_insert(Value::Null);
    }
    // `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("userId".to_owned(), json!(user_id));
    m.insert("joinedAt".to_owned(), json!(now_utc_string()));
    m.insert("leftAt".to_owned(), Value::Null);
}

/// One §Updating Avatar State, §Leaving a Region or §Re-entering a Region.
/// `Ok` is the `updated` echo of the properties the server set (RFC 8620
/// §5.3: "any properties that changed in a way not explicitly requested by
/// the PatchObject"): `joinedAt`, `position` and `orientation` on
/// re-entry, the server-set `leftAt` on leave or eject, a normalized
/// `orientation` when the patch set one, else `null`.
/// Vendor extension properties stay patchable and the spec-defined immutable
/// or server-set ones do not, unless sent with their stored value (RFC 8620
/// §5.3) (§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_avatar<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 avatar = visible_avatar(backend, caller, account_id, id).await?;
    let Value::Object(mut result) = jmap_server::serialize_value(&avatar)
        .map_err(|e| jmap_server::server_fail_value_from_backend(&e))?
    else {
        unreachable!("a SceneAvatar serializes as a JSON object")
    };
    let patched = patched_properties(&patch, &result);
    let touched = |k: &str| patched.iter().any(|p| p == k);
    let left_to = patch.as_map().get("leftAt").cloned();
    check_avatar_update_permission(
        backend,
        caller,
        account_id,
        &avatar,
        &patched,
        left_to.as_ref(),
    )
    .await?;

    // After the ownership check, so another user's avatar is `forbidden`
    // whatever the patch holds (§Avatar Permissions).
    // §SceneAvatar: `id`, `userId` and `joinedAt` are server-set, `regionId`
    // immutable. A changed value is rejected, an identical one dropped (RFC
    // 8620 §5.3), so only the client's changes are applied.
    strip_read_only_patch::<SceneAvatar>(patch.as_map_mut(), Some(&result)).map_err(|e| {
        serde_json::Value::from(
            &(*e).with_description("these properties are immutable or set by the server"),
        )
    })?;

    // An empty patch, literal or left empty above, is a no-op success
    // (decision on JMAP-t8ej.25): nothing is written.
    if patch.as_map().is_empty() {
        return Ok(Value::Null);
    }
    let mut echo = Map::new();
    if left_to.as_ref().is_some_and(Value::is_null) {
        let set = reentry_fields(backend, caller, account_id, &avatar, &patched).await?;
        patch.as_map_mut().extend(set.clone());
        echo = set;
    } else if touched("leftAt") {
        let now = leave_stamp(&avatar, left_to.as_ref())?;
        patch.as_map_mut().insert("leftAt".to_owned(), now.clone());
        echo.insert("leftAt".to_owned(), now);
    }

    apply_patch_object(&mut result, patch.as_map()).map_err(|e| {
        serde_json::Value::from(
            &SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
        )
    })?;
    refuse_malformed(malformed(&result))?;
    if touched("displayName") {
        refuse_reserved_name(backend, caller, account_id, &result).await?;
    }

    if touched("orientation")
        && let Some(q) = normalized_quaternion(&result, "orientation")
    {
        let map = patch.as_map_mut();
        map.retain(|k, _| top_level(k) != "orientation");
        map.insert("orientation".to_owned(), q.clone());
        echo.insert("orientation".to_owned(), q);
    }
    match backend
        .update_object::<SceneAvatar>(caller, account_id, id, patch)
        .await
        .map_err(backend_set_error_value)?
    {
        Some(avatar) => Ok(jmap_server::serialize_value(avatar)
            .map_err(|e| jmap_server::server_fail_value_from_backend(&e))?),
        None if echo.is_empty() => Ok(Value::Null),
        None => Ok(Value::Object(echo)),
    }
}

/// The top-level property a patch key `k` names.
fn top_level(k: &str) -> String {
    k.split('/').next().unwrap_or(k).to_owned()
}

/// Load the avatar `id` for an update. "The avatar id does not exist or
/// caller lacks access to the containing region": `notFound`.
///
/// "A hidden avatar is treated as if it did not exist: ... a
/// `SceneAvatar/set` update of it returns `notFound`" (jmap-chat-spec
/// 93f2258 §Avatar Visibility).
async fn visible_avatar<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
) -> Result<SceneAvatar, Value> {
    let avatar: SceneAvatar = fetch_one(backend, caller, account_id, id)
        .await?
        .ok_or_else(not_found)?;
    if !backend
        .may_access_region(caller, account_id, &avatar.region_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        return Err(not_found());
    }
    if avatar_view(backend, caller, account_id, &avatar)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
        == AvatarView::Hidden
    {
        return Err(not_found());
    }
    Ok(avatar)
}

/// The top-level properties `patch` changes on the avatar stored as
/// `stored`.
///
/// A server-set or immutable property sent with its stored value is not
/// a change (RFC 8620 §5.3), so it does not count against an eject
/// ("an eject update patches no other property", 77c3474 L2524). A
/// changed one stays, so another user's patch with it is `forbidden`.
fn patched_properties(patch: &PatchObject, stored: &Map<String, Value>) -> Vec<String> {
    let read_only =
        |k: &str| SceneAvatar::SERVER_SET.contains(&k) || SceneAvatar::IMMUTABLE.contains(&k);
    patch
        .as_map()
        .iter()
        .filter(|(k, v)| !(read_only(k) && stored.get(*k).unwrap_or(&Value::Null) == *v))
        .map(|(k, _)| top_level(k))
        .collect()
}

/// The owner-or-admin rule for `regionState` on `avatar`'s region, asked
/// only when a patch changes it.
async fn manages_region_state<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    avatar: &SceneAvatar,
) -> Result<bool, Value> {
    let region: SceneRegion = fetch_one(backend, caller, account_id, &avatar.region_id)
        .await?
        .ok_or_else(not_found)?;
    may_manage_region_state(backend, caller, account_id, &region).await
}

/// Check that the caller may make the changes `patched` (the properties
/// [`patched_properties`] found, `left_to` the patched `leftAt`) to
/// `avatar`: `regionState` needs the capability and the owner-or-admin
/// rule, and another user's avatar takes only an eject or a `regionState`
/// change.
async fn check_avatar_update_permission<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    avatar: &SceneAvatar,
    patched: &[String],
    left_to: Option<&Value>,
) -> Result<(), Value> {
    let touched = |k: &str| patched.iter().any(|p| p == k);
    let touches_region_state = touched(REGION_STATE);
    if touches_region_state && !region_state_supported(backend, caller, account_id).await? {
        return Err(invalid(
            &[REGION_STATE],
            "regionState needs supportsAvatarRegionState",
        ));
    }

    let user_id = backend
        .caller_user_id(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;
    if avatar.user_id != user_id {
        // "Users MUST NOT update other users' avatars. Exception: region
        // owners and administrators may set `leftAt` on another user's
        // avatar to eject them, and may change its `regionState`; such an
        // update patches no other property" (jmap-chat-spec 93f2258).
        // Re-entry (`leftAt: null`) is not an eject.
        let touches_left = touched("leftAt");
        let shape = (touches_left || touches_region_state)
            && patched
                .iter()
                .all(|p| EJECT_PROPERTIES.contains(&&**p) || p == REGION_STATE)
            && (!touches_left || left_to.is_some_and(|v| !v.is_null()));
        let allowed = shape
            && (!touches_left
                || backend
                    .may_eject_avatar(caller, account_id, avatar)
                    .await
                    .map_err(|e| server_fail_value_from_backend(&e))?)
            && (!touches_region_state
                || manages_region_state(backend, caller, account_id, avatar).await?);
        if !allowed {
            return Err(forbidden("Users MUST NOT update other users' avatars."));
        }
    } else if touches_region_state
        && !manages_region_state(backend, caller, account_id, avatar).await?
    {
        // "The avatar's user cannot change `regionState` unless that user
        // is also the region owner or an administrator; the server returns
        // `forbidden`."
        return Err(forbidden(
            "regionState is kept by the region; only its owner or an admin may change it",
        ));
    }
    Ok(())
}

/// The properties the server sets when `avatar` re-enters its region
/// (`patched` are the properties the patch changes).
///
/// §Re-entering a Region: "A user who has left (has a non-null
/// `leftAt`) re-enters the same region by updating their existing
/// `SceneAvatar` record to set `leftAt` to `null`." "The server sets
/// `joinedAt` to the current time, `position` to the region's
/// `spawnPosition`, and `orientation` to the region's
/// `spawnOrientation`."
async fn reentry_fields<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    avatar: &SceneAvatar,
    patched: &[String],
) -> Result<Map<String, Value>, Value> {
    if avatar.left_at.is_none() {
        return Err(invalid(
            &["leftAt"],
            "the avatar is present; only a departed avatar re-enters",
        ));
    }
    let spawn = present_in(
        patched.iter().map(String::as_str),
        &["position", "orientation"],
    );
    if !spawn.is_empty() {
        return Err(invalid(
            &spawn,
            "re-entry sets position and orientation from the region's spawn point",
        ));
    }
    // The caller passed `may_access_region` above, so lost access is
    // already `notFound`, as is a region that no longer exists. A
    // ban or cooldown is `forbidden`, as for a create.
    let region: SceneRegion = fetch_one(backend, caller, account_id, &avatar.region_id)
        .await?
        .ok_or_else(not_found)?;
    if !backend
        .may_enter_region(caller, account_id, &region)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        return Err(forbidden("The caller may not enter this region."));
    }
    let mut set = Map::new();
    set.insert("joinedAt".to_owned(), json!(now_utc_string()));
    set.insert("position".to_owned(), json!(region.spawn_position));
    set.insert("orientation".to_owned(), json!(region.spawn_orientation));
    if let Some(q) = normalized_quaternion(&set, "orientation") {
        set.insert("orientation".to_owned(), q);
    }
    Ok(set)
}

/// The `leftAt` the server records when `avatar` leaves or is ejected,
/// `left_to` being the patched value.
///
/// "The server MUST return `invalidProperties` naming `leftAt` if the
/// avatar has already left (`leftAt` is non-null)." §Leaving a Region:
/// "The server records its own current time as `leftAt`; the value the
/// client supplies only signals the intent to leave." RFC 8620 §5.3
/// echoes a value "changed in a way not explicitly requested by the
/// client".
fn leave_stamp(avatar: &SceneAvatar, left_to: Option<&Value>) -> Result<Value, Value> {
    if avatar.left_at.is_some() {
        return Err(invalid(&["leftAt"], "the avatar has already left"));
    }
    if !left_to.and_then(Value::as_str).is_some_and(utc_date_shaped) {
        return Err(invalid(&["leftAt"], "leftAt must be a UTCDate or null"));
    }
    Ok(json!(now_utc_string()))
}

#[cfg(test)]
mod tests {
    use super::utc_date_shaped;

    #[test]
    fn utc_date_shape() {
        // Oracle: RFC 8620 §1.4 UTCDate: a Date "where the "time-offset"
        // component MUST be "Z""; draft L2089 "2026-06-05T15:45:00Z".
        assert!(utc_date_shaped("2026-06-05T15:45:00Z"));
        assert!(utc_date_shaped("2026-06-05T15:45:00.123Z"));
        for bad in [
            "",
            "2026-06-05T15:45:00",
            "2026-06-05T15:45:00+00:00",
            "2026-06-05 15:45:00Z",
            "2026-06-05T15:45:00.Z",
            "yesterday",
        ] {
            assert!(!utc_date_shaped(bad), "{bad}");
        }
    }
}