use printobserver_core::AgentAssessmentPayload;
use printobserver_obico::ObicoFailureAlertPayload;
use printobserver_octoprint::{
FAN_PWM_PARAMETER, FAN_SET_COMMAND, fan_pwm_of_percent, percent_of_multiplier,
};
use printobserver_server::StartupReconciliationPayload;
use printobserver_server::{Effect, OPERATIONS, Operation};
use printobserver_supervisor_api::SupervisionSessionOpenedPayload;
use printobserver_types::serde_json::{Value, json};
use printobserver_types::{EventKind, EventPayload as _, PrintId};
use crate::composition::{
AGENT_DURATION_S, AGENT_FACTOR, AGENT_REFUSED_FACTOR, Composed, NARROWED, SECRET,
hold_the_print_running,
};
use crate::http_host::image_host;
use crate::proxy::Proxy;
use crate::scripted::Scripted;
use crate::waiting::until;
const HOLD_FILE: &str = "hold.gcode";
const OBICO_PRINT: i64 = 4211;
const DURATION_S: i64 = 600;
fn snapshot_bytes() -> Vec<u8> {
let frame =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/recorded-frame.jpg");
std::fs::read(&frame).expect("the recorded frame reads")
}
fn alert_body(image_url: &str) -> String {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../printobserver-obico/samples/obico/failure-alert.json");
let mut sample: Value = printobserver_types::serde_json::from_str(
&std::fs::read_to_string(&path).expect("the committed sample reads"),
)
.expect("the committed sample is JSON");
sample["print"]["id"] = json!(OBICO_PRINT);
sample["print"]["filename"] = json!(HOLD_FILE);
sample["img_url"] = json!(image_url);
sample.to_string()
}
fn body(extra: &[(&str, Value)]) -> Value {
let mut body = json!({ "reason": "the integration tier is asking", "actor": "operator" });
let object = body.as_object_mut().expect("the body is an object");
for (name, value) in extra {
object.insert((*name).to_owned(), value.clone());
}
body
}
fn as_the_agent(extra: &[(&str, Value)]) -> Value {
let mut body = body(extra);
body.as_object_mut().expect("the body is an object").insert(
"actor".to_owned(),
json!({ "agent": { "session_name": "watch-1" } }),
);
body
}
fn manifest() -> Value {
json!({
"file_name": HOLD_FILE,
"material": "PLA",
"nozzle_diameter_mm": 0.4,
"slicer_profile": "0.20mm QUALITY",
"sheet": "smooth-pei",
"allowed": { "feedrate": { "min": NARROWED.0, "max": NARROWED.1 } },
"metadata": {},
})
}
fn manifest_write(reason: Option<&str>) -> Value {
let mut body = json!({ "manifest": manifest() });
if let Some(reason) = reason {
body.as_object_mut()
.expect("the body is an object")
.insert("reason".to_owned(), json!(reason));
}
body
}
struct Live {
accepted: Value,
rejected: Value,
reaches: Option<&'static str>,
reported: Option<(&'static str, Value)>,
received: Vec<String>,
adjustable: Option<&'static str>,
}
fn refused_at_the_machine(extra: &[(&str, Value)]) -> Live {
Live {
accepted: body(extra),
rejected: as_the_agent(extra),
reaches: None,
reported: None,
received: Vec::new(),
adjustable: None,
}
}
fn live(name: &str) -> Live {
match name {
"pause" => Live {
accepted: body(&[]),
rejected: as_the_agent(&[]),
reaches: Some("paused"),
reported: None,
received: Vec::new(),
adjustable: None,
},
"resume" => Live {
accepted: body(&[]),
rejected: as_the_agent(&[]),
reaches: Some("printing"),
reported: None,
received: Vec::new(),
adjustable: None,
},
"cancel" => Live {
accepted: body(&[]),
rejected: as_the_agent(&[]),
reaches: Some("operational"),
reported: None,
received: Vec::new(),
adjustable: None,
},
"start_print" => Live {
accepted: body(&[("file_name", json!(HOLD_FILE)), ("manifest", manifest())]),
rejected: as_the_agent(&[("file_name", json!(HOLD_FILE)), ("manifest", manifest())]),
reaches: Some("printing"),
reported: None,
received: Vec::new(),
adjustable: None,
},
"acknowledge_failure" => Live {
accepted: body(&[
("event_id", json!(printobserver_types::EventId::new())),
("disposition", json!("stop")),
]),
rejected: as_the_agent(&[
("event_id", json!(printobserver_types::EventId::new())),
("disposition", json!("continue")),
]),
reaches: Some("printing"),
reported: None,
received: Vec::new(),
adjustable: None,
},
"set_tool_target_c" => Live {
accepted: body(&[("tool", json!(0)), ("target_c", json!(205.0))]),
rejected: body(&[("tool", json!(0)), ("target_c", json!(900.0))]),
reaches: None,
reported: Some(("printer.tools.0.target_c.value", json!(205.0))),
received: Vec::new(),
adjustable: Some("tool_target:0"),
},
"set_bed_target_c" => Live {
accepted: body(&[("target_c", json!(61.0))]),
rejected: body(&[("target_c", json!(400.0))]),
reaches: None,
reported: Some(("printer.bed.target_c.value", json!(61.0))),
received: Vec::new(),
adjustable: Some("bed_target"),
},
"set_feedrate_factor" => Live {
accepted: body(&[("factor", json!(1.13))]),
rejected: body(&[("factor", json!(1.45))]),
reaches: None,
reported: None,
received: vec![percent_of_multiplier(1.13).to_string()],
adjustable: Some("feedrate"),
},
"set_flowrate_factor" => Live {
accepted: body(&[("factor", json!(1.07))]),
rejected: body(&[("factor", json!(4.0))]),
reaches: None,
reported: None,
received: vec![percent_of_multiplier(1.07).to_string()],
adjustable: Some("flowrate"),
},
"set_fan_percent" => Live {
accepted: body(&[("percent", json!(55.0))]),
rejected: body(&[("percent", json!(500.0))]),
reaches: None,
reported: None,
received: vec![
FAN_SET_COMMAND.to_owned(),
FAN_PWM_PARAMETER.to_owned(),
fan_pwm_of_percent(55.0).to_string(),
],
adjustable: Some("fan"),
},
"close_print" => refused_at_the_machine(&[("outcome", json!("interrupted"))]),
other => panic!("`{other}` is a mutating operation this walk does not know"),
}
}
async fn deliver(world: &Composed, proxy: &Proxy, image_url: &str) {
proxy.forget();
world.forget_responder_log();
let mut completions = world.server.completions();
let status = world
.client
.post(format!("{}?token={SECRET}", world.server.ingress_url()))
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(alert_body(image_url))
.send()
.await
.expect("the ingress answers")
.status();
assert_eq!(
status,
reqwest::StatusCode::ACCEPTED,
"the real ingress did not take the committed sample"
);
completions.changed().await.expect("the handling finishes");
}
async fn print_of(world: &Composed) -> PrintId {
world
.stores
.prints
.print_by_provider_id(OBICO_PRINT)
.await
.expect("the print reads")
.expect("the alert opened a print")
.id
}
fn prints_url(world: &Composed) -> String {
format!(
"http://{}{}",
world.server.address(),
printobserver_server::operation("prints")
.expect("the prints read is served")
.full_path()
)
}
fn elapsed_times(listing: &mut Value) -> Vec<u64> {
listing["prints"]
.as_array_mut()
.expect("the prints are a list")
.iter_mut()
.map(|print| {
print
.as_object_mut()
.expect("each print is an object")
.remove("job_print_time_s")
.expect("the running job reports its elapsed time")
.as_u64()
.expect("elapsed job time is a nonnegative integer")
})
.collect()
}
async fn a_listing_adopts_the_running_job_before_any_alert(world: &Composed) -> PrintId {
let (code, mut listed) = world.get(&prints_url(world)).await;
assert_eq!(code, reqwest::StatusCode::OK, "{listed}");
let active = listed["active"]
.as_str()
.unwrap_or_else(|| panic!("the job the bring-up started was not named active: {listed}"))
.to_owned();
let prints = listed["prints"].as_array().expect("the prints are a list");
assert_eq!(
prints.len(),
1,
"a supervisor over a fresh store listed prints beside the one it adopted: {listed}"
);
assert_eq!(prints[0]["id"], json!(active), "{listed}");
assert_eq!(
prints[0]["file_name"],
json!(HOLD_FILE),
"the adopted print does not carry the job's file name: {listed}"
);
assert!(
prints[0].get("provider_print_id").is_none(),
"the adopted print carries an identifier nothing reported: {listed}"
);
let (code, mut again) = world.get(&prints_url(world)).await;
assert_eq!(code, reqwest::StatusCode::OK, "{again}");
let before_times = elapsed_times(&mut listed);
let after_times = elapsed_times(&mut again);
assert_eq!(
again, listed,
"a second read while the same job runs changed the listing"
);
assert!(
after_times
.iter()
.zip(&before_times)
.all(|(after, before)| after >= before),
"elapsed job time decreased: {before_times:?} to {after_times:?}"
);
let print_id: PrintId = active.parse().expect("a print identifier");
let (code, context) = world.get(&world.operation_url("context", print_id)).await;
assert_eq!(
code,
reqwest::StatusCode::OK,
"the adopted print cannot be read by the identifier the listing gave: {context}"
);
assert_eq!(
context["context"]["print"]["id"],
json!(active),
"{context}"
);
print_id
}
async fn the_listing_shows_one_print_for_the_job(world: &Composed, print_id: PrintId) {
let (code, listed) = world.get(&prints_url(world)).await;
assert_eq!(code, reqwest::StatusCode::OK, "{listed}");
let for_the_job: Vec<&Value> = listed["prints"]
.as_array()
.expect("the prints are a list")
.iter()
.filter(|print| print["file_name"] == json!(HOLD_FILE))
.collect();
assert_eq!(
for_the_job.len(),
1,
"the alert opened a second print for the job: {listed}"
);
assert_eq!(
for_the_job[0]["id"],
json!(print_id.to_string()),
"{listed}"
);
assert_eq!(
for_the_job[0]["provider_print_id"],
json!(OBICO_PRINT),
"the adopted print does not carry the alert's identifier: {listed}"
);
assert_eq!(listed["active"], json!(print_id.to_string()), "{listed}");
}
async fn status(world: &Composed, print_id: PrintId) -> Value {
let (code, answer) = world.get(&world.operation_url("status", print_id)).await;
assert_eq!(code, reqwest::StatusCode::OK, "{answer}");
answer
}
fn at<'a>(answer: &'a Value, path: &str) -> &'a Value {
let mut here = answer;
for segment in path.split('.') {
here = match segment.parse::<usize>() {
Ok(index) => &here[index],
Err(_) => &here[segment],
};
}
here
}
async fn until_state(world: &Composed, print_id: PrintId, wanted: &str) {
until(&format!("the machine to report {wanted}"), || async {
let seen = status(world, print_id).await["printer"]["connection"].clone();
if seen == json!(wanted) {
None
} else {
Some(seen.to_string())
}
})
.await;
}
async fn ask(world: &Composed, print_id: PrintId, name: &str, body: &Value) -> (u16, Value) {
let url = world.operation_url(name, print_id);
let (code, answer) = match name {
"manifest_set" => world.put(&url, body).await,
_ => world.post(&url, body).await,
};
(code.as_u16(), answer)
}
pub async fn walk(instance: &Scripted) {
let host = image_host(snapshot_bytes()).await;
hold_the_print_running(instance).await;
let proxy = Proxy::in_front_of(&instance.url);
let world = Composed::open(instance, &proxy.base_url()).await;
let adopted = a_listing_adopts_the_running_job_before_any_alert(&world).await;
let print_id =
an_alert_joins_the_print_opens_a_session_and_stores_an_image(&world, &proxy, &host.url())
.await;
assert_eq!(
print_id, adopted,
"the first alert about the adopted job was handled against another print"
);
the_listing_shows_one_print_for_the_job(&world, print_id).await;
the_agent_acted_through_the_api(&world, &proxy, print_id).await;
the_reads_answer_the_records_they_name(&world, print_id).await;
every_change_refuses_a_request_with_no_reason(&world, &proxy, print_id).await;
every_mutating_operation_is_rejected_in_its_own_kind(&world, &proxy, print_id).await;
every_adjustment_applies_the_duration_it_is_given(&world, print_id).await;
let mut walked =
every_operation_while_it_runs_has_its_own_effect(&world, &proxy, print_id).await;
the_history_accounts_for_every_step(&world, print_id).await;
hold_the_print_running(instance).await;
let world = world.restart().await;
assert!(
world.server.reconciliation().adopted.contains(&print_id),
"the restart did not adopt the print it was watching: {:?}",
world.server.reconciliation()
);
let before = status(&world, print_id).await["session"]["session_name"].clone();
deliver(&world, &proxy, &host.url()).await;
let after = status(&world, print_id).await;
assert_eq!(
after["session"]["session_name"], before,
"the second alert did not continue the first alert's session"
);
the_agent_acted_through_the_api(&world, &proxy, print_id).await;
let reconciled = history(&world, print_id).await;
assert!(
reconciled.contains(&StartupReconciliationPayload::kind()),
"the restart recorded none of what it adopted: {reconciled:?}"
);
assert_eq!(
reconciled
.iter()
.filter(|kind| **kind == SupervisionSessionOpenedPayload::kind())
.count(),
1,
"the second alert opened a session of its own: {reconciled:?}"
);
walked
.extend(a_cancel_ends_the_print_and_a_start_opens_its_own(&world, &proxy, print_id).await);
every_mutating_operation_was_walked(walked);
hold_the_print_running(instance).await;
world.server.stop().await;
}
async fn an_alert_joins_the_print_opens_a_session_and_stores_an_image(
world: &Composed,
proxy: &Proxy,
image_url: &str,
) -> PrintId {
deliver(world, proxy, image_url).await;
let print_id = print_of(world).await;
let recorded = history(world, print_id).await;
assert!(
recorded.contains(&ObicoFailureAlertPayload::kind()),
"the alert was not recorded: {recorded:?}"
);
assert!(
recorded.contains(&SupervisionSessionOpenedPayload::kind()),
"no session opened through the harness: {recorded:?}"
);
let opened = status(world, print_id).await;
assert!(
opened["session"]["session_name"]
.as_str()
.is_some_and(|name| !name.is_empty()),
"the alert opened no session through the harness: {opened}"
);
stored_image_is_a_path(world, print_id).await;
print_id
}
async fn the_agent_acted_through_the_api(world: &Composed, proxy: &Proxy, print_id: PrintId) {
let acted = world.responder_log();
assert!(
!acted.is_empty(),
"the agent's own turn issued no action through the API; nothing was written \
down since this alert"
);
let answered = |status: u16| -> Vec<&Value> {
acted
.iter()
.filter(|line| line["status"] == json!(status))
.collect()
};
let taken = answered(200);
let refused = answered(409);
assert_eq!(
taken.len(),
1,
"this turn issued {} accepted actions and the agent issues one: {acted:?}",
taken.len()
);
assert_eq!(
refused.len(),
1,
"this turn issued {} refused actions and the agent issues one: {acted:?}",
refused.len()
);
assert_eq!(
acted.len(),
2,
"this turn issued something beside the two actions the agent is scripted \
with: {acted:?}"
);
let accepted = &taken[0]["body"];
let rejected = &refused[0]["body"];
the_accepted_action_reached_the_machine(proxy);
the_accepted_action_says_what_the_agent_asked(accepted, print_id);
the_records_of_this_turn_are_about_one_print_and_one_session(world, print_id, accepted).await;
the_refused_action_says_what_it_was_refused_for(rejected, print_id);
}
fn the_accepted_action_reached_the_machine(proxy: &Proxy) {
let asked = percent_of_multiplier(AGENT_FACTOR).to_string();
let bodies = proxy.bodies();
assert!(
bodies.iter().any(|body| body.contains(asked.as_str())),
"the agent's accepted action answered `succeeded` and the instance received \
no request carrying {asked:?}: {bodies:?}"
);
let never_sent = percent_of_multiplier(AGENT_REFUSED_FACTOR).to_string();
assert!(
!bodies.iter().any(|body| body.contains(never_sent.as_str())),
"the value the policy refused reached the machine as {never_sent:?}: {bodies:?}"
);
}
fn the_accepted_action_says_what_the_agent_asked(accepted: &Value, print_id: PrintId) {
assert_eq!(
accepted["record"]["decision"],
json!("accepted"),
"{accepted}"
);
assert_eq!(
accepted["record"]["outcome"],
json!("succeeded"),
"{accepted}"
);
assert_eq!(
accepted["record"]["print_id"],
json!(print_id.to_string()),
"the agent's action was recorded against another print: {accepted}"
);
let asked_for = &accepted["record"]["request"]["action"];
assert_eq!(
asked_for["action"],
json!("set_feedrate_factor"),
"{accepted}"
);
assert_eq!(asked_for["factor"], json!(AGENT_FACTOR), "{accepted}");
assert_eq!(
asked_for["duration_s"],
json!(AGENT_DURATION_S),
"{accepted}"
);
let intervention = &accepted["intervention"];
assert!(
!intervention.is_null(),
"the bounded action the agent issued opened no intervention: {accepted}"
);
assert_eq!(intervention["adjustable"], json!("feedrate"), "{accepted}");
assert_eq!(
intervention["applied_value"],
json!(AGENT_FACTOR),
"the intervention is not about the value the agent asked for: {accepted}"
);
assert_eq!(
instant(&intervention["expires_at"]) - instant(&intervention["applied_at"]),
AGENT_DURATION_S,
"the intervention's expiry is not the duration the agent asked for: {accepted}"
);
assert_eq!(
intervention["action_id"], accepted["record"]["id"],
"the intervention was opened by another action: {accepted}"
);
assert_eq!(
intervention["print_id"],
json!(print_id.to_string()),
"the intervention is against another print: {accepted}"
);
}
async fn the_records_of_this_turn_are_about_one_print_and_one_session(
world: &Composed,
print_id: PrintId,
accepted: &Value,
) {
let answered = status(world, print_id).await;
let session = answered["session"]["session_name"].clone();
assert_eq!(
accepted["record"]["request"]["actor"]["agent"]["session_name"], session,
"the action the agent issued names another session than the turn it ran in: \
{accepted} against {session}"
);
let intervention = &accepted["intervention"];
let held = answered["interventions"]
.as_array()
.expect("the interventions read")
.iter()
.find(|found| found["id"] == intervention["id"])
.unwrap_or_else(|| {
panic!(
"the intervention the agent opened is not one this server holds in \
force: {answered}"
)
});
assert_eq!(
held["expires_at"], intervention["expires_at"],
"the intervention this server holds expires at another instant: {held}"
);
assert_eq!(
held["action_id"], accepted["record"]["id"],
"the intervention this server holds was opened by another action: {held}"
);
assert_eq!(
held["print_id"],
json!(print_id.to_string()),
"the intervention this server holds is against another print: {held}"
);
let assessed = history_records(world, print_id)
.await
.into_iter()
.find(|event| event["kind"] == json!("agent_assessment"))
.unwrap_or_else(|| panic!("the turn wrote down no assessment for print {print_id}"));
assert_eq!(
assessed["print_id"],
json!(print_id.to_string()),
"the assessment is about another print: {assessed}"
);
assert_eq!(
assessed["payload"]["session_name"], session,
"the assessment names another session than the action the agent issued: \
{assessed}"
);
}
fn the_refused_action_says_what_it_was_refused_for(rejected: &Value, print_id: PrintId) {
assert_eq!(
rejected["record"]["print_id"],
json!(print_id.to_string()),
"the refused action was recorded against another print: {rejected}"
);
let bounds = &rejected["record"]["decision"]["rejected"]["out_of_bounds"];
assert_eq!(
bounds["adjustable"],
json!("feedrate"),
"the policy refused the agent without naming what was out of bounds: {rejected}"
);
assert_eq!(
bounds["requested"],
json!(AGENT_REFUSED_FACTOR),
"the policy refused a value other than the one the agent asked: {rejected}"
);
assert!(
!bounds["allowed"].is_null(),
"the policy refused the agent without the range it holds it to: {rejected}"
);
assert!(
rejected["record"]["outcome"].is_null(),
"a refused action reached the machine anyway: {rejected}"
);
}
async fn every_change_refuses_a_request_with_no_reason(
world: &Composed,
proxy: &Proxy,
print_id: PrintId,
) {
let mut walked = Vec::new();
for operation in OPERATIONS {
if !operation.is_mutating() {
continue;
}
for (described, reason) in [
("no reason at all", None),
("a reason that is only whitespace", Some(" ")),
] {
let before = stored(world, print_id).await;
proxy.forget();
let body = reasonless(&operation, reason);
let (code, answer) = ask(world, print_id, operation.name, &body).await;
assert_eq!(
code, 400,
"`{}` took a request carrying {described}: {answer}",
operation.name
);
assert!(
asked_by_an_action(proxy).is_empty(),
"`{}` carried a request with {described} to the machine: {:?}",
operation.name,
asked_by_an_action(proxy)
);
assert_eq!(
stored(world, print_id).await,
before,
"`{}` changed a stored record for a request with {described}",
operation.name
);
}
walked.push(operation.name);
}
let declared: Vec<&str> = OPERATIONS
.iter()
.filter(|operation| operation.is_mutating())
.map(|operation| operation.name)
.collect();
assert_eq!(
walked, declared,
"the declared list holds an operation that changes something and this walk \
did not reach"
);
}
fn reasonless(operation: &Operation, reason: Option<&str>) -> Value {
if operation.effect == Effect::Write {
return manifest_write(reason);
}
let mut body = match operation.effect {
Effect::Command(_) => ledger_body(operation.name),
Effect::Recovery(_) => recovery_body(operation.name),
_ => live(operation.name).accepted,
};
let object = body.as_object_mut().expect("the body is an object");
match reason {
Some(blank) => {
object.insert("reason".to_owned(), json!(blank));
}
None => {
object.remove("reason");
}
}
body
}
fn recovery_body(name: &str) -> Value {
let mut body = json!({ "reason": "the live walk is asking a recovery", "actor": "operator" });
let object = body.as_object_mut().expect("the body is an object");
let fields = match name {
"recover_lift" => json!({ "mm": 5.0 }),
"recover_fan" => json!({ "percent": 50.0 }),
"recover_heat" => json!({ "tool": 0, "target_c": 150.0, "clearance_asserted": true }),
"recover_park" | "recover_home_xy" => json!({ "clearance_asserted": true }),
"recover_home_z" => json!({ "bed_clear_asserted": true }),
_ => json!({}),
};
if let Value::Object(fields) = fields {
object.extend(fields);
}
body
}
fn ledger_body(name: &str) -> Value {
let mut body = json!({ "reason": "the live walk is asking the ledger", "actor": "operator" });
let object = body.as_object_mut().expect("the body is an object");
match name {
"register_spool" => {
object.insert("name".to_owned(), json!("a live walk's spool"));
object.insert("material".to_owned(), json!("PLA"));
object.insert("initial_g".to_owned(), json!(1000.0));
}
"load_spool" => {
object.insert("tool".to_owned(), json!(0));
}
"adjust_spool" => {
object.insert("remaining_g".to_owned(), json!(500.0));
}
_ => {}
}
body
}
async fn every_mutating_operation_is_rejected_in_its_own_kind(
world: &Composed,
proxy: &Proxy,
print_id: PrintId,
) {
let mut walked = Vec::new();
for operation in OPERATIONS {
let Effect::Mutating(_) = operation.effect else {
continue;
};
let plan = live(operation.name);
let before = stored(world, print_id).await;
let state_before = status(world, print_id).await["printer"]["connection"].clone();
proxy.forget();
let (code, answer) = ask(world, print_id, operation.name, &plan.rejected).await;
if plan.adjustable.is_none() {
assert_eq!(
code, 403,
"`{}` claiming the agent under the operator's credential was not refused: \
{answer}",
operation.name
);
assert!(
answer["error"]
.as_str()
.is_some_and(|said| said.contains("the operator") && said.contains("agent")),
"`{}` was refused without naming who asked and who it claimed: {answer}",
operation.name
);
assert!(
asked_by_an_action(proxy).is_empty(),
"`{}` was refused and the machine was asked {:?}",
operation.name,
asked_by_an_action(proxy)
);
assert_eq!(
stored(world, print_id).await,
before,
"`{}` was refused before the policy and still moved the record",
operation.name
);
walked.push(operation.name);
continue;
}
assert_eq!(code, 409, "`{}` was not rejected: {answer}", operation.name);
let rejection = &answer["record"]["decision"]["rejected"];
assert!(
!rejection.is_null(),
"`{}` answered no rejection the caller can act on: {answer}",
operation.name
);
{
let adjustable = plan
.adjustable
.expect("only an adjustment reaches the policy here");
let bounds = &rejection["out_of_bounds"];
assert_eq!(
bounds["adjustable"],
json!(adjustable),
"`{}` was rejected without naming what was out of bounds: {answer}",
operation.name
);
assert!(
!bounds["requested"].is_null() && !bounds["allowed"].is_null(),
"`{}` was rejected without the value asked for and the range \
allowed: {answer}",
operation.name
);
}
assert!(
asked_by_an_action(proxy).is_empty(),
"`{}` was rejected and the machine was asked {:?}",
operation.name,
asked_by_an_action(proxy)
);
assert_eq!(
status(world, print_id).await["printer"]["connection"],
state_before,
"`{}` was rejected and the machine moved anyway",
operation.name
);
nothing_moved_but_the_record_of_the_rejection(
world,
print_id,
&before,
&answer["record"]["id"],
operation.name,
)
.await;
walked.push(operation.name);
}
assert_eq!(
walked,
vocabulary(),
"the declared list holds a mutating operation this walk did not reject"
);
}
async fn every_adjustment_applies_the_duration_it_is_given(world: &Composed, print_id: PrintId) {
let mut walked = Vec::new();
for operation in OPERATIONS {
let Effect::Mutating(_) = operation.effect else {
continue;
};
let plan = live(operation.name);
let Some(adjustable) = plan.adjustable else {
continue;
};
let mut bounded = plan.accepted.clone();
bounded
.as_object_mut()
.expect("the body is an object")
.insert("duration_s".to_owned(), json!(DURATION_S));
let (code, answer) = ask(world, print_id, operation.name, &bounded).await;
assert_eq!(code, 200, "`{}`: {answer}", operation.name);
let intervention = &answer["intervention"];
assert!(
!intervention.is_null(),
"`{}` was given a duration and opened no intervention: {answer}",
operation.name
);
assert_eq!(
intervention["adjustable"],
json!(adjustable),
"`{}` opened an intervention about something else: {answer}",
operation.name
);
assert_eq!(
instant(&intervention["expires_at"]) - instant(&intervention["applied_at"]),
DURATION_S,
"`{}` opened an intervention whose expiry is not the duration asked \
for: {answer}",
operation.name
);
let (code, answer) = ask(world, print_id, operation.name, &plan.accepted).await;
assert_eq!(code, 200, "`{}`: {answer}", operation.name);
assert!(
answer["intervention"].is_null(),
"`{}` was given no duration and opened an intervention anyway: {answer}",
operation.name
);
walked.push(operation.name);
}
assert_eq!(
walked.len(),
5,
"this walk bounded {} adjustments, and the vocabulary declares five: {walked:?}",
walked.len()
);
}
const WHILE_IT_RUNS: [&str; 8] = [
"set_bed_target_c",
"set_tool_target_c",
"set_feedrate_factor",
"set_flowrate_factor",
"set_fan_percent",
"pause",
"resume",
"acknowledge_failure",
];
const ENDING_IT: [&str; 3] = ["close_print", "cancel", "start_print"];
fn every_mutating_operation_was_walked(mut walked: Vec<&'static str>) {
walked.sort_unstable();
let mut declared = vocabulary();
declared.sort_unstable();
assert_eq!(
walked, declared,
"the declared lists hold a mutating operation whose effect this walk did \
not reach"
);
}
async fn every_operation_while_it_runs_has_its_own_effect(
world: &Composed,
proxy: &Proxy,
print_id: PrintId,
) -> Vec<&'static str> {
let mut walked = Vec::new();
for name in WHILE_IT_RUNS {
let plan = live(name);
proxy.forget();
let (code, answer) = ask(world, print_id, name, &plan.accepted).await;
assert_eq!(code, 200, "`{name}` was not accepted: {answer}");
assert_eq!(
answer["record"]["decision"],
json!("accepted"),
"`{name}` answered a decision that is not acceptance: {answer}"
);
assert_eq!(
answer["record"]["outcome"],
json!("succeeded"),
"`{name}` reached the real instance and it did not take it: {answer}"
);
if let Some(state) = plan.reaches {
until_state(world, print_id, state).await;
}
if let Some((path, value)) = plan.reported {
until(
&format!("the machine to report {path} as {value}"),
|| async {
let seen = at(&status(world, print_id).await, path).clone();
if seen == value {
None
} else {
Some(seen.to_string())
}
},
)
.await;
}
if !plan.received.is_empty() {
let bodies = proxy.bodies();
assert!(
bodies.iter().any(|body| plan
.received
.iter()
.all(|fragment| body.contains(fragment.as_str()))),
"`{name}` reports nothing a snapshot can read, and the instance \
received no request carrying all of {:?}: {bodies:?}",
plan.received
);
}
walked.push(name);
}
walked
}
async fn a_cancel_ends_the_print_and_a_start_opens_its_own(
world: &Composed,
proxy: &Proxy,
print_id: PrintId,
) -> Vec<&'static str> {
let [close, cancel, start] = ENDING_IT;
a_close_is_refused(
world,
proxy,
print_id,
&json!({ "print_still_active": { "state": "printing" } }),
)
.await;
proxy.forget();
let (code, cancelled) = ask(world, print_id, cancel, &live(cancel).accepted).await;
assert_eq!(code, 200, "`{cancel}` was not accepted: {cancelled}");
assert_eq!(
cancelled["record"]["outcome"],
json!("succeeded"),
"{cancelled}"
);
until_state(world, print_id, "operational").await;
let ended = status(world, print_id).await;
assert!(
ended["print"]["end_reason"]
.as_str()
.is_some_and(|reason| reason.starts_with("the print reached ")),
"a read of the cancelled print did not end it: {ended}"
);
a_close_is_refused(world, proxy, print_id, &json!("print_already_ended")).await;
let (code, started) = ask(world, print_id, start, &live(start).accepted).await;
assert_eq!(code, 200, "`{start}` was not accepted: {started}");
assert_eq!(
started["record"]["outcome"],
json!("succeeded"),
"{started}"
);
let opened: PrintId = started["record"]["print_id"]
.as_str()
.and_then(|text| text.parse().ok())
.unwrap_or_else(|| panic!("the start named no print it was recorded against: {started}"));
assert_ne!(
opened, print_id,
"the start was recorded against the ended print"
);
until_state(world, opened, "printing").await;
let running = status(world, opened).await;
assert!(running["print"].get("ended_at").is_none(), "{running}");
assert_eq!(
prints_active(world).await,
json!(opened.to_string()),
"the listing does not name the print the start opened as the running job's"
);
vec![close, cancel, start]
}
async fn a_close_is_refused(world: &Composed, proxy: &Proxy, print_id: PrintId, named: &Value) {
let close = ENDING_IT[0];
let before = stored(world, print_id).await;
proxy.forget();
let (code, answer) = ask(world, print_id, close, &live(close).accepted).await;
assert_eq!(code, 409, "`{close}` was not rejected as {named}: {answer}");
assert_eq!(
answer["record"]["decision"]["rejected"], *named,
"`{close}` was rejected for something else: {answer}"
);
assert!(
asked_by_an_action(proxy).is_empty(),
"`{close}` was rejected and the machine was asked {:?}",
asked_by_an_action(proxy)
);
nothing_moved_but_the_record_of_the_rejection(
world,
print_id,
&before,
&answer["record"]["id"],
close,
)
.await;
}
async fn prints_active(world: &Composed) -> Value {
let (code, listed) = world.get(&prints_url(world)).await;
assert_eq!(code, reqwest::StatusCode::OK, "{listed}");
listed["active"].clone()
}
async fn the_reads_answer_the_records_they_name(world: &Composed, print_id: PrintId) {
let (code, written) = ask(
world,
print_id,
"manifest_set",
&manifest_write(Some("the integration tier is narrowing the bounds")),
)
.await;
assert_eq!(code, 200, "{written}");
let (code, read_back) = world
.get(&world.operation_url("manifest_get", print_id))
.await;
assert_eq!(code, reqwest::StatusCode::OK);
assert_eq!(
read_back["manifest"],
manifest(),
"the manifest read back is not the one written"
);
let answered = status(world, print_id).await;
assert_eq!(answered["print"]["id"], json!(print_id.to_string()));
assert!(
!answered["printer"]["connection"].is_null(),
"the status carries nothing the machine reported: {answered}"
);
let (code, context) = world.get(&world.operation_url("context", print_id)).await;
assert_eq!(code, reqwest::StatusCode::OK);
assert_eq!(
context["context"]["manifest"],
manifest(),
"the context does not carry the manifest that was written"
);
assert_eq!(
context["context"]["print"]["id"],
json!(print_id.to_string()),
"the context is about another print: {context}"
);
let (code, events) = world.get(&world.operation_url("history", print_id)).await;
assert_eq!(code, reqwest::StatusCode::OK);
assert!(
events["events"]
.as_array()
.is_some_and(|found| !found.is_empty()),
"the history answered no events at all: {events}"
);
}
async fn stored_image_is_a_path(world: &Composed, print_id: PrintId) {
let image = world
.stores
.events
.history(printobserver_core::store::HistoryQuery {
print_id,
kinds: Vec::new(),
since: None,
until: None,
limit: None,
})
.await
.expect("the history reads")
.into_iter()
.find_map(|event| event.image)
.expect("the alert's image was stored");
let url = format!(
"http://{}{}",
world.server.address(),
printobserver_server::operation("image")
.expect("image is served")
.full_path()
.replace("{image_id}", &image.id.to_string())
);
let (code, answer) = world.get(&url).await;
assert_eq!(code, reqwest::StatusCode::OK, "{answer}");
let path = std::path::PathBuf::from(
answer["path"]
.as_str()
.unwrap_or_else(|| panic!("the image answer carries no path: {answer}")),
);
assert!(path.is_absolute() && path.exists(), "{}", path.display());
assert_eq!(
digest_at(&path),
answer["record"]["sha256"].as_str().expect("a digest"),
"what is at the path this server answered is not what the record declares"
);
}
async fn the_history_accounts_for_every_step(world: &Composed, print_id: PrintId) {
let records = history_records(world, print_id).await;
let kinds: Vec<Value> = records.iter().map(|event| event["kind"].clone()).collect();
for wanted in [
ObicoFailureAlertPayload::kind(),
SupervisionSessionOpenedPayload::kind(),
AgentAssessmentPayload::kind(),
] {
let spelled = printobserver_types::serde_json::to_value(&wanted).expect("a kind renders");
assert!(
kinds.contains(&spelled),
"the history does not account for {wanted:?}: {kinds:?}"
);
}
assert!(
records
.iter()
.all(|event| event["print_id"] == json!(print_id.to_string())),
"the history of one print carries an event about another: {records:?}"
);
let session = status(world, print_id).await["session"]["session_name"].clone();
let opened = records
.iter()
.find(|event| event["kind"] == json!("supervision_session_opened"))
.expect("the history accounts for the session that opened");
assert_eq!(
opened["payload"]["session_name"], session,
"the session the history says opened is not the one this print is watched \
through: {opened}"
);
for assessment in records
.iter()
.filter(|event| event["kind"] == json!("agent_assessment"))
{
assert_eq!(
assessment["payload"]["session_name"], session,
"an assessment was written into a session this print is not watched \
through: {assessment}"
);
}
let alert = records
.iter()
.find(|event| event["kind"] == json!("obico_failure_alert"))
.expect("the history accounts for the alert");
assert_eq!(
alert["payload"]["obico_print_id"],
json!(OBICO_PRINT),
"the alert in the history is about another of the producer's prints: {alert}"
);
assert!(
!alert["raw"].is_null(),
"the alert in the history carries none of the bytes that arrived: {alert}"
);
assert!(
!alert["image"].is_null(),
"the alert in the history carries no image: {alert}"
);
}
async fn stored(world: &Composed, print_id: PrintId) -> Value {
let mut answered = status(world, print_id).await;
if let Some(print) = answered["print"].as_object_mut() {
print.remove("job_print_time_s");
print.remove("job_started_at");
}
let (_, events) = world.get(&world.operation_url("history", print_id)).await;
let (_, manifest) = world
.get(&world.operation_url("manifest_get", print_id))
.await;
let (_, spools) = world
.get(&format!(
"{}?include_retired=true",
world.operation_url("spools", print_id)
))
.await;
json!({
"print": answered["print"],
"session": answered["session"],
"interventions": answered["interventions"],
"events": events["events"],
"manifest": manifest,
"spools": spools,
})
}
async fn nothing_moved_but_the_record_of_the_rejection(
world: &Composed,
print_id: PrintId,
before: &Value,
action_id: &Value,
named: &str,
) {
let mut after = stored(world, print_id).await;
let events = after["events"]
.as_array()
.expect("a history answers a list")
.clone();
let written: Vec<&Value> = events.iter().take(2).collect();
for (event, kind) in written.iter().zip(["action_rejected", "action_requested"]) {
assert_eq!(
event["kind"], kind,
"`{named}` was rejected and the newest events are not the record of that: {event}"
);
assert_eq!(
event["payload"]["action_id"], *action_id,
"`{named}` was rejected and the events written are about another action: {event}"
);
}
after["events"] = json!(events[2..]);
assert_eq!(
after, *before,
"`{named}` was rejected and something beside the record of that rejection moved"
);
}
fn vocabulary() -> Vec<&'static str> {
OPERATIONS
.iter()
.filter(|operation| matches!(operation.effect, Effect::Mutating(_)))
.map(|operation| operation.name)
.collect()
}
async fn history_records(world: &Composed, print_id: PrintId) -> Vec<Value> {
let (code, answer) = world.get(&world.operation_url("history", print_id)).await;
assert_eq!(code, reqwest::StatusCode::OK, "{answer}");
answer["events"]
.as_array()
.expect("a history is a list")
.clone()
}
async fn history(world: &Composed, print_id: PrintId) -> Vec<EventKind> {
let (code, answer) = world.get(&world.operation_url("history", print_id)).await;
assert_eq!(code, reqwest::StatusCode::OK, "{answer}");
answer["events"]
.as_array()
.expect("a history is a list")
.iter()
.filter_map(|event| printobserver_types::serde_json::from_value(event["kind"].clone()).ok())
.collect()
}
fn instant(value: &Value) -> i64 {
let text = value.as_str().expect("an instant is a string");
let parsed: printobserver_types::Timestamp = text.parse().expect("an instant is RFC 3339");
parsed.as_utc().timestamp()
}
fn digest_at(path: &std::path::Path) -> String {
use sha2::{Digest as _, Sha256};
let bytes = std::fs::read(path).expect("the image reads");
let mut hasher = Sha256::new();
hasher.update(&bytes);
hasher
.finalize()
.iter()
.fold(String::new(), |mut rendered, byte| {
use core::fmt::Write as _;
let _ = write!(rendered, "{byte:02x}");
rendered
})
}
fn asked_by_an_action(proxy: &Proxy) -> Vec<String> {
proxy.bodies_but_to(printobserver_octoprint::push::LOGIN_PATH)
}