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.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 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}