Skip to main content

jmap_scene_server/
lib.rs

1//! JMAP Scene method handlers (draft-atwood-jmap-scene-00).
2//!
3//! # Usage
4//!
5//! Implement [`SceneBackend`] for your storage layer, then call
6//! [`register_scene_handlers`] to wire the method names into a
7//! [`jmap_server::Dispatcher`]:
8//!
9//! ```rust,no_run
10//! # use std::sync::Arc;
11//! # use jmap_scene_server::{SceneBackend, register_scene_handlers};
12//! # use jmap_server::Dispatcher;
13//! # fn example<B: SceneBackend<CallerCtx = ()> + 'static>(backend: B) {
14//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
15//! register_scene_handlers(&mut dispatcher, Arc::new(backend));
16//! # }
17//! ```
18//!
19//! # Scope
20//!
21//! The `SceneAsset/*` methods (draft §SceneAsset Methods): standard
22//! `/get`, `/changes` and `/queryChanges`; `/set` with the create, update
23//! and destroy SetError conditions, glTF (`model/gltf-binary`) as the
24//! mandatory-to-implement format and the `maxAssetSizeBytes` quota; and
25//! `/query` with the draft's default sort.
26//!
27//! The `SceneRegion/*` methods (draft §SceneRegion Methods): `/set` with
28//! the create, update and destroy SetError conditions, `mayCreateRegion`,
29//! `maxRegionsPerAccount`, the binding checks through
30//! [`SceneBackend::region_binding`] and the destroy cascade; and `/query`
31//! with the draft's default sort and `accessPolicy` filter check.
32//!
33//! The `SceneObject/*` methods (draft §SceneObject Methods): `/set` with
34//! the create, update and destroy SetError conditions, `mayCreateObject`,
35//! `maxObjectsPerRegion`, a region-scoped acyclic scene graph at most 16
36//! levels deep, [`SceneBackend::may_modify_object`] and the recursive
37//! destroy; and `/query` with the draft's default sort, the §Filter
38//! Validation checks and the `withinRadius` and `withinBounds` spatial
39//! filters over region-local positions.
40//!
41//! `SceneObject/interact` (draft §SceneObject/interact): each interaction
42//! is checked for its properties (`invalidProperties`), region access,
43//! existence and the visibility set (`notFound`), an active avatar and
44//! `interactable` (`forbidden`), then passed to
45//! [`SceneBackend::accept_interaction`], which may refuse it with
46//! `rateLimit` and otherwise delivers the `SceneInteractionEvent`.
47//!
48//! The `SceneAvatar/*` methods (draft §SceneAvatar Methods): `/set` create
49//! enters a region (one avatar record per user and region, `alreadyExists`
50//! with `existingId` when the user has a present or departed record there,
51//! auto-eject from another region, `maxAvatarsPerRegion` and
52//! [`SceneBackend::may_enter_region`]), an update that sets `leftAt` leaves
53//! it or, through [`SceneBackend::may_eject_avatar`], ejects another user,
54//! an update that sets `leftAt` to `null` re-enters it at the spawn point,
55//! destroy is `forbidden`, a `displayName` from
56//! [`SceneBackend::reserved_display_names`] is `forbidden`, and the
57//! backend keeps `activeAvatarCount`; and
58//! `/query` with the draft's default sort and §Filter Validation.
59//!
60//! Visibility (draft §Visibility Contract, §Region Access, §Blocked-Contact
61//! Spatial Presence): `/get` of SceneRegion, SceneObject and SceneAvatar
62//! reports a record in a region the caller has no access to
63//! ([`SceneBackend::may_access_region`]), an object outside the caller's
64//! visibility set ([`SceneBackend::is_object_visible`]), an avatar of a
65//! user the caller blocked ([`SceneBackend::is_user_blocked`]) and an
66//! avatar in a region bound to an E2EE call the caller is not in
67//! ([`SceneBackend::may_see_region_avatars`]) in `notFound`, like a
68//! missing id; `SceneObject/set` refuses an update or
69//! destroy of a hidden object with `notFound`. The backend omits the same
70//! records from `/query` and `/queryChanges`. `activeAvatarCount` is the
71//! true count, blocked users included, as the draft says deployments
72//! "SHOULD prefer".
73//!
74//! Push (draft §Push Notifications): [`SCENE_DATA_TYPES`], the four types
75//! that participate in RFC 8620 state changes, and [`push_urgency`], the
76//! §Push Urgency recommendation for a `StateChange`, including the
77//! §Interaction with Chat Push rule that an avatar enter or leave already
78//! announced by a bound Chat's push is not sent at `normal` or higher.
79//!
80//! Ephemeral subscriptions (draft-atwood-jmap-scene-wss-00
81//! §SceneStreamEnable): [`SceneEphemeralSubscription`] holds the per-connection
82//! subscription a `SceneStreamEnable` frame replaces in its entirety, with
83//! a dynamic ([`RegionScope::All`]) or static ([`RegionScope::Only`])
84//! region scope and the `invalidArguments` check on `eventTypes`;
85//! [`should_deliver`], the per-event delivery check (active avatar,
86//! visibility, E2EE-call avatar suppression, blocked-sender suppression);
87//! and [`validate_interaction`],
88//! the check on a client-sent `SceneInteractionEvent` before relay.
89//!
90//! The crate depends on RFC 8620 only; Chat and VTC bindings live in
91//! separate binding crates, which implement
92//! [`SceneBackend::has_capability`] and [`SceneBackend::region_binding`].
93//!
94//! # `memory` feature (reference implementation)
95//!
96//! Enable the `memory` feature to expose `memory::MemoryBackend`, the
97//! in-memory reference implementation of [`SceneBackend`] used by this
98//! crate's tests. **Not production.** Its API may break in any minor
99//! release while the crate is pre-1.0.
100
101#![forbid(unsafe_code)]
102
103use std::sync::Arc;
104
105use jmap_server::{CallContext, ClosureHandler, Dispatcher, HandlerFuture, JmapHandler};
106
107mod asset;
108mod avatar;
109mod backend;
110mod ephemeral;
111mod helpers;
112mod interact;
113/// In-memory reference implementation of [`SceneBackend`].
114///
115/// Gated behind `feature = "memory"`. Not production.
116#[cfg(feature = "memory")]
117pub mod memory;
118mod object;
119mod push;
120pub mod query;
121mod region;
122
123pub use asset::{
124    GLTF_BINARY, handle_scene_asset_changes, handle_scene_asset_get, handle_scene_asset_query,
125    handle_scene_asset_query_changes, handle_scene_asset_set,
126};
127pub use avatar::{
128    handle_scene_avatar_changes, handle_scene_avatar_get, handle_scene_avatar_query,
129    handle_scene_avatar_query_changes, handle_scene_avatar_set,
130};
131pub use backend::{BindingProperty, BindingTarget, SceneBackend};
132pub use ephemeral::{
133    RegionScope, SceneEphemeralSubscription, SceneStreamFilter, should_deliver,
134    validate_interaction,
135};
136pub use interact::handle_scene_object_interact;
137pub use object::{
138    handle_scene_object_changes, handle_scene_object_get, handle_scene_object_query,
139    handle_scene_object_query_changes, handle_scene_object_set,
140};
141pub use push::{SCENE_DATA_TYPES, SceneEvent, Urgency, push_urgency};
142pub use region::{
143    handle_scene_region_changes, handle_scene_region_get, handle_scene_region_query,
144    handle_scene_region_query_changes, handle_scene_region_set,
145};
146
147/// Capability URI for `urn:ietf:params:jmap:scene`.
148pub use jmap_scene_types::JMAP_SCENE_URI;
149
150/// Register the `SceneAsset/*`, `SceneRegion/*`, `SceneObject/*` and
151/// `SceneAvatar/*` method handlers with `dispatcher`.
152///
153/// After this call the dispatcher handles `/get`, `/changes`, `/set`,
154/// `/query` and `/queryChanges` of `SceneAsset`, `SceneRegion`,
155/// `SceneObject` and `SceneAvatar`, and `SceneObject/interact`.
156/// [`Dispatcher::register`] silently replaces an existing handler of the
157/// same name, so register overrides afterwards.
158///
159/// This only wires dispatch. The consumer advertises [`JMAP_SCENE_URI`] in
160/// its Session capabilities, with the same account-level object
161/// [`SceneBackend::scene_capability`] returns.
162pub fn register_scene_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
163where
164    B: SceneBackend + 'static,
165{
166    // `ids` marks a `/set` handler that resolves `#creationId` references
167    // against `CallContext::created_ids` (RFC 8620 §5.3).
168    macro_rules! reg {
169        ($method:expr, $handler:ident) => {{
170            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
171                Arc::clone(&backend),
172                move |b: Arc<B>, cx: CallContext<B::CallerCtx>| {
173                    let CallContext {
174                        args: a,
175                        caller: ctx,
176                        ..
177                    } = cx;
178                    Box::pin(async move { $handler(&*b, &ctx, a).await }) as HandlerFuture
179                },
180            ));
181            dispatcher.register($method, h);
182        }};
183        ($method:expr, $handler:ident, ids) => {{
184            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
185                Arc::clone(&backend),
186                move |b: Arc<B>, cx: CallContext<B::CallerCtx>| {
187                    let CallContext {
188                        args: a,
189                        caller: ctx,
190                        created_ids: ids,
191                        ..
192                    } = cx;
193                    Box::pin(async move { $handler(&*b, &ctx, &ids, a).await }) as HandlerFuture
194                },
195            ));
196            dispatcher.register($method, h);
197        }};
198    }
199
200    reg!("SceneAsset/get", handle_scene_asset_get);
201    reg!("SceneAsset/changes", handle_scene_asset_changes);
202    reg!("SceneAsset/set", handle_scene_asset_set);
203    reg!("SceneAsset/query", handle_scene_asset_query);
204    reg!("SceneAsset/queryChanges", handle_scene_asset_query_changes);
205    reg!("SceneRegion/get", handle_scene_region_get);
206    reg!("SceneRegion/changes", handle_scene_region_changes);
207    reg!("SceneRegion/set", handle_scene_region_set, ids);
208    reg!("SceneRegion/query", handle_scene_region_query);
209    reg!(
210        "SceneRegion/queryChanges",
211        handle_scene_region_query_changes
212    );
213    reg!("SceneObject/get", handle_scene_object_get);
214    reg!("SceneObject/changes", handle_scene_object_changes);
215    reg!("SceneObject/set", handle_scene_object_set, ids);
216    reg!("SceneObject/query", handle_scene_object_query);
217    reg!(
218        "SceneObject/queryChanges",
219        handle_scene_object_query_changes
220    );
221    reg!("SceneObject/interact", handle_scene_object_interact);
222    reg!("SceneAvatar/get", handle_scene_avatar_get);
223    reg!("SceneAvatar/changes", handle_scene_avatar_changes);
224    reg!("SceneAvatar/set", handle_scene_avatar_set, ids);
225    reg!("SceneAvatar/query", handle_scene_avatar_query);
226    reg!(
227        "SceneAvatar/queryChanges",
228        handle_scene_avatar_query_changes
229    );
230}