1use 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#[derive(Debug, Clone, PartialEq)]
24pub struct BreakState {
25 pub decision: AdBreakDecision,
27 pub entered_at: ConditionedSplicePoint,
29 pub resumed_at: Option<ConditionedSplicePoint>,
31}
32
33impl BreakState {
34 pub fn new(decision: AdBreakDecision, entered_at: ConditionedSplicePoint) -> Self {
36 BreakState {
37 decision,
38 entered_at,
39 resumed_at: None,
40 }
41 }
42
43 pub fn is_resumed(&self) -> bool {
45 self.resumed_at.is_some()
46 }
47}
48
49const SSAI_MAX_SESSIONS_EMBEDDED: usize = 16;
51const SSAI_MAX_SESSIONS_DEVICE: usize = 64;
53const SSAI_MAX_SESSIONS_SERVER: usize = 512;
55const SSAI_MAX_SESSIONS_HEADEND: usize = 2048;
57
58const SSAI_MAX_DECISION_ITEMS_EMBEDDED: usize = 8;
60const SSAI_MAX_DECISION_ITEMS_DEVICE: usize = 32;
62const SSAI_MAX_DECISION_ITEMS_SERVER: usize = 128;
64const SSAI_MAX_DECISION_ITEMS_HEADEND: usize = 512;
66const SSAI_MAX_DECISION_TEXT_BYTES: usize = 256 << 10;
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct SessionLimits {
72 pub max_sessions: usize,
74 pub max_decision_items: usize,
76 pub max_decision_text_bytes: usize,
78}
79
80impl SessionLimits {
81 #[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 #[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 #[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 #[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#[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 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 pub fn advance(&mut self, now: Instant) {
166 self.now_us = self.now_us.max(now.as_micros());
167 }
168
169 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 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 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 pub fn get(&self, session_id: &str) -> Option<&BreakState> {
249 self.sessions.get(session_id).map(|t| &t.state)
250 }
251
252 pub fn end(&mut self, session_id: &str) -> Option<BreakState> {
255 self.sessions.remove(session_id).map(|t| t.state)
256 }
257
258 pub fn len(&self) -> usize {
260 self.sessions.len()
261 }
262
263 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 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}