Skip to main content

serialplugin_core/port/
tx_queue.rs

1//! FIFO turnstile for read-until transactions on one port (desktop).
2
3use crate::at::session::AtSessionConfig;
4use crate::error::Error;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, Condvar, Mutex};
7
8const CANCELLED_MSG: &str = "transaction queue cancelled";
9
10/// Serializes exchange / AT jobs on one port. Concurrent callers wait in FIFO order.
11pub struct PortTxQueue {
12    inner: Mutex<Inner>,
13    turn: Condvar,
14    at_session: Mutex<AtSessionConfig>,
15    /// Port-wide exchange cancel flag. Reset when a job *takes its turn*, not when
16    /// each exchange starts, so a cancel landing between the phases of one job
17    /// (`at_phases`, `send_sms_pdu`) is not wiped before the next phase.
18    cancel_flag: Arc<AtomicBool>,
19}
20
21struct Inner {
22    next_ticket: u64,
23    now_serving: u64,
24    /// Tickets below this value were cancelled and must not run.
25    cancel_below: u64,
26    /// A job holds the turn right now.
27    running: bool,
28}
29
30impl Default for PortTxQueue {
31    fn default() -> Self {
32        Self::new()
33    }
34}
35
36impl PortTxQueue {
37    pub fn new() -> Self {
38        Self {
39            inner: Mutex::new(Inner {
40                next_ticket: 0,
41                now_serving: 0,
42                cancel_below: 0,
43                running: false,
44            }),
45            turn: Condvar::new(),
46            at_session: Mutex::new(AtSessionConfig::default()),
47            cancel_flag: Arc::new(AtomicBool::new(false)),
48        }
49    }
50
51    pub fn cancel_flag(&self) -> Arc<AtomicBool> {
52        self.cancel_flag.clone()
53    }
54
55    pub fn configure_at_session(&self, session: AtSessionConfig) {
56        *crate::sync_util::lock_or_recover(&self.at_session) = session;
57    }
58
59    pub fn at_session(&self) -> AtSessionConfig {
60        crate::sync_util::lock_or_recover(&self.at_session).clone()
61    }
62
63    /// Reject every job queued so far. The running job (if any) is stopped through
64    /// the port's cancel flag by the caller; jobs submitted after this call run normally.
65    pub fn cancel_all(&self) {
66        let mut inner = crate::sync_util::lock_or_recover(&self.inner);
67        inner.cancel_below = inner.next_ticket;
68        if !inner.running {
69            inner.now_serving = inner.next_ticket;
70        }
71        self.turn.notify_all();
72    }
73
74    /// Run `f` when this caller's turn arrives (FIFO).
75    pub fn run_serial<F, T>(&self, f: F) -> Result<T, Error>
76    where
77        F: FnOnce() -> Result<T, Error>,
78    {
79        let mut inner = crate::sync_util::lock_or_recover(&self.inner);
80        let ticket = inner.next_ticket;
81        inner.next_ticket += 1;
82        while inner.now_serving != ticket {
83            if ticket < inner.cancel_below {
84                return Err(Error::String(CANCELLED_MSG.into()));
85            }
86            inner = self.turn.wait(inner).unwrap_or_else(|e| e.into_inner());
87        }
88        inner.running = true;
89        self.cancel_flag.store(false, Ordering::SeqCst);
90        drop(inner);
91
92        // Release the turn even if `f` panics, so the queue never wedges.
93        struct Turn<'a>(&'a PortTxQueue);
94        impl Drop for Turn<'_> {
95            fn drop(&mut self) {
96                let mut inner = crate::sync_util::lock_or_recover(&self.0.inner);
97                inner.running = false;
98                inner.now_serving = (inner.now_serving + 1).max(inner.cancel_below);
99                self.0.turn.notify_all();
100            }
101        }
102        let _turn = Turn(self);
103        f()
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use std::sync::atomic::{AtomicU32, Ordering};
111    use std::sync::Arc;
112    use std::thread;
113    use std::time::Duration;
114
115    #[test]
116    fn serializes_concurrent_jobs() {
117        let q = Arc::new(PortTxQueue::new());
118        let max_active = Arc::new(AtomicU32::new(0));
119        let peak = Arc::new(AtomicU32::new(0));
120        let completed = Arc::new(AtomicU32::new(0));
121        let mut handles = vec![];
122        for _ in 0..3u32 {
123            let q = q.clone();
124            let max_active = max_active.clone();
125            let peak = peak.clone();
126            let completed = completed.clone();
127            handles.push(thread::spawn(move || {
128                q.run_serial(|| {
129                    let active = max_active.fetch_add(1, Ordering::SeqCst) + 1;
130                    peak.fetch_max(active, Ordering::SeqCst);
131                    thread::sleep(Duration::from_millis(10));
132                    max_active.fetch_sub(1, Ordering::SeqCst);
133                    completed.fetch_add(1, Ordering::SeqCst);
134                    Ok(())
135                })
136                .unwrap();
137            }));
138        }
139        for h in handles {
140            h.join().unwrap();
141        }
142        assert_eq!(completed.load(Ordering::SeqCst), 3);
143        assert_eq!(peak.load(Ordering::SeqCst), 1);
144    }
145
146    #[test]
147    fn cancel_drains_waiters() {
148        let q = Arc::new(PortTxQueue::new());
149        let gate = Arc::new(Mutex::new(false));
150        let q1 = q.clone();
151        let gate1 = gate.clone();
152        let t1 = thread::spawn(move || {
153            q1.run_serial(|| {
154                *gate1.lock().unwrap() = true;
155                thread::sleep(Duration::from_millis(200));
156                Ok(())
157            })
158        });
159        while !*gate.lock().unwrap() {
160            thread::sleep(Duration::from_millis(5));
161        }
162        let q2 = q.clone();
163        let t2 = thread::spawn(move || q2.run_serial(|| Ok(())));
164        thread::sleep(Duration::from_millis(20));
165        q.cancel_all();
166        let r2 = t2.join().unwrap();
167        assert!(r2.is_err());
168        let _ = t1.join();
169    }
170
171    #[test]
172    fn cancel_all_then_next_job_runs() {
173        let q = Arc::new(PortTxQueue::new());
174        q.cancel_all();
175        let result = q.run_serial(|| Ok(42));
176        assert_eq!(result.unwrap(), 42);
177    }
178
179    /// Regression: cancelling while a job runs used to push `now_serving` past every
180    /// future ticket, so the next job on the port waited forever.
181    #[test]
182    fn cancel_during_running_job_does_not_wedge_queue() {
183        let q = Arc::new(PortTxQueue::new());
184        let started = Arc::new(std::sync::Barrier::new(2));
185        let (q1, s1) = (q.clone(), started.clone());
186        let t1 = thread::spawn(move || {
187            q1.run_serial(|| {
188                s1.wait();
189                thread::sleep(Duration::from_millis(50));
190                Ok(())
191            })
192        });
193        started.wait();
194        q.cancel_all();
195        t1.join().unwrap().unwrap();
196        let (tx, rx) = std::sync::mpsc::channel();
197        let q2 = q.clone();
198        thread::spawn(move || tx.send(q2.run_serial(|| Ok(7))).unwrap());
199        let r = rx
200            .recv_timeout(Duration::from_secs(2))
201            .expect("next job never ran");
202        assert_eq!(r.unwrap(), 7);
203    }
204
205    /// A cancel during one job stays visible for the rest of that job (later
206    /// phases) and is cleared only when the next job takes its turn.
207    #[test]
208    fn cancel_flag_survives_within_job_and_resets_for_next() {
209        let q = PortTxQueue::new();
210        let flag = q.cancel_flag();
211        q.run_serial(|| {
212            flag.store(true, Ordering::SeqCst);
213            assert!(flag.load(Ordering::SeqCst));
214            Ok(())
215        })
216        .unwrap();
217        q.run_serial(|| {
218            assert!(!flag.load(Ordering::SeqCst));
219            Ok(())
220        })
221        .unwrap();
222    }
223
224    #[test]
225    fn error_in_job_does_not_halt_queue() {
226        let q = Arc::new(PortTxQueue::new());
227        let r1: Result<i32, Error> = q.run_serial(|| Err(Error::String("boom".into())));
228        assert!(r1.is_err());
229        let r2 = q.run_serial(|| Ok(99));
230        assert_eq!(r2.unwrap(), 99);
231    }
232}