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//! `SceneRegion/broadcast` (draft §`SceneRegion/broadcast`, jmap-chat-spec
49//! 93f2258), on accounts whose capability has `supportsRegionBroadcast`
50//! (otherwise `unknownMethod`): each region event is checked for its
51//! properties (`invalidProperties`), region access (`notFound`) and the
52//! owner-or-admin rule ([`SceneBackend::may_update_region`], `forbidden`),
53//! then passed to [`SceneBackend::accept_region_event`], which may refuse
54//! it with `rateLimit` and otherwise delivers the `SceneRegionEvent`.
55//!
56//! The `SceneAvatar/*` methods (draft §`SceneAvatar` Methods): `/set` create
57//! enters a region (one avatar record per user and region, `alreadyExists`
58//! with `existingId` when the user has a present or departed record there,
59//! auto-eject from another region, `maxAvatarsPerRegion` and
60//! [`SceneBackend::may_enter_region`]), an update that sets `leftAt` leaves
61//! it or, through [`SceneBackend::may_eject_avatar`], ejects another user,
62//! an update that sets `leftAt` to `null` re-enters it at the spawn point,
63//! destroy is `forbidden`, a `displayName` from
64//! [`SceneBackend::reserved_display_names`] is `forbidden`, and the
65//! backend keeps `activeAvatarCount`; and
66//! `/query` with the draft's default sort and §Filter Validation.
67//!
68//! Visibility (draft §Visibility Contract, §Region Access, §Blocked-Contact
69//! Spatial Presence): `/get` of `SceneRegion`, `SceneObject` and `SceneAvatar`
70//! reports a record in a region the caller has no access to
71//! ([`SceneBackend::may_access_region`]), an object outside the caller's
72//! visibility set ([`SceneBackend::is_object_visible`]), an avatar of a
73//! user the caller blocked ([`SceneBackend::is_user_blocked`]) and an
74//! avatar in a region bound to an E2EE call the caller is not in
75//! ([`SceneBackend::may_see_region_avatars`]) in `notFound`, like a
76//! missing id; `SceneObject/set` refuses an update or
77//! destroy of a hidden object with `notFound`. The backend omits the same
78//! records from `/query` and `/queryChanges`. `activeAvatarCount` is the
79//! true count, blocked users included, as the draft says deployments
80//! "SHOULD prefer".
81//!
82//! Avatar Visibility (draft §Avatar Visibility, jmap-chat-spec 93f2258):
83//! [`SceneBackend::avatar_view`] hides another user's avatar from the
84//! caller ([`AvatarView::Hidden`]: `notFound` from `SceneAvatar/get` and
85//! from a `SceneAvatar/set` update, no `SceneAvatarEvent`) or withholds
86//! its `position`, `orientation` and `worldState` / `regionState` keys
87//! ([`AvatarRedaction`]). The default shows everything. The backend applies
88//! the same view in `/query` and, when it hides to protect information, in
89//! `SceneAvatar/changes`.
90//!
91//! Push (draft §Push Notifications): [`SCENE_DATA_TYPES`], the four types
92//! that participate in RFC 8620 state changes, and [`push_urgency`], the
93//! §Push Urgency suggestion for a `StateChange`, including the
94//! §Interaction with Chat Push rule that an avatar enter or leave already
95//! announced by a bound Chat's push is not sent at `normal` or higher.
96//!
97//! Ephemeral subscriptions (draft-atwood-jmap-scene-wss-00
98//! §`SceneStreamEnable`): [`SceneEphemeralSubscription`] holds the per-connection
99//! subscription a `SceneStreamEnable` frame replaces in its entirety, with
100//! a dynamic ([`RegionScope::All`]) or static ([`RegionScope::Only`])
101//! region scope and the `invalidArguments` check on `eventTypes`;
102//! [`should_deliver`], the per-event delivery check (active avatar,
103//! visibility, E2EE-call avatar suppression, blocked-sender suppression);
104//! and [`validate_interaction`],
105//! the check on a client-sent `SceneInteractionEvent` before relay.
106//!
107//! The crate depends on RFC 8620 only; Chat and VTC bindings live in
108//! separate binding crates, which implement
109//! [`SceneBackend::has_capability`] and [`SceneBackend::region_binding`].
110//!
111//! # `websocket` feature (ephemeral events over RFC 8887)
112//!
113//! Enable `websocket` for the `websocket` module: the `jmap-websocket`
114//! extension handler for `SceneStreamEnable` / `SceneStreamDisable` and
115//! client-sent `SceneInteractionEvent` (draft-atwood-jmap-scene-wss-00) and
116//! the server-wide hub the deployment publishes events to. Off by default, so
117//! a deployment without the WebSocket transport does not pull in
118//! `jmap-websocket`.
119//!
120//! # `memory` feature (reference implementation)
121//!
122//! Enable the `memory` feature to expose `memory::MemoryBackend`, the
123//! in-memory reference implementation of [`SceneBackend`] used by this
124//! crate's tests. **Not production.** Its API may break in any minor
125//! release while the crate is pre-1.0.
126
127#![cfg_attr(docsrs, feature(doc_cfg))]
128#![forbid(unsafe_code)]
129
130use std::sync::Arc;
131
132use jmap_server::{
133    CallContext, ClosureHandler, ConditionalBackend, Dispatcher, HandlerFuture, JmapHandler,
134    RegistrationError, SetSupport,
135};
136
137mod asset;
138mod avatar;
139mod backend;
140mod broadcast;
141mod ephemeral;
142mod helpers;
143mod history;
144mod interact;
145/// In-memory reference implementation of [`SceneBackend`].
146///
147/// Gated behind `feature = "memory"`. Not production.
148#[cfg(feature = "memory")]
149pub mod memory;
150mod object;
151mod push;
152pub mod query;
153mod region;
154#[cfg(feature = "websocket")]
155pub mod websocket;
156
157use asset::scene_asset_set;
158pub use asset::{
159    GLTF_BINARY, handle_scene_asset_changes, handle_scene_asset_get, handle_scene_asset_query,
160    handle_scene_asset_query_changes, handle_scene_asset_set,
161};
162pub use avatar::{
163    handle_scene_avatar_changes, handle_scene_avatar_get, handle_scene_avatar_query,
164    handle_scene_avatar_query_changes, handle_scene_avatar_set,
165};
166pub use backend::{AvatarRedaction, AvatarView, BindingProperty, BindingTarget, SceneBackend};
167pub use broadcast::handle_scene_region_broadcast;
168pub use ephemeral::{
169    RegionScope, SceneEphemeralSubscription, SceneStreamFilter, should_deliver,
170    validate_interaction,
171};
172pub use history::register_scene_handlers_with_history;
173pub use interact::handle_scene_object_interact;
174pub use object::{
175    handle_scene_object_changes, handle_scene_object_get, handle_scene_object_query,
176    handle_scene_object_query_changes, handle_scene_object_set,
177};
178pub use push::{SCENE_DATA_TYPES, SceneEvent, Urgency, push_urgency};
179pub use region::{
180    handle_scene_region_changes, handle_scene_region_get, handle_scene_region_query,
181    handle_scene_region_query_changes, handle_scene_region_set,
182};
183
184/// Capability URI for `urn:ietf:params:jmap:scene`.
185pub use jmap_scene_types::JMAP_SCENE_URI;
186
187/// Register the `SceneAsset/*`, `SceneRegion/*`, `SceneObject/*` and
188/// `SceneAvatar/*` method handlers with `dispatcher`.
189///
190/// After this call the dispatcher handles `/get`, `/changes`, `/set`,
191/// `/query` and `/queryChanges` of `SceneAsset`, `SceneRegion`,
192/// `SceneObject` and `SceneAvatar`, `SceneObject/interact` and
193/// `SceneRegion/broadcast` (which answers `unknownMethod` on an account
194/// without `supportsRegionBroadcast`).
195/// [`Dispatcher::register`] silently replaces an existing handler of the
196/// same name, so register overrides afterwards.
197///
198/// This only wires dispatch. The consumer advertises [`JMAP_SCENE_URI`] in
199/// its Session capabilities, with the same account-level object
200/// [`SceneBackend::scene_capability`] returns.
201pub fn register_scene_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
202where
203    B: SceneBackend + 'static,
204{
205    // `ids` marks a `/set` handler that resolves `#creationId` references
206    // against `CallContext::created_ids` (RFC 8620 §5.3).
207    macro_rules! reg {
208        ($method:expr, $handler:ident) => {{
209            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
210                Arc::clone(&backend),
211                move |b: Arc<B>, cx: CallContext<B::CallerCtx>| {
212                    let CallContext {
213                        args: a,
214                        caller: ctx,
215                        ..
216                    } = cx;
217                    Box::pin(async move { $handler(&*b, &ctx, a).await }) as HandlerFuture
218                },
219            ));
220            dispatcher.register($method, h);
221        }};
222        ($method:expr, $handler:ident, ids) => {{
223            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
224                Arc::clone(&backend),
225                move |b: Arc<B>, cx: CallContext<B::CallerCtx>| {
226                    let CallContext {
227                        args: a,
228                        caller: ctx,
229                        created_ids: ids,
230                        ..
231                    } = cx;
232                    Box::pin(async move { $handler(&*b, &ctx, &ids, a).await }) as HandlerFuture
233                },
234            ));
235            dispatcher.register($method, h);
236        }};
237    }
238
239    reg!("SceneAsset/get", handle_scene_asset_get);
240    reg!("SceneAsset/changes", handle_scene_asset_changes);
241    reg!("SceneAsset/set", scene_asset_set, ids);
242    reg!("SceneAsset/query", handle_scene_asset_query);
243    reg!("SceneAsset/queryChanges", handle_scene_asset_query_changes);
244    reg!("SceneRegion/get", handle_scene_region_get);
245    reg!("SceneRegion/changes", handle_scene_region_changes);
246    reg!("SceneRegion/set", handle_scene_region_set, ids);
247    reg!("SceneRegion/query", handle_scene_region_query);
248    reg!(
249        "SceneRegion/queryChanges",
250        handle_scene_region_query_changes
251    );
252    reg!("SceneObject/get", handle_scene_object_get);
253    reg!("SceneObject/changes", handle_scene_object_changes);
254    reg!("SceneObject/set", handle_scene_object_set, ids);
255    reg!("SceneObject/query", handle_scene_object_query);
256    reg!(
257        "SceneObject/queryChanges",
258        handle_scene_object_query_changes
259    );
260    reg!("SceneObject/interact", handle_scene_object_interact);
261    reg!("SceneRegion/broadcast", handle_scene_region_broadcast);
262    reg!("SceneAvatar/get", handle_scene_avatar_get);
263    reg!("SceneAvatar/changes", handle_scene_avatar_changes);
264    reg!("SceneAvatar/set", handle_scene_avatar_set, ids);
265    reg!("SceneAvatar/query", handle_scene_avatar_query);
266    reg!(
267        "SceneAvatar/queryChanges",
268        handle_scene_avatar_query_changes
269    );
270}
271
272/// Opt this crate's registered Foo/set methods in to
273/// draft-ietf-jmap-conditional-02 (`ifUnchangedBy` and `atomic`;
274/// docs/design/DECISIONS.md decisions 1 and 17).
275///
276/// Call after [`register_scene_handlers`]. Attaches [`SetSupport`] to each
277/// of `SceneAsset/set`, `SceneRegion/set`, `SceneObject/set`, `SceneAvatar/set` that is registered, and skips the rest; no handler is
278/// re-registered.
279///
280/// The dispatcher reads preconditions through each type's `/get` and runs
281/// each call in the scope `backend` opens
282/// ([`ConditionalBackend::begin_set`]).
283/// Under `atomic` that scope must check `maxAvatarsPerRegion` on the final
284/// state; the memory backend does.
285/// Advertise `urn:ietf:params:jmap:conditional` only once
286/// [`Dispatcher::conditional_ready`] is true for the whole dispatcher.
287pub fn register_scene_conditional<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
288where
289    B: SceneBackend + ConditionalBackend + 'static,
290{
291    fn attach<C: Clone + Send + 'static>(
292        dispatcher: &mut Dispatcher<C>,
293        method: &str,
294        support: SetSupport<C>,
295    ) {
296        match dispatcher.attach_set_support(method, support) {
297            Ok(()) | Err(RegistrationError::NotRegistered(_)) => {}
298            Err(e) => unreachable!("{method} pairs with its own data type: {e}"),
299        }
300    }
301    macro_rules! attach {
302        ($($t:ident),*) => {$(
303            attach(
304                dispatcher,
305                concat!(stringify!($t), "/set"),
306                SetSupport::new::<jmap_scene_types::$t, B>(Arc::clone(&backend)),
307            );
308        )*};
309    }
310    attach!(SceneAsset, SceneRegion, SceneObject, SceneAvatar);
311}