1use 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
39pub const EXPECTED_WORDS: &str = "printobserver harness ready";
42
43#[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
53pub const SIGN_IN_COMMAND: &str = "printobserver sign-in";
57
58fn check_command() -> String {
61 format!(
62 "printobserver {}",
63 crate::operations::command_for(crate::operations::CHECK_HARNESS)
64 )
65}
66
67pub const STATUS_BOUND: Duration = Duration::from_secs(30);
72
73const STATUS_POLL: Duration = Duration::from_millis(50);
75
76#[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 Yes,
83 No,
85 Unknown,
88}
89
90#[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 Answered,
97 Failed,
100 NotTried,
102}
103
104#[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)]
109pub struct HarnessReadiness {
114 ready: bool,
116 harness: String,
118 signed_in: HarnessSignedIn,
120 turn: HarnessTurn,
122 reason: Option<String>,
124 next_step: Option<String>,
127}
128
129impl HarnessReadiness {
130 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 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 #[must_use]
162 pub const fn is_ready(&self) -> bool {
163 self.ready
164 }
165}
166
167fn 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
180pub struct HarnessCheck {
183 harness: HarnessIdentity,
185 state_dir: PathBuf,
187 timeout: Duration,
189 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 #[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 #[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 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 .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
321fn carries_expected_words(reply: &str) -> bool {
323 reply.to_lowercase().contains(EXPECTED_WORDS)
324}
325
326fn 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 received.recv_timeout(STATUS_POLL * 20).ok()?.ok()
353}
354
355#[cfg(test)]
356mod tests {
357 use super::carries_expected_words;
358
359 #[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}