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;
pub const EXPECTED_WORDS: &str = "printobserver harness ready";
#[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."
)
}
pub const SIGN_IN_COMMAND: &str = "printobserver sign-in";
fn check_command() -> String {
format!(
"printobserver {}",
crate::operations::command_for(crate::operations::CHECK_HARNESS)
)
}
pub const STATUS_BOUND: Duration = Duration::from_secs(30);
const STATUS_POLL: Duration = Duration::from_millis(50);
#[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 {
Yes,
No,
Unknown,
}
#[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 {
Answered,
Failed,
NotTried,
}
#[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)]
pub struct HarnessReadiness {
ready: bool,
harness: String,
signed_in: HarnessSignedIn,
turn: HarnessTurn,
reason: Option<String>,
next_step: Option<String>,
}
impl HarnessReadiness {
fn ready(harness: String, signed_in: HarnessSignedIn) -> Self {
Self {
ready: true,
harness,
signed_in,
turn: HarnessTurn::Answered,
reason: None,
next_step: None,
}
}
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),
}
}
#[must_use]
pub const fn is_ready(&self) -> bool {
self.ready
}
}
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));
}
pub struct HarnessCheck {
harness: HarnessIdentity,
state_dir: PathBuf,
timeout: Duration,
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 {
#[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,
}
}
#[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."
),
),
}
}
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())
.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,
}
}
}
fn carries_expected_words(reply: &str) -> bool {
reply.to_lowercase().contains(EXPECTED_WORDS)
}
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;
}
}
}
received.recv_timeout(STATUS_POLL * 20).ok()?.ok()
}
#[cfg(test)]
mod tests {
use super::carries_expected_words;
#[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(""));
}
}