use printobserver_core::store::Stores;
use printobserver_supervisor_api::SupervisorError;
use printobserver_types::PrintId;
use printobserver_types::serde_json::{Value, json};
use crate::agent::{Pass, StandInAgent, session_of};
use crate::authenticating::history;
use crate::printer::RecordingPrinter;
use crate::world::{SECRET, World, failure_alert, presenting, set};
const OBICO_PRINT: i64 = 4211;
async fn alert(world: &World) {
let status = reqwest::Client::new()
.post(format!("{}?token={SECRET}", world.server.ingress_url()))
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(failure_alert(OBICO_PRINT, "http://127.0.0.1:1/frame.jpg").to_string())
.send()
.await
.expect("the ingress answers")
.status();
assert_eq!(status, reqwest::StatusCode::ACCEPTED);
}
pub async fn held_turn(world: &World) -> (PrintId, Pass) {
let print_id = world.open_print().await;
world.agent.hold_turns();
alert(world).await;
let pass = world
.agent
.issued(1)
.await
.into_iter()
.next()
.expect("one pass");
(print_id, pass)
}
fn claiming(actor: &Value, extra: &[(&str, Value)]) -> Value {
let mut body = json!({
"reason": "a journey is asking as somebody",
"actor": actor,
});
for (key, value) in extra {
body[*key] = value.clone();
}
body
}
fn manifest() -> Value {
printobserver_types::serde_json::to_value(crate::world::start_manifest())
.expect("a manifest renders")
}
pub fn agent(session_name: &str) -> Value {
json!({ "agent": { "session_name": session_name } })
}
pub async fn sent(request: reqwest::RequestBuilder) -> (reqwest::StatusCode, Value) {
let response = request.send().await.expect("the server answers");
let status = response.status();
let body: Value = response.json().await.expect("the answer is JSON");
(status, body)
}
fn action_url(world: &World, print_id: PrintId, action: &str) -> String {
world.url(&format!("/prints/{print_id}/actions/{action}"))
}
async fn record_of(stores: &Stores, print_id: PrintId) -> usize {
history(stores, print_id).await
}
fn assert_forbidden(answer: &(reqwest::StatusCode, Value), what: &str, naming: &[&str]) {
assert_eq!(
answer.0,
reqwest::StatusCode::FORBIDDEN,
"{what} was not refused as forbidden: {}",
answer.1
);
let said = answer.1["error"].as_str().unwrap_or_default();
for named in naming {
assert!(
said.contains(named),
"the refusal of {what} does not name {named:?}: {said}"
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_is_its_own_session_on_its_own_print() {
let world = World::open().await;
let (print_id, pass) = held_turn(&world).await;
let turn = presenting(&pass.credential);
let session = session_of(print_id);
assert_eq!(pass.session_name, session);
assert_eq!(
pass.server.as_deref(),
Some(format!("http://{}", world.server.address()).as_str()),
"the turn was not told the address this server bound"
);
for path in [
format!("/prints/{print_id}/status"),
format!("/prints/{print_id}/context"),
format!("/prints/{print_id}/history"),
format!("/prints/{print_id}/manifest"),
format!("/events?print_id={print_id}"),
"/prints".to_owned(),
] {
let (status, body) = sent(turn.get(world.url(&path))).await;
assert_eq!(status, reqwest::StatusCode::OK, "{path}: {body}");
}
let (status, body) = sent(
turn.post(action_url(&world, print_id, "pause"))
.json(&claiming(&agent(&session), &[])),
)
.await;
assert_eq!(status, reqwest::StatusCode::OK, "{body}");
assert_eq!(
body["record"]["request"]["actor"],
agent(&session),
"{body}"
);
world.agent.release_turns();
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_reaching_past_its_own_session_and_print_is_refused() {
let world = World::open().await;
let (print_id, pass) = held_turn(&world).await;
let other = world.open_print().await;
let turn = presenting(&pass.credential);
let session = session_of(print_id);
world.printer.forget();
let before = record_of(&world.stores, print_id).await;
for (claimed, named) in [
(json!("operator"), "the operator"),
(json!("system"), "the system"),
(agent("print-another-session"), "print-another-session"),
] {
let answer = sent(
turn.post(action_url(&world, print_id, "cancel"))
.json(&claiming(&claimed, &[])),
)
.await;
assert_forbidden(
&answer,
&format!("a turn claiming {claimed}"),
&[&session, named],
);
}
let answer = sent(turn.get(world.url(&format!("/prints/{other}/status")))).await;
assert_forbidden(
&answer,
"a turn reading another print",
&[&session, &other.to_string()],
);
let answer = sent(
turn.post(action_url(&world, other, "pause"))
.json(&claiming(&agent(&session), &[])),
)
.await;
assert_forbidden(
&answer,
"a turn acting on another print",
&[&session, &other.to_string()],
);
let answer = sent(
turn.post(action_url(&world, print_id, "start_print"))
.json(&claiming(
&agent(&session),
&[
("file_name", json!("benchy.gcode")),
("manifest", manifest()),
],
)),
)
.await;
assert_forbidden(
&answer,
"a turn starting a print",
&[&session, "start-print"],
);
let answer = sent(
turn.put(world.url(&format!("/prints/{print_id}/manifest")))
.json(&json!({"reason": "widening my own bounds", "manifest": manifest()})),
)
.await;
assert_forbidden(
&answer,
"a turn replacing a manifest",
&[&session, "manifest-set"],
);
assert!(
world.printer.calls().is_empty(),
"a refused request reached the machine: {:?}",
world.printer.calls()
);
assert_eq!(
record_of(&world.stores, print_id).await,
before,
"a refused request was decided on or recorded"
);
world.agent.release_turns();
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_asking_to_cancel_as_the_operator_is_refused() {
let world = World::open().await;
let (print_id, pass) = held_turn(&world).await;
world.printer.forget();
let answer = sent(
presenting(&pass.credential)
.post(action_url(&world, print_id, "cancel"))
.json(&claiming(&json!("operator"), &[])),
)
.await;
assert_forbidden(
&answer,
"a turn cancelling as the operator",
&["the operator", &session_of(print_id)],
);
assert!(world.printer.calls().is_empty());
world.agent.release_turns();
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn the_operators_credential_claiming_anybody_else_is_refused() {
let world = World::open().await;
let print_id = world.open_print().await;
let before = record_of(&world.stores, print_id).await;
for (claimed, named) in [
(agent(&session_of(print_id)), "the agent"),
(json!("system"), "the system"),
] {
let answer = sent(
world
.client
.post(action_url(&world, print_id, "pause"))
.json(&claiming(&claimed, &[])),
)
.await;
assert_forbidden(
&answer,
&format!("the operator claiming {claimed}"),
&["the operator", named],
);
}
assert!(world.printer.calls().is_empty());
assert_eq!(record_of(&world.stores, print_id).await, before);
let (status, body) = sent(
world
.client
.post(action_url(&world, print_id, "pause"))
.json(&claiming(&json!("operator"), &[])),
)
.await;
assert_eq!(status, reqwest::StatusCode::OK, "{body}");
world.server.stop().await;
}
async fn admitted(world: &World, credential: &str) -> bool {
presenting(credential)
.get(world.url("/prints"))
.send()
.await
.expect("the server answers")
.status()
!= reqwest::StatusCode::UNAUTHORIZED
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_ends_with_its_turn_and_is_written_nowhere() {
let world = World::open().await;
let (_, first) = held_turn(&world).await;
assert!(admitted(&world, &first.credential).await);
let mut completions = world.server.completions();
world.agent.release_turns();
completions.changed().await.expect("the handling finishes");
assert!(
!admitted(&world, &first.credential).await,
"a turn's credential was admitted after its turn returned"
);
world.agent.hold_turns();
alert(&world).await;
let second = world.agent.issued(2).await[1].clone();
assert_ne!(
first.credential, second.credential,
"two turns shared a credential"
);
assert!(admitted(&world, &second.credential).await);
let state = world.state_dir();
for credential in [&first.credential, &second.credential] {
let carrying = crate::world::files_carrying(&state, credential);
assert!(
carrying.is_empty(),
"a turn's credential is written under the state directory: {carrying:?}"
);
}
world.agent.release_turns();
let world = world.restart().await;
assert!(
!admitted(&world, &second.credential).await,
"a turn's credential was admitted after a restart"
);
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn the_agent_interval_holds_every_turn_whatever_it_claims() {
let world = World::configured(
RecordingPrinter::printing(),
StandInAgent::new(),
|document| {
set(
document,
"safety.agent_min_interval_s",
toml::Value::Integer(30),
);
},
)
.await;
let (print_id, pass) = held_turn(&world).await;
let turn = presenting(&pass.credential);
let session = session_of(print_id);
let (status, body) = sent(
turn.post(action_url(&world, print_id, "set_fan_percent"))
.json(&claiming(&agent(&session), &[("percent", json!(40.0))])),
)
.await;
assert_eq!(status, reqwest::StatusCode::OK, "{body}");
let (status, body) = sent(
turn.post(action_url(&world, print_id, "set_feedrate_factor"))
.json(&claiming(&agent(&session), &[("factor", json!(1.1))])),
)
.await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{body}");
assert!(
body["record"]["decision"]["rejected"]
.get("min_interval_not_elapsed")
.is_some(),
"the second change was not held by the agent's interval: {body}"
);
let answer = sent(
turn.post(action_url(&world, print_id, "set_feedrate_factor"))
.json(&claiming(&json!("operator"), &[("factor", json!(1.1))])),
)
.await;
assert_forbidden(
&answer,
"a turn stepping around its interval as the operator",
&[&session, "the operator"],
);
world.agent.release_turns();
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_that_fails_or_times_out_is_revoked_when_it_returns() {
for (what, error) in [
("timed out", SupervisorError::TimedOut),
(
"failed",
SupervisorError::Unavailable {
detail: "the harness could not be reached".to_owned(),
},
),
] {
let world = World::open().await;
world.agent.fail_turns_with(error);
let (_, pass) = held_turn(&world).await;
assert!(
admitted(&world, &pass.credential).await,
"the credential of a turn that {what} was not admitted while it ran"
);
let mut completions = world.server.completions();
world.agent.release_turns();
completions.changed().await.expect("the handling finishes");
assert!(
!admitted(&world, &pass.credential).await,
"the credential of a turn that {what} was admitted after it returned"
);
world.server.stop().await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_moved_to_a_second_session_holds_only_that_sessions_credential() {
let world = World::open().await;
world.agent.move_turns_to_a_second_session();
let print_id = world.open_print().await;
world.agent.hold_turns();
alert(&world).await;
let passes = world.agent.issued(2).await;
let (first, second) = (&passes[0], &passes[1]);
assert_eq!(first.session_name, session_of(print_id));
assert_eq!(second.session_name, format!("{}-2", session_of(print_id)));
assert!(
!admitted(&world, &first.credential).await,
"the first session's credential is still admitted once the second is issued"
);
let turn = presenting(&second.credential);
let answer = sent(
turn.post(action_url(&world, print_id, "pause"))
.json(&claiming(&agent(&first.session_name), &[])),
)
.await;
assert_forbidden(
&answer,
"the second session claiming the first",
&[&first.session_name, &second.session_name],
);
let (status, body) = sent(
turn.post(action_url(&world, print_id, "pause"))
.json(&claiming(&agent(&second.session_name), &[])),
)
.await;
assert_eq!(status, reqwest::StatusCode::OK, "{body}");
world.agent.release_turns();
world.server.stop().await;
}
async fn an_image_of(world: &World, print_id: PrintId) -> printobserver_core::ImageRecord {
let event = world
.stores
.events
.append_event(printobserver_core::store::EventDraft {
print_id: Some(print_id),
source: printobserver_core::system_source(),
received_at: printobserver_types::Timestamp::now(),
body: printobserver_types::EventBody {
kind: printobserver_types::EventKind::new("malformed_external_event")
.expect("a kind name"),
payload: json!({ "detail": "a journey's own event" }),
},
raw: None,
})
.await
.expect("an event is appended");
world
.stores
.images
.put_image(
print_id,
event.id,
None,
"image/jpeg".to_owned(),
printobserver_types::RawBytes::new(b"the bytes of a frame".to_vec()),
)
.await
.expect("an image is stored")
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_reads_nothing_of_another_print() {
let world = World::open().await;
let (print_id, pass) = held_turn(&world).await;
let other = world.open_print().await;
let turn = presenting(&pass.credential);
let session = session_of(print_id);
for path in [
format!("/prints/{other}/context"),
format!("/prints/{other}/look"),
format!("/prints/{other}/history"),
format!("/prints/{other}/manifest"),
format!("/events?print_id={other}"),
] {
let answer = sent(turn.get(world.url(&path))).await;
assert_forbidden(
&answer,
&format!("a turn reading {path}"),
&[&session, &other.to_string()],
);
}
let answer = sent(turn.get(world.url("/events"))).await;
assert_forbidden(
&answer,
"a turn reading every print's events",
&[&print_id.to_string(), "print_id"],
);
let own = an_image_of(&world, print_id).await;
let (status, body) = sent(turn.get(world.url(&format!("/images/{}", own.id)))).await;
assert_eq!(status, reqwest::StatusCode::OK, "{body}");
let foreign = an_image_of(&world, other).await;
let answer = sent(turn.get(world.url(&format!("/images/{}", foreign.id)))).await;
assert_forbidden(&answer, "a turn reading another print's image", &[&session]);
std::fs::remove_file(world.state_dir().join(&foreign.relative_path))
.expect("the image's file is removable");
let answer = sent(turn.get(world.url(&format!("/images/{}", foreign.id)))).await;
assert_forbidden(
&answer,
"a turn reading another print's image whose file is gone",
&[&session],
);
world.agent.release_turns();
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credentials_forbidden_requests_are_refused_whatever_their_bodies() {
let world = World::open().await;
let (print_id, pass) = held_turn(&world).await;
let other = world.open_print().await;
let turn = presenting(&pass.credential);
let session = session_of(print_id);
let not_a_body = "{ this is not a body";
for (what, request) in [
(
"a start",
turn.post(action_url(&world, print_id, "start_print")),
),
(
"a manifest replacement",
turn.put(world.url(&format!("/prints/{print_id}/manifest"))),
),
(
"an action on another print",
turn.post(action_url(&world, other, "pause")),
),
] {
let answer = sent(
request
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(not_a_body),
)
.await;
assert_forbidden(&answer, &format!("{what} with no body"), &[&session]);
}
world.agent.release_turns();
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn reads_during_a_turn_reflect_the_operators_latest_action() {
let world = World::open().await;
let (print_id, pass) = held_turn(&world).await;
let action = action_url(&world, print_id, "set_feedrate_factor");
let (accepted, answer) = world
.post(
&action,
&claiming(
&json!("operator"),
&[("factor", json!(1.2)), ("duration_s", json!(120))],
),
)
.await;
assert_eq!(accepted, reqwest::StatusCode::OK, "{answer}");
let intervention = answer["intervention"]["id"].clone();
assert!(intervention.is_string(), "{answer}");
for credential in [&world.credential, &pass.credential] {
for read in ["status", "context"] {
let (status, answer) =
sent(presenting(credential).get(world.url(&format!("/prints/{print_id}/{read}"))))
.await;
assert_eq!(status, reqwest::StatusCode::OK, "{answer}");
let context = if read == "context" {
&answer["context"]
} else {
&answer
};
if read == "status" {
assert_eq!(
context["printer"]["feedrate_factor"]["value"],
json!(1.2),
"{answer}"
);
}
assert!(
context["interventions"]
.as_array()
.expect("interventions")
.iter()
.any(|held| held["id"] == intervention),
"the operator's intervention is absent during the held turn: {answer}"
);
}
}
let (refused, answer) = world
.post(
&action,
&claiming(&json!("operator"), &[("factor", json!(9.0))]),
)
.await;
assert_eq!(refused, reqwest::StatusCode::CONFLICT, "{answer}");
let (_, unchanged) = world
.get(&world.url(&format!("/prints/{print_id}/status")))
.await;
assert_eq!(
unchanged["printer"]["feedrate_factor"]["value"],
json!(1.2),
"{unchanged}"
);
assert_eq!(
unchanged["interventions"][0]["id"], intervention,
"{unchanged}"
);
let (_, history) = world
.get(&world.url(&format!("/prints/{print_id}/history")))
.await;
assert!(
history.to_string().contains("9.0"),
"the refused action is absent: {history}"
);
world.agent.release_turns();
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_credential_is_refused_what_belongs_to_no_print() {
let world = World::open().await;
let (print_id, pass) = held_turn(&world).await;
let turn = presenting(&pass.credential);
let session = session_of(print_id);
let answer = sent(turn.get(world.url("/look"))).await;
assert_forbidden(&answer, "a turn's look at the printer", &[&session]);
let (status, look) = world.get(&world.url("/look")).await;
assert_eq!(status, reqwest::StatusCode::OK, "{look}");
assert!(look["event"].get("print_id").is_none(), "{look}");
let printless = world
.stores
.events
.append_event_with_image(
printobserver_core::store::EventDraft {
print_id: None,
source: printobserver_core::system_source(),
received_at: printobserver_types::Timestamp::now(),
body: printobserver_types::EventBody {
kind: printobserver_types::EventKind::new("camera_look").expect("a kind"),
payload: json!({ "waited_s": 0, "delivered": [] }),
},
raw: None,
},
printobserver_core::store::ImageDraft {
source_url: None,
content_type: "image/jpeg".to_owned(),
bytes: printobserver_types::RawBytes::new(b"a frame of the printer".to_vec()),
},
)
.await
.expect("a frame of no print is stored");
let frame = printless.image.expect("the frame is the event's image");
let path = format!("/images/{}", frame.id);
let answer = sent(turn.get(world.url(&path))).await;
assert_forbidden(
&answer,
"a turn reading a frame of the printer",
&[&session, "no print"],
);
let (status, image) = world.get(&world.url(&path)).await;
assert_eq!(status, reqwest::StatusCode::OK, "{image}");
assert!(image["record"].get("print_id").is_none(), "{image}");
assert!(image["path"].is_string(), "{image}");
world.agent.release_turns();
world.server.stop().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_turn_acknowledges_only_after_a_look_even_one_its_camera_failed() {
let camera = crate::http_host::Host::answering(
"500 Internal Server Error",
"text/plain",
b"no".to_vec(),
)
.await;
let world = World::configured(
RecordingPrinter::printing(),
crate::agent::StandInAgent::new(),
|document| {
let mut table = toml::Table::new();
table.insert("snapshot_url".to_owned(), toml::Value::String(camera.url()));
set(document, "camera", toml::Value::Table(table));
set(
document,
"safety.actions.agent",
toml::Value::Array(vec![toml::Value::String("acknowledge_failure".to_owned())]),
);
},
)
.await;
let (print_id, pass) = held_turn(&world).await;
let turn = presenting(&pass.credential);
let alerted = world
.stores
.events
.history(printobserver_core::store::HistoryQuery {
print_id,
kinds: Vec::new(),
since: None,
until: None,
limit: Some(50),
})
.await
.expect("the history reads")
.into_iter()
.find(|event| event.body.kind.as_str() == "obico_failure_alert")
.expect("the alert is in the history");
let acknowledgement = claiming(
&agent(&pass.session_name),
&[
("event_id", json!(alerted.id.to_string())),
("disposition", json!("stop")),
],
);
let before = record_of(&world.stores, print_id).await;
let early = sent(
turn.post(action_url(&world, print_id, "acknowledge_failure"))
.json(&acknowledgement),
)
.await;
assert_forbidden(
&early,
"an acknowledgement before the turn's look",
&[
"before the turn has taken a look",
&format!("printobserver look --print-id {print_id}"),
],
);
assert_eq!(
record_of(&world.stores, print_id).await,
before,
"a refused acknowledgement was recorded"
);
let (status, look) =
sent(turn.get(world.url(&format!("/prints/{print_id}/look?wait_s=0")))).await;
assert_eq!(status, reqwest::StatusCode::OK, "{look}");
assert!(
look.get("frame").is_none(),
"the failing camera gave a frame: {look}"
);
let (status, body) = sent(
turn.post(action_url(&world, print_id, "acknowledge_failure"))
.json(&acknowledgement),
)
.await;
assert_eq!(status, reqwest::StatusCode::OK, "{body}");
assert_eq!(body["record"]["decision"], "accepted", "{body}");
world.agent.release_turns();
world.server.stop().await;
}