Skip to main content

ssai_runtime/
session.rs

1//! Per-session ad-break state.
2//!
3//! Issue #929's design decision: the per-session record is session id ->
4//! ad-break decision -> timeline offsets, and it is deliberately **not** a
5//! media cursor. Every viewer in a break watches one of a small set of ad
6//! assets, and outside a break every viewer sees byte-identical primary
7//! content; what differs per session is which URIs appear in that session's
8//! rendered playlist. `media-plane`'s "writer cost is O(N) in cursor count"
9//! rule is about the shared media rings — a `SessionStore` holds no cursor
10//! into any of them, just this one small [`BreakState`] record per session.
11
12use crate::decision::AdBreakDecision;
13use crate::error::{Error, Result};
14use crate::splice::ConditionedSplicePoint;
15use alloc::collections::BTreeMap;
16use alloc::string::String;
17use broadcast_core::stage::Instant;
18use core::time::Duration;
19
20/// One session's ad break: the decision being rendered, plus the conditioned
21/// splice points it entered (and, once known, resumed) at.
22// `AdBreakDecision` is `PartialEq`-only (carries `f64` fields), so this is too.
23#[derive(Debug, Clone, PartialEq)]
24pub struct BreakState {
25    /// The decision being rendered for this break.
26    pub decision: AdBreakDecision,
27    /// The conditioned splice point the break was entered at.
28    pub entered_at: ConditionedSplicePoint,
29    /// The conditioned splice point playback resumed at, once known.
30    pub resumed_at: Option<ConditionedSplicePoint>,
31}
32
33impl BreakState {
34    /// Start a new break with no resumption point yet known.
35    pub fn new(decision: AdBreakDecision, entered_at: ConditionedSplicePoint) -> Self {
36        BreakState {
37            decision,
38            entered_at,
39            resumed_at: None,
40        }
41    }
42
43    /// Whether [`Self::resumed_at`] has been recorded (the break has ended).
44    pub fn is_resumed(&self) -> bool {
45        self.resumed_at.is_some()
46    }
47}
48
49/// Embedded: one channel's ad breaks on a small device. No run-time cost: a timing or retry count.
50const SSAI_MAX_SESSIONS_EMBEDDED: usize = 16;
51/// Device: one playback session plus a few followers.
52const SSAI_MAX_SESSIONS_DEVICE: usize = 64;
53/// Server: the ad breaks of a few channels.
54const SSAI_MAX_SESSIONS_SERVER: usize = 512;
55/// Headend: a whole multiplex's breaks.
56const SSAI_MAX_SESSIONS_HEADEND: usize = 2048;
57
58/// Embedded: a short decision on a small device. Provisional until measured (#4834): an SSAI session would exercise it.
59const SSAI_MAX_DECISION_ITEMS_EMBEDDED: usize = 8;
60/// Device: the identifiers one ad decision carries.
61const SSAI_MAX_DECISION_ITEMS_DEVICE: usize = 32;
62/// Server: a decision from several providers.
63const SSAI_MAX_DECISION_ITEMS_SERVER: usize = 128;
64/// Headend: the widest decision carried.
65const SSAI_MAX_DECISION_ITEMS_HEADEND: usize = 512;
66/// Every profile: the old Headend decision-document ceiling, 256 KiB, a hostile-input bound (#4809).
67const SSAI_MAX_DECISION_TEXT_BYTES: usize = 256 << 10;
68
69/// The bounds a [`SessionStore`] holds, all chosen by the caller.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct SessionLimits {
72    /// Sessions tracked at once (at least 1 is enforced).
73    pub max_sessions: usize,
74    /// `X-SNAP` plus `X-RESTRICT` identifiers one break's decision may carry.
75    pub max_decision_items: usize,
76    /// Bytes of the decision's `ID` and asset URI taken together.
77    pub max_decision_text_bytes: usize,
78}
79
80impl SessionLimits {
81    /// The [`broadcast_core::Profile`] preset: every field is a documented constant of
82    /// this module, replaceable through its `with_*` setter.
83    #[must_use]
84    pub fn for_profile(profile: broadcast_core::Profile) -> Self {
85        Self {
86            max_sessions: profile.select(
87                SSAI_MAX_SESSIONS_EMBEDDED,
88                SSAI_MAX_SESSIONS_DEVICE,
89                SSAI_MAX_SESSIONS_SERVER,
90                SSAI_MAX_SESSIONS_HEADEND,
91            ),
92            max_decision_items: profile.select(
93                SSAI_MAX_DECISION_ITEMS_EMBEDDED,
94                SSAI_MAX_DECISION_ITEMS_DEVICE,
95                SSAI_MAX_DECISION_ITEMS_SERVER,
96                SSAI_MAX_DECISION_ITEMS_HEADEND,
97            ),
98            max_decision_text_bytes: SSAI_MAX_DECISION_TEXT_BYTES,
99        }
100    }
101
102    /// Replace [`Self::max_sessions`].
103    #[must_use]
104    pub fn with_max_sessions(mut self, max_sessions: usize) -> Self {
105        self.max_sessions = max_sessions;
106        self
107    }
108
109    /// Replace [`Self::max_decision_items`].
110    #[must_use]
111    pub fn with_max_decision_items(mut self, max_decision_items: usize) -> Self {
112        self.max_decision_items = max_decision_items;
113        self
114    }
115
116    /// Replace [`Self::max_decision_text_bytes`].
117    #[must_use]
118    pub fn with_max_decision_text_bytes(mut self, max_decision_text_bytes: usize) -> Self {
119        self.max_decision_text_bytes = max_decision_text_bytes;
120        self
121    }
122}
123
124/// Per-session ad-break records.
125///
126/// A `BTreeMap` keyed by session id: the records here are small (one
127/// [`BreakState`] per session, per the module's design decision), so there
128/// is no per-peer *media* state to bound with a cursor count the way
129/// `media-plane`'s `Trunk` must. The store is nonetheless bounded: it holds at
130/// most [`SessionLimits::max_sessions`] sessions, and [`Self::begin_break`] for a new session id
131/// past that is [`Error::SessionStoreFull`], so a flood of distinct ids cannot
132/// grow it forever. This crate has no clock of its own: the caller feeds the
133/// time in with [`Self::advance`] and calls [`Self::expire_idle`] to drop
134/// sessions nobody has touched for a while; [`Self::end`] evicts one directly.
135#[derive(Debug, Clone)]
136pub struct SessionStore {
137    sessions: BTreeMap<String, Tracked>,
138    limits: SessionLimits,
139    now_us: u64,
140}
141
142#[derive(Debug, Clone)]
143struct Tracked {
144    state: BreakState,
145    touched_us: u64,
146}
147
148impl SessionStore {
149    /// An empty store held to the caller's `limits`.
150    pub fn new(limits: SessionLimits) -> Self {
151        SessionStore {
152            sessions: BTreeMap::new(),
153            limits: SessionLimits {
154                max_sessions: limits.max_sessions.max(1),
155                ..limits
156            },
157            now_us: 0,
158        }
159    }
160
161    /// Moves the store's clock to `now` (the caller's own monotonic clock, the
162    /// `broadcast_core::stage::Instant` every sans-IO engine takes; a value
163    /// earlier than the current one is ignored). Records touched from now on
164    /// carry this time.
165    pub fn advance(&mut self, now: Instant) {
166        self.now_us = self.now_us.max(now.as_micros());
167    }
168
169    /// Evicts every session last touched (by [`Self::begin_break`] or
170    /// [`Self::resume`]) more than `ttl` before the store's clock; returns
171    /// how many were evicted.
172    pub fn expire_idle(&mut self, ttl: Duration) -> usize {
173        let ttl_us = u64::try_from(ttl.as_micros()).unwrap_or(u64::MAX);
174        let before = self.sessions.len();
175        let now = self.now_us;
176        self.sessions
177            .retain(|_, t| now.saturating_sub(t.touched_us) <= ttl_us);
178        before - self.sessions.len()
179    }
180
181    /// Start a break for `session_id`. Errors with
182    /// [`Error::BreakAlreadyActive`] if the session already has an
183    /// unresumed break — call [`Self::resume`] or [`Self::end`] first — and
184    /// with [`Error::SessionStoreFull`] if `session_id` is new and the store
185    /// is at its bound, and with [`Error::DecisionTooLarge`] if `state`'s
186    /// decision exceeds [`SessionLimits::max_decision_items`] or
187    /// [`SessionLimits::max_decision_text_bytes`].
188    pub fn begin_break(&mut self, session_id: impl Into<String>, state: BreakState) -> Result<()> {
189        let session_id = session_id.into();
190        let decision = &state.decision;
191        let items = decision.snap.len().saturating_add(decision.restrict.len());
192        if items > self.limits.max_decision_items {
193            return Err(Error::DecisionTooLarge {
194                what: "snap and restrict identifiers",
195                max: self.limits.max_decision_items,
196            });
197        }
198        let uri = match &decision.asset {
199            crate::decision::AssetSource::Uri(u) | crate::decision::AssetSource::List(u) => u,
200        };
201        if decision.id.len().saturating_add(uri.len()) > self.limits.max_decision_text_bytes {
202            return Err(Error::DecisionTooLarge {
203                what: "id and asset uri bytes",
204                max: self.limits.max_decision_text_bytes,
205            });
206        }
207        match self.sessions.get(&session_id) {
208            Some(existing) if !existing.state.is_resumed() => {
209                return Err(Error::BreakAlreadyActive(session_id));
210            }
211            None if self.sessions.len() >= self.limits.max_sessions => {
212                return Err(Error::SessionStoreFull {
213                    max: self.limits.max_sessions,
214                });
215            }
216            _ => {}
217        }
218        self.sessions.insert(
219            session_id,
220            Tracked {
221                state,
222                touched_us: self.now_us,
223            },
224        );
225        Ok(())
226    }
227
228    /// Record the resumption point for `session_id`'s active break. Errors
229    /// with [`Error::NoActiveBreak`] if there is no record for the session and
230    /// with [`Error::BreakAlreadyResumed`] if its break was already resumed
231    /// (the first resumption point is kept).
232    pub fn resume(&mut self, session_id: &str, resumed_at: ConditionedSplicePoint) -> Result<()> {
233        let tracked = self
234            .sessions
235            .get_mut(session_id)
236            .ok_or_else(|| Error::NoActiveBreak(session_id.into()))?;
237        if tracked.state.is_resumed() {
238            return Err(Error::BreakAlreadyResumed(session_id.into()));
239        }
240        tracked.state.resumed_at = Some(resumed_at);
241        tracked.touched_us = self.now_us;
242        Ok(())
243    }
244
245    /// The current break record for `session_id`, if any. A resumed record
246    /// stays until [`Self::end`] evicts it, so a caller can still render the
247    /// just-ended break's `EXT-X-DATERANGE` for one more playlist reload.
248    pub fn get(&self, session_id: &str) -> Option<&BreakState> {
249        self.sessions.get(session_id).map(|t| &t.state)
250    }
251
252    /// Evict `session_id`'s record entirely (session ended, or its break has
253    /// aged out of the sliding window). Returns the evicted record, if any.
254    pub fn end(&mut self, session_id: &str) -> Option<BreakState> {
255        self.sessions.remove(session_id).map(|t| t.state)
256    }
257
258    /// Number of tracked sessions.
259    pub fn len(&self) -> usize {
260        self.sessions.len()
261    }
262
263    /// Whether the store is empty.
264    pub fn is_empty(&self) -> bool {
265        self.sessions.is_empty()
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272    use crate::splice::condition_splice_point;
273    use broadcast_common::clock33::Clock33;
274
275    const TEST_LIMITS: SessionLimits = SessionLimits {
276        max_sessions: 65_536,
277        max_decision_items: 64,
278        max_decision_text_bytes: 4096,
279    };
280
281    fn splice_point() -> ConditionedSplicePoint {
282        condition_splice_point(
283            Clock33::try_new(1_000).unwrap(),
284            &[Clock33::try_new(1_000).unwrap()],
285            core::time::Duration::ZERO,
286        )
287        .unwrap()
288    }
289
290    #[test]
291    fn begin_get_resume_end_lifecycle() {
292        let mut store = SessionStore::new(TEST_LIMITS);
293        assert!(store.is_empty());
294
295        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
296        store
297            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
298            .unwrap();
299        assert_eq!(store.len(), 1);
300        assert!(!store.is_empty());
301        assert!(!store.get("s1").unwrap().is_resumed());
302
303        store.resume("s1", splice_point()).unwrap();
304        assert!(store.get("s1").unwrap().is_resumed());
305
306        let evicted = store.end("s1").unwrap();
307        assert_eq!(evicted.decision, decision);
308        assert!(store.is_empty());
309    }
310
311    #[test]
312    fn cannot_begin_a_break_while_one_is_already_active() {
313        let mut store = SessionStore::new(TEST_LIMITS);
314        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
315        store
316            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
317            .unwrap();
318
319        let err = store
320            .begin_break("s1", BreakState::new(decision, splice_point()))
321            .unwrap_err();
322        assert!(matches!(err, Error::BreakAlreadyActive(ref s) if s == "s1"));
323    }
324
325    #[test]
326    fn begin_break_is_allowed_again_after_resume() {
327        let mut store = SessionStore::new(TEST_LIMITS);
328        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
329        store
330            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
331            .unwrap();
332        store.resume("s1", splice_point()).unwrap();
333
334        // A second, later break for the same session is fine once resumed.
335        store
336            .begin_break("s1", BreakState::new(decision, splice_point()))
337            .unwrap();
338        assert_eq!(store.len(), 1);
339    }
340
341    #[test]
342    fn resume_without_an_active_break_errors() {
343        let mut store = SessionStore::new(TEST_LIMITS);
344        let err = store.resume("nope", splice_point()).unwrap_err();
345        assert!(matches!(err, Error::NoActiveBreak(ref s) if s == "nope"));
346    }
347
348    #[test]
349    fn resume_on_an_already_resumed_break_keeps_the_first_point() {
350        let mut store = SessionStore::new(TEST_LIMITS);
351        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
352        store
353            .begin_break("s1", BreakState::new(decision, splice_point()))
354            .unwrap();
355        let first = condition_splice_point(
356            Clock33::try_new(2_000).unwrap(),
357            &[Clock33::try_new(2_000).unwrap()],
358            core::time::Duration::ZERO,
359        )
360        .unwrap();
361        store.resume("s1", first).unwrap();
362        let err = store.resume("s1", splice_point()).unwrap_err();
363        assert!(matches!(err, Error::BreakAlreadyResumed(ref s) if s == "s1"));
364        assert_eq!(store.get("s1").unwrap().resumed_at, Some(first));
365    }
366
367    #[test]
368    fn the_store_is_bounded_and_existing_sessions_still_begin_breaks() {
369        let mut store = SessionStore::new(SessionLimits {
370            max_sessions: 2,
371            ..TEST_LIMITS
372        });
373        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
374        for id in ["a", "b"] {
375            store
376                .begin_break(id, BreakState::new(decision.clone(), splice_point()))
377                .unwrap();
378        }
379        let err = store
380            .begin_break("c", BreakState::new(decision.clone(), splice_point()))
381            .unwrap_err();
382        assert!(matches!(err, Error::SessionStoreFull { max: 2 }));
383        store.resume("a", splice_point()).unwrap();
384        store
385            .begin_break("a", BreakState::new(decision, splice_point()))
386            .unwrap();
387        assert_eq!(store.len(), 2);
388    }
389
390    #[test]
391    fn expire_idle_drops_only_sessions_untouched_for_longer_than_the_ttl() {
392        let mut store = SessionStore::new(TEST_LIMITS);
393        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
394        store.advance(Instant::from_micros(1_000));
395        store
396            .begin_break("old", BreakState::new(decision.clone(), splice_point()))
397            .unwrap();
398        store.advance(Instant::from_micros(5_000));
399        store
400            .begin_break("new", BreakState::new(decision, splice_point()))
401            .unwrap();
402        store.advance(Instant::from_micros(6_000));
403        assert_eq!(store.expire_idle(Duration::from_micros(2_000)), 1);
404        assert!(store.get("old").is_none());
405        assert!(store.get("new").is_some());
406        store.advance(Instant::from_micros(1));
407        assert_eq!(
408            store.expire_idle(Duration::from_micros(1_000)),
409            0,
410            "the clock never goes backwards"
411        );
412    }
413
414    #[test]
415    fn the_decision_size_limits_are_the_callers() {
416        let mut store = SessionStore::new(SessionLimits {
417            max_decision_items: 1,
418            max_decision_text_bytes: 12,
419            ..TEST_LIMITS
420        });
421        let mut snapped = AdBreakDecision::single_asset("b", "u");
422        snapped.snap = alloc::vec![crate::SnapMode::Out, crate::SnapMode::In];
423        assert!(matches!(
424            store.begin_break("a", BreakState::new(snapped, splice_point())),
425            Err(Error::DecisionTooLarge { max: 1, .. })
426        ));
427        let long = AdBreakDecision::single_asset("b", "https://x/a.m3u8");
428        assert!(matches!(
429            store.begin_break("a", BreakState::new(long, splice_point())),
430            Err(Error::DecisionTooLarge { max: 12, .. })
431        ));
432        let fits = AdBreakDecision::single_asset("b", "https://x/a");
433        assert!(
434            store
435                .begin_break("a", BreakState::new(fits, splice_point()))
436                .is_ok()
437        );
438        assert!(store.is_empty() || store.len() == 1);
439    }
440
441    #[test]
442    fn no_session_limits_default() {
443        trait AmbiguousIfDefault<A> {
444            fn some_item() {}
445        }
446        impl<T> AmbiguousIfDefault<()> for T {}
447        impl<T: Default> AmbiguousIfDefault<u8> for T {}
448        <SessionLimits as AmbiguousIfDefault<_>>::some_item();
449        <SessionStore as AmbiguousIfDefault<_>>::some_item();
450    }
451
452    #[test]
453    fn session_presets_pin_the_server_and_headend_values() {
454        use broadcast_core::Profile;
455        let server = SessionLimits::for_profile(Profile::Server);
456        assert_eq!(server.max_sessions, 512);
457        assert_eq!(server.max_decision_items, 128);
458        assert_eq!(server.max_decision_text_bytes, 256 << 10);
459        let headend = SessionLimits::for_profile(Profile::Headend);
460        assert_eq!(headend.max_sessions, 2048);
461        assert_eq!(headend.max_decision_items, 512);
462    }
463
464    #[test]
465    fn session_caps_grow_with_the_profile() {
466        use broadcast_core::Profile;
467        let values = Profile::ALL.map(|p| {
468            let l = SessionLimits::for_profile(p);
469            [
470                l.max_sessions,
471                l.max_decision_items,
472                l.max_decision_text_bytes,
473            ]
474        });
475        assert!(
476            values
477                .windows(2)
478                .all(|w| w[0].iter().zip(w[1].iter()).all(|(a, b)| a <= b))
479        );
480    }
481}