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