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
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct SessionLimits {
52 pub max_sessions: usize,
54 pub max_decision_items: usize,
56 pub max_decision_text_bytes: usize,
58}
59
60#[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 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 pub fn advance(&mut self, now: Instant) {
102 self.now_us = self.now_us.max(now.as_micros());
103 }
104
105 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 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 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 pub fn get(&self, session_id: &str) -> Option<&BreakState> {
185 self.sessions.get(session_id).map(|t| &t.state)
186 }
187
188 pub fn end(&mut self, session_id: &str) -> Option<BreakState> {
191 self.sessions.remove(session_id).map(|t| t.state)
192 }
193
194 pub fn len(&self) -> usize {
196 self.sessions.len()
197 }
198
199 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 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}