vvv_engine/
cancellation.rs1use crate::EngineError;
4use std::sync::{
5 Arc, Mutex,
6 atomic::{AtomicBool, AtomicU8, Ordering},
7};
8
9#[derive(Debug, Clone, Default)]
13pub struct ReadCancellation(Arc<ReadState>);
14#[derive(Debug, Default)]
15struct ReadState {
16 state: AtomicU8,
17 claimed: AtomicBool,
18 publication: Mutex<()>,
19}
20impl ReadCancellation {
21 const ACTIVE: u8 = 0;
22 const CANCELLED: u8 = 1;
23 const COMPLETE: u8 = 2;
24 pub fn cancel(&self) {
25 let _gate = self
26 .0
27 .publication
28 .lock()
29 .unwrap_or_else(std::sync::PoisonError::into_inner);
30 let _ = self.0.state.compare_exchange(
31 Self::ACTIVE,
32 Self::CANCELLED,
33 Ordering::AcqRel,
34 Ordering::Acquire,
35 );
36 }
37 pub fn is_cancelled(&self) -> bool {
38 self.0.state.load(Ordering::Acquire) == Self::CANCELLED
39 }
40 pub(crate) fn claim(&self) -> Result<(), EngineError> {
41 if self.0.claimed.swap(true, Ordering::AcqRel) {
42 return Err(EngineError::ReusedCancellation);
43 }
44 self.check()
45 }
46 pub(crate) fn check(&self) -> Result<(), EngineError> {
47 if self.is_cancelled() {
48 Err(EngineError::ReadCancelled)
49 } else {
50 Ok(())
51 }
52 }
53 pub(crate) fn complete<T>(
56 &self,
57 publish: impl FnOnce() -> Result<T, EngineError>,
58 ) -> Result<T, EngineError> {
59 let _gate = self
60 .0
61 .publication
62 .lock()
63 .unwrap_or_else(std::sync::PoisonError::into_inner);
64 self.check()?;
65 let answer = publish()?;
66 self.0.state.store(Self::COMPLETE, Ordering::Release);
67 Ok(answer)
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn cancelled_work_cannot_publish_and_completed_work_ignores_late_cancellation() {
77 let cancelled = ReadCancellation::default();
78 cancelled.claim().unwrap();
79 cancelled.cancel();
80 assert!(matches!(
81 cancelled.complete::<()>(|| panic!("must not publish")),
82 Err(EngineError::ReadCancelled)
83 ));
84 let completed = ReadCancellation::default();
85 completed.claim().unwrap();
86 assert_eq!(completed.complete(|| Ok(42)).unwrap(), 42);
87 completed.cancel();
88 assert!(!completed.is_cancelled());
89 assert!(matches!(
90 completed.claim(),
91 Err(EngineError::ReusedCancellation)
92 ));
93 }
94}