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