jmap_scene_server/ephemeral.rs
1//! Ephemeral Scene event subscription state (draft-atwood-jmap-scene-wss-00
2//! §SceneStreamEnable).
3//!
4//! A WebSocket transport keeps one [`SceneEphemeralSubscription`] per
5//! connection, starting from [`SceneEphemeralSubscription::default`]
6//! (inactive). Each `SceneStreamEnable` frame goes through
7//! [`SceneEphemeralSubscription::replace_with`], which validates the frame,
8//! normalizes it, and replaces the whole subscription. A
9//! `SceneStreamDisable` frame resets it to the default, which "MUST
10//! silently succeed if no ephemeral Scene subscription is currently
11//! active" (§SceneStreamDisable).
12//!
13//! # Active avatars are checked at delivery
14//!
15//! `regionIds` is kept as sent. An entry naming a region in which the user
16//! has no active avatar "produces no events but is retained in the
17//! subscription record" (§SceneStreamEnable, Semantics), so whether a
18//! region produces events is decided per event at delivery time, not here.
19//! That lets events "begin (or resume) without a new `SceneStreamEnable`"
20//! when the user enters or re-enters a listed region.
21//!
22//! # Delivery and relay
23//!
24//! Before sending an event to a connection, the transport asks
25//! [`should_deliver`] whether that connection may receive it. A
26//! `SceneInteractionEvent` frame a client sends goes through
27//! [`validate_interaction`] first; the transport silently discards it on
28//! `None` and otherwise relays the returned event, whose `userId` is the
29//! sender's, to every connection for which [`should_deliver`] holds
30//! (§Client-to-Server Submission).
31
32use jmap_scene_types::{
33 ObjectEventKind, SCENE_EVENT_TYPES, SceneAvatar, SceneEvent, SceneInteractionEvent,
34 SceneObject, SceneStreamEnable,
35};
36use jmap_types::{Id, JmapError};
37
38use crate::SceneBackend;
39use crate::helpers::is_visible;
40use crate::region::JMAP_CHAT_URI;
41
42/// Which regions a subscription covers.
43#[non_exhaustive]
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum RegionScope {
46 /// The frame sent `null` or left `regionIds` out. The subscription is
47 /// dynamic: every region in which the user has an active avatar,
48 /// adjusting as the user enters and leaves regions (§Subscription
49 /// Scope).
50 All,
51 /// The frame sent an explicit list, in the order sent. The
52 /// subscription is static: only these regions, and of them only those
53 /// with an active avatar of the user at delivery time. An empty list
54 /// covers no region.
55 Only(Vec<Id>),
56}
57
58impl RegionScope {
59 /// Whether `region_id` is in scope. Always `true` for
60 /// [`RegionScope::All`]; the active-avatar check is separate.
61 pub fn covers(&self, region_id: &Id) -> bool {
62 match self {
63 RegionScope::All => true,
64 RegionScope::Only(ids) => ids.contains(region_id),
65 }
66 }
67}
68
69/// The active filters of an enabled subscription.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct SceneStreamFilter {
72 region_ids: RegionScope,
73 event_types: Option<Vec<&'static str>>,
74}
75
76impl SceneStreamFilter {
77 /// The regions covered.
78 pub fn region_ids(&self) -> &RegionScope {
79 &self.region_ids
80 }
81
82 /// Whether `event_type` (an `@type` such as `"SceneAvatarEvent"`) was
83 /// requested. Always `true` when the frame's `eventTypes` was `null`.
84 pub fn includes(&self, event_type: &str) -> bool {
85 self.event_types
86 .as_ref()
87 .is_none_or(|types| types.contains(&event_type))
88 }
89}
90
91/// The ephemeral Scene subscription of one WebSocket connection.
92///
93/// The default value is inactive, which is the state before the first
94/// `SceneStreamEnable` and after a `SceneStreamDisable`.
95#[derive(Debug, Clone, PartialEq, Eq, Default)]
96pub struct SceneEphemeralSubscription {
97 active: Option<SceneStreamFilter>,
98}
99
100impl SceneEphemeralSubscription {
101 /// Replaces this subscription with the one in `enable`.
102 ///
103 /// The new frame "REPLACES any previous `SceneStreamEnable`
104 /// subscription in its entirety"; nothing is merged from it.
105 /// Unrecognized `eventTypes` values next to recognized ones are dropped
106 /// (draft-atwood-jmap-scene-wss-00 §SceneStreamEnable, Semantics).
107 ///
108 /// # Errors
109 ///
110 /// Returns an `invalidArguments` [`JmapError`] when `eventTypes` is an
111 /// empty array or holds only values outside [`SCENE_EVENT_TYPES`]. On
112 /// error `self` is unchanged, as the draft requires. The transport
113 /// sends the error as an RFC 8887 §4.3.4 `RequestError` frame whose
114 /// `type` is the full URN
115 /// `"urn:ietf:params:jmap:error:invalidArguments"` and whose
116 /// `requestId` is [`SceneStreamEnable::id`] when the client sent one;
117 /// the returned [`JmapError`] carries the short method-level name. The
118 /// connection stays open.
119 pub fn replace_with(&mut self, enable: &SceneStreamEnable) -> Result<(), JmapError> {
120 let event_types = match &enable.event_types {
121 None => None,
122 Some(requested) => {
123 let recognized: Vec<&'static str> = SCENE_EVENT_TYPES
124 .iter()
125 .copied()
126 .filter(|t| requested.iter().any(|r| r.as_str() == *t))
127 .collect();
128 if recognized.is_empty() {
129 return Err(JmapError::invalid_arguments(
130 "eventTypes contains no recognized values",
131 ));
132 }
133 Some(recognized)
134 }
135 };
136 self.active = Some(SceneStreamFilter {
137 region_ids: enable
138 .region_ids
139 .clone()
140 .map_or(RegionScope::All, RegionScope::Only),
141 event_types,
142 });
143 Ok(())
144 }
145
146 /// The active filters, or `None` when no subscription is enabled.
147 pub fn filter(&self) -> Option<&SceneStreamFilter> {
148 self.active.as_ref()
149 }
150}
151
152/// Whether `event` may be delivered on a connection whose subscription is
153/// `subscription`.
154///
155/// `caller` is the connection's authenticated identity, the recipient.
156/// The transport calls this at delivery time, for each event and
157/// connection. The originating user is never told of a suppression
158/// (draft-atwood-jmap-scene-wss-00 §Blocked-Sender Suppression).
159///
160/// Delivery needs an active subscription whose `eventTypes` includes the
161/// event's `@type`; an unrecognized `@type` is never delivered. All
162/// three events are per-region (§Event Summary): the event's region must
163/// be in the subscription's [`RegionScope`], the recipient must have
164/// access to it ([`SceneBackend::may_access_region`]) and an active
165/// avatar (`leftAt` `null`) in it. Then:
166///
167/// - `SceneAvatarEvent` needs the recipient to see the region's avatars
168/// ([`SceneBackend::may_see_region_avatars`]): a region bound to an
169/// E2EE VTCCall suppresses them toward non-participants
170/// (draft-atwood-jmap-scene-00 at 6bcd9d8, L2654), through
171/// `SceneStreamEnable` and `ChatStreamEnable` alike
172/// (draft-atwood-jmap-scene-wss-00 at 6bcd9d8, L1233-1234).
173/// - `SceneObjectEvent` and `SceneInteractionEvent` need the named object
174/// to pass the `SceneObject/get` visibility contract for the recipient
175/// ([`SceneBackend::is_object_visible`]; §Visibility Filtering). A
176/// `"destroyed"` event whose object the backend no longer returns has
177/// no record to check and needs region access only; any other event
178/// for an object the backend does not return is dropped.
179/// - When the recipient's account has `urn:ietf:params:jmap:chat`
180/// ([`SceneBackend::has_capability`]), the event is dropped if the
181/// recipient blocked its originating user
182/// ([`SceneBackend::is_user_blocked`]): the `userId` of a
183/// `SceneAvatarEvent` or `SceneInteractionEvent`, the `updatedBy` of a
184/// `SceneObjectEvent`. A `SceneObjectEvent` with `updatedBy` `null` is
185/// never suppressed. Without Chat no blocked-sender filtering applies.
186///
187/// `hosting_account_id` is the account the region, avatars and object are
188/// read from. It must be the event's `accountId`, "the id of the region's
189/// hosting account ... Other users reach that account as a shared
190/// account" (draft-atwood-jmap-scene-wss-00 at 33702a5, L178-181); an
191/// event whose `accountId` differs is not delivered, since "SceneRegion
192/// and SceneObject ids are unique only within an account".
193/// `recipient_account_id` is the recipient's own account: the Chat
194/// capability is checked there ("available for the receiving account",
195/// L791-792). `caller` is the recipient, so
196/// [`SceneBackend::is_user_blocked`] consults "the recipient's ChatContact
197/// records" (L793-795).
198///
199/// This function does not rate-limit; the §Rate Limiting SHOULD rules are
200/// the transport's or deployment's to apply.
201///
202/// # Errors
203///
204/// Returns the backend's error if reading the recipient's userId, its
205/// avatars, the object, region access, visibility, avatar visibility or
206/// block status fails.
207pub async fn should_deliver<B: SceneBackend>(
208 backend: &B,
209 caller: &B::CallerCtx,
210 hosting_account_id: &Id,
211 recipient_account_id: &Id,
212 subscription: &SceneEphemeralSubscription,
213 event: &SceneEvent,
214) -> Result<bool, B::Error> {
215 let Some(filter) = subscription.filter() else {
216 return Ok(false);
217 };
218 if !filter.includes(event.type_name()) {
219 return Ok(false);
220 }
221 let (event_account, region_id, object, origin) = match event {
222 SceneEvent::Avatar(e) => (&e.account_id, &e.region_id, None, Some(e.user_id.as_str())),
223 SceneEvent::Object(e) => (
224 &e.account_id,
225 &e.region_id,
226 Some((&e.object_id, e.event == ObjectEventKind::Destroyed)),
227 e.updated_by.as_deref(),
228 ),
229 SceneEvent::Interaction(e) => (
230 &e.account_id,
231 &e.region_id,
232 Some((&e.object_id, false)),
233 Some(e.user_id.as_str()),
234 ),
235 _ => return Ok(false),
236 };
237 if event_account != hosting_account_id
238 || !filter.region_ids().covers(region_id)
239 || !backend
240 .may_access_region(caller, hosting_account_id, region_id)
241 .await?
242 {
243 return Ok(false);
244 }
245 let me = backend.caller_user_id(caller, hosting_account_id).await?;
246 if !has_active_avatar(backend, caller, hosting_account_id, &me, region_id).await? {
247 return Ok(false);
248 }
249 if matches!(event, SceneEvent::Avatar(_))
250 && !backend
251 .may_see_region_avatars(caller, hosting_account_id, region_id)
252 .await?
253 {
254 return Ok(false);
255 }
256 if let Some((object_id, destroyed)) = object {
257 let visible = match fetch_object(backend, caller, hosting_account_id, object_id).await? {
258 Some(o) => {
259 o.region_id == *region_id
260 && is_visible(backend, caller, hosting_account_id, &o).await?
261 }
262 None => destroyed,
263 };
264 if !visible {
265 return Ok(false);
266 }
267 }
268 Ok(match origin {
269 Some(user) if backend.has_capability(caller, recipient_account_id, JMAP_CHAT_URI) => {
270 !backend.is_user_blocked(caller, user).await?
271 }
272 _ => true,
273 })
274}
275
276/// The `SceneInteractionEvent` to relay for a frame a client sent, or
277/// `None` to discard it (draft-atwood-jmap-scene-wss-00 §Client-to-Server
278/// Submission).
279///
280/// `caller` is the sending connection's authenticated identity and
281/// `account_id` the account the region and object are read from. "The
282/// server sets `userId` on the relayed event to the authenticated user's
283/// userId; a `userId` supplied in the frame is ignored", so the returned
284/// event is `event` with `userId` replaced by the caller's. The frame is
285/// relayable when its `accountId` is `account_id`, the caller has an
286/// active avatar (`leftAt` `null`) "in the region identified by
287/// `accountId` and `regionId`", and its `objectId` is a SceneObject in that
288/// region with `interactable` `true`. On `None` the server "discards the
289/// frame and returns no error to the sender"; on `Some` it relays the
290/// returned event, filtered per recipient by [`should_deliver`].
291///
292/// The opaque `data` is not inspected; size limits on it are
293/// deployment-defined, as is the §Rate Limiting SHOULD of five events per
294/// user per region per second.
295///
296/// # Errors
297///
298/// Returns the backend's error if reading the caller's userId, its
299/// avatars or the object fails.
300pub async fn validate_interaction<B: SceneBackend>(
301 backend: &B,
302 caller: &B::CallerCtx,
303 account_id: &Id,
304 event: &SceneInteractionEvent,
305) -> Result<Option<SceneInteractionEvent>, B::Error> {
306 if event.account_id != *account_id {
307 return Ok(None);
308 }
309 let me = backend.caller_user_id(caller, account_id).await?;
310 if !has_active_avatar(backend, caller, account_id, &me, &event.region_id).await? {
311 return Ok(None);
312 }
313 let interactable = fetch_object(backend, caller, account_id, &event.object_id)
314 .await?
315 .is_some_and(|o| o.region_id == event.region_id && o.interactable);
316 Ok(interactable.then(|| {
317 let mut relayed = event.clone();
318 relayed.user_id = me;
319 relayed
320 }))
321}
322
323/// `true` if `user_id` has an avatar in `region_id` with `leftAt` `null`.
324///
325/// ponytail: reads every SceneAvatar in the account; O(avatars) per
326/// check. Upgrade: a backend hook for the user's active avatar once a
327/// deployment needs it.
328pub(crate) async fn has_active_avatar<B: SceneBackend>(
329 backend: &B,
330 caller: &B::CallerCtx,
331 account_id: &Id,
332 user_id: &str,
333 region_id: &Id,
334) -> Result<bool, B::Error> {
335 let (avatars, _) = backend
336 .get_objects::<SceneAvatar>(caller, account_id, None, None)
337 .await?;
338 Ok(avatars
339 .iter()
340 .any(|a| a.region_id == *region_id && a.user_id == user_id && a.left_at.is_none()))
341}
342
343async fn fetch_object<B: SceneBackend>(
344 backend: &B,
345 caller: &B::CallerCtx,
346 account_id: &Id,
347 object_id: &Id,
348) -> Result<Option<SceneObject>, B::Error> {
349 let (objects, _) = backend
350 .get_objects::<SceneObject>(
351 caller,
352 account_id,
353 Some(std::slice::from_ref(object_id)),
354 None,
355 )
356 .await?;
357 Ok(objects.into_iter().next())
358}