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/// The bounds a [`SessionStore`] holds, all chosen by the caller.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct SessionLimits {
52    /// Sessions tracked at once (at least 1 is enforced).
53    pub max_sessions: usize,
54    /// `X-SNAP` plus `X-RESTRICT` identifiers one break's decision may carry.
55    pub max_decision_items: usize,
56    /// Bytes of the decision's `ID` and asset URI taken together.
57    pub max_decision_text_bytes: usize,
58}
59
60/// Per-session ad-break records.
61///
62/// A `BTreeMap` keyed by session id: the records here are small (one
63/// [`BreakState`] per session, per the module's design decision), so there
64/// is no per-peer *media* state to bound with a cursor count the way
65/// `media-plane`'s `Trunk` must. The store is nonetheless bounded: it holds at
66/// most [`SessionLimits::max_sessions`] sessions, and [`Self::begin_break`] for a new session id
67/// past that is [`Error::SessionStoreFull`], so a flood of distinct ids cannot
68/// grow it forever. This crate has no clock of its own: the caller feeds the
69/// time in with [`Self::advance`] and calls [`Self::expire_idle`] to drop
70/// sessions nobody has touched for a while; [`Self::end`] evicts one directly.
71#[derive(Debug, Clone)]
72pub struct SessionStore {
73    sessions: BTreeMap<String, Tracked>,
74    limits: SessionLimits,
75    now_us: u64,
76}
77
78#[derive(Debug, Clone)]
79struct Tracked {
80    state: BreakState,
81    touched_us: u64,
82}
83
84impl SessionStore {
85    /// An empty store held to the caller's `limits`.
86    pub fn new(limits: SessionLimits) -> Self {
87        SessionStore {
88            sessions: BTreeMap::new(),
89            limits: SessionLimits {
90                max_sessions: limits.max_sessions.max(1),
91                ..limits
92            },
93            now_us: 0,
94        }
95    }
96
97    /// Moves the store's clock to `now` (the caller's own monotonic clock, the
98    /// `broadcast_core::stage::Instant` every sans-IO engine takes; a value
99    /// earlier than the current one is ignored). Records touched from now on
100    /// carry this time.
101    pub fn advance(&mut self, now: Instant) {
102        self.now_us = self.now_us.max(now.as_micros());
103    }
104
105    /// Evicts every session last touched (by [`Self::begin_break`] or
106    /// [`Self::resume`]) more than `ttl` before the store's clock; returns
107    /// how many were evicted.
108    pub fn expire_idle(&mut self, ttl: Duration) -> usize {
109        let ttl_us = u64::try_from(ttl.as_micros()).unwrap_or(u64::MAX);
110        let before = self.sessions.len();
111        let now = self.now_us;
112        self.sessions
113            .retain(|_, t| now.saturating_sub(t.touched_us) <= ttl_us);
114        before - self.sessions.len()
115    }
116
117    /// Start a break for `session_id`. Errors with
118    /// [`Error::BreakAlreadyActive`] if the session already has an
119    /// unresumed break — call [`Self::resume`] or [`Self::end`] first — and
120    /// with [`Error::SessionStoreFull`] if `session_id` is new and the store
121    /// is at its bound, and with [`Error::DecisionTooLarge`] if `state`'s
122    /// decision exceeds [`SessionLimits::max_decision_items`] or
123    /// [`SessionLimits::max_decision_text_bytes`].
124    pub fn begin_break(&mut self, session_id: impl Into<String>, state: BreakState) -> Result<()> {
125        let session_id = session_id.into();
126        let decision = &state.decision;
127        let items = decision.snap.len().saturating_add(decision.restrict.len());
128        if items > self.limits.max_decision_items {
129            return Err(Error::DecisionTooLarge {
130                what: "snap and restrict identifiers",
131                max: self.limits.max_decision_items,
132            });
133        }
134        let uri = match &decision.asset {
135            crate::decision::AssetSource::Uri(u) | crate::decision::AssetSource::List(u) => u,
136        };
137        if decision.id.len().saturating_add(uri.len()) > self.limits.max_decision_text_bytes {
138            return Err(Error::DecisionTooLarge {
139                what: "id and asset uri bytes",
140                max: self.limits.max_decision_text_bytes,
141            });
142        }
143        match self.sessions.get(&session_id) {
144            Some(existing) if !existing.state.is_resumed() => {
145                return Err(Error::BreakAlreadyActive(session_id));
146            }
147            None if self.sessions.len() >= self.limits.max_sessions => {
148                return Err(Error::SessionStoreFull {
149                    max: self.limits.max_sessions,
150                });
151            }
152            _ => {}
153        }
154        self.sessions.insert(
155            session_id,
156            Tracked {
157                state,
158                touched_us: self.now_us,
159            },
160        );
161        Ok(())
162    }
163
164    /// Record the resumption point for `session_id`'s active break. Errors
165    /// with [`Error::NoActiveBreak`] if there is no record for the session and
166    /// with [`Error::BreakAlreadyResumed`] if its break was already resumed
167    /// (the first resumption point is kept).
168    pub fn resume(&mut self, session_id: &str, resumed_at: ConditionedSplicePoint) -> Result<()> {
169        let tracked = self
170            .sessions
171            .get_mut(session_id)
172            .ok_or_else(|| Error::NoActiveBreak(session_id.into()))?;
173        if tracked.state.is_resumed() {
174            return Err(Error::BreakAlreadyResumed(session_id.into()));
175        }
176        tracked.state.resumed_at = Some(resumed_at);
177        tracked.touched_us = self.now_us;
178        Ok(())
179    }
180
181    /// The current break record for `session_id`, if any. A resumed record
182    /// stays until [`Self::end`] evicts it, so a caller can still render the
183    /// just-ended break's `EXT-X-DATERANGE` for one more playlist reload.
184    pub fn get(&self, session_id: &str) -> Option<&BreakState> {
185        self.sessions.get(session_id).map(|t| &t.state)
186    }
187
188    /// Evict `session_id`'s record entirely (session ended, or its break has
189    /// aged out of the sliding window). Returns the evicted record, if any.
190    pub fn end(&mut self, session_id: &str) -> Option<BreakState> {
191        self.sessions.remove(session_id).map(|t| t.state)
192    }
193
194    /// Number of tracked sessions.
195    pub fn len(&self) -> usize {
196        self.sessions.len()
197    }
198
199    /// Whether the store is empty.
200    pub fn is_empty(&self) -> bool {
201        self.sessions.is_empty()
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use crate::splice::condition_splice_point;
209    use broadcast_common::clock33::Clock33;
210
211    const TEST_LIMITS: SessionLimits = SessionLimits {
212        max_sessions: 65_536,
213        max_decision_items: 64,
214        max_decision_text_bytes: 4096,
215    };
216
217    fn splice_point() -> ConditionedSplicePoint {
218        condition_splice_point(
219            Clock33::try_new(1_000).unwrap(),
220            &[Clock33::try_new(1_000).unwrap()],
221            core::time::Duration::ZERO,
222        )
223        .unwrap()
224    }
225
226    #[test]
227    fn begin_get_resume_end_lifecycle() {
228        let mut store = SessionStore::new(TEST_LIMITS);
229        assert!(store.is_empty());
230
231        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
232        store
233            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
234            .unwrap();
235        assert_eq!(store.len(), 1);
236        assert!(!store.is_empty());
237        assert!(!store.get("s1").unwrap().is_resumed());
238
239        store.resume("s1", splice_point()).unwrap();
240        assert!(store.get("s1").unwrap().is_resumed());
241
242        let evicted = store.end("s1").unwrap();
243        assert_eq!(evicted.decision, decision);
244        assert!(store.is_empty());
245    }
246
247    #[test]
248    fn cannot_begin_a_break_while_one_is_already_active() {
249        let mut store = SessionStore::new(TEST_LIMITS);
250        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
251        store
252            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
253            .unwrap();
254
255        let err = store
256            .begin_break("s1", BreakState::new(decision, splice_point()))
257            .unwrap_err();
258        assert!(matches!(err, Error::BreakAlreadyActive(ref s) if s == "s1"));
259    }
260
261    #[test]
262    fn begin_break_is_allowed_again_after_resume() {
263        let mut store = SessionStore::new(TEST_LIMITS);
264        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
265        store
266            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
267            .unwrap();
268        store.resume("s1", splice_point()).unwrap();
269
270        // A second, later break for the same session is fine once resumed.
271        store
272            .begin_break("s1", BreakState::new(decision, splice_point()))
273            .unwrap();
274        assert_eq!(store.len(), 1);
275    }
276
277    #[test]
278    fn resume_without_an_active_break_errors() {
279        let mut store = SessionStore::new(TEST_LIMITS);
280        let err = store.resume("nope", splice_point()).unwrap_err();
281        assert!(matches!(err, Error::NoActiveBreak(ref s) if s == "nope"));
282    }
283
284    #[test]
285    fn resume_on_an_already_resumed_break_keeps_the_first_point() {
286        let mut store = SessionStore::new(TEST_LIMITS);
287        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
288        store
289            .begin_break("s1", BreakState::new(decision, splice_point()))
290            .unwrap();
291        let first = condition_splice_point(
292            Clock33::try_new(2_000).unwrap(),
293            &[Clock33::try_new(2_000).unwrap()],
294            core::time::Duration::ZERO,
295        )
296        .unwrap();
297        store.resume("s1", first).unwrap();
298        let err = store.resume("s1", splice_point()).unwrap_err();
299        assert!(matches!(err, Error::BreakAlreadyResumed(ref s) if s == "s1"));
300        assert_eq!(store.get("s1").unwrap().resumed_at, Some(first));
301    }
302
303    #[test]
304    fn the_store_is_bounded_and_existing_sessions_still_begin_breaks() {
305        let mut store = SessionStore::new(SessionLimits {
306            max_sessions: 2,
307            ..TEST_LIMITS
308        });
309        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
310        for id in ["a", "b"] {
311            store
312                .begin_break(id, BreakState::new(decision.clone(), splice_point()))
313                .unwrap();
314        }
315        let err = store
316            .begin_break("c", BreakState::new(decision.clone(), splice_point()))
317            .unwrap_err();
318        assert!(matches!(err, Error::SessionStoreFull { max: 2 }));
319        store.resume("a", splice_point()).unwrap();
320        store
321            .begin_break("a", BreakState::new(decision, splice_point()))
322            .unwrap();
323        assert_eq!(store.len(), 2);
324    }
325
326    #[test]
327    fn expire_idle_drops_only_sessions_untouched_for_longer_than_the_ttl() {
328        let mut store = SessionStore::new(TEST_LIMITS);
329        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
330        store.advance(Instant::from_micros(1_000));
331        store
332            .begin_break("old", BreakState::new(decision.clone(), splice_point()))
333            .unwrap();
334        store.advance(Instant::from_micros(5_000));
335        store
336            .begin_break("new", BreakState::new(decision, splice_point()))
337            .unwrap();
338        store.advance(Instant::from_micros(6_000));
339        assert_eq!(store.expire_idle(Duration::from_micros(2_000)), 1);
340        assert!(store.get("old").is_none());
341        assert!(store.get("new").is_some());
342        store.advance(Instant::from_micros(1));
343        assert_eq!(
344            store.expire_idle(Duration::from_micros(1_000)),
345            0,
346            "the clock never goes backwards"
347        );
348    }
349
350    #[test]
351    fn the_decision_size_limits_are_the_callers() {
352        let mut store = SessionStore::new(SessionLimits {
353            max_decision_items: 1,
354            max_decision_text_bytes: 12,
355            ..TEST_LIMITS
356        });
357        let mut snapped = AdBreakDecision::single_asset("b", "u");
358        snapped.snap = alloc::vec![crate::SnapMode::Out, crate::SnapMode::In];
359        assert!(matches!(
360            store.begin_break("a", BreakState::new(snapped, splice_point())),
361            Err(Error::DecisionTooLarge { max: 1, .. })
362        ));
363        let long = AdBreakDecision::single_asset("b", "https://x/a.m3u8");
364        assert!(matches!(
365            store.begin_break("a", BreakState::new(long, splice_point())),
366            Err(Error::DecisionTooLarge { max: 12, .. })
367        ));
368        let fits = AdBreakDecision::single_asset("b", "https://x/a");
369        assert!(
370            store
371                .begin_break("a", BreakState::new(fits, splice_point()))
372                .is_ok()
373        );
374        assert!(store.is_empty() || store.len() == 1);
375    }
376
377    #[test]
378    fn no_session_limits_default() {
379        trait AmbiguousIfDefault<A> {
380            fn some_item() {}
381        }
382        impl<T> AmbiguousIfDefault<()> for T {}
383        impl<T: Default> AmbiguousIfDefault<u8> for T {}
384        <SessionLimits as AmbiguousIfDefault<_>>::some_item();
385        <SessionStore as AmbiguousIfDefault<_>>::some_item();
386    }
387}