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 #[tokio::test]
243 async fn test_event_router_register_and_route() {
244 let (tx, mut rx) = mpsc::unbounded_channel();
245 let router = EventRouter::new(tx);
246
247 let sub_id = "test-sub-123".to_string();
248
249 // Register subscription
250 router.register(sub_id.clone()).await;
251
252 // Route an event
253 let event_xml = "<event>test</event>".to_string();
254 router.route_event(sub_id.clone(), event_xml.clone()).await;
255
256 // Verify payload was sent
257 let payload = rx.recv().await.unwrap();
258 assert_eq!(payload.subscription_id, sub_id);
259 assert_eq!(payload.event_xml, event_xml);
260 }
261
262 #[tokio::test]
263 async fn test_replayed_event_keeps_original_arrival_instant() {
264 // An event that arrives before its SID is registered is buffered and
265 // replayed later. Downstream orders writes by `received_at`, so the
266 // replayed payload must carry when it *arrived*, not when it was
267 // replayed — otherwise a notification held in the buffer would come out
268 // looking freshly observed and could displace a newer local write.
269 let (tx, mut rx) = mpsc::unbounded_channel();
270 let router = EventRouter::new(tx);
271
272 let sub_id = "test-sub-replay".to_string();
273
274 // Arrives before registration, so it is buffered.
275 let before = Instant::now();
276 router
277 .route_event(sub_id.clone(), "<event>buffered</event>".to_string())
278 .await;
279 assert!(rx.try_recv().is_err(), "precondition: event was buffered");
280
281 // Time passes, then registration replays it.
282 tokio::time::sleep(Duration::from_millis(20)).await;
283 let after_delay = Instant::now();
284 router.register(sub_id.clone()).await;
285
286 let payload = rx.try_recv().expect("buffered event should be replayed");
287 assert_eq!(payload.subscription_id, sub_id);
288 assert!(
289 payload.received_at >= before && payload.received_at < after_delay,
290 "replayed payload must keep its original arrival instant, not the replay instant"
291 );
292 }
293
294 #[tokio::test]
295 async fn test_event_router_unregister() {
296 let (tx, mut rx) = mpsc::unbounded_channel();
297 let router = EventRouter::new(tx);
298
299 let sub_id = "test-sub-123".to_string();
300
301 // Register and then unregister
302 router.register(sub_id.clone()).await;
303 router.unregister(&sub_id).await;
304
305 // Route an event — should be buffered (not delivered), since SID is unregistered
306 let event_xml = "<event>test</event>".to_string();
307 router.route_event(sub_id, event_xml).await;
308
309 // No immediate payload — event was buffered, not routed
310 assert!(rx.try_recv().is_err());
311 }
312
313 #[tokio::test]
314 async fn test_event_router_unknown_subscription_buffers() {
315 let (tx, mut rx) = mpsc::unbounded_channel();
316 let router = EventRouter::new(tx);
317
318 // Route event for unknown subscription — should be buffered, not dropped
319 router
320 .route_event("unknown-sub".to_string(), "<event>test</event>".to_string())
321 .await;
322
323 // No immediate payload — event was buffered
324 assert!(rx.try_recv().is_err());
325 }
326
327 /// Proves the registration race condition: an event arriving before register()
328 /// should be buffered and replayed when register() is called.
329 #[tokio::test]
330 async fn test_event_buffered_and_replayed_on_late_register() {
331 let (tx, mut rx) = mpsc::unbounded_channel();
332 let router = EventRouter::new(tx);
333
334 let sub_id = "uuid:late-register".to_string();
335 let event_xml =
336 "<e:propertyset><CurrentPlayMode>NORMAL</CurrentPlayMode></e:propertyset>".to_string();
337
338 // 1. Event arrives BEFORE register (the race condition)
339 router.route_event(sub_id.clone(), event_xml.clone()).await;
340
341 // 2. Register happens moments later
342 router.register(sub_id.clone()).await;
343
344 // 3. The buffered event should have been replayed on register
345 let payload = rx.try_recv().expect("expected replayed event");
346 assert_eq!(payload.subscription_id, sub_id);
347 assert_eq!(payload.event_xml, event_xml);
348 }
349
350 /// Stale buffered events (older than BUFFER_TTL) are cleaned up during register().
351 #[tokio::test]
352 async fn test_stale_buffer_entries_cleaned_on_register() {
353 let (tx, mut rx) = mpsc::unbounded_channel();
354 let router = EventRouter::new(tx);
355
356 // Manually insert a stale entry by writing to state directly
357 {
358 let mut state = router.state.write().await;
359 state.pending.push((
360 "uuid:stale-sid".to_string(),
361 "<event>stale</event>".to_string(),
362 Instant::now() - Duration::from_secs(10), // 10s ago, well past TTL
363 ));
364 }
365
366 // Register a different SID — should clean up the stale entry
367 router.register("uuid:fresh-sid".to_string()).await;
368
369 // No events replayed (the stale entry was for a different SID and expired)
370 assert!(rx.try_recv().is_err());
371
372 // Verify the stale entry was cleaned up
373 let state = router.state.read().await;
374 assert!(state.pending.is_empty(), "stale entry should be cleaned up");
375 }
376
377 /// unregister() drains buffered events for the removed SID.
378 #[tokio::test]
379 async fn test_unregister_drains_buffer() {
380 let (tx, mut rx) = mpsc::unbounded_channel();
381 let router = EventRouter::new(tx);
382
383 let sub_id = "uuid:drain-test".to_string();
384
385 // Buffer an event
386 router
387 .route_event(sub_id.clone(), "<event>buffered</event>".to_string())
388 .await;
389
390 // Unregister — should drain the buffered event
391 router.unregister(&sub_id).await;
392
393 // Re-register — should NOT replay the drained event
394 router.register(sub_id.clone()).await;
395
396 // No events replayed (buffer was drained by unregister)
397 assert!(rx.try_recv().is_err());
398 }
399
400 /// Multiple buffered events for the same SID are all replayed.
401 #[tokio::test]
402 async fn test_multiple_buffered_events_replayed() {
403 let (tx, mut rx) = mpsc::unbounded_channel();
404 let router = EventRouter::new(tx);
405
406 let sub_id = "uuid:multi".to_string();
407
408 // Buffer two events before registering
409 router
410 .route_event(sub_id.clone(), "<event>first</event>".to_string())
411 .await;
412 router
413 .route_event(sub_id.clone(), "<event>second</event>".to_string())
414 .await;
415
416 // Register — both events should be replayed
417 router.register(sub_id.clone()).await;
418
419 let p1 = rx.try_recv().expect("expected first replayed event");
420 assert!(p1.event_xml.contains("first"));
421
422 let p2 = rx.try_recv().expect("expected second replayed event");
423 assert!(p2.event_xml.contains("second"));
424
425 // No more events
426 assert!(rx.try_recv().is_err());
427 }
428
429 /// The pending buffer is hard-capped so unknown-SID traffic cannot grow it
430 /// without bound. Only `register()` used to sweep the buffer, so a sender
431 /// spraying random SIDs would never trigger cleanup.
432 #[tokio::test]
433 async fn test_pending_buffer_is_bounded() {
434 let (tx, _rx) = mpsc::unbounded_channel();
435 let router = EventRouter::new(tx);
436
437 for i in 0..(MAX_PENDING_EVENTS + 50) {
438 router
439 .route_event(
440 format!("uuid:unknown-{i}"),
441 "<event>spam</event>".to_string(),
442 )
443 .await;
444 }
445
446 let state = router.state.read().await;
447 assert!(
448 state.pending.len() <= MAX_PENDING_EVENTS,
449 "pending buffer grew to {} entries (cap is {MAX_PENDING_EVENTS})",
450 state.pending.len()
451 );
452 }
453
454 /// Dropping the oldest entry keeps the newest events, which are the ones a
455 /// pending `register()` is most likely to still care about.
456 #[tokio::test]
457 async fn test_pending_buffer_evicts_oldest_first() {
458 let (tx, mut rx) = mpsc::unbounded_channel();
459 let router = EventRouter::new(tx);
460
461 // First event is the oldest and should be evicted once the cap is hit.
462 router
463 .route_event(
464 "uuid:oldest".to_string(),
465 "<event>oldest</event>".to_string(),
466 )
467 .await;
468 for i in 0..MAX_PENDING_EVENTS {
469 router
470 .route_event(
471 format!("uuid:filler-{i}"),
472 "<event>filler</event>".to_string(),
473 )
474 .await;
475 }
476
477 // The evicted SID has nothing to replay.
478 router.register("uuid:oldest".to_string()).await;
479 assert!(rx.try_recv().is_err(), "oldest entry should be evicted");
480
481 // The most recent SID is still buffered and replays fine.
482 let newest = format!("uuid:filler-{}", MAX_PENDING_EVENTS - 1);
483 router.register(newest.clone()).await;
484 let payload = rx
485 .try_recv()
486 .expect("newest entry should still be buffered");
487 assert_eq!(payload.subscription_id, newest);
488 }
489
490 /// Stale entries are swept by `route_event`, not only by `register()`.
491 #[tokio::test]
492 async fn test_stale_entries_swept_on_route() {
493 let (tx, _rx) = mpsc::unbounded_channel();
494 let router = EventRouter::new(tx);
495
496 {
497 let mut state = router.state.write().await;
498 state.pending.push((
499 "uuid:stale".to_string(),
500 "<event>stale</event>".to_string(),
501 Instant::now() - Duration::from_secs(10),
502 ));
503 }
504
505 router
506 .route_event("uuid:fresh".to_string(), "<event>fresh</event>".to_string())
507 .await;
508
509 let state = router.state.read().await;
510 assert_eq!(state.pending.len(), 1, "stale entry should have been swept");
511 assert_eq!(state.pending[0].0, "uuid:fresh");
512 }
513
514 /// Buffered events for different SIDs don't interfere.
515 #[tokio::test]
516 async fn test_buffer_isolates_different_sids() {
517 let (tx, mut rx) = mpsc::unbounded_channel();
518 let router = EventRouter::new(tx);
519
520 // Buffer events for two different SIDs
521 router
522 .route_event("uuid:sid-a".to_string(), "<event>a</event>".to_string())
523 .await;
524 router
525 .route_event("uuid:sid-b".to_string(), "<event>b</event>".to_string())
526 .await;
527
528 // Register only SID-A
529 router.register("uuid:sid-a".to_string()).await;
530
531 // Only SID-A's event should be replayed
532 let p = rx.try_recv().expect("expected replayed event for sid-a");
533 assert_eq!(p.subscription_id, "uuid:sid-a");
534 assert!(p.event_xml.contains("a"));
535
536 // SID-B's event is still in the buffer
537 assert!(rx.try_recv().is_err());
538
539 // Now register SID-B
540 router.register("uuid:sid-b".to_string()).await;
541
542 let p2 = rx.try_recv().expect("expected replayed event for sid-b");
543 assert_eq!(p2.subscription_id, "uuid:sid-b");
544 assert!(p2.event_xml.contains("b"));
545 }
546}