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
//! `SceneAsset/*` method handlers (draft-atwood-jmap-scene-00 §`SceneAsset`
//! Methods).
//!
//! `/get`, `/changes` and `/queryChanges` are the standard RFC 8620 §5.1,
//! §5.2 and §5.6 methods. `/set` applies §`SceneAsset/set` and its §`SetError`
//! Conditions: required `blobId` and `mediaType`, the server-set
//! properties (including `ownerId`, the caller's `userId`), the media-type
//! rule with glTF as the mandatory-to-implement format,
//! `invalidProperties` for a missing blob, `overQuota` above `maxAssetSizeBytes`, the immutable
//! properties on update and the owner-or-admin rule on update and destroy.
//! `/query` supplies the "Default sort: `createdAt` descending" before the
//! standard RFC 8620 §5.5 handling.
//!
//! Every handler first returns `unknownMethod` when the account's
//! [`SceneCapability::supports_scene_asset`] is `false`: "When `false`, a
//! call to any `SceneAsset` method returns an `unknownMethod` error"
//! (§Account-Level Capability Object).

use jmap_scene_types::SceneAssetComparator;
use jmap_scene_types::{SceneAsset, SceneCapability};
use jmap_types::{Id, JmapError, PatchObject};
use serde_json::{Map, Value, json};

use crate::SceneBackend;
use crate::helpers::{
    SetAccumulators, default_sort, enforce_max_objects_in_set, extract_account_id, fetch_one,
    finalize_set_response, forbidden, invalid, not_found, over_quota, reject_unsupported_sort,
};
use jmap_server::{
    HandlerOutput, SetError, SetErrorType, backend_set_error_value, now_utc_string,
    reject_server_set, server_fail_from_backend, server_fail_value_from_backend,
    strip_read_only_patch,
};

/// The mandatory-to-implement visual asset media type: "The IANA media
/// type `model/gltf-binary` (.glb) MUST be listed in
/// `supportedVisualTypes`" (draft-atwood-jmap-scene-00 §Preferred Asset
/// Format).
///
/// `SceneAsset/set` accepts it even when the backend's
/// [`SceneBackend::scene_capability`] leaves it out.
pub const GLTF_BINARY: &str = "model/gltf-binary";

/// The optional `String|null` properties: "Optional: `name` (String),
/// `assetUri` (String), `sha256` (String)."
const OPTIONAL_STRINGS: &[&str] = &["name", "assetUri", "sha256"];

/// Capability gate shared by the `SceneAsset/*` handlers.
///
/// Returns `unknownMethod` (RFC 8620 §3.6.2) when
/// [`SceneBackend::scene_capability`] reports `supportsSceneAsset: false`
/// for the request's account. A missing, malformed or unknown `accountId`
/// passes through so the handler reports `invalidArguments` or
/// `accountNotFound` itself.
async fn ensure_scene_asset_supported<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: &Value,
) -> Result<(), JmapError> {
    let Some(account_id) = args
        .get("accountId")
        .and_then(Value::as_str)
        .and_then(|s| Id::new_validated(s).ok())
    else {
        return Ok(());
    };
    let exists = backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;
    if !exists {
        return Ok(());
    }
    let cap = backend
        .scene_capability(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;
    if !cap.supports_scene_asset {
        return Err(JmapError::unknown_method());
    }
    Ok(())
}

/// Handle `SceneAsset/get` (draft-atwood-jmap-scene-00 §`SceneAsset/get`):
/// standard RFC 8620 §5.1 `/get`.
///
/// # Errors
///
/// Returns a method-level [`JmapError`]:
///
/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
///   when `ids` or `properties` is malformed;
/// - `unknownMethod` when the account's [`SceneBackend::scene_capability`]
///   has `supportsSceneAsset: false`;
/// - `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_asset_get<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    ensure_scene_asset_supported(backend, caller, &args).await?;
    jmap_server::handle_get::<SceneAsset, B>(backend, caller, args).await
}

/// Handle `SceneAsset/changes` (draft-atwood-jmap-scene-00
/// §`SceneAsset/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;
/// - `unknownMethod` when the account's [`SceneBackend::scene_capability`]
///   has `supportsSceneAsset: false`;
/// - `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_asset_changes<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    ensure_scene_asset_supported(backend, caller, &args).await?;
    jmap_server::handle_changes::<SceneAsset, B>(backend, caller, args, &[]).await
}

/// Handle `SceneAsset/query` (draft-atwood-jmap-scene-00
/// §`SceneAsset/query`).
///
/// Supplies the "Default sort: `createdAt` descending" and refuses any
/// other sort property with `unsupportedSort`; an unknown filter property
/// is `unsupportedFilter`. The backend evaluates the filter;
/// [`crate::query::asset_matches`] and [`crate::query::compare_assets`]
/// 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;
/// - `unknownMethod` when the account's [`SceneBackend::scene_capability`]
///   has `supportsSceneAsset: false`;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `unsupportedFilter` when the filter does not decode as a `SceneAsset` 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_asset_query<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    ensure_scene_asset_supported(backend, caller, &args).await?;
    jmap_server::handle_query::<SceneAsset, B>(backend, caller, prepare_query(args)?).await
}

/// Handle `SceneAsset/queryChanges` (draft-atwood-jmap-scene-00
/// §`SceneAsset/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;
/// - `unknownMethod` when the account's [`SceneBackend::scene_capability`]
///   has `supportsSceneAsset: false`;
/// - `accountNotFound` when the backend does not know `accountId`;
/// - `unsupportedFilter` when the filter does not decode as a `SceneAsset` 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_asset_query_changes<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    ensure_scene_asset_supported(backend, caller, &args).await?;
    jmap_server::handle_query_changes::<SceneAsset, 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::<SceneAssetComparator>(args.get("sort"))?;
    Ok(args)
}

/// Handle `SceneAsset/set` (draft-atwood-jmap-scene-00 §`SceneAsset/set`).
///
/// Create validates the arguments, looks the blob up with
/// [`SceneBackend::blob_size`], applies `maxAssetSizeBytes` and hands the
/// asset to [`SceneBackend::create_object`]. Update and destroy require
/// [`SceneBackend::may_modify_asset`].
///
/// A `#creationId` `blobId` needs the request's creation ids, which this
/// function does not take: [`register_scene_handlers`](crate::register_scene_handlers)
/// resolves them (RFC 8620 §5.3).
///
/// # 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;
/// - `unknownMethod` when the account's [`SceneBackend::scene_capability`]
///   has `supportsSceneAsset: false`;
/// - `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_asset_set<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
) -> Result<HandlerOutput, JmapError> {
    scene_asset_set(backend, caller, &std::collections::BTreeMap::new(), args).await
}

/// [`handle_scene_asset_set`], with a `#creationId` `blobId` naming a blob
/// created earlier in the request resolved against `created_ids`
/// ([`jmap_server::CallContext::created_ids`]; RFC 8620 §5.3,
/// draft-ietf-jmap-blobext-03 §8). An unknown reference is not a valid Id,
/// as before: `invalidProperties` naming `blobId`.
pub(crate) async fn scene_asset_set<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    created_ids: &std::collections::BTreeMap<jmap_types::Id, jmap_types::Id>,
    mut args: Value,
) -> Result<HandlerOutput, JmapError> {
    jmap_server::resolve_blob_refs(&mut args, &["blobId"], created_ids);
    ensure_scene_asset_supported(backend, caller, &args).await?;
    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::<SceneAsset>(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();
    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, SceneAsset>(backend, caller, &account_id, old_state, mutated, acc)
        .await
}

/// What every `SceneAsset/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 `SceneAsset/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, obj) in create_map {
            match create_asset(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 `SceneAsset/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, 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;
                }
            };
            match update_asset(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 `SceneAsset/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_asset(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)
}

/// `true` if the server accepts `media_type` for a `SceneAsset`: "MUST be a
/// value present in the account-level `supportedVisualTypes` or a
/// recognized audio/image type", with [`GLTF_BINARY`] always supported.
///
/// Media type names are case-insensitive (RFC 6838 §4.2).
///
/// ponytail: "recognized audio/image type" is read as any media type whose
/// top-level type is `audio` or `image` (RFC 6838 §4.2.3, §4.2.2), without
/// consulting a registry. A deployment that restricts audio and image
/// subtypes registers its own `SceneAsset/set` handler.
fn media_type_supported(cap: &SceneCapability, media_type: &str) -> bool {
    let listed = |t: &str| t.eq_ignore_ascii_case(media_type);
    let audio_or_image = media_type.split_once('/').is_some_and(|(top, sub)| {
        !sub.is_empty() && (top.eq_ignore_ascii_case("audio") || top.eq_ignore_ascii_case("image"))
    });
    listed(GLTF_BINARY) || cap.supported_visual_types.iter().any(|t| listed(t)) || audio_or_image
}

/// `sha256`: "SHA-256 hash of the asset file, lowercase hexadecimal."
fn is_lowercase_sha256(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// The offending names among `mediaType` and the optional string
/// properties present in `m`, for an `invalidProperties` `SetError`.
///
/// A `mediaType` key must hold a string the server supports. The optional
/// properties must be a string or `null`, and `sha256` lowercase hex.
fn malformed<'a>(m: &'a Map<String, Value>, cap: &SceneCapability) -> Vec<&'a str> {
    let mut bad = Vec::new();
    if let Some((key, v)) = m.get_key_value("mediaType")
        && !v.as_str().is_some_and(|t| media_type_supported(cap, t))
    {
        bad.push(key.as_str());
    }
    for (key, v) in m
        .iter()
        .filter(|(k, _)| OPTIONAL_STRINGS.contains(&k.as_str()))
    {
        let ok = match v {
            Value::Null => true,
            Value::String(s) => match key.as_str() {
                "sha256" => is_lowercase_sha256(s),
                // draft-atwood-jmap-updates-00 §7.1: an RFC 3986 URI.
                "assetUri" => jmap_types::uri::check_uri(s).is_ok(),
                _ => true,
            },
            _ => false,
        };
        if !ok {
            bad.push(key.as_str());
        }
    }
    bad
}

async fn capability<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
) -> Result<SceneCapability, Value> {
    backend
        .scene_capability(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))
}

/// One §`SceneAsset/set` create. The `Ok` value is the `created` entry: the
/// server-set `id`, `accountId`, `ownerId` (the caller's
/// [`SceneBackend::caller_user_id`]), `size` and `createdAt`.
async fn create_asset<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 SceneAsset create must be a JSON object"));
    };

    // "The server sets `id`, `accountId`, `ownerId`, `size`, and
    // `createdAt`."
    if let Some(e) = reject_server_set::<SceneAsset>(&m) {
        return Err(serde_json::Value::from(
            &e.with_description("these properties are set by the server"),
        ));
    }

    let cap = capability(backend, caller, account_id).await?;
    // "`invalidProperties` (`properties` lists each offending property) --
    // missing or malformed fields": `blobId` and `mediaType` are required.
    let mut bad = malformed(&m, &cap);
    if !m.contains_key("mediaType") {
        bad.push("mediaType");
    }
    let blob_id = m
        .get("blobId")
        .and_then(Value::as_str)
        .and_then(|s| Id::new_validated(s).ok());
    if blob_id.is_none() {
        bad.push("blobId");
    }
    let Some(blob_id) = blob_id.filter(|_| bad.is_empty()) else {
        bad.sort_unstable();
        return Err(invalid(
            &bad,
            "blobId and mediaType are required; mediaType must be supported; \
             name, assetUri and sha256 must be strings or null, assetUri an RFC 3986 URI, \
             sha256 lowercase hex",
        ));
    };

    // "The server MUST reject the create if `blobId` does not reference a
    // valid blob"; the `invalidProperties` table covers that case "whether
    // the blobId is malformed or well-formed but absent".
    let size = backend
        .blob_size(caller, account_id, &blob_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
        .ok_or_else(|| invalid(&["blobId"], "blobId does not reference an uploaded blob"))?;
    // "The server MUST return `overQuota` if the asset exceeds
    // `maxAssetSizeBytes`."
    if cap.max_asset_size_bytes.is_some_and(|max| size > max) {
        return Err(over_quota("the asset exceeds maxAssetSizeBytes"));
    }
    let owner_id = backend
        .caller_user_id(caller, account_id)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;

    for key in OPTIONAL_STRINGS {
        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("accountId".to_owned(), json!(account_id));
    m.insert("ownerId".to_owned(), json!(owner_id));
    m.insert("size".to_owned(), json!(size));
    m.insert("createdAt".to_owned(), json!(now_utc_string()));
    let mut asset: SceneAsset = serde_json::from_value(Value::Object(m))
        .map_err(|e| invalid(&[], &format!("invalid SceneAsset: {e}")))?;
    let (id, stored) = backend
        .create_object(caller, account_id, create_id, move |id: &Id| {
            asset.id = id.clone();
            asset
        })
        .await
        .map_err(backend_set_error_value)?;
    Ok(json!({
        "id": id,
        "accountId": stored.account_id,
        "ownerId": stored.owner_id,
        "size": stored.size,
        "createdAt": stored.created_at,
    }))
}

/// Fetch asset `id` and require [`SceneBackend::may_modify_asset`]: "Caller
/// does not own the asset and lacks admin privileges" is `forbidden`, "The
/// asset id does not exist" is `notFound`.
async fn fetch_modifiable<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
) -> Result<SceneAsset, Value> {
    let asset: SceneAsset = fetch_one(backend, caller, account_id, id)
        .await?
        .ok_or_else(not_found)?;
    if !backend
        .may_modify_asset(caller, account_id, &asset)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
    {
        return Err(forbidden(
            "only the asset owner or an admin may modify this asset",
        ));
    }
    Ok(asset)
}

/// One §`SceneAsset/set` update. `Ok` is the `updated` echo.
/// 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_asset<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 asset = fetch_modifiable(backend, caller, account_id, id).await?;
    let Value::Object(stored) = jmap_server::serialize_value(&asset)
        .map_err(|e| jmap_server::server_fail_value_from_backend(&e))?
    else {
        unreachable!("a SceneAsset serializes as a JSON object")
    };

    // 77c3474 L912: "Attempting to change `id`, `accountId`, `ownerId`,
    // `blobId`, `mediaType`, `size`, or `createdAt`" is `invalidProperties`;
    // an identical value is dropped (RFC 8620 §5.3). Vendor extension
    // properties stay patchable (§Extension Properties in Updates).
    strip_read_only_patch::<SceneAsset>(patch.as_map_mut(), Some(&stored)).map_err(|e| {
        serde_json::Value::from(&(*e).with_description("these properties cannot be changed"))
    })?;
    // 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 cap = capability(backend, caller, account_id).await?;
    let bad = malformed(patch.as_map(), &cap);
    if !bad.is_empty() {
        return Err(invalid(
            &bad,
            "name, assetUri and sha256 must be strings or null, assetUri an RFC 3986 URI, \
             sha256 lowercase hex",
        ));
    }

    match backend
        .update_object::<SceneAsset>(caller, account_id, id, patch)
        .await
        .map_err(backend_set_error_value)?
    {
        Some(asset) => Ok(jmap_server::serialize_value(asset)
            .map_err(|e| jmap_server::server_fail_value_from_backend(&e))?),
        None => Ok(Value::Null),
    }
}

/// One §`SceneAsset/set` destroy, under the "Same permission model as
/// update".
async fn destroy_asset<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::<SceneAsset>(caller, account_id, id)
        .await
        .map_err(backend_set_error_value)
}