jmap_scene_server/websocket.rs
1//! `SceneStreamEnable` / `SceneStreamDisable`, the Scene ephemeral events
2//! they turn on, and client-sent `SceneInteractionEvent` frames, as a
3//! [`jmap_websocket`] extension (draft-atwood-jmap-scene-wss-00).
4//!
5//! - The deployment keeps one [`SceneEventHub`] and publishes every Scene
6//! event to it with [`SceneEventHub::publish`]: avatar and object
7//! events, the interactions accepted by `SceneObject/interact`, and the
8//! region events accepted by `SceneRegion/broadcast` or originated by
9//! the server. Every event carries `accountId`, "the id of the region's hosting
10//! account" (§Ephemeral Event Types).
11//! - For each WebSocket connection it builds a [`SceneStreamHandler`] with
12//! the connection's caller and the caller's own account, and registers
13//! it with
14//! [`Connection::with_extension`](jmap_websocket::server::Connection::with_extension)
15//! next to advertising `urn:ietf:params:jmap:scene:websocket`.
16//!
17//! For each published event the handler asks [`should_deliver`], at
18//! delivery time, with the event's `accountId` as the hosting account,
19//! applies the draft's rate limit on object updates
20//! ([`SceneStreamLimits`]), and queues the frame with
21//! [`ExtensionSender::try_send`], which drops it if the client is too
22//! slow.
23//!
24//! A `SceneInteractionEvent` frame from the client goes through
25//! [`validate_interaction`] and the hub's per-user rate limit, and is then
26//! published to the hub for every connection, the sender's included, to
27//! decide on. A frame that fails any check, or does not parse, is
28//! discarded: "the server discards the frame and returns no error to the
29//! sender" (§Submitting Interactions).
30//!
31//! `ChatStreamEnable` with `"scene"` in `dataTypes` is a second path to
32//! the same events (§Interoperability with JMAP Chat WebSocket). The Chat
33//! handler switches it through the [`SceneChatAlias`] of this handler
34//! (`jmap-chat-scene-server` wires the two), so both paths are decided
35//! here, once per event: the union is delivered without duplicates.
36//!
37//! Observer subscriptions (`observe: true`, jmap-chat-spec 93f2258) are
38//! recognized when [`SceneBackend::supports_observe`] is `true`, the
39//! server advertising `{"supportsObserve": true}`; otherwise `observe` is
40//! ignored, as the draft requires. An observing `SceneStreamEnable` needs
41//! `regionIds` (`invalidArguments` without), looks each listed region up
42//! in [`SceneBackend::observer_accounts`], and fails with a `forbidden`
43//! `RequestError` whose `regionIds` member lists the accessible regions
44//! that refuse observers (`allowObservers` `false`, or
45//! [`SceneBackend::may_observe_region`]), leaving the subscription as it
46//! was.
47//!
48//! For `observerCount` the handler reports to
49//! [`SceneBackend::set_observing`] every `(account, region)` pair its
50//! observer subscription covers: each listed region in each of the
51//! [`SceneBackend::observer_accounts`] when the subscription is enabled,
52//! whether or not the user has access to it then, and, from the first
53//! event for it that reaches the handler, each listed region of any
54//! other account ("delivery is not limited to those accounts"). It
55//! releases a pair when a later `SceneStreamEnable`, `SceneStreamDisable`
56//! or the connection's close stops covering it. Which of the reported
57//! users count (access, `allowObservers`, policy, an active avatar) the
58//! backend decides, as delivery does, so the count follows delivery.
59//!
60//! Credential expiry is the deployment's (§Credential Expiry): the
61//! handler does not know when credentials expire; close the connection
62//! then.
63//!
64//! ```
65//! use std::sync::Arc;
66//! use jmap_scene_server::SceneBackend;
67//! use jmap_scene_server::websocket::{SceneEventHub, SceneStreamHandler};
68//! use jmap_types::Id;
69//! use jmap_websocket::server::{Connection, DispatcherHandler};
70//!
71//! /// Called once per accepted connection; `hub` is the server's.
72//! fn wire<B: SceneBackend<CallerCtx = ()>>(
73//! backend: Arc<B>,
74//! hub: &SceneEventHub,
75//! connection: Connection<DispatcherHandler<()>>,
76//! ) -> Connection<DispatcherHandler<()>> {
77//! let scene = SceneStreamHandler::new(backend, (), Id::from("acct-alice"), hub);
78//! connection.with_extension(scene)
79//! }
80//! ```
81
82mod limit;
83
84use std::fmt;
85use std::sync::atomic::{AtomicBool, Ordering};
86use std::sync::{Arc, Mutex, PoisonError};
87use std::time::Duration;
88
89use jmap_scene_types::{ObjectEventKind, SceneEvent, SceneInteractionEvent, SceneStreamEnable};
90use jmap_types::{Id, JmapError};
91use jmap_websocket::server::{ExtensionHandler, ExtensionMessage, ExtensionSender};
92use tokio::sync::broadcast;
93use tokio::task::JoinHandle;
94use tokio::time::Instant;
95
96use crate::SceneBackend;
97use crate::SceneStreamFilter;
98use crate::ephemeral::{
99 SceneEphemeralSubscription, observer_regions, should_deliver, validate_interaction,
100};
101use limit::{Limiter, Window, sleep_until};
102
103/// The `@type` of the message that enables ephemeral Scene events.
104const ENABLE: &str = "SceneStreamEnable";
105/// The `@type` of the message that disables them.
106const DISABLE: &str = "SceneStreamDisable";
107/// The `@type` of a client-submitted interaction.
108const INTERACTION: &str = "SceneInteractionEvent";
109
110/// Interaction limiter key: (`accountId`, `regionId`, `userId`).
111type InteractionKey = (Id, Id, String);
112
113/// The server-wide source of Scene ephemeral events: the deployment
114/// publishes each event here, and every connection's
115/// [`SceneStreamHandler`] decides whether its client receives it.
116///
117/// The hub also holds the per-user interaction rate limit, so that it
118/// counts a user's frames over all of that user's connections:
119/// "`SceneInteractionEvent`: no more than five events per user per region
120/// per second. Frames above this rate MAY be silently dropped"
121/// (§Rate Limiting). Frames over it are dropped.
122///
123/// The hub keeps the last `capacity` events for connections that fall
124/// behind; a connection that falls further behind skips the events it
125/// missed. Clones share the hub.
126#[derive(Clone)]
127pub struct SceneEventHub {
128 tx: broadcast::Sender<SceneEvent>,
129 interactions: Arc<Mutex<Limiter<InteractionKey, ()>>>,
130}
131
132impl fmt::Debug for SceneEventHub {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 f.debug_struct("SceneEventHub")
135 .field("connections", &self.tx.receiver_count())
136 .finish_non_exhaustive()
137 }
138}
139
140impl SceneEventHub {
141 /// A hub that buffers `capacity` events per slow connection, with the
142 /// draft's interaction limit of five per user per region per second.
143 ///
144 /// # Panics
145 ///
146 /// If `capacity` is 0.
147 pub fn new(capacity: usize) -> Self {
148 Self::with_interaction_window(capacity, Some(Duration::from_secs(1)))
149 }
150
151 /// As [`new`](Self::new), with at most five client-submitted
152 /// interactions per user per region in `window`; `None` for no
153 /// limit.
154 ///
155 /// # Panics
156 ///
157 /// If `capacity` is 0.
158 pub fn with_interaction_window(capacity: usize, window: Option<Duration>) -> Self {
159 let (tx, _) = broadcast::channel(capacity);
160 let rule = window.map(|per| Window {
161 max: 5,
162 per,
163 keep_latest: false,
164 });
165 Self {
166 tx,
167 interactions: Arc::new(Mutex::new(Limiter::new(rule))),
168 }
169 }
170
171 /// Offer `event` to every connection. With none connected it is
172 /// dropped.
173 pub fn publish(&self, event: SceneEvent) {
174 let _ = self.tx.send(event);
175 }
176
177 /// Whether a client-submitted interaction keyed `key` is within the
178 /// rate limit, counting it if so.
179 fn admit_interaction(&self, key: InteractionKey) -> bool {
180 self.interactions
181 .lock()
182 .unwrap_or_else(PoisonError::into_inner)
183 .offer(key, (), Instant::now())
184 .is_some()
185 }
186}
187
188/// The outbound rate limit a [`SceneStreamHandler`] applies, per
189/// connection. The default is the draft's (§Rate Limiting):
190/// "`SceneObjectEvent` with `event: "updated"`: no more than two events
191/// per object per second. Events above this rate MAY be silently dropped;
192/// the most recent state SHOULD be delivered when the rate window
193/// reopens." The latest one over the limit is held and sent when the
194/// window reopens, after the delivery checks run again.
195///
196/// The interaction limit is per user, so it is the [`SceneEventHub`]'s.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub struct SceneStreamLimits {
199 object_update: Option<Duration>,
200}
201
202impl Default for SceneStreamLimits {
203 fn default() -> Self {
204 Self {
205 object_update: Some(Duration::from_secs(1)),
206 }
207 }
208}
209
210impl SceneStreamLimits {
211 /// The object-update window: at most two `"updated"` events per object
212 /// in it, the latest one over the limit sent when it reopens; `None`
213 /// for no limit.
214 pub fn object_update_window(mut self, window: Option<Duration>) -> Self {
215 self.object_update = window;
216 self
217 }
218
219 /// The object-update window.
220 pub fn object_update_window_value(&self) -> Option<Duration> {
221 self.object_update
222 }
223}
224
225/// The `"scene"` switch of one connection's `ChatStreamEnable`
226/// subscription, shared with that connection's [`SceneStreamHandler`].
227///
228/// While on, the handler delivers every Scene event the user may
229/// receive, as a `SceneStreamEnable` with `regionIds` and `eventTypes`
230/// both `null` would: the `"scene"` path "Subscribes to all Scene event
231/// types for all regions in which the user has an active avatar"
232/// (draft-atwood-jmap-scene-wss-00 §Interoperability with JMAP Chat
233/// WebSocket). That covers every `SceneStreamEnable` subscription
234/// without `observe`. An observer subscription also reaches listed
235/// regions without an avatar ("It has no observer form", jmap-chat-spec
236/// 93f2258), so for an event the `"scene"` path does not admit the
237/// handler still asks the connection's own observer subscription. Either
238/// way the union the server "MUST deliver" is decided once per event:
239/// "if an event matches both subscriptions, it is delivered exactly once"
240/// (§Subscription Union).
241/// `SceneStreamDisable` does not touch it, and turning it off leaves the
242/// `SceneStreamEnable` subscription in place (§Subscription
243/// Independence).
244///
245/// Set it to `jmap_chat_server::EphemeralSubscription::scene` after every
246/// change of the Chat subscription; `jmap-chat-scene-server` does.
247#[derive(Debug, Clone, Default)]
248pub struct SceneChatAlias {
249 on: Arc<AtomicBool>,
250}
251
252impl SceneChatAlias {
253 /// Switch the `"scene"` path on or off.
254 pub fn set(&self, on: bool) {
255 self.on.store(on, Ordering::SeqCst);
256 }
257
258 /// Whether the `"scene"` path is on.
259 pub fn is_on(&self) -> bool {
260 self.on.load(Ordering::SeqCst)
261 }
262}
263
264/// What the forwarding task needs.
265struct Shared<B: SceneBackend> {
266 backend: Arc<B>,
267 caller: B::CallerCtx,
268 recipient_account_id: Id,
269 subscription: Mutex<SceneEphemeralSubscription>,
270 alias: SceneChatAlias,
271 /// The subscription of the `"scene"` path: everything.
272 every: SceneEphemeralSubscription,
273 /// The `(account, region)` pairs this connection reported observing
274 /// with [`SceneBackend::set_observing`]: the pairs its observer
275 /// subscription covers ([`Shared::observe`], [`Shared::observe_event`]).
276 observing: tokio::sync::Mutex<Vec<(Id, Id)>>,
277}
278
279impl<B: SceneBackend> Shared<B> {
280 fn subscription(&self) -> SceneEphemeralSubscription {
281 self.subscription
282 .lock()
283 .unwrap_or_else(PoisonError::into_inner)
284 .clone()
285 }
286
287 /// Whether this connection receives `event` now. A backend error
288 /// drops it.
289 ///
290 /// With the `"scene"` path on, its everything-subscription decides,
291 /// except that an event it refuses may still reach the connection's
292 /// observer subscription, the one `SceneStreamEnable` the path does
293 /// not cover.
294 async fn admits(&self, event: &SceneEvent) -> bool {
295 let Some(hosting) = hosting_account(event) else {
296 return false;
297 };
298 let deliver = |subscription| {
299 should_deliver(
300 &*self.backend,
301 &self.caller,
302 hosting,
303 &self.recipient_account_id,
304 subscription,
305 event,
306 )
307 };
308 let own = self.subscription();
309 if self.alias.is_on() {
310 if deliver(&self.every).await.unwrap_or(false) {
311 return true;
312 }
313 if !own.filter().is_some_and(SceneStreamFilter::observes) {
314 return false;
315 }
316 }
317 deliver(&own).await.unwrap_or(false)
318 }
319
320 /// Whether the connection's current observer subscription covers
321 /// region `region_id`, in any account.
322 fn observer_covers(&self, region_id: &Id) -> bool {
323 self.subscription()
324 .filter()
325 .is_some_and(|f| f.observes() && f.region_ids().covers(region_id))
326 }
327
328 /// After the subscription changed: observe `listed`, the pairs a new
329 /// observer subscription names in the observer accounts, keep the
330 /// pairs learned from events ([`Self::observe_event`]) that the current
331 /// subscription still covers, and release the rest, telling the
332 /// backend of each pair started and stopped. Starts are reported
333 /// first, so a region kept across two subscriptions never dips. A
334 /// backend error is ignored: the count is advisory and the
335 /// subscription stands.
336 ///
337 /// Call it after storing the new subscription: the coverage check
338 /// reads it under the `observing` lock, as [`Self::observe_event`]
339 /// does, so a pair that call adds concurrently is kept or released
340 /// with the rest.
341 async fn observe(&self, listed: Vec<(Id, Id)>) {
342 let mut observing = self.observing.lock().await;
343 let mut next = listed;
344 for pair in observing.iter() {
345 if !next.contains(pair) && self.observer_covers(&pair.1) {
346 next.push(pair.clone());
347 }
348 }
349 let previous = std::mem::replace(&mut *observing, next);
350 for (account, region) in observing.iter().filter(|p| !previous.contains(p)) {
351 let _ = self
352 .backend
353 .set_observing(&self.caller, account, region, true)
354 .await;
355 }
356 for (account, region) in previous.iter().filter(|p| !observing.contains(p)) {
357 let _ = self
358 .backend
359 .set_observing(&self.caller, account, region, false)
360 .await;
361 }
362 }
363
364 /// Before deciding on `event`: if the observer subscription covers its
365 /// region and this connection has not yet reported its
366 /// `(accountId, regionId)` pair, report it with
367 /// [`SceneBackend::set_observing`]. That reaches the regions of
368 /// accounts outside [`SceneBackend::observer_accounts`], whose events
369 /// the subscription delivers too: "delivery is not limited to those
370 /// accounts". The pair is reported whether or not `event` itself is
371 /// delivered, since its `eventTypes` or the user's current access may
372 /// refuse this one event; the backend counts only the users delivery
373 /// reaches.
374 ///
375 /// The pair is recorded only once the backend call returns, so a
376 /// forwarding task aborted during the call leaves no pair to release.
377 async fn observe_event(&self, event: &SceneEvent) {
378 let (Some(account), Some(region)) = (hosting_account(event), event_region(event)) else {
379 return;
380 };
381 if !self.observer_covers(region) {
382 return;
383 }
384 let mut observing = self.observing.lock().await;
385 let pair = (account.clone(), region.clone());
386 if observing.contains(&pair) || !self.observer_covers(region) {
387 return;
388 }
389 let _ = self
390 .backend
391 .set_observing(&self.caller, account, region, true)
392 .await;
393 observing.push(pair);
394 }
395}
396
397/// The event's `regionId`; `None` for an unrecognized `@type`.
398fn event_region(event: &SceneEvent) -> Option<&Id> {
399 Some(match event {
400 SceneEvent::Avatar(e) => &e.region_id,
401 SceneEvent::Object(e) => &e.region_id,
402 SceneEvent::Interaction(e) => &e.region_id,
403 SceneEvent::Region(e) => &e.region_id,
404 _ => return None,
405 })
406}
407
408/// The event's `accountId`, its region's hosting account; `None` for an
409/// unrecognized `@type`.
410fn hosting_account(event: &SceneEvent) -> Option<&Id> {
411 Some(match event {
412 SceneEvent::Avatar(e) => &e.account_id,
413 SceneEvent::Object(e) => &e.account_id,
414 SceneEvent::Interaction(e) => &e.account_id,
415 SceneEvent::Region(e) => &e.account_id,
416 _ => return None,
417 })
418}
419
420/// The `SceneStreamEnable` / `SceneStreamDisable` /
421/// `SceneInteractionEvent` handler of one WebSocket connection; see the
422/// [module docs](self).
423///
424/// - `SceneStreamEnable` replaces the subscription through
425/// [`SceneEphemeralSubscription::replace_with`], or
426/// [`SceneEphemeralSubscription::replace_with_observe`] when
427/// [`SceneBackend::supports_observe`]. Its error becomes the
428/// `RequestError` (`invalidArguments`, or `forbidden` with `regionIds`
429/// for a refused observer subscription, with the message's `id` as
430/// `requestId`) and leaves the subscription unchanged; "This error does
431/// not close the WebSocket connection". A malformed message is
432/// `notRequest`.
433/// - `SceneStreamDisable` clears it, silently, whether or not one was
434/// active. The `"scene"` path of `ChatStreamEnable` is unaffected.
435/// - `SceneInteractionEvent` is validated and relayed, never answered.
436/// - Closing the connection clears the subscription and stops delivery
437/// (§Subscription Lifecycle).
438///
439/// Each of these that changes which regions the connection observes
440/// reports it to [`SceneBackend::set_observing`].
441pub struct SceneStreamHandler<B: SceneBackend> {
442 shared: Arc<Shared<B>>,
443 hub: SceneEventHub,
444 limits: SceneStreamLimits,
445 task: Option<JoinHandle<()>>,
446}
447
448impl<B: SceneBackend> fmt::Debug for SceneStreamHandler<B> {
449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450 f.debug_struct("SceneStreamHandler")
451 .field("recipient_account_id", &self.shared.recipient_account_id)
452 .field("subscription", &self.shared.subscription())
453 .field("chat_alias", &self.shared.alias.is_on())
454 .field("limits", &self.limits)
455 .finish_non_exhaustive()
456 }
457}
458
459impl<B: SceneBackend> SceneStreamHandler<B> {
460 /// The handler of a connection authenticated as `caller`, whose own
461 /// account is `recipient_account_id` (the account whose Chat
462 /// capability the blocked-sender check consults, as
463 /// [`should_deliver`] takes it), receiving events from and relaying
464 /// interactions to `hub`.
465 ///
466 /// The default [`SceneStreamLimits`] apply.
467 ///
468 /// # Panics
469 ///
470 /// Does not panic: the `expect` on the catch-all subscription holds
471 /// because [`SceneEphemeralSubscription::replace_with`] fails only on an
472 /// `eventTypes` array with no recognized value, and the default
473 /// [`SceneStreamEnable`] has `eventTypes` `null`.
474 pub fn new(
475 backend: Arc<B>,
476 caller: B::CallerCtx,
477 recipient_account_id: Id,
478 hub: &SceneEventHub,
479 ) -> Self {
480 let mut every = SceneEphemeralSubscription::default();
481 every
482 .replace_with(&SceneStreamEnable::default())
483 .expect("a SceneStreamEnable with null eventTypes is always valid");
484 Self {
485 shared: Arc::new(Shared {
486 backend,
487 caller,
488 recipient_account_id,
489 subscription: Mutex::new(SceneEphemeralSubscription::default()),
490 alias: SceneChatAlias::default(),
491 every,
492 observing: tokio::sync::Mutex::new(Vec::new()),
493 }),
494 hub: hub.clone(),
495 limits: SceneStreamLimits::default(),
496 task: None,
497 }
498 }
499
500 /// Replace the outbound rate limit.
501 pub fn with_limits(mut self, limits: SceneStreamLimits) -> Self {
502 self.limits = limits;
503 self
504 }
505
506 /// The `"scene"` switch of this connection's `ChatStreamEnable`
507 /// subscription; off until set.
508 pub fn chat_alias(&self) -> SceneChatAlias {
509 self.shared.alias.clone()
510 }
511
512 /// The connection's current `SceneStreamEnable` subscription.
513 pub fn subscription(&self) -> SceneEphemeralSubscription {
514 self.shared.subscription()
515 }
516
517 fn set(&self, subscription: SceneEphemeralSubscription) {
518 *self
519 .shared
520 .subscription
521 .lock()
522 .unwrap_or_else(PoisonError::into_inner) = subscription;
523 }
524
525 async fn enable(&self, message: &ExtensionMessage) -> Result<(), JmapError> {
526 let enable: SceneStreamEnable = message.deserialize()?;
527 let shared = &self.shared;
528 let backend = &*shared.backend;
529 let mut next = self.subscription();
530 // "Recognized only when the server advertises `supportsObserve`".
531 let observing = backend.supports_observe(&shared.caller);
532 if observing {
533 next.replace_with_observe(&enable)?;
534 } else {
535 next.replace_with(&enable)?;
536 }
537 let mut listed = Vec::new();
538 if observing
539 && enable.observe == Some(true)
540 && let Some(region_ids) = &enable.region_ids
541 {
542 let fail = |e: B::Error| jmap_server::server_fail_from_backend(&e);
543 let accounts = backend
544 .observer_accounts(&shared.caller, &shared.recipient_account_id)
545 .await
546 .map_err(fail)?;
547 let refused = observer_regions(backend, &shared.caller, &accounts, region_ids)
548 .await
549 .map_err(fail)?;
550 if !refused.is_empty() {
551 // "the server MUST respond with a `RequestError` ... with a
552 // `type` of `\"urn:ietf:params:jmap:error:forbidden\"` and a
553 // `regionIds` member listing the refused regions, and MUST
554 // NOT update the current ephemeral subscription state".
555 let mut err = JmapError::forbidden();
556 err.description = Some("these regions do not admit observers".to_owned());
557 err.extra
558 .insert("regionIds".to_owned(), serde_json::json!(refused));
559 return Err(err);
560 }
561 // Every listed region in every observer account, whether the
562 // user has access to it now or not: delivery re-checks access
563 // per event, so a region the user gains access to later must
564 // count from then on. The backend decides who counts.
565 for account in &accounts {
566 for region in region_ids {
567 let pair = (account.clone(), region.clone());
568 if !listed.contains(&pair) {
569 listed.push(pair);
570 }
571 }
572 }
573 }
574 self.set(next);
575 shared.observe(listed).await;
576 Ok(())
577 }
578
579 /// Validates a client-submitted interaction and relays it; every
580 /// failure is silent.
581 async fn interact(&self, message: &ExtensionMessage) {
582 let Ok(mut frame) = message.deserialize::<SceneInteractionEvent>() else {
583 return;
584 };
585 // "A frame carries the properties defined above": members the
586 // server does not know, the frame's `id` among them, are not
587 // relayed to other users.
588 frame.extra.clear();
589 let shared = &self.shared;
590 let Ok(Some(relayed)) =
591 validate_interaction(&*shared.backend, &shared.caller, &frame.account_id, &frame).await
592 else {
593 return;
594 };
595 let key = (
596 relayed.account_id.clone(),
597 relayed.region_id.clone(),
598 relayed.user_id.clone(),
599 );
600 if self.hub.admit_interaction(key) {
601 self.hub.publish(SceneEvent::Interaction(relayed));
602 }
603 }
604}
605
606impl<B: SceneBackend> ExtensionHandler for SceneStreamHandler<B> {
607 fn message_types(&self) -> &[&str] {
608 &[ENABLE, DISABLE, INTERACTION]
609 }
610
611 fn start(&mut self, events: ExtensionSender) {
612 let rx = self.hub.tx.subscribe();
613 self.task = Some(tokio::spawn(forward(
614 Arc::clone(&self.shared),
615 self.limits,
616 rx,
617 events,
618 )));
619 }
620
621 async fn handle(&mut self, message: ExtensionMessage) -> Result<(), JmapError> {
622 match message.message_type.as_str() {
623 ENABLE => self.enable(&message).await,
624 INTERACTION => {
625 self.interact(&message).await;
626 Ok(())
627 }
628 _ => {
629 self.set(SceneEphemeralSubscription::default());
630 self.shared.observe(Vec::new()).await;
631 Ok(())
632 }
633 }
634 }
635
636 async fn close(&mut self) {
637 if let Some(task) = self.task.take() {
638 task.abort();
639 }
640 self.set(SceneEphemeralSubscription::default());
641 // "The count drops when the subscription stops covering the
642 // region, through ... the connection closing."
643 self.shared.observe(Vec::new()).await;
644 }
645}
646
647impl<B: SceneBackend> Drop for SceneStreamHandler<B> {
648 fn drop(&mut self) {
649 if let Some(task) = self.task.take() {
650 task.abort();
651 }
652 }
653}
654
655/// Object-update limiter key: (`accountId`, `objectId`).
656type ObjectKey = (Id, Id);
657
658/// Delivers the hub's events to one connection until it closes.
659async fn forward<B: SceneBackend>(
660 shared: Arc<Shared<B>>,
661 limits: SceneStreamLimits,
662 mut rx: broadcast::Receiver<SceneEvent>,
663 events: ExtensionSender,
664) {
665 let mut updates: Limiter<ObjectKey, SceneEvent> =
666 Limiter::new(limits.object_update.map(|per| Window {
667 max: 2,
668 per,
669 keep_latest: true,
670 }));
671 loop {
672 tokio::select! {
673 () = events.closed() => return,
674 () = sleep_until(updates.next_due()) => {
675 for (_, held) in updates.take_due(Instant::now()) {
676 if shared.admits(&held).await {
677 send(&events, &held);
678 }
679 }
680 }
681 received = rx.recv() => match received {
682 Ok(event) => {
683 shared.observe_event(&event).await;
684 if !shared.admits(&event).await {
685 continue;
686 }
687 let pass = match &event {
688 SceneEvent::Object(e) if e.event == ObjectEventKind::Updated => {
689 let key = (e.account_id.clone(), e.object_id.clone());
690 updates.offer(key, event.clone(), Instant::now()).is_some()
691 }
692 _ => true,
693 };
694 if pass {
695 send(&events, &event);
696 }
697 }
698 Err(broadcast::error::RecvError::Lagged(_)) => {}
699 Err(broadcast::error::RecvError::Closed) => return,
700 },
701 }
702 }
703}
704
705/// Queues `event`, dropping it if the client is too slow.
706fn send(events: &ExtensionSender, event: &SceneEvent) {
707 let _ = events.try_send(event);
708}
709
710#[cfg(all(test, feature = "memory"))]
711mod tests {
712 use super::*;
713 use crate::RegionScope;
714 use crate::memory::MemoryBackend;
715 use serde_json::{Value, json};
716
717 fn handler(hub: &SceneEventHub) -> SceneStreamHandler<MemoryBackend> {
718 SceneStreamHandler::new(
719 Arc::new(MemoryBackend::new()),
720 Id::from("user:alice@example.com"),
721 Id::from("a1"),
722 hub,
723 )
724 }
725
726 fn message(ty: &str, body: Value) -> ExtensionMessage {
727 let Value::Object(body) = body else {
728 panic!("object")
729 };
730 ExtensionMessage::new(ty, body)
731 }
732
733 #[test]
734 fn registers_the_control_messages_and_interactions() {
735 assert_eq!(
736 handler(&SceneEventHub::new(8)).message_types(),
737 [
738 "SceneStreamEnable",
739 "SceneStreamDisable",
740 "SceneInteractionEvent"
741 ]
742 );
743 }
744
745 /// §`SceneStreamEnable`: a new message "replaces the previous ephemeral
746 /// subscription in its entirety"; §`SceneStreamDisable` "MUST silently
747 /// succeed if no ephemeral Scene subscription is currently active".
748 #[tokio::test]
749 async fn enable_replaces_and_disable_clears() {
750 let mut h = handler(&SceneEventHub::new(8));
751 h.handle(message(ENABLE, json!({"regionIds": ["r1"]})))
752 .await
753 .unwrap();
754 assert_eq!(
755 h.subscription().filter().unwrap().region_ids(),
756 &RegionScope::Only(vec![Id::from("r1")])
757 );
758 h.handle(message(ENABLE, json!({}))).await.unwrap();
759 assert_eq!(
760 h.subscription().filter().unwrap().region_ids(),
761 &RegionScope::All
762 );
763 h.handle(message(DISABLE, json!({}))).await.unwrap();
764 assert!(h.subscription().filter().is_none());
765 h.handle(message(DISABLE, json!({}))).await.unwrap();
766 }
767
768 /// §`SceneStreamEnable`: only unrecognized `eventTypes` is
769 /// `invalidArguments` and "MUST NOT update the current ephemeral
770 /// subscription state". Without `supportsObserve`, `observe` is not
771 /// recognized: `observe: true` with `regionIds: null` is not the
772 /// invalidArguments the draft requires of an observing server.
773 #[tokio::test]
774 async fn invalid_event_types_and_unrecognized_observe() {
775 let mut h = handler(&SceneEventHub::new(8));
776 h.handle(message(ENABLE, json!({"eventTypes": ["SceneAvatarEvent"]})))
777 .await
778 .unwrap();
779 let err = h
780 .handle(message(ENABLE, json!({"eventTypes": ["SceneFooBarEvent"]})))
781 .await
782 .unwrap_err();
783 assert_eq!(err.error_type.as_str(), "invalidArguments");
784 assert!(
785 h.subscription()
786 .filter()
787 .unwrap()
788 .includes("SceneAvatarEvent")
789 );
790 h.handle(message(ENABLE, json!({"observe": true, "regionIds": null})))
791 .await
792 .unwrap();
793 assert_eq!(
794 h.subscription().filter().unwrap().region_ids(),
795 &RegionScope::All
796 );
797 }
798
799 /// §Submitting Interactions: "If any check fails, the server discards
800 /// the frame and returns no error to the sender." A malformed frame
801 /// and one from a user without an avatar are both silent.
802 #[tokio::test]
803 async fn failed_interactions_are_silent() {
804 let hub = SceneEventHub::new(8);
805 let mut rx = hub.tx.subscribe();
806 let mut h = handler(&hub);
807 h.handle(message(INTERACTION, json!({"action": 1})))
808 .await
809 .unwrap();
810 h.handle(message(
811 INTERACTION,
812 json!({"accountId": "a1", "regionId": "r1", "objectId": "o1", "action": "click", "data": null}),
813 ))
814 .await
815 .unwrap();
816 assert!(rx.try_recv().is_err());
817 }
818
819 /// Which `(account, region)` pairs the handler reports to
820 /// `set_observing`, against draft-atwood-jmap-scene-wss-00 at
821 /// jmap-chat-spec 42aed85 §Semantics: "While an observer subscription
822 /// delivers events for a region to a user without an active avatar
823 /// there, the user counts toward the region's `observerCount`", and
824 /// "delivery is not limited to those accounts" the server checks at
825 /// enable time (bd:JMAP-1mep).
826 #[cfg(feature = "test-helpers")]
827 mod observing {
828 use super::*;
829 use jmap_scene_types::{SceneCapability, SceneRegion};
830 use jmap_server::JmapReads as _;
831
832 const OWN: &str = "a1";
833 const OTHER: &str = "a2";
834 const R1: &str = "r1";
835 const R2: &str = "r2";
836 const ALICE: &str = "user:alice@example.com";
837 const CAROL: &str = "user:carol@example.com";
838
839 /// Accounts [`OWN`] and [`OTHER`], `supportsObserve` on.
840 fn backend() -> Arc<MemoryBackend> {
841 let backend = MemoryBackend::new();
842 let cap: SceneCapability = serde_json::from_value(json!({
843 "mayCreateRegion": true,
844 "mayCreateObject": true,
845 "supportedVisualTypes": ["model/gltf-binary"],
846 "maxRegionsPerAccount": null,
847 "maxObjectsPerRegion": null,
848 "maxAvatarsPerRegion": null,
849 "maxAssetSizeBytes": null
850 }))
851 .unwrap();
852 backend.register_account(&Id::from(OWN), cap.clone());
853 backend.register_account(&Id::from(OTHER), cap);
854 backend.set_supports_observe(true);
855 Arc::new(backend)
856 }
857
858 /// Seed region `id` of `account`, owned by [`ALICE`], open to
859 /// observers.
860 fn region(backend: &MemoryBackend, account: &str, id: &str, policy: &str) {
861 backend.insert_object_for_test(
862 "SceneRegion",
863 &Id::from(account),
864 id,
865 json!({
866 "id": id,
867 "accountId": account,
868 "ownerId": ALICE,
869 "name": id,
870 "description": null,
871 "bounds": {"min": [-20, 0, -20], "max": [20, 8, 20]},
872 "environment": null,
873 "simulationUri": null,
874 "spawnPosition": [0, 0, 5],
875 "spawnOrientation": [0, 0, 0, 1],
876 "activeAvatarCount": 0,
877 "viewHint": "3d",
878 "accessPolicy": policy,
879 "createdAt": "2026-06-01T10:00:00Z",
880 "updatedAt": "2026-06-01T10:00:00Z",
881 "allowObservers": true,
882 "observerCount": 0
883 }),
884 );
885 }
886
887 async fn count(backend: &MemoryBackend, account: &str, region: &str) -> u64 {
888 let (list, _) = backend
889 .get_objects::<SceneRegion>(
890 &Id::from(ALICE),
891 &Id::from(account),
892 Some(&[Id::from(region)]),
893 None,
894 )
895 .await
896 .unwrap();
897 list[0].observer_count.unwrap()
898 }
899
900 fn carol(backend: &Arc<MemoryBackend>) -> SceneStreamHandler<MemoryBackend> {
901 SceneStreamHandler::new(
902 Arc::clone(backend),
903 Id::from(CAROL),
904 Id::from(OWN),
905 &SceneEventHub::new(8),
906 )
907 }
908
909 async fn observe(h: &mut SceneStreamHandler<MemoryBackend>, regions: &[&str]) {
910 h.handle(message(
911 ENABLE,
912 json!({"regionIds": regions, "observe": true}),
913 ))
914 .await
915 .unwrap();
916 }
917
918 fn round_start(account: &str, region: &str) -> SceneEvent {
919 serde_json::from_value(json!({
920 "@type": "SceneRegionEvent",
921 "accountId": account,
922 "regionId": region,
923 "event": "com.example.round-start",
924 "data": null
925 }))
926 .unwrap()
927 }
928
929 async fn reported(h: &SceneStreamHandler<MemoryBackend>) -> Vec<(Id, Id)> {
930 h.shared.observing.lock().await.clone()
931 }
932
933 /// (b) A listed region the user has no access to when the
934 /// subscription is enabled is reported anyway: once access is
935 /// granted, events flow ("events resume without a new
936 /// `SceneStreamEnable` once the region admits the observer
937 /// again") and the user counts.
938 #[tokio::test]
939 async fn a_region_the_user_gains_access_to_later_counts() {
940 let backend = backend();
941 region(&backend, OWN, R1, "invite");
942 let mut h = carol(&backend);
943 observe(&mut h, &[R1]).await;
944 assert_eq!(count(&backend, OWN, R1).await, 0);
945 assert!(reported(&h).await.contains(&(Id::from(OWN), Id::from(R1))));
946 backend.grant_region_access(R1, CAROL);
947 assert_eq!(count(&backend, OWN, R1).await, 1);
948 backend.revoke_region_access(R1, CAROL);
949 assert_eq!(count(&backend, OWN, R1).await, 0);
950 backend.grant_region_access(R1, CAROL);
951 h.close().await;
952 assert_eq!(count(&backend, OWN, R1).await, 0);
953 }
954
955 /// (a) A listed region of an account outside `observer_accounts`
956 /// still gets events, so its first event reports it; it is kept
957 /// while a new subscription still lists it, and released when
958 /// one does not. Events of unlisted regions report nothing.
959 #[tokio::test]
960 async fn a_region_outside_the_observer_accounts_counts_from_its_first_event() {
961 let backend = backend();
962 backend.restrict_observer_accounts(&[OWN]);
963 region(&backend, OTHER, R1, "public");
964 region(&backend, OTHER, R2, "public");
965 let mut h = carol(&backend);
966 observe(&mut h, &[R1]).await;
967 assert_eq!(count(&backend, OTHER, R1).await, 0);
968
969 h.shared.observe_event(&round_start(OTHER, R2)).await;
970 assert_eq!(count(&backend, OTHER, R2).await, 0);
971 h.shared.observe_event(&round_start(OTHER, R1)).await;
972 assert!(h.shared.admits(&round_start(OTHER, R1)).await);
973 assert_eq!(count(&backend, OTHER, R1).await, 1);
974 // A second event is not a second report.
975 h.shared.observe_event(&round_start(OTHER, R1)).await;
976 let pair = (Id::from(OTHER), Id::from(R1));
977 assert_eq!(reported(&h).await.iter().filter(|p| **p == pair).count(), 1);
978
979 observe(&mut h, &[R1, R2]).await;
980 assert_eq!(count(&backend, OTHER, R1).await, 1);
981 observe(&mut h, &[R2]).await;
982 assert_eq!(count(&backend, OTHER, R1).await, 0);
983 assert!(!reported(&h).await.contains(&pair));
984
985 h.shared.observe_event(&round_start(OTHER, R2)).await;
986 assert_eq!(count(&backend, OTHER, R2).await, 1);
987 h.handle(message(DISABLE, json!({}))).await.unwrap();
988 assert_eq!(count(&backend, OTHER, R2).await, 0);
989 assert!(reported(&h).await.is_empty());
990 }
991
992 /// A subscription without `observe` reports nothing, from enable
993 /// or from events.
994 #[tokio::test]
995 async fn a_plain_subscription_reports_nothing() {
996 let backend = backend();
997 region(&backend, OWN, R1, "public");
998 let mut h = carol(&backend);
999 h.handle(message(ENABLE, json!({"regionIds": [R1]})))
1000 .await
1001 .unwrap();
1002 h.shared.observe_event(&round_start(OWN, R1)).await;
1003 assert!(reported(&h).await.is_empty());
1004 assert_eq!(count(&backend, OWN, R1).await, 0);
1005 }
1006
1007 /// "A user with several observing connections counts once",
1008 /// however each connection came to report the region.
1009 #[tokio::test]
1010 async fn several_connections_count_once() {
1011 let backend = backend();
1012 backend.restrict_observer_accounts(&[OWN]);
1013 region(&backend, OWN, R1, "public");
1014 region(&backend, OTHER, R1, "public");
1015 let mut first = carol(&backend);
1016 let mut second = carol(&backend);
1017 observe(&mut first, &[R1]).await;
1018 observe(&mut second, &[R1]).await;
1019 for h in [&first, &second] {
1020 h.shared.observe_event(&round_start(OTHER, R1)).await;
1021 }
1022 assert_eq!(count(&backend, OWN, R1).await, 1);
1023 assert_eq!(count(&backend, OTHER, R1).await, 1);
1024 first.close().await;
1025 assert_eq!(count(&backend, OWN, R1).await, 1);
1026 assert_eq!(count(&backend, OTHER, R1).await, 1);
1027 second.close().await;
1028 assert_eq!(count(&backend, OWN, R1).await, 0);
1029 assert_eq!(count(&backend, OTHER, R1).await, 0);
1030 }
1031 }
1032
1033 #[test]
1034 fn the_hub_limits_interactions_per_user_per_region() {
1035 let hub = SceneEventHub::new(8);
1036 let key = |region: &str| (Id::from("a1"), Id::from(region), "u".to_owned());
1037 for _ in 0..5 {
1038 assert!(hub.admit_interaction(key("r1")));
1039 }
1040 assert!(!hub.admit_interaction(key("r1")));
1041 assert!(hub.admit_interaction(key("r2")));
1042 let unlimited = SceneEventHub::with_interaction_window(8, None);
1043 for _ in 0..10 {
1044 assert!(unlimited.admit_interaction(key("r1")));
1045 }
1046 }
1047
1048 #[test]
1049 fn default_limits_are_the_drafts() {
1050 let l = SceneStreamLimits::default();
1051 assert_eq!(l.object_update_window_value(), Some(Duration::from_secs(1)));
1052 assert_eq!(
1053 l.object_update_window(None).object_update_window_value(),
1054 None
1055 );
1056 }
1057}