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 and raw XML body,
39/// with 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}
47
48/// Internal state protected by a single lock to eliminate TOCTOU gaps.
49struct RouterState {
50 subscriptions: HashSet<String>,
51 /// Flat buffer of (subscription_id, event_xml, buffered_at).
52 /// Expected size: 0-5 entries for well-behaved senders — only populated
53 /// during the microsecond race window between SUBSCRIBE response and
54 /// register(). Hard-capped at `MAX_PENDING_EVENTS` because the HTTP endpoint
55 /// is unauthenticated and cannot rely on senders being well-behaved.
56 pending: Vec<(String, String, Instant)>,
57}
58
59impl RouterState {
60 /// Drop buffered entries older than `BUFFER_TTL`.
61 fn sweep_stale(&mut self) {
62 let now = Instant::now();
63 self.pending
64 .retain(|(_, _, buffered_at)| now.duration_since(*buffered_at) <= BUFFER_TTL);
65 }
66
67 /// Buffer an event, enforcing `MAX_PENDING_EVENTS` by dropping the oldest.
68 fn push_pending(&mut self, subscription_id: String, event_xml: String) {
69 self.sweep_stale();
70
71 while self.pending.len() >= MAX_PENDING_EVENTS {
72 // Evict by timestamp rather than position: swap_remove elsewhere
73 // means index order does not track insertion order.
74 let oldest = self
75 .pending
76 .iter()
77 .enumerate()
78 .min_by_key(|(_, (_, _, at))| *at)
79 .map(|(i, _)| i);
80 match oldest {
81 Some(i) => {
82 let (sid, _, _) = self.pending.remove(i);
83 debug!(
84 sid = %sid,
85 cap = MAX_PENDING_EVENTS,
86 "Pending event buffer full; dropped oldest entry"
87 );
88 }
89 None => break,
90 }
91 }
92
93 self.pending
94 .push((subscription_id, event_xml, Instant::now()));
95 }
96}
97
98/// Routes events from HTTP callbacks to a channel.
99///
100/// The `EventRouter` maintains a set of active subscription IDs. When an event
101/// is received via HTTP callback, the router checks if the subscription is
102/// registered and sends the notification payload to the configured channel.
103///
104/// Events for unregistered SIDs are buffered briefly and replayed when
105/// `register()` is called, preventing the race between SUBSCRIBE response
106/// and initial UPnP NOTIFY delivery.
107#[derive(Clone)]
108pub struct EventRouter {
109 state: Arc<RwLock<RouterState>>,
110 /// Channel for sending notification payloads
111 event_sender: mpsc::UnboundedSender<NotificationPayload>,
112}
113
114impl EventRouter {
115 /// Create a new event router.
116 ///
117 /// # Arguments
118 ///
119 /// * `event_sender` - Channel for sending notification payloads
120 ///
121 /// # Example
122 ///
123 /// ```
124 /// use tokio::sync::mpsc;
125 /// use callback_server::router::{EventRouter, NotificationPayload};
126 ///
127 /// let (tx, mut rx) = mpsc::unbounded_channel::<NotificationPayload>();
128 /// let router = EventRouter::new(tx);
129 /// ```
130 pub fn new(event_sender: mpsc::UnboundedSender<NotificationPayload>) -> Self {
131 Self {
132 state: Arc::new(RwLock::new(RouterState {
133 subscriptions: HashSet::new(),
134 pending: Vec::new(),
135 })),
136 event_sender,
137 }
138 }
139
140 /// Register a subscription ID for event routing.
141 ///
142 /// Adds the SID to the active set and replays any buffered events that
143 /// arrived before registration (the SUBSCRIBE/NOTIFY race window).
144 /// Also cleans up stale buffer entries older than `BUFFER_TTL`.
145 pub async fn register(&self, subscription_id: String) {
146 let mut state = self.state.write().await;
147 state.subscriptions.insert(subscription_id.clone());
148
149 // Replay buffered events for this SID and remove stale entries.
150 let now = Instant::now();
151 let mut i = 0;
152 while i < state.pending.len() {
153 let (ref sid, _, buffered_at) = state.pending[i];
154 if sid == &subscription_id {
155 let (_, xml, _) = state.pending.swap_remove(i);
156 debug!(sid = %subscription_id, "Replayed buffered event");
157 let payload = NotificationPayload {
158 subscription_id: subscription_id.clone(),
159 event_xml: xml,
160 };
161 let _ = self.event_sender.send(payload);
162 // Don't increment i — swap_remove moved the last element here
163 } else if now.duration_since(buffered_at) > BUFFER_TTL {
164 state.pending.swap_remove(i);
165 // Don't increment i
166 } else {
167 i += 1;
168 }
169 }
170 }
171
172 /// Unregister a subscription ID.
173 ///
174 /// Removes the SID from the active set and drains any buffered events
175 /// for it, preventing stale replays on future re-registration.
176 pub async fn unregister(&self, subscription_id: &str) {
177 let mut state = self.state.write().await;
178 state.subscriptions.remove(subscription_id);
179 state.pending.retain(|(sid, _, _)| sid != subscription_id);
180 }
181
182 /// Route an incoming event to the unified event stream.
183 ///
184 /// If the subscription is registered, the event is sent immediately.
185 /// If not, the event is buffered for replay when `register()` is called.
186 /// The caller should always return HTTP 200 OK — buffered events are
187 /// accepted for processing, not rejected.
188 ///
189 /// Buffering sweeps entries older than `BUFFER_TTL` and enforces a hard cap
190 /// of `MAX_PENDING_EVENTS`, dropping the oldest entry on overflow. Without
191 /// this, unrecognised SIDs could grow the buffer without bound.
192 pub async fn route_event(&self, subscription_id: String, event_xml: String) {
193 let mut state = self.state.write().await;
194 if state.subscriptions.contains(&subscription_id) {
195 let payload = NotificationPayload {
196 subscription_id,
197 event_xml,
198 };
199 let _ = self.event_sender.send(payload);
200 } else {
201 debug!(sid = %subscription_id, "Buffered event for pending SID");
202 // Sweeps stale entries and enforces MAX_PENDING_EVENTS. Doing this
203 // here (not only in register()) is what bounds the buffer: register()
204 // is called on genuine new subscriptions only, so events for random
205 // SIDs would otherwise never trigger cleanup.
206 state.push_pending(subscription_id, event_xml);
207 }
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[tokio::test]
216 async fn test_event_router_register_and_route() {
217 let (tx, mut rx) = mpsc::unbounded_channel();
218 let router = EventRouter::new(tx);
219
220 let sub_id = "test-sub-123".to_string();
221
222 // Register subscription
223 router.register(sub_id.clone()).await;
224
225 // Route an event
226 let event_xml = "<event>test</event>".to_string();
227 router.route_event(sub_id.clone(), event_xml.clone()).await;
228
229 // Verify payload was sent
230 let payload = rx.recv().await.unwrap();
231 assert_eq!(payload.subscription_id, sub_id);
232 assert_eq!(payload.event_xml, event_xml);
233 }
234
235 #[tokio::test]
236 async fn test_event_router_unregister() {
237 let (tx, mut rx) = mpsc::unbounded_channel();
238 let router = EventRouter::new(tx);
239
240 let sub_id = "test-sub-123".to_string();
241
242 // Register and then unregister
243 router.register(sub_id.clone()).await;
244 router.unregister(&sub_id).await;
245
246 // Route an event — should be buffered (not delivered), since SID is unregistered
247 let event_xml = "<event>test</event>".to_string();
248 router.route_event(sub_id, event_xml).await;
249
250 // No immediate payload — event was buffered, not routed
251 assert!(rx.try_recv().is_err());
252 }
253
254 #[tokio::test]
255 async fn test_event_router_unknown_subscription_buffers() {
256 let (tx, mut rx) = mpsc::unbounded_channel();
257 let router = EventRouter::new(tx);
258
259 // Route event for unknown subscription — should be buffered, not dropped
260 router
261 .route_event("unknown-sub".to_string(), "<event>test</event>".to_string())
262 .await;
263
264 // No immediate payload — event was buffered
265 assert!(rx.try_recv().is_err());
266 }
267
268 /// Proves the registration race condition: an event arriving before register()
269 /// should be buffered and replayed when register() is called.
270 #[tokio::test]
271 async fn test_event_buffered_and_replayed_on_late_register() {
272 let (tx, mut rx) = mpsc::unbounded_channel();
273 let router = EventRouter::new(tx);
274
275 let sub_id = "uuid:late-register".to_string();
276 let event_xml =
277 "<e:propertyset><CurrentPlayMode>NORMAL</CurrentPlayMode></e:propertyset>".to_string();
278
279 // 1. Event arrives BEFORE register (the race condition)
280 router.route_event(sub_id.clone(), event_xml.clone()).await;
281
282 // 2. Register happens moments later
283 router.register(sub_id.clone()).await;
284
285 // 3. The buffered event should have been replayed on register
286 let payload = rx.try_recv().expect("expected replayed event");
287 assert_eq!(payload.subscription_id, sub_id);
288 assert_eq!(payload.event_xml, event_xml);
289 }
290
291 /// Stale buffered events (older than BUFFER_TTL) are cleaned up during register().
292 #[tokio::test]
293 async fn test_stale_buffer_entries_cleaned_on_register() {
294 let (tx, mut rx) = mpsc::unbounded_channel();
295 let router = EventRouter::new(tx);
296
297 // Manually insert a stale entry by writing to state directly
298 {
299 let mut state = router.state.write().await;
300 state.pending.push((
301 "uuid:stale-sid".to_string(),
302 "<event>stale</event>".to_string(),
303 Instant::now() - Duration::from_secs(10), // 10s ago, well past TTL
304 ));
305 }
306
307 // Register a different SID — should clean up the stale entry
308 router.register("uuid:fresh-sid".to_string()).await;
309
310 // No events replayed (the stale entry was for a different SID and expired)
311 assert!(rx.try_recv().is_err());
312
313 // Verify the stale entry was cleaned up
314 let state = router.state.read().await;
315 assert!(state.pending.is_empty(), "stale entry should be cleaned up");
316 }
317
318 /// unregister() drains buffered events for the removed SID.
319 #[tokio::test]
320 async fn test_unregister_drains_buffer() {
321 let (tx, mut rx) = mpsc::unbounded_channel();
322 let router = EventRouter::new(tx);
323
324 let sub_id = "uuid:drain-test".to_string();
325
326 // Buffer an event
327 router
328 .route_event(sub_id.clone(), "<event>buffered</event>".to_string())
329 .await;
330
331 // Unregister — should drain the buffered event
332 router.unregister(&sub_id).await;
333
334 // Re-register — should NOT replay the drained event
335 router.register(sub_id.clone()).await;
336
337 // No events replayed (buffer was drained by unregister)
338 assert!(rx.try_recv().is_err());
339 }
340
341 /// Multiple buffered events for the same SID are all replayed.
342 #[tokio::test]
343 async fn test_multiple_buffered_events_replayed() {
344 let (tx, mut rx) = mpsc::unbounded_channel();
345 let router = EventRouter::new(tx);
346
347 let sub_id = "uuid:multi".to_string();
348
349 // Buffer two events before registering
350 router
351 .route_event(sub_id.clone(), "<event>first</event>".to_string())
352 .await;
353 router
354 .route_event(sub_id.clone(), "<event>second</event>".to_string())
355 .await;
356
357 // Register — both events should be replayed
358 router.register(sub_id.clone()).await;
359
360 let p1 = rx.try_recv().expect("expected first replayed event");
361 assert!(p1.event_xml.contains("first"));
362
363 let p2 = rx.try_recv().expect("expected second replayed event");
364 assert!(p2.event_xml.contains("second"));
365
366 // No more events
367 assert!(rx.try_recv().is_err());
368 }
369
370 /// The pending buffer is hard-capped so unknown-SID traffic cannot grow it
371 /// without bound. Only `register()` used to sweep the buffer, so a sender
372 /// spraying random SIDs would never trigger cleanup.
373 #[tokio::test]
374 async fn test_pending_buffer_is_bounded() {
375 let (tx, _rx) = mpsc::unbounded_channel();
376 let router = EventRouter::new(tx);
377
378 for i in 0..(MAX_PENDING_EVENTS + 50) {
379 router
380 .route_event(
381 format!("uuid:unknown-{i}"),
382 "<event>spam</event>".to_string(),
383 )
384 .await;
385 }
386
387 let state = router.state.read().await;
388 assert!(
389 state.pending.len() <= MAX_PENDING_EVENTS,
390 "pending buffer grew to {} entries (cap is {MAX_PENDING_EVENTS})",
391 state.pending.len()
392 );
393 }
394
395 /// Dropping the oldest entry keeps the newest events, which are the ones a
396 /// pending `register()` is most likely to still care about.
397 #[tokio::test]
398 async fn test_pending_buffer_evicts_oldest_first() {
399 let (tx, mut rx) = mpsc::unbounded_channel();
400 let router = EventRouter::new(tx);
401
402 // First event is the oldest and should be evicted once the cap is hit.
403 router
404 .route_event(
405 "uuid:oldest".to_string(),
406 "<event>oldest</event>".to_string(),
407 )
408 .await;
409 for i in 0..MAX_PENDING_EVENTS {
410 router
411 .route_event(
412 format!("uuid:filler-{i}"),
413 "<event>filler</event>".to_string(),
414 )
415 .await;
416 }
417
418 // The evicted SID has nothing to replay.
419 router.register("uuid:oldest".to_string()).await;
420 assert!(rx.try_recv().is_err(), "oldest entry should be evicted");
421
422 // The most recent SID is still buffered and replays fine.
423 let newest = format!("uuid:filler-{}", MAX_PENDING_EVENTS - 1);
424 router.register(newest.clone()).await;
425 let payload = rx
426 .try_recv()
427 .expect("newest entry should still be buffered");
428 assert_eq!(payload.subscription_id, newest);
429 }
430
431 /// Stale entries are swept by `route_event`, not only by `register()`.
432 #[tokio::test]
433 async fn test_stale_entries_swept_on_route() {
434 let (tx, _rx) = mpsc::unbounded_channel();
435 let router = EventRouter::new(tx);
436
437 {
438 let mut state = router.state.write().await;
439 state.pending.push((
440 "uuid:stale".to_string(),
441 "<event>stale</event>".to_string(),
442 Instant::now() - Duration::from_secs(10),
443 ));
444 }
445
446 router
447 .route_event("uuid:fresh".to_string(), "<event>fresh</event>".to_string())
448 .await;
449
450 let state = router.state.read().await;
451 assert_eq!(state.pending.len(), 1, "stale entry should have been swept");
452 assert_eq!(state.pending[0].0, "uuid:fresh");
453 }
454
455 /// Buffered events for different SIDs don't interfere.
456 #[tokio::test]
457 async fn test_buffer_isolates_different_sids() {
458 let (tx, mut rx) = mpsc::unbounded_channel();
459 let router = EventRouter::new(tx);
460
461 // Buffer events for two different SIDs
462 router
463 .route_event("uuid:sid-a".to_string(), "<event>a</event>".to_string())
464 .await;
465 router
466 .route_event("uuid:sid-b".to_string(), "<event>b</event>".to_string())
467 .await;
468
469 // Register only SID-A
470 router.register("uuid:sid-a".to_string()).await;
471
472 // Only SID-A's event should be replayed
473 let p = rx.try_recv().expect("expected replayed event for sid-a");
474 assert_eq!(p.subscription_id, "uuid:sid-a");
475 assert!(p.event_xml.contains("a"));
476
477 // SID-B's event is still in the buffer
478 assert!(rx.try_recv().is_err());
479
480 // Now register SID-B
481 router.register("uuid:sid-b".to_string()).await;
482
483 let p2 = rx.try_recv().expect("expected replayed event for sid-b");
484 assert_eq!(p2.subscription_id, "uuid:sid-b");
485 assert!(p2.event_xml.contains("b"));
486 }
487}