Skip to main content

printobserver_server/
watch.rs

1//! The drivers of the printer watch.
2//!
3//! Core decides what a read of the machine means and writes it down
4//! ([`Supervisor::watch_printer`], [`Supervisor::note_push`],
5//! [`Supervisor::check_detector`]); this is what asks it to, and what holds
6//! the two things core may not: the printer's push channel, and the one
7//! command the watch sends.
8//!
9//! * **The reads**, once per
10//!   [`CoreConfig::printer_poll`](printobserver_core::CoreConfig), whether or
11//!   not a print is active, each turn they claimed run as an observation's is.
12//! * **The push reader**, which opens the printer's push channel, hands each
13//!   reset and error to core as it arrives and keeps each terminal line for the
14//!   position probe — and, when the channel drops or cannot be opened, tells
15//!   core it is down and opens it again after [`REOPEN_AFTER`].
16//! * **The position probe**, which core asks only once a read has found no job
17//!   running: it sends [`PrinterCommand::ReportPosition`] and reads the reply
18//!   off the push channel's terminal lines, waiting up to [`POSITION_WAIT`].
19//!   With the channel down it sends nothing and answers no position.
20//! * **The detector check**, once per observation interval, when
21//!   `obico.ml_api_url` is configured.
22//!
23//! `send_command` is called here and nowhere else in this program: no
24//! operation, agent or client can reach it.
25//!
26//! Every core call is made on a blocking thread, as the observation driver
27//! makes its own, because the ports' futures block the thread that polls them.
28
29use std::collections::VecDeque;
30use std::future::poll_fn;
31use std::sync::atomic::{AtomicBool, Ordering};
32use std::sync::{Arc, Mutex, Weak};
33use std::time::{Duration, Instant};
34
35use printobserver_core::{
36    DetectorProbe, HeadPosition, PendingTurn, PositionProbe, Supervisor, block_on,
37};
38use printobserver_printer_api::{BoxFuture, PrinterCommand, PrinterPort, PrinterPush};
39use tokio::task::JoinHandle;
40
41/// How long after the push channel drops, or refuses to open, it is opened
42/// again.
43pub const REOPEN_AFTER: Duration = Duration::from_secs(5);
44
45/// How long the position probe waits for the reply to its command.
46pub const POSITION_WAIT: Duration = Duration::from_secs(3);
47
48/// How many terminal lines the position probe keeps, newest last.
49const KEPT_LINES: usize = 64;
50
51/// The printer watch's tasks, aborted together and when dropped.
52#[derive(Debug)]
53pub struct Watching {
54    /// Each task.
55    tasks: Vec<JoinHandle<()>>,
56}
57
58impl Watching {
59    /// Stop every task.
60    pub fn abort(&self) {
61        for task in &self.tasks {
62            task.abort();
63        }
64    }
65}
66
67impl Drop for Watching {
68    fn drop(&mut self) {
69        self.abort();
70    }
71}
72
73/// What the push reader shares with the position probe.
74#[derive(Debug, Default)]
75struct Terminal {
76    /// Whether the push channel is open now.
77    open: AtomicBool,
78    /// The terminal lines read since the probe last asked, newest last.
79    lines: Mutex<VecDeque<String>>,
80}
81
82impl Terminal {
83    /// Keep one line.
84    fn keep(&self, line: String) {
85        let mut lines = self
86            .lines
87            .lock()
88            .unwrap_or_else(std::sync::PoisonError::into_inner);
89        lines.push_back(line);
90        while lines.len() > KEPT_LINES {
91            lines.pop_front();
92        }
93    }
94
95    /// Take every line kept.
96    fn take(&self) -> Vec<String> {
97        self.lines
98            .lock()
99            .unwrap_or_else(std::sync::PoisonError::into_inner)
100            .drain(..)
101            .collect()
102    }
103}
104
105/// Reads the head's position by asking the printer and reading the reply off
106/// its push channel.
107struct Probe {
108    /// The printer.
109    printer: Arc<dyn PrinterPort>,
110    /// What the push reader keeps.
111    terminal: Arc<Terminal>,
112}
113
114impl Probe {
115    /// Ask once, waiting for the reply.
116    async fn position(&self) -> Option<HeadPosition> {
117        if !self.terminal.open.load(Ordering::SeqCst) {
118            return None;
119        }
120        // What arrived before the command is not its reply.
121        let _ = self.terminal.take();
122        self.printer
123            .send_command(PrinterCommand::ReportPosition)
124            .await
125            .ok()?;
126        let deadline = Instant::now() + POSITION_WAIT;
127        while Instant::now() < deadline {
128            let found = self
129                .terminal
130                .take()
131                .iter()
132                .find_map(|line| printobserver_octoprint::push::position_of(line));
133            if let Some([x, y, z]) = found {
134                return Some(HeadPosition { x, y, z });
135            }
136            // A blocking thread of the runtime's own, which is where the watch
137            // runs: waiting here holds no asynchronous worker.
138            std::thread::sleep(Duration::from_millis(50));
139        }
140        None
141    }
142}
143
144impl PositionProbe for Probe {
145    fn read_position(&self) -> BoxFuture<'_, Option<HeadPosition>> {
146        Box::pin(self.position())
147    }
148}
149
150/// Start the printer watch: its reads, its push reader and, when a detector
151/// check is given, that check.
152pub fn start(
153    supervisor: &Arc<Supervisor>,
154    printer: Arc<dyn PrinterPort>,
155    detector: Option<Arc<dyn DetectorProbe>>,
156) -> Watching {
157    let terminal = Arc::new(Terminal::default());
158    let probe = Arc::new(Probe {
159        printer: Arc::clone(&printer),
160        terminal: Arc::clone(&terminal),
161    });
162    let mut tasks = vec![
163        reading(Arc::downgrade(supervisor), probe),
164        pushing(Arc::downgrade(supervisor), printer, terminal),
165    ];
166    if let Some(detector) = detector {
167        tasks.push(checking(Arc::downgrade(supervisor), detector));
168    }
169    Watching { tasks }
170}
171
172/// Run each claimed turn on a blocking thread of its own.
173fn run_turns(supervisor: &Arc<Supervisor>, turns: Vec<PendingTurn>) {
174    for turn in turns {
175        let runner = Arc::clone(supervisor);
176        tokio::spawn(async move {
177            let supervised = tokio::task::spawn_blocking(move || {
178                let _ = block_on(runner.run_supervision(turn));
179            })
180            .await;
181            debug_assert!(supervised.is_ok(), "one watch turn panicked");
182        });
183    }
184}
185
186/// Read the machine once per poll, and run what the reads claimed.
187fn reading(weak: Weak<Supervisor>, probe: Arc<Probe>) -> JoinHandle<()> {
188    tokio::spawn(async move {
189        loop {
190            let Some(poll) = weak.upgrade().map(|held| held.config().printer_poll) else {
191                return;
192            };
193            tokio::time::sleep(poll).await;
194            let Some(supervisor) = weak.upgrade() else {
195                return;
196            };
197            let watching = Arc::clone(&supervisor);
198            let probing = Arc::clone(&probe);
199            let watched = tokio::task::spawn_blocking(move || {
200                block_on(watching.watch_printer(probing.as_ref()))
201            })
202            .await;
203            // A round the store refused recorded nothing; the next one reads
204            // the machine again.
205            if let Ok(Ok(watched)) = watched {
206                run_turns(&supervisor, watched.turns);
207            }
208        }
209    })
210}
211
212/// Keep the printer's push channel open, handing what it pushes to core.
213fn pushing(
214    weak: Weak<Supervisor>,
215    printer: Arc<dyn PrinterPort>,
216    terminal: Arc<Terminal>,
217) -> JoinHandle<()> {
218    tokio::spawn(async move {
219        loop {
220            let opening = Arc::clone(&printer);
221            let opened = tokio::task::spawn_blocking(move || block_on(opening.push_events())).await;
222            let Some(supervisor) = weak.upgrade() else {
223                return;
224            };
225            match opened {
226                Ok(Ok(mut stream)) => {
227                    terminal.open.store(true, Ordering::SeqCst);
228                    supervisor.note_push_channel(Ok(()));
229                    drop(supervisor);
230                    while let Some(push) =
231                        poll_fn(|context| stream.as_mut().poll_next(context)).await
232                    {
233                        match push {
234                            PrinterPush::Log { line } => terminal.keep(line),
235                            other => {
236                                let Some(supervisor) = weak.upgrade() else {
237                                    return;
238                                };
239                                let noted = tokio::task::spawn_blocking(move || {
240                                    block_on(supervisor.note_push(other))
241                                })
242                                .await;
243                                debug_assert!(noted.is_ok(), "noting one push panicked");
244                            }
245                        }
246                    }
247                    terminal.open.store(false, Ordering::SeqCst);
248                    let Some(supervisor) = weak.upgrade() else {
249                        return;
250                    };
251                    supervisor.note_push_channel(Err("the push channel dropped".to_owned()));
252                }
253                Ok(Err(error)) => {
254                    terminal.open.store(false, Ordering::SeqCst);
255                    supervisor.note_push_channel(Err(error.to_string()));
256                }
257                Err(_) => {
258                    terminal.open.store(false, Ordering::SeqCst);
259                    supervisor
260                        .note_push_channel(Err("opening the push channel panicked".to_owned()));
261                }
262            }
263            tokio::time::sleep(REOPEN_AFTER).await;
264        }
265    })
266}
267
268/// Check the detector once per observation interval, and run the turn going
269/// unavailable claimed.
270fn checking(weak: Weak<Supervisor>, detector: Arc<dyn DetectorProbe>) -> JoinHandle<()> {
271    tokio::spawn(async move {
272        loop {
273            let Some(interval) = weak
274                .upgrade()
275                .map(|held| held.config().observation_interval)
276            else {
277                return;
278            };
279            tokio::time::sleep(interval).await;
280            let Some(supervisor) = weak.upgrade() else {
281                return;
282            };
283            let checking = Arc::clone(&supervisor);
284            let probe = Arc::clone(&detector);
285            let checked = tokio::task::spawn_blocking(move || {
286                block_on(checking.check_detector(probe.as_ref()))
287            })
288            .await;
289            if let Ok(Ok(Some(turn))) = checked {
290                run_turns(&supervisor, vec![turn]);
291            }
292        }
293    })
294}