1use std::collections::VecDeque;
11use std::sync::{Condvar, Mutex};
12use std::time::Duration;
13
14pub type Worker = fn(Service);
16
17struct Queues {
18 to_service: VecDeque<String>,
19 to_ui: VecDeque<String>,
20 running: bool,
21 stop: bool,
22}
23
24static QUEUES: Mutex<Queues> = Mutex::new(Queues { to_service: VecDeque::new(), to_ui: VecDeque::new(), running: false, stop: false });
25static WAKE: Condvar = Condvar::new();
26static WORKER: Mutex<Option<Worker>> = Mutex::new(None);
27
28pub struct Service {
30 _private: (),
31}
32
33impl Service {
34 pub fn recv(&self, timeout: Duration) -> Option<String> {
36 let mut q = QUEUES.lock().ok()?;
37 if q.to_service.is_empty() && !q.stop {
38 q = WAKE.wait_timeout(q, timeout).ok()?.0;
39 }
40 q.to_service.pop_front()
41 }
42
43 pub fn send(&self, text: impl Into<String>) {
45 if let Ok(mut q) = QUEUES.lock() {
46 q.to_ui.push_back(text.into());
47 }
48 }
49
50 pub fn stopped(&self) -> bool {
52 QUEUES.lock().is_ok_and(|q| q.stop)
53 }
54}
55
56pub fn set_worker(worker: Worker) {
58 if let Ok(mut w) = WORKER.lock() {
59 *w = Some(worker);
60 }
61}
62
63pub fn start(worker: Option<Worker>) -> bool {
66 let Some(worker) = worker.or_else(|| WORKER.lock().ok().and_then(|w| *w)) else { return false };
67 {
68 let Ok(mut q) = QUEUES.lock() else { return false };
69 q.stop = false;
70 if q.running {
71 return true;
72 }
73 q.running = true;
74 }
75 std::thread::Builder::new()
76 .name("aylis-background".into())
77 .spawn(move || {
78 worker(Service { _private: () });
79 if let Ok(mut q) = QUEUES.lock() {
80 q.running = false;
81 }
82 })
83 .is_ok()
84}
85
86pub fn stop() {
88 if let Ok(mut q) = QUEUES.lock() {
89 q.stop = true;
90 }
91 WAKE.notify_all();
92}
93
94pub fn running() -> bool {
96 QUEUES.lock().is_ok_and(|q| q.running)
97}
98
99pub fn send_to_service(text: impl Into<String>) {
101 if let Ok(mut q) = QUEUES.lock() {
102 q.to_service.push_back(text.into());
103 }
104 WAKE.notify_all();
105}
106
107pub fn take_messages() -> Vec<String> {
109 QUEUES.lock().map(|mut q| q.to_ui.drain(..).collect()).unwrap_or_default()
110}
111
112#[cfg(test)]
113mod tests {
114 use super::*;
115
116 fn echo(service: Service) {
117 while !service.stopped() {
118 if let Some(m) = service.recv(Duration::from_millis(50)) {
119 service.send(format!("eco: {m}"));
120 }
121 }
122 }
123
124 #[test]
125 fn the_service_runs_once_and_talks_with_the_screen() {
126 assert!(!start(None) || running(), "sem lógica registrada, não começa");
127 set_worker(echo);
128 assert!(start(None) && start(None), "a segunda vez não abre outra thread");
129 send_to_service("oi");
130 let mut got = Vec::new();
131 for _ in 0..100 {
132 got.extend(take_messages());
133 if !got.is_empty() {
134 break;
135 }
136 std::thread::sleep(Duration::from_millis(10));
137 }
138 assert_eq!(got, ["eco: oi"]);
139 stop();
140 for _ in 0..100 {
141 if !running() {
142 break;
143 }
144 std::thread::sleep(Duration::from_millis(10));
145 }
146 assert!(!running());
147 }
148}