1use 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#[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
49pub const DEFAULT_MAX_SESSIONS: usize = 65_536;
51
52#[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 pub fn new() -> Self {
86 SessionStore {
87 sessions: BTreeMap::new(),
88 max_sessions: DEFAULT_MAX_SESSIONS,
89 now_us: 0,
90 }
91 }
92
93 pub fn with_max_sessions(mut self, max_sessions: usize) -> Self {
95 self.max_sessions = max_sessions.max(1);
96 self
97 }
98
99 pub fn advance(&mut self, now: Timestamp) {
104 self.now_us = self.now_us.max(now.as_micros());
105 }
106
107 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 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 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 pub fn get(&self, session_id: &str) -> Option<&BreakState> {
168 self.sessions.get(session_id).map(|t| &t.state)
169 }
170
171 pub fn end(&mut self, session_id: &str) -> Option<BreakState> {
174 self.sessions.remove(session_id).map(|t| t.state)
175 }
176
177 pub fn len(&self) -> usize {
179 self.sessions.len()
180 }
181
182 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.get("s1").unwrap().is_resumed());
214
215 store.resume("s1", splice_point()).unwrap();
216 assert!(store.get("s1").unwrap().is_resumed());
217
218 let evicted = store.end("s1").unwrap();
219 assert_eq!(evicted.decision, decision);
220 assert!(store.is_empty());
221 }
222
223 #[test]
224 fn cannot_begin_a_break_while_one_is_already_active() {
225 let mut store = SessionStore::new();
226 let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
227 store
228 .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
229 .unwrap();
230
231 let err = store
232 .begin_break("s1", BreakState::new(decision, splice_point()))
233 .unwrap_err();
234 assert!(matches!(err, Error::BreakAlreadyActive(ref s) if s == "s1"));
235 }
236
237 #[test]
238 fn begin_break_is_allowed_again_after_resume() {
239 let mut store = SessionStore::new();
240 let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
241 store
242 .begin_break("s1", BreakState::new(decision.clone(), splice_point()))
243 .unwrap();
244 store.resume("s1", splice_point()).unwrap();
245
246 store
248 .begin_break("s1", BreakState::new(decision, splice_point()))
249 .unwrap();
250 assert_eq!(store.len(), 1);
251 }
252
253 #[test]
254 fn resume_without_an_active_break_errors() {
255 let mut store = SessionStore::new();
256 let err = store.resume("nope", splice_point()).unwrap_err();
257 assert!(matches!(err, Error::NoActiveBreak(ref s) if s == "nope"));
258 }
259
260 #[test]
261 fn resume_on_an_already_resumed_break_keeps_the_first_point() {
262 let mut store = SessionStore::new();
263 let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
264 store
265 .begin_break("s1", BreakState::new(decision, splice_point()))
266 .unwrap();
267 let first = condition_splice_point(
268 Clock33::try_new(2_000).unwrap(),
269 &[Clock33::try_new(2_000).unwrap()],
270 core::time::Duration::ZERO,
271 )
272 .unwrap();
273 store.resume("s1", first).unwrap();
274 let err = store.resume("s1", splice_point()).unwrap_err();
275 assert!(matches!(err, Error::BreakAlreadyResumed(ref s) if s == "s1"));
276 assert_eq!(store.get("s1").unwrap().resumed_at, Some(first));
277 }
278
279 #[test]
280 fn the_store_is_bounded_and_existing_sessions_still_begin_breaks() {
281 let mut store = SessionStore::new().with_max_sessions(2);
282 let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
283 for id in ["a", "b"] {
284 store
285 .begin_break(id, BreakState::new(decision.clone(), splice_point()))
286 .unwrap();
287 }
288 let err = store
289 .begin_break("c", BreakState::new(decision.clone(), splice_point()))
290 .unwrap_err();
291 assert!(matches!(err, Error::SessionStoreFull { max: 2 }));
292 store.resume("a", splice_point()).unwrap();
293 store
294 .begin_break("a", BreakState::new(decision, splice_point()))
295 .unwrap();
296 assert_eq!(store.len(), 2);
297 }
298
299 #[test]
300 fn expire_idle_drops_only_sessions_untouched_for_longer_than_the_ttl() {
301 let mut store = SessionStore::new();
302 let decision = AdBreakDecision::single_asset("b1", "https://x/a.m3u8");
303 store.advance(Timestamp::from_micros(1_000));
304 store
305 .begin_break("old", BreakState::new(decision.clone(), splice_point()))
306 .unwrap();
307 store.advance(Timestamp::from_micros(5_000));
308 store
309 .begin_break("new", BreakState::new(decision, splice_point()))
310 .unwrap();
311 store.advance(Timestamp::from_micros(6_000));
312 assert_eq!(store.expire_idle(Duration::from_micros(2_000)), 1);
313 assert!(store.get("old").is_none());
314 assert!(store.get("new").is_some());
315 store.advance(Timestamp::from_micros(1));
316 assert_eq!(
317 store.expire_idle(Duration::from_micros(1_000)),
318 0,
319 "the clock never goes backwards"
320 );
321 }
322}