printobserver-server 0.20.2

The printobserver server.
Documentation
//! Whether the supervising agent's harness can run a turn right now, exactly
//! as this server runs one.
//!
//! # What is checked is the harness this server's turns use
//!
//! The check runs inside the server, as the user the server runs as, so the
//! sign-in it reads is the one under the state directory every supervision
//! turn is pointed at — never whatever sign-in the operator's own shell holds.
//! Two things are asked, in order:
//!
//! 1. **The harness's own status command**, declared beside its sign-in in the
//!    adapter's table and run with that table's variable pointing at the
//!    sign-in directory. Only the one field saying whether it is signed in is
//!    read; nothing else it printed is kept, logged or echoed, and what it
//!    printed on its error stream is not read at all. A harness the table
//!    declares no status command for is `unknown`, and is decided by its turn.
//! 2. **One minimal turn** through the very port supervision uses: a fixed
//!    one-line prompt, in no session, bounded by
//!    `supervisor.check_turn_timeout_s`, answered only when the reply carries
//!    [`EXPECTED_WORDS`]. A token that has lapsed can still report signed in
//!    and fails here. A harness that says it is not signed in is not asked.
//!
//! The check sends nothing to the printer, opens no print and writes no
//! record: it is a read.

use std::io::Read as _;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};

use printobserver_oneharness::{HarnessIdentity, HarnessSignIn};
use printobserver_supervisor_api::{SupervisorError, SupervisorPort};
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};

use crate::config::ServerConfig;

/// The words a reply has to carry for the turn to count as answered,
/// compared without regard to case.
pub const EXPECTED_WORDS: &str = "printobserver harness ready";

/// The one line every check's turn is asked: to reply with
/// [`EXPECTED_WORDS`] and nothing else.
#[must_use]
pub fn check_prompt() -> String {
    format!(
        "This is a readiness check, not a print: reply with exactly the words \
         {EXPECTED_WORDS}, and nothing else."
    )
}

/// The command that signs the harness in, which every answer a sign-in would
/// fix names as its next step. The command-line program's own tier holds it to
/// that program's `sign-in`.
pub const SIGN_IN_COMMAND: &str = "printobserver sign-in";

/// The command that runs this check, spelled from the operation it reaches,
/// which every answer naming something to try again names.
fn check_command() -> String {
    format!(
        "printobserver {}",
        crate::operations::command_for(crate::operations::CHECK_HARNESS)
    )
}

/// The longest the harness's status command may take before its answer is
/// taken as no answer, and never longer than the check's own turn may: it
/// reads a file and prints, and a command still running after this is not
/// going to say anything the turn after it will not.
pub const STATUS_BOUND: Duration = Duration::from_secs(30);

/// How often a running status command is looked at.
const STATUS_POLL: Duration = Duration::from_millis(50);

/// Whether the harness says it is signed in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum HarnessSignedIn {
    /// Its status command says it is.
    Yes,
    /// Its status command says it is not.
    No,
    /// It has no status command this program knows, or that command gave no
    /// answer this program could read.
    Unknown,
}

/// What became of the check's one turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum HarnessTurn {
    /// The harness replied, carrying the expected words.
    Answered,
    /// The turn ran and failed: refused, timed out, or replied without the
    /// expected words.
    Failed,
    /// The turn was not tried, because the harness says it is not signed in.
    NotTried,
}

/// Whether the supervising agent's harness can run a turn right now, why not
/// when it cannot, and what to do about it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars", transform = every_field_is_sent)]
// Its fields are private and it is made by `HarnessReadiness::ready` or
// `HarnessReadiness::not_ready` alone, so a ready answer carrying a reason, or a
// not-ready one carrying none, cannot be built. A plain comment rather than a
// doc comment, because the doc comment is the published schema's description.
pub struct HarnessReadiness {
    /// True only when `signed_in` is not `no` and `turn` is `answered`.
    ready: bool,
    /// The configured harness identity, `supervisor.harness`.
    harness: String,
    /// Whether the harness's own status command says it is signed in.
    signed_in: HarnessSignedIn,
    /// What became of the check's one turn.
    turn: HarnessTurn,
    /// Why it is not ready, in one plain sentence; null when it is.
    reason: Option<String>,
    /// What to do about it: `printobserver sign-in` when a sign-in would fix
    /// it, and a sentence otherwise; null when it is ready.
    next_step: Option<String>,
}

impl HarnessReadiness {
    /// A harness whose turn answered, and which did not say it is signed out.
    fn ready(harness: String, signed_in: HarnessSignedIn) -> Self {
        Self {
            ready: true,
            harness,
            signed_in,
            turn: HarnessTurn::Answered,
            reason: None,
            next_step: None,
        }
    }

    /// A harness that is not ready, why, and what to do about it.
    fn not_ready(
        harness: String,
        signed_in: HarnessSignedIn,
        turn: HarnessTurn,
        reason: String,
        next_step: String,
    ) -> Self {
        Self {
            ready: false,
            harness,
            signed_in,
            turn,
            reason: Some(reason),
            next_step: Some(next_step),
        }
    }

    /// Whether the harness can run a turn right now.
    #[must_use]
    pub const fn is_ready(&self) -> bool {
        self.ready
    }
}

/// Declare every field of the answer required, the two that are null when it
/// is ready included: each is always sent, its null meaning what its
/// description says, rather than left out.
fn every_field_is_sent(schema: &mut printobserver_types::schemars::Schema) {
    use printobserver_types::serde_json::Value;
    let named: Vec<Value> = schema
        .get("properties")
        .and_then(Value::as_object)
        .map(|properties| properties.keys().cloned().map(Value::String).collect())
        .unwrap_or_default();
    schema.insert("required".to_owned(), Value::Array(named));
}

/// What the check runs against: the configured harness, where its sign-in is
/// kept, how long its turn may take, and the port that runs the turn.
pub struct HarnessCheck {
    /// The configured harness identity.
    harness: HarnessIdentity,
    /// The state directory the sign-in is kept under.
    state_dir: PathBuf,
    /// How long the one turn may take.
    timeout: Duration,
    /// The port every supervision turn runs through.
    agent: Arc<dyn SupervisorPort>,
}

impl core::fmt::Debug for HarnessCheck {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("HarnessCheck")
            .field("harness", &self.harness)
            .field("timeout", &self.timeout)
            .finish_non_exhaustive()
    }
}

impl HarnessCheck {
    /// The check of the harness `config` names, through `agent`.
    #[must_use]
    pub fn new(config: &ServerConfig, agent: Arc<dyn SupervisorPort>) -> Self {
        Self {
            harness: config.harness.clone(),
            state_dir: config.state_dir.clone(),
            timeout: config.check_turn_timeout,
            agent,
        }
    }

    /// Run the check, blocking the calling thread until it has an answer.
    #[must_use]
    pub fn run(&self) -> HarnessReadiness {
        let harness = self.harness.as_str().to_owned();
        let signed_in = match HarnessSignIn::of(&self.harness) {
            Some(entry) => self.status_of(entry),
            None => HarnessSignedIn::Unknown,
        };
        if signed_in == HarnessSignedIn::No {
            let reason = format!(
                "The {harness} harness reports that it is not signed in for the user this server \
                 runs as, so no check turn was tried."
            );
            return HarnessReadiness::not_ready(
                harness,
                signed_in,
                HarnessTurn::NotTried,
                reason,
                SIGN_IN_COMMAND.to_owned(),
            );
        }
        let replied =
            printobserver_core::block_on(self.agent.readiness_turn(check_prompt(), self.timeout));
        let check_command = check_command();
        let failed = |reason: String, next_step: String| {
            HarnessReadiness::not_ready(
                harness.clone(),
                signed_in,
                HarnessTurn::Failed,
                reason,
                next_step,
            )
        };
        match replied {
            Ok(reply) if carries_expected_words(&reply) => {
                HarnessReadiness::ready(harness.clone(), signed_in)
            }
            Ok(_) => failed(
                format!(
                    "The {harness} harness replied to its check turn, but the reply did not \
                     carry the expected words \"{EXPECTED_WORDS}\"."
                ),
                format!(
                    "Run `{check_command}` again, and if the reply still does not carry them, \
                     check the configured {harness} harness and the model it runs."
                ),
            ),
            Err(SupervisorError::IdentityRefused { .. }) => failed(
                format!(
                    "The {harness} harness's check turn failed with an authentication failure: \
                     the harness refused the sign-in this server's turns run under."
                ),
                SIGN_IN_COMMAND.to_owned(),
            ),
            Err(SupervisorError::TimedOut) => failed(
                format!(
                    "The {harness} harness's check turn timed out: no reply came within {} \
                     seconds.",
                    self.timeout.as_secs()
                ),
                format!(
                    "Check that the {harness} harness can reach its service from this host, \
                     then run `{check_command}` again."
                ),
            ),
            Err(
                SupervisorError::Unavailable { detail } | SupervisorError::InvalidAnswer { detail },
            ) => failed(
                format!("The {harness} harness could not run its check turn: {detail}."),
                format!(
                    "Check that the {harness} harness is installed where this server's PATH \
                     finds it, then run `{check_command}` again."
                ),
            ),
        }
    }

    /// What the harness's own status command says, read for its one field.
    fn status_of(&self, entry: &HarnessSignIn) -> HarnessSignedIn {
        let Some(status) = entry.status_command() else {
            return HarnessSignedIn::Unknown;
        };
        let directory = entry.directory(&self.state_dir);
        let program = entry.program_on(&std::env::var_os("PATH").unwrap_or_default());
        let mut command = Command::new(program);
        command
            .args(status.arguments())
            .env(entry.config_env(), &directory)
            .current_dir(&directory)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            // Never read: what a harness says on its error stream is nothing
            // this check repeats.
            .stderr(Stdio::null());
        for assigned in entry.session_assignments().unwrap_or_default() {
            command.env(assigned.name(), assigned.value());
        }
        let printed = printed_within(command, STATUS_BOUND.min(self.timeout));
        match printed.as_deref().and_then(|text| status.signed_in(text)) {
            Some(true) => HarnessSignedIn::Yes,
            Some(false) => HarnessSignedIn::No,
            None => HarnessSignedIn::Unknown,
        }
    }
}

/// Whether a reply carries the expected words, whatever their case.
fn carries_expected_words(reply: &str) -> bool {
    reply.to_lowercase().contains(EXPECTED_WORDS)
}

/// What one command printed on its standard output, when it ran and ended
/// inside `bound`; `None` when it could not be started or did not end in
/// time, and then it is ended here.
fn printed_within(mut command: Command, bound: Duration) -> Option<String> {
    let mut child = command.spawn().ok()?;
    let mut stdout = child.stdout.take()?;
    let (sender, received) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut text = String::new();
        let read = stdout.read_to_string(&mut text).map(|_| text);
        let _ = sender.send(read);
    });
    let deadline = Instant::now() + bound;
    loop {
        match child.try_wait() {
            Ok(Some(_)) => break,
            Ok(None) if Instant::now() < deadline => std::thread::sleep(STATUS_POLL),
            _ => {
                let _ = child.kill();
                let _ = child.wait();
                return None;
            }
        }
    }
    // The command has ended; whatever it left holding its output gets a
    // moment to let go of it, and no more.
    received.recv_timeout(STATUS_POLL * 20).ok()?.ok()
}

#[cfg(test)]
mod tests {
    use super::carries_expected_words;

    /// The expected words are found in a reply whatever its case and whatever
    /// surrounds them, and a reply without all of them does not carry them.
    #[test]
    fn the_expected_words_are_found_whatever_their_case() {
        assert!(carries_expected_words("printobserver harness ready"));
        assert!(carries_expected_words("PrintObserver Harness Ready.\n"));
        assert!(!carries_expected_words("harness ready"));
        assert!(!carries_expected_words(""));
    }
}