Skip to main content

kcode_k1_ese_driver_state/
lib.rs

1use std::{
2    collections::HashMap,
3    sync::{Arc, Condvar, Mutex, MutexGuard},
4};
5
6pub use kcode_k1_ese_format::{ExternalSubsystem, TxId};
7
8const UNAVAILABLE: &str = "ESE driver state is unavailable";
9const LOCK_FAILED: &str = "ESE driver state lock failed";
10const CONFLICT: &str = "external subsystem operation conflicts with its pending payload";
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub struct SubmitOutcome {
14    progress: TxId,
15    duplicate: bool,
16}
17impl SubmitOutcome {
18    pub const fn new(progress: TxId, duplicate: bool) -> Self {
19        Self {
20            progress,
21            duplicate,
22        }
23    }
24    pub const fn progress(self) -> TxId {
25        self.progress
26    }
27    pub const fn duplicate(self) -> bool {
28        self.duplicate
29    }
30}
31
32#[derive(Clone, Debug, Eq, Hash, PartialEq)]
33struct Key {
34    stream: ExternalSubsystem,
35    operation_id: [u8; 32],
36}
37struct Slot {
38    payload: Arc<[u8]>,
39    result: Mutex<Option<Result<SubmitOutcome, String>>>,
40    changed: Condvar,
41}
42impl Slot {
43    fn new(payload: &[u8]) -> Self {
44        Self {
45            payload: Arc::from(payload),
46            result: Mutex::new(None),
47            changed: Condvar::new(),
48        }
49    }
50    fn publish(&self, result: Result<SubmitOutcome, String>) -> Result<(), String> {
51        let mut stored = self.result.lock().map_err(|_| LOCK_FAILED.to_owned())?;
52        if stored.is_some() {
53            return Err("ESE pending operation was completed twice".to_owned());
54        }
55        *stored = Some(result);
56        self.changed.notify_all();
57        Ok(())
58    }
59    fn wait(&self) -> Result<SubmitOutcome, String> {
60        let mut stored = self.result.lock().map_err(|_| LOCK_FAILED.to_owned())?;
61        while stored.is_none() {
62            stored = self
63                .changed
64                .wait(stored)
65                .map_err(|_| LOCK_FAILED.to_owned())?;
66        }
67        stored.as_ref().expect("result checked").clone()
68    }
69}
70
71pub enum Claim {
72    Owner(Ticket),
73    Waiter(Ticket),
74}
75pub struct Ticket {
76    key: Key,
77    slot: Arc<Slot>,
78    owner: bool,
79}
80struct State {
81    available: bool,
82    pending: HashMap<Key, Arc<Slot>>,
83}
84pub struct DriverState {
85    state: Mutex<State>,
86}
87
88impl DriverState {
89    #[allow(clippy::new_without_default)]
90    pub fn new() -> Self {
91        Self {
92            state: Mutex::new(State {
93                available: true,
94                pending: HashMap::new(),
95            }),
96        }
97    }
98
99    pub fn ensure_available(&self) -> Result<(), String> {
100        if self.lock()?.available {
101            Ok(())
102        } else {
103            Err(UNAVAILABLE.to_owned())
104        }
105    }
106
107    pub fn claim(
108        &self,
109        stream: ExternalSubsystem,
110        operation_id: [u8; 32],
111        payload: &[u8],
112    ) -> Result<Claim, String> {
113        let key = Key {
114            stream,
115            operation_id,
116        };
117        let mut state = self.lock()?;
118        if !state.available {
119            return Err(UNAVAILABLE.to_owned());
120        }
121        if let Some(slot) = state.pending.get(&key) {
122            if slot.payload.as_ref() != payload {
123                return Err(CONFLICT.to_owned());
124            }
125            return Ok(Claim::Waiter(Ticket {
126                key,
127                slot: Arc::clone(slot),
128                owner: false,
129            }));
130        }
131        let slot = Arc::new(Slot::new(payload));
132        state.pending.insert(key.clone(), Arc::clone(&slot));
133        Ok(Claim::Owner(Ticket {
134            key,
135            slot,
136            owner: true,
137        }))
138    }
139
140    pub fn complete(
141        &self,
142        ticket: Ticket,
143        result: Result<SubmitOutcome, String>,
144    ) -> Result<SubmitOutcome, String> {
145        if !ticket.owner {
146            self.fault()?;
147            return Err("ESE waiter cannot complete an operation".to_owned());
148        }
149        if let Err(error) = ticket.slot.publish(result.clone()) {
150            let _ = self.fault();
151            return Err(error);
152        }
153        let mut state = self.lock()?;
154        match state.pending.get(&ticket.key) {
155            Some(slot) if Arc::ptr_eq(slot, &ticket.slot) => {
156                state.pending.remove(&ticket.key);
157            }
158            _ => {
159                Self::make_unavailable(&mut state);
160                return Err("ESE pending operation identity changed".to_owned());
161            }
162        }
163        if !state.available {
164            return Err(UNAVAILABLE.to_owned());
165        }
166        result
167    }
168
169    pub fn wait(&self, ticket: Ticket) -> Result<SubmitOutcome, String> {
170        if ticket.owner {
171            self.fault()?;
172            return Err("ESE owner cannot wait as a duplicate".to_owned());
173        }
174        ticket.slot.wait()
175    }
176
177    pub fn fault(&self) -> Result<(), String> {
178        let slots = {
179            let mut state = self.lock()?;
180            Self::make_unavailable(&mut state)
181        };
182        for slot in slots {
183            let _ = slot.publish(Err(UNAVAILABLE.to_owned()));
184        }
185        Ok(())
186    }
187
188    fn lock(&self) -> Result<MutexGuard<'_, State>, String> {
189        self.state.lock().map_err(|_| LOCK_FAILED.to_owned())
190    }
191
192    fn make_unavailable(state: &mut State) -> Vec<Arc<Slot>> {
193        state.available = false;
194        std::mem::take(&mut state.pending).into_values().collect()
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use kcode_k1_ese_format::{Authority, UserId};
202    use std::sync::Arc;
203
204    fn tx(byte: u8) -> TxId {
205        TxId::from_bytes([byte; 12])
206    }
207    fn stream() -> ExternalSubsystem {
208        ExternalSubsystem::new(
209            Authority::User(UserId::from_tx_id(tx(1))),
210            "titles".to_owned(),
211        )
212        .unwrap()
213    }
214
215    #[test]
216    fn equal_concurrent_claims_share_one_result() {
217        let state = Arc::new(DriverState::new());
218        let owner = match state.claim(stream(), [2; 32], b"same").unwrap() {
219            Claim::Owner(ticket) => ticket,
220            Claim::Waiter(_) => panic!("first claim must own"),
221        };
222        let waiter = match state.claim(stream(), [2; 32], b"same").unwrap() {
223            Claim::Waiter(ticket) => ticket,
224            Claim::Owner(_) => panic!("second claim must wait"),
225        };
226        let waiting = {
227            let state = Arc::clone(&state);
228            std::thread::spawn(move || state.wait(waiter))
229        };
230        let outcome = SubmitOutcome::new(tx(3), false);
231        assert_eq!(state.complete(owner, Ok(outcome)), Ok(outcome));
232        assert_eq!(waiting.join().unwrap(), Ok(outcome));
233        assert!(matches!(
234            state.claim(stream(), [2; 32], b"same").unwrap(),
235            Claim::Owner(_)
236        ));
237    }
238
239    #[test]
240    fn conflicts_and_fault_wakeup_are_exact() {
241        let state = Arc::new(DriverState::new());
242        let _owner = match state.claim(stream(), [4; 32], b"first").unwrap() {
243            Claim::Owner(ticket) => ticket,
244            Claim::Waiter(_) => unreachable!(),
245        };
246        assert_eq!(
247            state.claim(stream(), [4; 32], b"other").err(),
248            Some(CONFLICT.to_owned())
249        );
250        let waiter = match state.claim(stream(), [4; 32], b"first").unwrap() {
251            Claim::Waiter(ticket) => ticket,
252            Claim::Owner(_) => unreachable!(),
253        };
254        let waiting = {
255            let state = Arc::clone(&state);
256            std::thread::spawn(move || state.wait(waiter))
257        };
258        state.fault().unwrap();
259        assert_eq!(waiting.join().unwrap(), Err(UNAVAILABLE.to_owned()));
260        assert_eq!(state.ensure_available(), Err(UNAVAILABLE.to_owned()));
261    }
262
263    #[test]
264    fn complete_error_is_shared_and_package_is_bounded() {
265        let state = DriverState::new();
266        let owner = match state.claim(stream(), [5; 32], b"x").unwrap() {
267            Claim::Owner(ticket) => ticket,
268            Claim::Waiter(_) => unreachable!(),
269        };
270        let waiter = match state.claim(stream(), [5; 32], b"x").unwrap() {
271            Claim::Waiter(ticket) => ticket,
272            Claim::Owner(_) => unreachable!(),
273        };
274        assert_eq!(
275            state.complete(owner, Err("submission failed".to_owned())),
276            Err("submission failed".to_owned())
277        );
278        assert_eq!(state.wait(waiter), Err("submission failed".to_owned()));
279        let files = [
280            include_str!("../Cargo.toml"),
281            include_str!("../Documentation.md"),
282            include_str!("lib.rs"),
283        ];
284        assert!(
285            files
286                .iter()
287                .flat_map(|file| file.lines())
288                .filter(|line| !line.trim().is_empty())
289                .count()
290                < 500
291        );
292    }
293}