callback_server/router.rs
1//! Event routing for HTTP callback notifications.
2//!
3//! This module provides the `EventRouter` which maintains a set of active
4//! subscription IDs and routes incoming UPnP event notifications to a channel.
5//! Events for not-yet-registered SIDs are buffered and replayed when
6//! registration completes, preventing the race between SUBSCRIBE response
7//! and initial NOTIFY delivery.
8
9use std::collections::HashSet;
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12use tokio::sync::{mpsc, RwLock};
13use tracing::debug;
14
15/// Maximum time a buffered event is kept before being discarded.
16/// The race window is typically microseconds; 5 seconds handles any
17/// pathological scheduling delay.
18const BUFFER_TTL: Duration = Duration::from_secs(5);
19
20/// Hard cap on buffered pending events.
21///
22/// The buffer exists only to bridge the microsecond race between a SUBSCRIBE
23/// response and the `register()` call that follows it, so legitimate occupancy is
24/// 0-5 entries. But `route_event` buffers events for *any* unrecognised SID, and
25/// the endpoint is unauthenticated — a hostile or buggy sender spraying random
26/// SIDs would grow this Vec without bound (each entry holds a full event body).
27///
28/// 256 is ~50x the legitimate high-water mark, so it cannot be reached by normal
29/// operation even on a large household bringing every subscription up at once,
30/// while bounding worst-case retention to 256 bodies. On overflow the oldest
31/// entry is dropped: these are pending state snapshots, and the newest is both
32/// the most current and the most likely to still have a `register()` coming.
33const MAX_PENDING_EVENTS: usize = 256;
34
35/// Generic notification payload for UPnP event notifications.
36///
37/// This represents an unparsed UPnP event notification that has been received
38/// via HTTP callback. It contains only the subscription ID, raw XML body, and
39/// when the notification arrived — no device-specific context.
40#[derive(Debug, Clone)]
41pub struct NotificationPayload {
42 /// The subscription ID from the UPnP SID header
43 pub subscription_id: String,
44 /// The raw XML event body
45 pub event_xml: String,
46 /// When this notification reached the router, on the monotonic clock.
47 ///
48 /// This is the earliest instant at which the process can be said to have
49 /// *observed* the values in `event_xml`, and downstream consumers order
50 /// writes by it. It is deliberately `Instant` and not `SystemTime`: an
51 /// ordering built on the wall clock would reverse itself whenever NTP
52 /// stepped the clock backwards.
53 ///
54 /// For an event that arrived before its SID was registered, this is the
55 /// original arrival instant, *not* the replay instant — a notification held
56 /// in the pending buffer for seconds must not be treated as freshly
57 /// observed when it is finally replayed.
58 pub received_at: Instant,
59}
60
61/// Internal state protected by a single lock to eliminate TOCTOU gaps.
62struct RouterState {
63 subscriptions: HashSet<String>,
64 /// Flat buffer of (subscription_id, event_xml, buffered_at).
65 /// Expected size: 0-5 entries for well-behaved senders — only populated
66 /// during the microsecond race window between SUBSCRIBE response and
67 /// register(). Hard-capped at `MAX_PENDING_EVENTS` because the HTTP endpoint
68 /// is unauthenticated and cannot rely on senders being well-behaved.
69 pending: Vec<(String, String, Instant)>,
70}
71
72impl RouterState {
73 /// Drop buffered entries older than `BUFFER_TTL`.
74 fn sweep_stale(&mut self) {
75 let now = Instant::now();
76 self.pending
77 .retain(|(_, _, buffered_at)| now.duration_since(*buffered_at) <= BUFFER_TTL);
78 }
79
80 /// Buffer an event, enforcing `MAX_PENDING_EVENTS` by dropping the oldest.
81 ///
82 /// `received_at` is the caller's arrival instant, carried through so that a
83 /// replayed event is stamped with when it arrived rather than when it was
84 /// replayed. It doubles as the TTL/eviction key, which is what it already
85 /// was.
86 fn push_pending(&mut self, subscription_id: String, event_xml: String, received_at: Instant) {
87 self.sweep_stale();
88
89 while self.pending.len() >= MAX_PENDING_EVENTS {
90 // Evict by timestamp rather than position: swap_remove elsewhere
91 // means index order does not track insertion order.
92 let oldest = self
93 .pending
94 .iter()
95 .enumerate()
96 .min_by_key(|(_, (_, _, at))| *at)
97 .map(|(i, _)| i);
98 match oldest {
99 Some(i) => {
100 let (sid, _, _) = self.pending.remove(i);
101 debug!(
102 sid = %sid,
103 cap = MAX_PENDING_EVENTS,
104 "Pending event buffer full; dropped oldest entry"
105 );
106 }
107 None => break,
108 }
109 }
110
111 self.pending.push((subscription_id, event_xml, received_at));
112 }
113}
114
115/// Routes events from HTTP callbacks to a channel.
116///
117/// The `EventRouter` maintains a set of active subscription IDs. When an event
118/// is received via HTTP callback, the router checks if the subscription is
119/// registered and sends the notification payload to the configured channel.
120///
121/// Events for unregistered SIDs are buffered briefly and replayed when
122/// `register()` is called, preventing the race between SUBSCRIBE response
123/// and initial UPnP NOTIFY delivery.
124#[derive(Clone)]
125pub struct EventRouter {
126 state: Arc<RwLock<RouterState>>,
127 /// Channel for sending notification payloads
128 event_sender: mpsc::UnboundedSender<NotificationPayload>,
129}
130
131impl EventRouter {
132 /// Create a new event router.
133 ///
134 /// # Arguments
135 ///
136 /// * `event_sender` - Channel for sending notification payloads
137 ///
138 /// # Example
139 ///
140 /// ```
141 /// use tokio::sync::mpsc;
142 /// use callback_server::router::{EventRouter, NotificationPayload};
143 ///
144 /// let (tx, mut rx) = mpsc::unbounded_channel::<NotificationPayload>();
145 /// let router = EventRouter::new(tx);
146 /// ```
147 pub fn new(event_sender: mpsc::UnboundedSender<NotificationPayload>) -> Self {
148 Self {
149 state: Arc::new(RwLock::new(RouterState {
150 subscriptions: HashSet::new(),
151 pending: Vec::new(),
152 })),
153 event_sender,
154 }
155 }
156
157 /// Register a subscription ID for event routing.
158 ///
159 /// Adds the SID to the active set and replays any buffered events that
160 /// arrived before registration (the SUBSCRIBE/NOTIFY race window).
161 /// Also cleans up stale buffer entries older than `BUFFER_TTL`.
162 pub async fn register(&self, subscription_id: String) {
163 let mut state = self.state.write().await;
164 state.subscriptions.insert(subscription_id.clone());
165
166 // Replay buffered events for this SID and remove stale entries.
167 let now = Instant::now();
168 let mut i = 0;
169 while i < state.pending.len() {
170 let (ref sid, _, buffered_at) = state.pending[i];
171 if sid == &subscription_id {
172 let (_, xml, arrived_at) = state.pending.swap_remove(i);
173 debug!(sid = %subscription_id, "Replayed buffered event");
174 let payload = NotificationPayload {
175 subscription_id: subscription_id.clone(),
176 event_xml: xml,
177 // The buffer entry's instant *is* the arrival instant, so a
178 // replayed event keeps its original observation time rather
179 // than looking as though it just arrived.
180 received_at: arrived_at,
181 };
182 let _ = self.event_sender.send(payload);
183 // Don't increment i — swap_remove moved the last element here
184 } else if now.duration_since(buffered_at) > BUFFER_TTL {
185 state.pending.swap_remove(i);
186 // Don't increment i
187 } else {
188 i += 1;
189 }
190 }
191 }
192
193 /// Unregister a subscription ID.
194 ///
195 /// Removes the SID from the active set and drains any buffered events
196 /// for it, preventing stale replays on future re-registration.
197 pub async fn unregister(&self, subscription_id: &str) {
198 let mut state = self.state.write().await;
199 state.subscriptions.remove(subscription_id);
200 state.pending.retain(|(sid, _, _)| sid != subscription_id);
201 }
202
203 /// Route an incoming event to the unified event stream.
204 ///
205 /// If the subscription is registered, the event is sent immediately.
206 /// If not, the event is buffered for replay when `register()` is called.
207 /// The caller should always return HTTP 200 OK — buffered events are
208 /// accepted for processing, not rejected.
209 ///
210 /// Buffering sweeps entries older than `BUFFER_TTL` and enforces a hard cap
211 /// of `MAX_PENDING_EVENTS`, dropping the oldest entry on overflow. Without
212 /// this, unrecognised SIDs could grow the buffer without bound.
213 pub async fn route_event(&self, subscription_id: String, event_xml: String) {
214 // Taken before acquiring the lock: waiting on a contended write lock is
215 // not part of the observation, and stamping afterwards would push the
216 // event's apparent observation time later than it really was.
217 let received_at = Instant::now();
218
219 let mut state = self.state.write().await;
220 if state.subscriptions.contains(&subscription_id) {
221 let payload = NotificationPayload {
222 subscription_id,
223 event_xml,
224 received_at,
225 };
226 let _ = self.event_sender.send(payload);
227 } else {
228 debug!(sid = %subscription_id, "Buffered event for pending SID");
229 // Sweeps stale entries and enforces MAX_PENDING_EVENTS. Doing this
230 // here (not only in register()) is what bounds the buffer: register()
231 // is called on genuine new subscriptions only, so events for random
232 // SIDs would otherwise never trigger cleanup.
233 state.push_pending(subscription_id, event_xml, received_at);
234 }
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241
242 /// An `Instant` the given duration in the past.
243 ///
244 /// `Instant::now() - d` can panic where the monotonic clock's zero point is
245 /// near process start, so subtract fallibly and fail with a clear message
246 /// instead of an opaque arithmetic panic.
247 fn stale_instant(ago: Duration) -> Instant {
248 Instant::now()
249 .checked_sub(ago)
250 .expect("clock has enough history to backdate a test instant")
251 }
252
253 #[tokio::test]
254 async fn test_event_router_register_and_route() {
255 let (tx, mut rx) = mpsc::unbounded_channel();
256 let router = EventRouter::new(tx);
257
258 let sub_id = "test-sub-123".to_string();
259
260 // Register subscription
261 router.register(sub_id.clone()).await;
262
263 // Route an event
264 let event_xml = "<event>test</event>".to_string();
265 router.route_event(sub_id.clone(), event_xml.clone()).await;
266
267 // Verify payload was sent
268 let payload = rx.recv().await.unwrap();
269 assert_eq!(payload.subscription_id, sub_id);
270 assert_eq!(payload.event_xml, event_xml);
271 }
272
273 #[tokio::test]
274 async fn test_replayed_event_keeps_original_arrival_instant() {
275 // An event that arrives before its SID is registered is buffered and
276 // replayed later. Downstream orders writes by `received_at`, so the
277 // replayed payload must carry when it *arrived*, not when it was
278 // replayed — otherwise a notification held in the buffer would come out
279 // looking freshly observed and could displace a newer local write.
280 let (tx, mut rx) = mpsc::unbounded_channel();
281 let router = EventRouter::new(tx);
282
283 let sub_id = "test-sub-replay".to_string();
284
285 // Arrives before registration, so it is buffered.
286 let before = Instant::now();
287 router
288 .route_event(sub_id.clone(), "<event>buffered</event>".to_string())
289 .await;
290 assert!(rx.try_recv().is_err(), "precondition: event was buffered");
291
292 // Time passes, then registration replays it.
293 tokio::time::sleep(Duration::from_millis(20)).await;
294 let after_delay = Instant::now();
295 router.register(sub_id.clone()).await;
296
297 let payload = rx.try_recv().expect("buffered event should be replayed");
298 assert_eq!(payload.subscription_id, sub_id);
299 assert!(
300 payload.received_at >= before && payload.received_at < after_delay,
301 "replayed payload must keep its original arrival instant, not the replay instant"
302 );
303 }
304
305 #[tokio::test]
306 async fn test_event_router_unregister() {
307 let (tx, mut rx) = mpsc::unbounded_channel();
308 let router = EventRouter::new(tx);
309
310 let sub_id = "test-sub-123".to_string();
311
312 // Register and then unregister
313 router.register(sub_id.clone()).await;
314 router.unregister(&sub_id).await;
315
316 // Route an event — should be buffered (not delivered), since SID is unregistered
317 let event_xml = "<event>test</event>".to_string();
318 router.route_event(sub_id, event_xml).await;
319
320 // No immediate payload — event was buffered, not routed
321 assert!(rx.try_recv().is_err());
322 }
323
324 #[tokio::test]
325 async fn test_event_router_unknown_subscription_buffers() {
326 let (tx, mut rx) = mpsc::unbounded_channel();
327 let router = EventRouter::new(tx);
328
329 // Route event for unknown subscription — should be buffered, not dropped
330 router
331 .route_event("unknown-sub".to_string(), "<event>test</event>".to_string())
332 .await;
333
334 // No immediate payload — event was buffered
335 assert!(rx.try_recv().is_err());
336 }
337
338 /// Proves the registration race condition: an event arriving before register()
339 /// should be buffered and replayed when register() is called.
340 #[tokio::test]
341 async fn test_event_buffered_and_replayed_on_late_register() {
342 let (tx, mut rx) = mpsc::unbounded_channel();
343 let router = EventRouter::new(tx);
344
345 let sub_id = "uuid:late-register".to_string();
346 let event_xml =
347 "<e:propertyset><CurrentPlayMode>NORMAL</CurrentPlayMode></e:propertyset>".to_string();
348
349 // 1. Event arrives BEFORE register (the race condition)
350 router.route_event(sub_id.clone(), event_xml.clone()).await;
351
352 // 2. Register happens moments later
353 router.register(sub_id.clone()).await;
354
355 // 3. The buffered event should have been replayed on register
356 let payload = rx.try_recv().expect("expected replayed event");
357 assert_eq!(payload.subscription_id, sub_id);
358 assert_eq!(payload.event_xml, event_xml);
359 }
360
361 /// Stale buffered events (older than BUFFER_TTL) are cleaned up during register().
362 #[tokio::test]
363 async fn test_stale_buffer_entries_cleaned_on_register() {
364 let (tx, mut rx) = mpsc::unbounded_channel();
365 let router = EventRouter::new(tx);
366
367 // Manually insert a stale entry by writing to state directly
368 {
369 let mut state = router.state.write().await;
370 state.pending.push((
371 "uuid:stale-sid".to_string(),
372 "<event>stale</event>".to_string(),
373 stale_instant(Duration::from_secs(10)), // 10s ago, well past TTL
374 ));
375 }
376
377 // Register a different SID — should clean up the stale entry
378 router.register("uuid:fresh-sid".to_string()).await;
379
380 // No events replayed (the stale entry was for a different SID and expired)
381 assert!(rx.try_recv().is_err());
382
383 // Verify the stale entry was cleaned up
384 let state = router.state.read().await;
385 assert!(state.pending.is_empty(), "stale entry should be cleaned up");
386 }
387
388 /// unregister() drains buffered events for the removed SID.
389 #[tokio::test]
390 async fn test_unregister_drains_buffer() {
391 let (tx, mut rx) = mpsc::unbounded_channel();
392 let router = EventRouter::new(tx);
393
394 let sub_id = "uuid:drain-test".to_string();
395
396 // Buffer an event
397 router
398 .route_event(sub_id.clone(), "<event>buffered</event>".to_string())
399 .await;
400
401 // Unregister — should drain the buffered event
402 router.unregister(&sub_id).await;
403
404 // Re-register — should NOT replay the drained event
405 router.register(sub_id.clone()).await;
406
407 // No events replayed (buffer was drained by unregister)
408 assert!(rx.try_recv().is_err());
409 }
410
411 /// Multiple buffered events for the same SID are all replayed.
412 #[tokio::test]
413 async fn test_multiple_buffered_events_replayed() {
414 let (tx, mut rx) = mpsc::unbounded_channel();
415 let router = EventRouter::new(tx);
416
417 let sub_id = "uuid:multi".to_string();
418
419 // Buffer two events before registering
420 router
421 .route_event(sub_id.clone(), "<event>first</event>".to_string())
422 .await;
423 router
424 .route_event(sub_id.clone(), "<event>second</event>".to_string())
425 .await;
426
427 // Register — both events should be replayed
428 router.register(sub_id.clone()).await;
429
430 let p1 = rx.try_recv().expect("expected first replayed event");
431 assert!(p1.event_xml.contains("first"));
432
433 let p2 = rx.try_recv().expect("expected second replayed event");
434 assert!(p2.event_xml.contains("second"));
435
436 // No more events
437 assert!(rx.try_recv().is_err());
438 }
439
440 /// The pending buffer is hard-capped so unknown-SID traffic cannot grow it
441 /// without bound. Only `register()` used to sweep the buffer, so a sender
442 /// spraying random SIDs would never trigger cleanup.
443 #[tokio::test]
444 async fn test_pending_buffer_is_bounded() {
445 let (tx, _rx) = mpsc::unbounded_channel();
446 let router = EventRouter::new(tx);
447
448 for i in 0..(MAX_PENDING_EVENTS + 50) {
449 router
450 .route_event(
451 format!("uuid:unknown-{i}"),
452 "<event>spam</event>".to_string(),
453 )
454 .await;
455 }
456
457 let state = router.state.read().await;
458 assert!(
459 state.pending.len() <= MAX_PENDING_EVENTS,
460 "pending buffer grew to {} entries (cap is {MAX_PENDING_EVENTS})",
461 state.pending.len()
462 );
463 }
464
465 /// Dropping the oldest entry keeps the newest events, which are the ones a
466 /// pending `register()` is most likely to still care about.
467 #[tokio::test]
468 async fn test_pending_buffer_evicts_oldest_first() {
469 let (tx, mut rx) = mpsc::unbounded_channel();
470 let router = EventRouter::new(tx);
471
472 // First event is the oldest and should be evicted once the cap is hit.
473 router
474 .route_event(
475 "uuid:oldest".to_string(),
476 "<event>oldest</event>".to_string(),
477 )
478 .await;
479 for i in 0..MAX_PENDING_EVENTS {
480 router
481 .route_event(
482 format!("uuid:filler-{i}"),
483 "<event>filler</event>".to_string(),
484 )
485 .await;
486 }
487
488 // The evicted SID has nothing to replay.
489 router.register("uuid:oldest".to_string()).await;
490 assert!(rx.try_recv().is_err(), "oldest entry should be evicted");
491
492 // The most recent SID is still buffered and replays fine.
493 let newest = format!("uuid:filler-{}", MAX_PENDING_EVENTS - 1);
494 router.register(newest.clone()).await;
495 let payload = rx
496 .try_recv()
497 .expect("newest entry should still be buffered");
498 assert_eq!(payload.subscription_id, newest);
499 }
500
501 /// Stale entries are swept by `route_event`, not only by `register()`.
502 #[tokio::test]
503 async fn test_stale_entries_swept_on_route() {
504 let (tx, _rx) = mpsc::unbounded_channel();
505 let router = EventRouter::new(tx);
506
507 {
508 let mut state = router.state.write().await;
509 state.pending.push((
510 "uuid:stale".to_string(),
511 "<event>stale</event>".to_string(),
512 stale_instant(Duration::from_secs(10)),
513 ));
514 }
515
516 router
517 .route_event("uuid:fresh".to_string(), "<event>fresh</event>".to_string())
518 .await;
519
520 let state = router.state.read().await;
521 assert_eq!(state.pending.len(), 1, "stale entry should have been swept");
522 assert_eq!(state.pending[0].0, "uuid:fresh");
523 }
524
525 /// Buffered events for different SIDs don't interfere.
526 #[tokio::test]
527 async fn test_buffer_isolates_different_sids() {
528 let (tx, mut rx) = mpsc::unbounded_channel();
529 let router = EventRouter::new(tx);
530
531 // Buffer events for two different SIDs
532 router
533 .route_event("uuid:sid-a".to_string(), "<event>a</event>".to_string())
534 .await;
535 router
536 .route_event("uuid:sid-b".to_string(), "<event>b</event>".to_string())
537 .await;
538
539 // Register only SID-A
540 router.register("uuid:sid-a".to_string()).await;
541
542 // Only SID-A's event should be replayed
543 let p = rx.try_recv().expect("expected replayed event for sid-a");
544 assert_eq!(p.subscription_id, "uuid:sid-a");
545 assert!(p.event_xml.contains("a"));
546
547 // SID-B's event is still in the buffer
548 assert!(rx.try_recv().is_err());
549
550 // Now register SID-B
551 router.register("uuid:sid-b".to_string()).await;
552
553 let p2 = rx.try_recv().expect("expected replayed event for sid-b");
554 assert_eq!(p2.subscription_id, "uuid:sid-b");
555 assert!(p2.event_xml.contains("b"));
556 }
557}