Skip to main content

printobserver_server/
readiness.rs

1//! Whether the supervising agent's harness can run a turn right now, exactly
2//! as this server runs one.
3//!
4//! # What is checked is the harness this server's turns use
5//!
6//! The check runs inside the server, as the user the server runs as, so the
7//! sign-in it reads is the one under the state directory every supervision
8//! turn is pointed at — never whatever sign-in the operator's own shell holds.
9//! Two things are asked, in order:
10//!
11//! 1. **The harness's own status command**, declared beside its sign-in in the
12//!    adapter's table and run with that table's variable pointing at the
13//!    sign-in directory. Only the one field saying whether it is signed in is
14//!    read; nothing else it printed is kept, logged or echoed, and what it
15//!    printed on its error stream is not read at all. A harness the table
16//!    declares no status command for is `unknown`, and is decided by its turn.
17//! 2. **One minimal turn** through the very port supervision uses: a fixed
18//!    one-line prompt, in no session, bounded by
19//!    `supervisor.check_turn_timeout_s`, answered only when the reply carries
20//!    [`EXPECTED_WORDS`]. A token that has lapsed can still report signed in
21//!    and fails here. A harness that says it is not signed in is not asked.
22//!
23//! The check sends nothing to the printer, opens no print and writes no
24//! record: it is a read.
25
26use std::io::Read as _;
27use std::path::PathBuf;
28use std::process::{Command, Stdio};
29use std::sync::Arc;
30use std::time::{Duration, Instant};
31
32use printobserver_oneharness::{HarnessIdentity, HarnessSignIn};
33use printobserver_supervisor_api::{SupervisorError, SupervisorPort};
34use printobserver_types::schemars::JsonSchema;
35use printobserver_types::serde::{Deserialize, Serialize};
36
37use crate::config::ServerConfig;
38
39/// The words a reply has to carry for the turn to count as answered,
40/// compared without regard to case.
41pub const EXPECTED_WORDS: &str = "printobserver harness ready";
42
43/// The one line every check's turn is asked: to reply with
44/// [`EXPECTED_WORDS`] and nothing else.
45#[must_use]
46pub fn check_prompt() -> String {
47    format!(
48        "This is a readiness check, not a print: reply with exactly the words \
49         {EXPECTED_WORDS}, and nothing else."
50    )
51}
52
53/// The command that signs the harness in, which every answer a sign-in would
54/// fix names as its next step. The command-line program's own tier holds it to
55/// that program's `sign-in`.
56pub const SIGN_IN_COMMAND: &str = "printobserver sign-in";
57
58/// The command that runs this check, spelled from the operation it reaches,
59/// which every answer naming something to try again names.
60fn check_command() -> String {
61    format!(
62        "printobserver {}",
63        crate::operations::command_for(crate::operations::CHECK_HARNESS)
64    )
65}
66
67/// The longest the harness's status command may take before its answer is
68/// taken as no answer, and never longer than the check's own turn may: it
69/// reads a file and prints, and a command still running after this is not
70/// going to say anything the turn after it will not.
71pub const STATUS_BOUND: Duration = Duration::from_secs(30);
72
73/// How often a running status command is looked at.
74const STATUS_POLL: Duration = Duration::from_millis(50);
75
76/// Whether the harness says it is signed in.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
78#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
79#[schemars(crate = "printobserver_types::schemars")]
80pub enum HarnessSignedIn {
81    /// Its status command says it is.
82    Yes,
83    /// Its status command says it is not.
84    No,
85    /// It has no status command this program knows, or that command gave no
86    /// answer this program could read.
87    Unknown,
88}
89
90/// What became of the check's one turn.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
92#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
93#[schemars(crate = "printobserver_types::schemars")]
94pub enum HarnessTurn {
95    /// The harness replied, carrying the expected words.
96    Answered,
97    /// The turn ran and failed: refused, timed out, or replied without the
98    /// expected words.
99    Failed,
100    /// The turn was not tried, because the harness says it is not signed in.
101    NotTried,
102}
103
104/// Whether the supervising agent's harness can run a turn right now, why not
105/// when it cannot, and what to do about it.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
107#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
108#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
109// Its fields are private and it is made by `HarnessReadiness::ready` or
110// `HarnessReadiness::not_ready` alone, so a ready answer carrying a reason, or a
111// not-ready one carrying none, cannot be built. A plain comment rather than a
112// doc comment, because the doc comment is the published schema's description.
113pub struct HarnessReadiness {
114    /// True only when `signed_in` is not `no` and `turn` is `answered`.
115    ready: bool,
116    /// The configured harness identity, `supervisor.harness`.
117    harness: String,
118    /// Whether the harness's own status command says it is signed in.
119    signed_in: HarnessSignedIn,
120    /// What became of the check's one turn.
121    turn: HarnessTurn,
122    /// Why it is not ready, in one plain sentence; null when it is.
123    reason: Option<String>,
124    /// What to do about it: `printobserver sign-in` when a sign-in would fix
125    /// it, and a sentence otherwise; null when it is ready.
126    next_step: Option<String>,
127}
128
129impl HarnessReadiness {
130    /// A harness whose turn answered, and which did not say it is signed out.
131    fn ready(harness: String, signed_in: HarnessSignedIn) -> Self {
132        Self {
133            ready: true,
134            harness,
135            signed_in,
136            turn: HarnessTurn::Answered,
137            reason: None,
138            next_step: None,
139        }
140    }
141
142    /// A harness that is not ready, why, and what to do about it.
143    fn not_ready(
144        harness: String,
145        signed_in: HarnessSignedIn,
146        turn: HarnessTurn,
147        reason: String,
148        next_step: String,
149    ) -> Self {
150        Self {
151            ready: false,
152            harness,
153            signed_in,
154            turn,
155            reason: Some(reason),
156            next_step: Some(next_step),
157        }
158    }
159
160    /// Whether the harness can run a turn right now.
161    #[must_use]
162    pub const fn is_ready(&self) -> bool {
163        self.ready
164    }
165}
166
167/// Declare every field of the answer required, the two that are null when it
168/// is ready included: each is always sent, its null meaning what its
169/// description says, rather than left out.
170fn every_field_is_sent(schema: &mut printobserver_types::schemars::Schema) {
171    use printobserver_types::serde_json::Value;
172    let named: Vec<Value> = schema
173        .get("properties")
174        .and_then(Value::as_object)
175        .map(|properties| properties.keys().cloned().map(Value::String).collect())
176        .unwrap_or_default();
177    schema.insert("required".to_owned(), Value::Array(named));
178}
179
180/// What the check runs against: the configured harness, where its sign-in is
181/// kept, how long its turn may take, and the port that runs the turn.
182pub struct HarnessCheck {
183    /// The configured harness identity.
184    harness: HarnessIdentity,
185    /// The state directory the sign-in is kept under.
186    state_dir: PathBuf,
187    /// How long the one turn may take.
188    timeout: Duration,
189    /// The port every supervision turn runs through.
190    agent: Arc<dyn SupervisorPort>,
191}
192
193impl core::fmt::Debug for HarnessCheck {
194    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
195        formatter
196            .debug_struct("HarnessCheck")
197            .field("harness", &self.harness)
198            .field("timeout", &self.timeout)
199            .finish_non_exhaustive()
200    }
201}
202
203impl HarnessCheck {
204    /// The check of the harness `config` names, through `agent`.
205    #[must_use]
206    pub fn new(config: &ServerConfig, agent: Arc<dyn SupervisorPort>) -> Self {
207        Self {
208            harness: config.harness.clone(),
209            state_dir: config.state_dir.clone(),
210            timeout: config.check_turn_timeout,
211            agent,
212        }
213    }
214
215    /// Run the check, blocking the calling thread until it has an answer.
216    #[must_use]
217    pub fn run(&self) -> HarnessReadiness {
218        let harness = self.harness.as_str().to_owned();
219        let signed_in = match HarnessSignIn::of(&self.harness) {
220            Some(entry) => self.status_of(entry),
221            None => HarnessSignedIn::Unknown,
222        };
223        if signed_in == HarnessSignedIn::No {
224            let reason = format!(
225                "The {harness} harness reports that it is not signed in for the user this server \
226                 runs as, so no check turn was tried."
227            );
228            return HarnessReadiness::not_ready(
229                harness,
230                signed_in,
231                HarnessTurn::NotTried,
232                reason,
233                SIGN_IN_COMMAND.to_owned(),
234            );
235        }
236        let replied =
237            printobserver_core::block_on(self.agent.readiness_turn(check_prompt(), self.timeout));
238        let check_command = check_command();
239        let failed = |reason: String, next_step: String| {
240            HarnessReadiness::not_ready(
241                harness.clone(),
242                signed_in,
243                HarnessTurn::Failed,
244                reason,
245                next_step,
246            )
247        };
248        match replied {
249            Ok(reply) if carries_expected_words(&reply) => {
250                HarnessReadiness::ready(harness.clone(), signed_in)
251            }
252            Ok(_) => failed(
253                format!(
254                    "The {harness} harness replied to its check turn, but the reply did not \
255                     carry the expected words \"{EXPECTED_WORDS}\"."
256                ),
257                format!(
258                    "Run `{check_command}` again, and if the reply still does not carry them, \
259                     check the configured {harness} harness and the model it runs."
260                ),
261            ),
262            Err(SupervisorError::IdentityRefused { .. }) => failed(
263                format!(
264                    "The {harness} harness's check turn failed with an authentication failure: \
265                     the harness refused the sign-in this server's turns run under."
266                ),
267                SIGN_IN_COMMAND.to_owned(),
268            ),
269            Err(SupervisorError::TimedOut) => failed(
270                format!(
271                    "The {harness} harness's check turn timed out: no reply came within {} \
272                     seconds.",
273                    self.timeout.as_secs()
274                ),
275                format!(
276                    "Check that the {harness} harness can reach its service from this host, \
277                     then run `{check_command}` again."
278                ),
279            ),
280            Err(
281                SupervisorError::Unavailable { detail } | SupervisorError::InvalidAnswer { detail },
282            ) => failed(
283                format!("The {harness} harness could not run its check turn: {detail}."),
284                format!(
285                    "Check that the {harness} harness is installed where this server's PATH \
286                     finds it, then run `{check_command}` again."
287                ),
288            ),
289        }
290    }
291
292    /// What the harness's own status command says, read for its one field.
293    fn status_of(&self, entry: &HarnessSignIn) -> HarnessSignedIn {
294        let Some(status) = entry.status_command() else {
295            return HarnessSignedIn::Unknown;
296        };
297        let directory = entry.directory(&self.state_dir);
298        let program = entry.program_on(&std::env::var_os("PATH").unwrap_or_default());
299        let mut command = Command::new(program);
300        command
301            .args(status.arguments())
302            .env(entry.config_env(), &directory)
303            .current_dir(&directory)
304            .stdin(Stdio::null())
305            .stdout(Stdio::piped())
306            // Never read: what a harness says on its error stream is nothing
307            // this check repeats.
308            .stderr(Stdio::null());
309        for assigned in entry.session_assignments().unwrap_or_default() {
310            command.env(assigned.name(), assigned.value());
311        }
312        let printed = printed_within(command, STATUS_BOUND.min(self.timeout));
313        match printed.as_deref().and_then(|text| status.signed_in(text)) {
314            Some(true) => HarnessSignedIn::Yes,
315            Some(false) => HarnessSignedIn::No,
316            None => HarnessSignedIn::Unknown,
317        }
318    }
319}
320
321/// Whether a reply carries the expected words, whatever their case.
322fn carries_expected_words(reply: &str) -> bool {
323    reply.to_lowercase().contains(EXPECTED_WORDS)
324}
325
326/// What one command printed on its standard output, when it ran and ended
327/// inside `bound`; `None` when it could not be started or did not end in
328/// time, and then it is ended here.
329fn printed_within(mut command: Command, bound: Duration) -> Option<String> {
330    let mut child = command.spawn().ok()?;
331    let mut stdout = child.stdout.take()?;
332    let (sender, received) = std::sync::mpsc::channel();
333    std::thread::spawn(move || {
334        let mut text = String::new();
335        let read = stdout.read_to_string(&mut text).map(|_| text);
336        let _ = sender.send(read);
337    });
338    let deadline = Instant::now() + bound;
339    loop {
340        match child.try_wait() {
341            Ok(Some(_)) => break,
342            Ok(None) if Instant::now() < deadline => std::thread::sleep(STATUS_POLL),
343            _ => {
344                let _ = child.kill();
345                let _ = child.wait();
346                return None;
347            }
348        }
349    }
350    // The command has ended; whatever it left holding its output gets a
351    // moment to let go of it, and no more.
352    received.recv_timeout(STATUS_POLL * 20).ok()?.ok()
353}
354
355#[cfg(test)]
356mod tests {
357    use super::carries_expected_words;
358
359    /// The expected words are found in a reply whatever its case and whatever
360    /// surrounds them, and a reply without all of them does not carry them.
361    #[test]
362    fn the_expected_words_are_found_whatever_their_case() {
363        assert!(carries_expected_words("printobserver harness ready"));
364        assert!(carries_expected_words("PrintObserver Harness Ready.\n"));
365        assert!(!carries_expected_words("harness ready"));
366        assert!(!carries_expected_words(""));
367    }
368}