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 suggestion 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#![cfg_attr(docsrs, feature(doc_cfg))]
102#![forbid(unsafe_code)]
103
104use std::sync::Arc;
105
106use jmap_server::{
107 CallContext, ClosureHandler, ConditionalBackend, Dispatcher, HandlerFuture, JmapHandler,
108 RegistrationError, SetSupport,
109};
110
111mod asset;
112mod avatar;
113mod backend;
114mod ephemeral;
115mod helpers;
116mod history;
117mod interact;
118/// In-memory reference implementation of [`SceneBackend`].
119///
120/// Gated behind `feature = "memory"`. Not production.
121#[cfg(feature = "memory")]
122pub mod memory;
123mod object;
124mod push;
125pub mod query;
126mod region;
127
128use asset::scene_asset_set;
129pub use asset::{
130 GLTF_BINARY, handle_scene_asset_changes, handle_scene_asset_get, handle_scene_asset_query,
131 handle_scene_asset_query_changes, handle_scene_asset_set,
132};
133pub use avatar::{
134 handle_scene_avatar_changes, handle_scene_avatar_get, handle_scene_avatar_query,
135 handle_scene_avatar_query_changes, handle_scene_avatar_set,
136};
137pub use backend::{BindingProperty, BindingTarget, SceneBackend};
138pub use ephemeral::{
139 RegionScope, SceneEphemeralSubscription, SceneStreamFilter, should_deliver,
140 validate_interaction,
141};
142pub use history::register_scene_handlers_with_history;
143pub use interact::handle_scene_object_interact;
144pub use object::{
145 handle_scene_object_changes, handle_scene_object_get, handle_scene_object_query,
146 handle_scene_object_query_changes, handle_scene_object_set,
147};
148pub use push::{SCENE_DATA_TYPES, SceneEvent, Urgency, push_urgency};
149pub use region::{
150 handle_scene_region_changes, handle_scene_region_get, handle_scene_region_query,
151 handle_scene_region_query_changes, handle_scene_region_set,
152};
153
154/// Capability URI for `urn:ietf:params:jmap:scene`.
155pub use jmap_scene_types::JMAP_SCENE_URI;
156
157/// Register the `SceneAsset/*`, `SceneRegion/*`, `SceneObject/*` and
158/// `SceneAvatar/*` method handlers with `dispatcher`.
159///
160/// After this call the dispatcher handles `/get`, `/changes`, `/set`,
161/// `/query` and `/queryChanges` of `SceneAsset`, `SceneRegion`,
162/// `SceneObject` and `SceneAvatar`, and `SceneObject/interact`.
163/// [`Dispatcher::register`] silently replaces an existing handler of the
164/// same name, so register overrides afterwards.
165///
166/// This only wires dispatch. The consumer advertises [`JMAP_SCENE_URI`] in
167/// its Session capabilities, with the same account-level object
168/// [`SceneBackend::scene_capability`] returns.
169pub fn register_scene_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
170where
171 B: SceneBackend + 'static,
172{
173 // `ids` marks a `/set` handler that resolves `#creationId` references
174 // against `CallContext::created_ids` (RFC 8620 §5.3).
175 macro_rules! reg {
176 ($method:expr, $handler:ident) => {{
177 let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
178 Arc::clone(&backend),
179 move |b: Arc<B>, cx: CallContext<B::CallerCtx>| {
180 let CallContext {
181 args: a,
182 caller: ctx,
183 ..
184 } = cx;
185 Box::pin(async move { $handler(&*b, &ctx, a).await }) as HandlerFuture
186 },
187 ));
188 dispatcher.register($method, h);
189 }};
190 ($method:expr, $handler:ident, ids) => {{
191 let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
192 Arc::clone(&backend),
193 move |b: Arc<B>, cx: CallContext<B::CallerCtx>| {
194 let CallContext {
195 args: a,
196 caller: ctx,
197 created_ids: ids,
198 ..
199 } = cx;
200 Box::pin(async move { $handler(&*b, &ctx, &ids, a).await }) as HandlerFuture
201 },
202 ));
203 dispatcher.register($method, h);
204 }};
205 }
206
207 reg!("SceneAsset/get", handle_scene_asset_get);
208 reg!("SceneAsset/changes", handle_scene_asset_changes);
209 reg!("SceneAsset/set", scene_asset_set, ids);
210 reg!("SceneAsset/query", handle_scene_asset_query);
211 reg!("SceneAsset/queryChanges", handle_scene_asset_query_changes);
212 reg!("SceneRegion/get", handle_scene_region_get);
213 reg!("SceneRegion/changes", handle_scene_region_changes);
214 reg!("SceneRegion/set", handle_scene_region_set, ids);
215 reg!("SceneRegion/query", handle_scene_region_query);
216 reg!(
217 "SceneRegion/queryChanges",
218 handle_scene_region_query_changes
219 );
220 reg!("SceneObject/get", handle_scene_object_get);
221 reg!("SceneObject/changes", handle_scene_object_changes);
222 reg!("SceneObject/set", handle_scene_object_set, ids);
223 reg!("SceneObject/query", handle_scene_object_query);
224 reg!(
225 "SceneObject/queryChanges",
226 handle_scene_object_query_changes
227 );
228 reg!("SceneObject/interact", handle_scene_object_interact);
229 reg!("SceneAvatar/get", handle_scene_avatar_get);
230 reg!("SceneAvatar/changes", handle_scene_avatar_changes);
231 reg!("SceneAvatar/set", handle_scene_avatar_set, ids);
232 reg!("SceneAvatar/query", handle_scene_avatar_query);
233 reg!(
234 "SceneAvatar/queryChanges",
235 handle_scene_avatar_query_changes
236 );
237}
238
239/// Opt this crate's registered Foo/set methods in to
240/// draft-ietf-jmap-conditional-02 (`ifUnchangedBy` and `atomic`;
241/// docs/design/DECISIONS.md decisions 1 and 17).
242///
243/// Call after [`register_scene_handlers`]. Attaches [`SetSupport`] to each
244/// of `SceneAsset/set`, `SceneRegion/set`, `SceneObject/set`, `SceneAvatar/set` that is registered, and skips the rest; no handler is
245/// re-registered.
246///
247/// The dispatcher reads preconditions through each type's `/get` and runs
248/// each call in the scope `backend` opens
249/// ([`ConditionalBackend::begin_set`]).
250/// Under `atomic` that scope must check `maxAvatarsPerRegion` on the final
251/// state; the memory backend does.
252/// Advertise `urn:ietf:params:jmap:conditional` only once
253/// [`Dispatcher::conditional_ready`] is true for the whole dispatcher.
254pub fn register_scene_conditional<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
255where
256 B: SceneBackend + ConditionalBackend + 'static,
257{
258 fn attach<C: Clone + Send + 'static>(
259 dispatcher: &mut Dispatcher<C>,
260 method: &str,
261 support: SetSupport<C>,
262 ) {
263 match dispatcher.attach_set_support(method, support) {
264 Ok(()) | Err(RegistrationError::NotRegistered(_)) => {}
265 Err(e) => unreachable!("{method} pairs with its own data type: {e}"),
266 }
267 }
268 macro_rules! attach {
269 ($($t:ident),*) => {$(
270 attach(
271 dispatcher,
272 concat!(stringify!($t), "/set"),
273 SetSupport::new::<jmap_scene_types::$t, B>(Arc::clone(&backend)),
274 );
275 )*};
276 }
277 attach!(SceneAsset, SceneRegion, SceneObject, SceneAvatar);
278}