Skip to main content

aylis_core/
background.rs

1//! O serviço em segundo plano (o componente `BackgroundService`): a lógica sem tela do app (a
2//! unidade `background` do projeto, `pub fn run(service: Service)`) numa thread que continua
3//! com a tela fechada. No Android ela fica num serviço em primeiro plano (a notificação fixa)
4//! e o sistema não mata o processo; no desktop, enquanto o app roda.
5//!
6//! A tela e o serviço conversam por mensagens de texto: [`send_to_service`] (o `send` do
7//! componente) e [`Service::send`] (que chega no `on_message` dele). As mensagens esperam
8//! numa fila: a tela fechada e aberta de novo recebe o que o serviço mandou nesse meio tempo.
9
10use std::collections::VecDeque;
11use std::sync::{Condvar, Mutex};
12use std::time::Duration;
13
14/// A lógica sem tela do app.
15pub 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
28/// O lado do serviço: recebe as mensagens da tela e manda as dele.
29pub struct Service {
30    _private: (),
31}
32
33impl Service {
34    /// A próxima mensagem da tela, esperando até `timeout` (`None`: nada chegou).
35    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    /// Manda uma mensagem à tela (o `on_message` do `BackgroundService`).
44    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    /// O serviço foi parado (`stop` do componente): a lógica deve terminar.
51    pub fn stopped(&self) -> bool {
52        QUEUES.lock().is_ok_and(|q| q.stop)
53    }
54}
55
56/// O app diz qual é a lógica sem tela (a geração faz isso no `app()`).
57pub fn set_worker(worker: Worker) {
58    if let Ok(mut w) = WORKER.lock() {
59        *w = Some(worker);
60    }
61}
62
63/// Começa a lógica (uma vez por processo; de novo só depois de ela terminar). `worker`: a do
64/// app; `None`, a registrada por [`set_worker`]. Devolve se havia lógica para rodar.
65pub 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
86/// Pede à lógica que termine (ela vê em [`Service::stopped`] e acorda do `recv`).
87pub fn stop() {
88    if let Ok(mut q) = QUEUES.lock() {
89        q.stop = true;
90    }
91    WAKE.notify_all();
92}
93
94/// A lógica está rodando.
95pub fn running() -> bool {
96    QUEUES.lock().is_ok_and(|q| q.running)
97}
98
99/// Manda uma mensagem ao serviço (o `send` do componente).
100pub 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
107/// Tira da fila o que o serviço mandou para a tela.
108pub 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}