use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use printobserver_core::store::Stores;
use printobserver_obico::{ObicoVision, ObicoVisionConfig};
use printobserver_octoprint::standin::Terminal;
use printobserver_octoprint::{OctoPrintConfig, OctoPrintPrinter};
use printobserver_printer_api::{PrinterPort as _, PrinterState};
use printobserver_server::{Ports, Running, Server, ServerConfig};
use printobserver_store_sqlite::SqliteStore;
use printobserver_types::serde_json::{Value, json};
use tempfile::TempDir;
use crate::minted::minted;
use crate::scripted::Scripted;
struct Absent;
impl printobserver_supervisor_api::SupervisorPort for Absent {
fn run_turn(
&self,
_request: printobserver_supervisor_api::TurnRequest,
_access: Arc<dyn printobserver_supervisor_api::TurnAccess>,
) -> printobserver_supervisor_api::BoxFuture<
'_,
Result<
printobserver_supervisor_api::TurnOutcome,
printobserver_supervisor_api::SupervisorError,
>,
> {
Box::pin(async {
Err(printobserver_supervisor_api::SupervisorError::Unavailable {
detail: "this walk runs no turn".to_owned(),
})
})
}
fn close_session(
&self,
_print_id: printobserver_types::PrintId,
_close_reason: String,
) -> printobserver_supervisor_api::BoxFuture<
'_,
Result<(), printobserver_supervisor_api::SupervisorError>,
> {
Box::pin(async { Ok(()) })
}
}
const POLL: Duration = Duration::from_secs(1);
const PATIENCE: Duration = Duration::from_secs(60);
const HOLD_FILE: &str = "hold.gcode";
const FINISH_FILE: &str = "finish.gcode";
struct Watching {
_root: TempDir,
server: Running,
client: reqwest::Client,
}
impl Watching {
async fn open(instance: &Scripted) -> Self {
let root = TempDir::new().expect("a root");
let credential = minted("operator-credential");
let skill =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../skills/printobserver/SKILL.md");
let text = format!(
r#"
state_dir = {state}
listen = "127.0.0.1:0"
[octoprint]
url = "{url}"
api_key = "{key}"
[supervisor]
harness = "claude-code"
skill_path = {skill}
[ingress]
shared_secret = "{secret}"
[api]
credential_verifier = "{verifier}"
[safety]
agent_min_interval_s = 0
[safety.allowed]
feedrate = {{ min = 0.5, max = 1.5 }}
[safety.actions]
operator = ["cancel"]
agent = []
system = []
"#,
state = toml::Value::String(root.path().join("state").display().to_string()),
url = instance.url,
key = instance.api_key,
skill = toml::Value::String(skill.display().to_string()),
secret = minted("ingress-secret"),
verifier = printobserver_server::CredentialVerifier::of(&credential),
);
let path = root.path().join("config.toml");
std::fs::write(&path, text).expect("the configuration is writable");
let mut config = ServerConfig::load(&path).expect("the configuration is accepted");
config.printer_poll = POLL;
let stores = Stores::of(Arc::new(
SqliteStore::open(&config.state_dir).expect("the store opens"),
));
let server = Server::start_with(
config.clone(),
Ports {
printer: Arc::new(OctoPrintPrinter::new(config.octoprint.clone())),
stores,
vision: Arc::new(ObicoVision::new(ObicoVisionConfig::default()).expect("built")),
agent: Arc::new(Absent),
},
)
.await
.expect("the server starts");
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::AUTHORIZATION,
reqwest::header::HeaderValue::from_str(&format!("Bearer {credential}"))
.expect("a header value"),
);
Self {
_root: root,
server,
client: reqwest::Client::builder()
.default_headers(headers)
.build()
.expect("a client"),
}
}
async fn get(&self, path: &str) -> Value {
self.client
.get(format!("{}{path}", self.server.base_url()))
.send()
.await
.expect("the server answers")
.json()
.await
.expect("a JSON answer")
}
async fn history(&self) -> Vec<Value> {
let mut events = self.get("/history?limit=500").await["events"]
.as_array()
.cloned()
.unwrap_or_default();
events.reverse();
events
}
async fn until(&self, what: &str, accepts: impl Fn(&Value) -> bool) -> Value {
let deadline = tokio::time::Instant::now() + PATIENCE;
loop {
if let Some(found) = self
.history()
.await
.into_iter()
.find(|event| accepts(event))
{
return found;
}
assert!(
tokio::time::Instant::now() < deadline,
"{what} was never recorded: {:#}",
Value::Array(self.history().await)
);
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
async fn adopted(&self, after: usize) -> String {
let deadline = tokio::time::Instant::now() + PATIENCE;
loop {
let started: Vec<Value> = self
.history()
.await
.into_iter()
.filter(|event| event["kind"] == "print_started")
.collect();
if started.len() > after {
return started[after]["print_id"]
.as_str()
.expect("a print")
.to_owned();
}
assert!(
tokio::time::Instant::now() < deadline,
"no print was adopted"
);
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
async fn ending(&self, print_id: &str) -> String {
let ended = self
.until(&format!("the end of {print_id}"), |event| {
event["kind"] == "print_ended" && event["print_id"] == print_id
})
.await;
ended["payload"]["outcome"]
.as_str()
.unwrap_or_default()
.to_owned()
}
async fn read_failures_of(&self, print_id: &str) -> Vec<Value> {
self.get(&format!("/prints/{print_id}/history")).await["events"]
.as_array()
.cloned()
.unwrap_or_default()
.into_iter()
.filter(|event| {
event["kind"] == "port_failure"
&& ["printer_snapshot", "printer_job"]
.contains(&event["payload"]["site"].as_str().unwrap_or_default())
})
.collect()
}
async fn offline_count(&self) -> usize {
self.history()
.await
.iter()
.filter(|event| {
event["kind"] == "printer_connection_changed" && event["payload"]["to"] == "offline"
})
.count()
}
async fn went_offline_after(&self, before: usize) {
let deadline = tokio::time::Instant::now() + PATIENCE;
while self.offline_count().await <= before {
assert!(
tokio::time::Instant::now() < deadline,
"going offline was never recorded"
);
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
}
fn reach(instance: &Scripted) -> (OctoPrintPrinter, Terminal) {
let config = OctoPrintConfig::new(&instance.url, instance.api_key.clone())
.expect("the instance's configuration");
(OctoPrintPrinter::new(config.clone()), Terminal::new(config))
}
async fn until_job(printer: &OctoPrintPrinter, wanted: &PrinterState) {
let deadline = tokio::time::Instant::now() + PATIENCE;
loop {
if printer.job().await.is_ok_and(|job| job.state == *wanted) {
return;
}
assert!(
tokio::time::Instant::now() < deadline,
"the machine never reported {wanted:?}"
);
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
async fn settled(printer: &OctoPrintPrinter) {
let deadline = tokio::time::Instant::now() + PATIENCE;
while printer
.job()
.await
.is_ok_and(|job| job.state == PrinterState::Cancelling)
{
assert!(
tokio::time::Instant::now() < deadline,
"the machine never finished cancelling"
);
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
async fn hold_printing(printer: &OctoPrintPrinter) {
let deadline = tokio::time::Instant::now() + PATIENCE;
while !printer
.job()
.await
.is_ok_and(|job| job.state == PrinterState::Printing)
{
match printer
.start(printobserver_types::FileName::new(HOLD_FILE).expect("a file name"))
.await
{
Ok(()) | Err(printobserver_printer_api::PrinterError::StateConflict { .. }) => {}
Err(error) => panic!("the hold print would not start: {error}"),
}
assert!(
tokio::time::Instant::now() < deadline,
"the hold print never started"
);
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
async fn reconnected(printer: &OctoPrintPrinter, terminal: &Terminal) {
terminal.connect().expect("the printer reconnects");
until_job(printer, &PrinterState::Operational).await;
}
fn serial_log() -> String {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.octoprint-env/instance/logs/serial.log");
std::fs::read_to_string(path).unwrap_or_default()
}
fn m114_sent_after(from: usize) -> Vec<String> {
serial_log()
.get(from..)
.unwrap_or_default()
.lines()
.filter(|line| line.contains("Send:") && line.contains("M114"))
.map(str::to_owned)
.collect()
}
fn upload_finish_file() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
let file = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/finish.gcode");
let status = std::process::Command::new("uv")
.args([
"run",
"-q",
"python",
"tools/octoprint-env/octoprint_env.py",
"upload",
])
.arg("--file")
.arg(&file)
.current_dir(&root)
.status()
.expect("the environment's upload runs");
assert!(status.success(), "the finish file was not uploaded");
}
async fn stop(
watch: &Watching,
instance: &Scripted,
adopted: usize,
cause: impl AsyncFnOnce(),
outcome: &str,
) -> String {
let (printer, terminal) = reach(instance);
settled(&printer).await;
if printer
.job()
.await
.is_ok_and(|job| job.state == PrinterState::Offline)
{
reconnected(&printer, &terminal).await;
}
hold_printing(&printer).await;
let print_id = watch.adopted(adopted).await;
let log_before = serial_log().len();
cause().await;
let ended = watch.ending(&print_id).await;
let sent = m114_sent_after(log_before);
assert_eq!(ended, outcome, "print {print_id} ended otherwise");
assert!(sent.is_empty(), "M114 was sent while a job ran: {sent:?}");
assert_eq!(watch.read_failures_of(&print_id).await, Vec::<Value>::new());
print_id
}
pub async fn walk(instance: &Scripted) {
let watch = Watching::open(instance).await;
the_stops_that_go_offline(&watch, instance).await;
the_stops_that_land_idle(&watch, instance).await;
let (printer, _) = reach(instance);
settled(&printer).await;
hold_printing(&printer).await;
}
async fn the_stops_that_go_offline(watch: &Watching, instance: &Scripted) {
let (printer, terminal) = reach(instance);
let dropped = stop(
watch,
instance,
0,
async || terminal.send("!!DEBUG:drop_connection").expect("sent"),
"interrupted",
)
.await;
watch.went_offline_after(0).await;
reconnected(&printer, &terminal).await;
terminal.send("M104 S0").expect("sent");
terminal.send("M140 S0").expect("sent");
tokio::time::sleep(POLL * 4).await;
terminal.send("G1 X50 Y60 Z20 F6000").expect("sent");
let moved = watch
.until("the printer moving on its own", |event| {
event["kind"] == "unattended_printer_activity" && event["payload"]["moved"] == true
})
.await;
assert_eq!(moved["payload"]["last_print_id"], dropped.as_str());
assert_eq!(moved["payload"]["tools"], json!([]));
let before = watch.offline_count().await;
stop(
watch,
instance,
1,
async || {
terminal
.send("!!DEBUG:trigger_fatal_error_marlin")
.expect("sent");
},
"failed",
)
.await;
watch.went_offline_after(before).await;
}
async fn the_stops_that_land_idle(watch: &Watching, instance: &Scripted) {
let (printer, terminal) = reach(instance);
stop(
watch,
instance,
2,
async || terminal.send("!!DEBUG:action_custom cancel").expect("sent"),
"cancelled",
)
.await;
stop(
watch,
instance,
3,
async || printer.cancel().await.expect("OctoPrint cancels its job"),
"cancelled",
)
.await;
settled(&printer).await;
until_job(&printer, &PrinterState::Operational).await;
upload_finish_file();
printer
.start(printobserver_types::FileName::new(FINISH_FILE).expect("a file name"))
.await
.expect("the finish file starts");
let finished = watch.adopted(4).await;
assert_eq!(watch.ending(&finished).await, "completed");
hold_printing(&printer).await;
let operated = watch.adopted(5).await;
let answer = watch
.client
.post(format!(
"{}/prints/{operated}/actions/cancel",
watch.server.base_url()
))
.json(&json!({ "reason": "the operator stopped it", "actor": "operator" }))
.send()
.await
.expect("the server answers");
assert!(answer.status().is_success(), "{}", answer.status());
assert_eq!(watch.ending(&operated).await, "cancelled");
settled(&printer).await;
until_job(&printer, &PrinterState::Operational).await;
terminal.send("!!DEBUG:send start").expect("sent");
let reset = watch
.until("the idle reset", |event| event["kind"] == "printer_reset")
.await;
assert_eq!(reset["payload"]["during_print"], Value::Null);
}