1use crate::sessions::SessionError;
2use std::{
3 collections::BTreeMap,
4 sync::{Arc, Mutex},
5};
6use tokio_util::sync::CancellationToken;
7
8struct ActiveRun {
9 id: String,
10 token: CancellationToken,
11}
12#[derive(Default)]
13pub struct RunCoordinator {
14 active: Arc<Mutex<BTreeMap<String, ActiveRun>>>,
15}
16pub struct RunLease {
17 active: Arc<Mutex<BTreeMap<String, ActiveRun>>>,
18 session: String,
19 id: String,
20 token: CancellationToken,
21}
22impl RunCoordinator {
23 pub fn begin(
24 &self,
25 session: &str,
26 parent: &CancellationToken,
27 ) -> Result<RunLease, SessionError> {
28 if session.is_empty() || session.len() > 128 || parent.is_cancelled() {
29 return Err(SessionError::Invalid);
30 }
31 let mut active = self.active.lock().map_err(|_| SessionError::Storage)?;
32 active.retain(|_, run| !run.token.is_cancelled());
33 if active.contains_key(session) || active.len() >= 1024 {
34 return Err(SessionError::Conflict);
35 }
36 let id = uuid::Uuid::new_v4().to_string();
37 let token = parent.child_token();
38 active.insert(
39 session.into(),
40 ActiveRun {
41 id: id.clone(),
42 token: token.clone(),
43 },
44 );
45 Ok(RunLease {
46 active: self.active.clone(),
47 session: session.into(),
48 id,
49 token,
50 })
51 }
52 pub fn cancel(&self, session: &str, id: Option<&str>) -> Result<bool, SessionError> {
53 let mut active = self.active.lock().map_err(|_| SessionError::Storage)?;
54 let Some(run) = active.get(session) else {
55 return Ok(false);
56 };
57 if id.is_some_and(|id| run.id != id) {
58 return Ok(false);
59 }
60 run.token.cancel();
61 active.remove(session);
62 Ok(true)
63 }
64 pub fn active_id(&self, session: &str) -> Result<Option<String>, SessionError> {
65 Ok(self
66 .active
67 .lock()
68 .map_err(|_| SessionError::Storage)?
69 .get(session)
70 .filter(|run| !run.token.is_cancelled())
71 .map(|run| run.id.clone()))
72 }
73}
74impl RunLease {
75 pub fn id(&self) -> &str {
76 &self.id
77 }
78 pub fn token(&self) -> &CancellationToken {
79 &self.token
80 }
81 pub fn commit<ResultValue>(
82 &self,
83 write: impl FnOnce() -> Result<ResultValue, SessionError>,
84 ) -> Result<ResultValue, SessionError> {
85 let mut active = self.active.lock().map_err(|_| SessionError::Storage)?;
86 if self.token.is_cancelled()
87 || active
88 .get(&self.session)
89 .is_none_or(|run| run.id != self.id)
90 {
91 return Err(SessionError::Conflict);
92 }
93 let result = write()?;
94 active.remove(&self.session);
95 Ok(result)
96 }
97}
98impl Drop for RunLease {
99 fn drop(&mut self) {
100 self.token.cancel();
101 if let Ok(mut active) = self.active.lock()
102 && active
103 .get(&self.session)
104 .is_some_and(|run| run.id == self.id)
105 {
106 active.remove(&self.session);
107 }
108 }
109}