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