ssai-runtime 0.9.1

Sans-IO SCTE-35 SSAI session core: per-session ad-break state, a pluggable ad-decision trait, splice-point conditioning, and per-session HLS Interstitial playlist rendering. No HTTP, no ad-decision client. no_std.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Per-session ad-break state.
//!
//! Issue #929's design decision: the per-session record is session id ->
//! ad-break decision -> timeline offsets, and it is deliberately **not** a
//! media cursor. Every viewer in a break watches one of a small set of ad
//! assets, and outside a break every viewer sees byte-identical primary
//! content; what differs per session is which URIs appear in that session's
//! rendered playlist. `media-plane`'s "writer cost is O(N) in cursor count"
//! rule is about the shared media rings — a `SessionStore` holds no cursor
//! into any of them, just this one small [`BreakState`] record per session.

use crate::decision::AdBreakDecision;
use crate::error::{Error, Result};
use crate::splice::ConditionedSplicePoint;
use alloc::collections::BTreeMap;
use alloc::string::String;
use broadcast_core::stage::Instant;
use core::time::Duration;

/// One session's ad break: the decision being rendered, plus the conditioned
/// splice points it entered (and, once known, resumed) at.
// `AdBreakDecision` is `PartialEq`-only (carries `f64` fields), so this is too.
#[derive(Debug, Clone, PartialEq)]
pub struct BreakState {
    /// The decision being rendered for this break.
    pub decision: AdBreakDecision,
    /// The conditioned splice point the break was entered at.
    pub entered_at: ConditionedSplicePoint,
    /// The conditioned splice point playback resumed at, once known.
    pub resumed_at: Option<ConditionedSplicePoint>,
}

impl BreakState {
    /// Start a new break with no resumption point yet known.
    pub fn new(decision: AdBreakDecision, entered_at: ConditionedSplicePoint) -> Self {
        BreakState {
            decision,
            entered_at,
            resumed_at: None,
        }
    }

    /// Whether [`Self::resumed_at`] has been recorded (the break has ended).
    pub fn is_resumed(&self) -> bool {
        self.resumed_at.is_some()
    }
}

/// Embedded: one channel's ad breaks on a small device. No run-time cost: a timing or retry count.
const SSAI_MAX_SESSIONS_EMBEDDED: usize = 16;
/// Device: one playback session plus a few followers.
const SSAI_MAX_SESSIONS_DEVICE: usize = 64;
/// Server: the ad breaks of a few channels.
const SSAI_MAX_SESSIONS_SERVER: usize = 512;
/// Headend: a whole multiplex's breaks.
const SSAI_MAX_SESSIONS_HEADEND: usize = 2048;

/// Embedded: a short decision on a small device. Provisional until measured (#4834): an SSAI session would exercise it.
const SSAI_MAX_DECISION_ITEMS_EMBEDDED: usize = 8;
/// Device: the identifiers one ad decision carries.
const SSAI_MAX_DECISION_ITEMS_DEVICE: usize = 32;
/// Server: a decision from several providers.
const SSAI_MAX_DECISION_ITEMS_SERVER: usize = 128;
/// Headend: the widest decision carried.
const SSAI_MAX_DECISION_ITEMS_HEADEND: usize = 512;
/// Every profile: the old Headend decision-document ceiling, 256 KiB, a hostile-input bound (#4809).
const SSAI_MAX_DECISION_TEXT_BYTES: usize = 256 << 10;

/// The bounds a [`SessionStore`] holds, all chosen by the caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionLimits {
    /// Sessions tracked at once (at least 1 is enforced).
    pub max_sessions: usize,
    /// `X-SNAP` plus `X-RESTRICT` identifiers one break's decision may carry.
    pub max_decision_items: usize,
    /// Bytes of the decision's `ID` and asset URI taken together.
    pub max_decision_text_bytes: usize,
}

impl SessionLimits {
    /// The [`broadcast_core::Profile`] preset: every field is a documented constant of
    /// this module, replaceable through its `with_*` setter.
    #[must_use]
    pub fn for_profile(profile: broadcast_core::Profile) -> Self {
        Self {
            max_sessions: profile.select(
                SSAI_MAX_SESSIONS_EMBEDDED,
                SSAI_MAX_SESSIONS_DEVICE,
                SSAI_MAX_SESSIONS_SERVER,
                SSAI_MAX_SESSIONS_HEADEND,
            ),
            max_decision_items: profile.select(
                SSAI_MAX_DECISION_ITEMS_EMBEDDED,
                SSAI_MAX_DECISION_ITEMS_DEVICE,
                SSAI_MAX_DECISION_ITEMS_SERVER,
                SSAI_MAX_DECISION_ITEMS_HEADEND,
            ),
            max_decision_text_bytes: SSAI_MAX_DECISION_TEXT_BYTES,
        }
    }

    /// Replace [`Self::max_sessions`].
    #[must_use]
    pub fn with_max_sessions(mut self, max_sessions: usize) -> Self {
        self.max_sessions = max_sessions;
        self
    }

    /// Replace [`Self::max_decision_items`].
    #[must_use]
    pub fn with_max_decision_items(mut self, max_decision_items: usize) -> Self {
        self.max_decision_items = max_decision_items;
        self
    }

    /// Replace [`Self::max_decision_text_bytes`].
    #[must_use]
    pub fn with_max_decision_text_bytes(mut self, max_decision_text_bytes: usize) -> Self {
        self.max_decision_text_bytes = max_decision_text_bytes;
        self
    }
}

/// Per-session ad-break records.
///
/// A `BTreeMap` keyed by session id: the records here are small (one
/// [`BreakState`] per session, per the module's design decision), so there
/// is no per-peer *media* state to bound with a cursor count the way
/// `media-plane`'s `Trunk` must. The store is nonetheless bounded: it holds at
/// most [`SessionLimits::max_sessions`] sessions, and [`Self::begin_break`] for a new session id
/// past that is [`Error::SessionStoreFull`], so a flood of distinct ids cannot
/// grow it forever. This crate has no clock of its own: the caller feeds the
/// time in with [`Self::advance`] and calls [`Self::expire_idle`] to drop
/// sessions nobody has touched for a while; [`Self::end`] evicts one directly.
#[derive(Debug, Clone)]
pub struct SessionStore {
    sessions: BTreeMap<String, Tracked>,
    limits: SessionLimits,
    now_us: u64,
}

#[derive(Debug, Clone)]
struct Tracked {
    state: BreakState,
    touched_us: u64,
}

impl SessionStore {
    /// An empty store held to the caller's `limits`.
    pub fn new(limits: SessionLimits) -> Self {
        SessionStore {
            sessions: BTreeMap::new(),
            limits: SessionLimits {
                max_sessions: limits.max_sessions.max(1),
                ..limits
            },
            now_us: 0,
        }
    }

    /// Moves the store's clock to `now` (the caller's own monotonic clock, the
    /// `broadcast_core::stage::Instant` every sans-IO engine takes; a value
    /// earlier than the current one is ignored). Records touched from now on
    /// carry this time.
    pub fn advance(&mut self, now: Instant) {
        self.now_us = self.now_us.max(now.as_micros());
    }

    /// Evicts every session last touched (by [`Self::begin_break`] or
    /// [`Self::resume`]) more than `ttl` before the store's clock; returns
    /// how many were evicted.
    pub fn expire_idle(&mut self, ttl: Duration) -> usize {
        let ttl_us = u64::try_from(ttl.as_micros()).unwrap_or(u64::MAX);
        let before = self.sessions.len();
        let now = self.now_us;
        self.sessions
            .retain(|_, t| now.saturating_sub(t.touched_us) <= ttl_us);
        before - self.sessions.len()
    }

    /// Start a break for `session_id`. Errors with
    /// [`Error::BreakAlreadyActive`] if the session already has an
    /// unresumed break — call [`Self::resume`] or [`Self::end`] first — and
    /// with [`Error::SessionStoreFull`] if `session_id` is new and the store
    /// is at its bound, and with [`Error::DecisionTooLarge`] if `state`'s
    /// decision exceeds [`SessionLimits::max_decision_items`] or
    /// [`SessionLimits::max_decision_text_bytes`].
    pub fn begin_break(&mut self, session_id: impl Into<String>, state: BreakState) -> Result<()> {
        let session_id = session_id.into();
        let decision = &state.decision;
        let items = decision.snap.len().saturating_add(decision.restrict.len());
        if items > self.limits.max_decision_items {
            return Err(Error::DecisionTooLarge {
                what: "snap and restrict identifiers",
                max: self.limits.max_decision_items,
            });
        }
        let uri = match &decision.asset {
            crate::decision::AssetSource::Uri(u) | crate::decision::AssetSource::List(u) => u,
        };
        if decision.id.len().saturating_add(uri.len()) > self.limits.max_decision_text_bytes {
            return Err(Error::DecisionTooLarge {
                what: "id and asset uri bytes",
                max: self.limits.max_decision_text_bytes,
            });
        }
        match self.sessions.get(&session_id) {
            Some(existing) if !existing.state.is_resumed() => {
                return Err(Error::BreakAlreadyActive(session_id));
            }
            None if self.sessions.len() >= self.limits.max_sessions => {
                return Err(Error::SessionStoreFull {
                    max: self.limits.max_sessions,
                });
            }
            _ => {}
        }
        self.sessions.insert(
            session_id,
            Tracked {
                state,
                touched_us: self.now_us,
            },
        );
        Ok(())
    }

    /// Record the resumption point for `session_id`'s active break. Errors
    /// with [`Error::NoActiveBreak`] if there is no record for the session and
    /// with [`Error::BreakAlreadyResumed`] if its break was already resumed
    /// (the first resumption point is kept).
    pub fn resume(&mut self, session_id: &str, resumed_at: ConditionedSplicePoint) -> Result<()> {
        let tracked = self
            .sessions
            .get_mut(session_id)
            .ok_or_else(|| Error::NoActiveBreak(session_id.into()))?;
        if tracked.state.is_resumed() {
            return Err(Error::BreakAlreadyResumed(session_id.into()));
        }
        tracked.state.resumed_at = Some(resumed_at);
        tracked.touched_us = self.now_us;
        Ok(())
    }

    /// The current break record for `session_id`, if any. A resumed record
    /// stays until [`Self::end`] evicts it, so a caller can still render the
    /// just-ended break's `EXT-X-DATERANGE` for one more playlist reload.
    pub fn get(&self, session_id: &str) -> Option<&BreakState> {
        self.sessions.get(session_id).map(|t| &t.state)
    }

    /// Evict `session_id`'s record entirely (session ended, or its break has
    /// aged out of the sliding window). Returns the evicted record, if any.
    pub fn end(&mut self, session_id: &str) -> Option<BreakState> {
        self.sessions.remove(session_id).map(|t| t.state)
    }

    /// Number of tracked sessions.
    pub fn len(&self) -> usize {
        self.sessions.len()
    }

    /// Whether the store is empty.
    pub fn is_empty(&self) -> bool {
        self.sessions.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::splice::condition_splice_point;
    use broadcast_common::clock33::Clock33;

    const TEST_LIMITS: SessionLimits = SessionLimits {
        max_sessions: 65_536,
        max_decision_items: 64,
        max_decision_text_bytes: 4096,
    };

    fn splice_point() -> ConditionedSplicePoint {
        condition_splice_point(
            Clock33::try_new(1_000).unwrap(),
            &[Clock33::try_new(1_000).unwrap()],
            core::time::Duration::ZERO,
        )
        .unwrap()
    }

    #[test]
    fn begin_get_resume_end_lifecycle() {
        let mut store = SessionStore::new(TEST_LIMITS);
        assert!(store.is_empty());

        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
        store
            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
            .unwrap();
        assert_eq!(store.len(), 1);
        assert!(!store.is_empty());
        assert!(!store.get("s1").unwrap().is_resumed());

        store.resume("s1", splice_point()).unwrap();
        assert!(store.get("s1").unwrap().is_resumed());

        let evicted = store.end("s1").unwrap();
        assert_eq!(evicted.decision, decision);
        assert!(store.is_empty());
    }

    #[test]
    fn cannot_begin_a_break_while_one_is_already_active() {
        let mut store = SessionStore::new(TEST_LIMITS);
        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
        store
            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
            .unwrap();

        let err = store
            .begin_break("s1", BreakState::new(decision, splice_point()))
            .unwrap_err();
        assert!(matches!(err, Error::BreakAlreadyActive(ref s) if s == "s1"));
    }

    #[test]
    fn begin_break_is_allowed_again_after_resume() {
        let mut store = SessionStore::new(TEST_LIMITS);
        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
        store
            .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
            .unwrap();
        store.resume("s1", splice_point()).unwrap();

        // A second, later break for the same session is fine once resumed.
        store
            .begin_break("s1", BreakState::new(decision, splice_point()))
            .unwrap();
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn resume_without_an_active_break_errors() {
        let mut store = SessionStore::new(TEST_LIMITS);
        let err = store.resume("nope", splice_point()).unwrap_err();
        assert!(matches!(err, Error::NoActiveBreak(ref s) if s == "nope"));
    }

    #[test]
    fn resume_on_an_already_resumed_break_keeps_the_first_point() {
        let mut store = SessionStore::new(TEST_LIMITS);
        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
        store
            .begin_break("s1", BreakState::new(decision, splice_point()))
            .unwrap();
        let first = condition_splice_point(
            Clock33::try_new(2_000).unwrap(),
            &[Clock33::try_new(2_000).unwrap()],
            core::time::Duration::ZERO,
        )
        .unwrap();
        store.resume("s1", first).unwrap();
        let err = store.resume("s1", splice_point()).unwrap_err();
        assert!(matches!(err, Error::BreakAlreadyResumed(ref s) if s == "s1"));
        assert_eq!(store.get("s1").unwrap().resumed_at, Some(first));
    }

    #[test]
    fn the_store_is_bounded_and_existing_sessions_still_begin_breaks() {
        let mut store = SessionStore::new(SessionLimits {
            max_sessions: 2,
            ..TEST_LIMITS
        });
        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
        for id in ["a", "b"] {
            store
                .begin_break(id, BreakState::new(decision.clone(), splice_point()))
                .unwrap();
        }
        let err = store
            .begin_break("c", BreakState::new(decision.clone(), splice_point()))
            .unwrap_err();
        assert!(matches!(err, Error::SessionStoreFull { max: 2 }));
        store.resume("a", splice_point()).unwrap();
        store
            .begin_break("a", BreakState::new(decision, splice_point()))
            .unwrap();
        assert_eq!(store.len(), 2);
    }

    #[test]
    fn expire_idle_drops_only_sessions_untouched_for_longer_than_the_ttl() {
        let mut store = SessionStore::new(TEST_LIMITS);
        let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
        store.advance(Instant::from_micros(1_000));
        store
            .begin_break("old", BreakState::new(decision.clone(), splice_point()))
            .unwrap();
        store.advance(Instant::from_micros(5_000));
        store
            .begin_break("new", BreakState::new(decision, splice_point()))
            .unwrap();
        store.advance(Instant::from_micros(6_000));
        assert_eq!(store.expire_idle(Duration::from_micros(2_000)), 1);
        assert!(store.get("old").is_none());
        assert!(store.get("new").is_some());
        store.advance(Instant::from_micros(1));
        assert_eq!(
            store.expire_idle(Duration::from_micros(1_000)),
            0,
            "the clock never goes backwards"
        );
    }

    #[test]
    fn the_decision_size_limits_are_the_callers() {
        let mut store = SessionStore::new(SessionLimits {
            max_decision_items: 1,
            max_decision_text_bytes: 12,
            ..TEST_LIMITS
        });
        let mut snapped = AdBreakDecision::single_asset("b", "u");
        snapped.snap = alloc::vec![crate::SnapMode::Out, crate::SnapMode::In];
        assert!(matches!(
            store.begin_break("a", BreakState::new(snapped, splice_point())),
            Err(Error::DecisionTooLarge { max: 1, .. })
        ));
        let long = AdBreakDecision::single_asset("b", "https://x/a.m3u8");
        assert!(matches!(
            store.begin_break("a", BreakState::new(long, splice_point())),
            Err(Error::DecisionTooLarge { max: 12, .. })
        ));
        let fits = AdBreakDecision::single_asset("b", "https://x/a");
        assert!(
            store
                .begin_break("a", BreakState::new(fits, splice_point()))
                .is_ok()
        );
        assert!(store.is_empty() || store.len() == 1);
    }

    #[test]
    fn no_session_limits_default() {
        trait AmbiguousIfDefault<A> {
            fn some_item() {}
        }
        impl<T> AmbiguousIfDefault<()> for T {}
        impl<T: Default> AmbiguousIfDefault<u8> for T {}
        <SessionLimits as AmbiguousIfDefault<_>>::some_item();
        <SessionStore as AmbiguousIfDefault<_>>::some_item();
    }

    #[test]
    fn session_presets_pin_the_server_and_headend_values() {
        use broadcast_core::Profile;
        let server = SessionLimits::for_profile(Profile::Server);
        assert_eq!(server.max_sessions, 512);
        assert_eq!(server.max_decision_items, 128);
        assert_eq!(server.max_decision_text_bytes, 256 << 10);
        let headend = SessionLimits::for_profile(Profile::Headend);
        assert_eq!(headend.max_sessions, 2048);
        assert_eq!(headend.max_decision_items, 512);
    }

    #[test]
    fn session_caps_grow_with_the_profile() {
        use broadcast_core::Profile;
        let values = Profile::ALL.map(|p| {
            let l = SessionLimits::for_profile(p);
            [
                l.max_sessions,
                l.max_decision_items,
                l.max_decision_text_bytes,
            ]
        });
        assert!(
            values
                .windows(2)
                .all(|w| w[0].iter().zip(w[1].iter()).all(|(a, b)| a <= b))
        );
    }
}