use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use printobserver_core::{
ActionKind, Actor, ActorClass, JobManifest, PrintAction, PrintRecord, SafetyEnvelope,
};
use printobserver_core::{ActionOutcome, CoreConfig, CoreError, Supervisor, block_on};
use printobserver_printer_api::Adjustable;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{
EventBody, EventKind, EventPayload, EventRecord, EventSource, PrintId, Range, RawBytes,
Timestamp,
};
use printobserver_vision_api::{
MalformedExternalEventPayload, NormalizedAlert, ProviderPrint, WebAddress,
};
use crate::fakes::{FakeClock, FakePrinter, FakeStore, FakeSupervisor, FakeVision};
use crate::journal::Journal;
pub const CAMERA_URL: &str = "http://camera.local/frame.jpeg";
pub const EPOCH_SECONDS: i64 = 1_700_000_000;
pub const ACTION_KINDS: [ActionKind; 11] = [
ActionKind::Pause,
ActionKind::Resume,
ActionKind::Cancel,
ActionKind::StartPrint,
ActionKind::SetFeedrateFactor,
ActionKind::SetFlowrateFactor,
ActionKind::SetToolTargetC,
ActionKind::SetBedTargetC,
ActionKind::SetFanPercent,
ActionKind::AcknowledgeFailure,
ActionKind::ClosePrint,
];
#[must_use]
pub fn permissive_envelope() -> SafetyEnvelope {
let mut allowed = BTreeMap::new();
allowed.insert(Adjustable::Feedrate, Range::new(0.5, 2.0));
allowed.insert(Adjustable::Flowrate, Range::new(0.8, 1.2));
allowed.insert(Adjustable::ToolTarget { tool: 0 }, Range::new(180.0, 250.0));
allowed.insert(Adjustable::BedTarget, Range::new(0.0, 80.0));
allowed.insert(Adjustable::Fan, Range::new(0.0, 100.0));
let mut actions = BTreeMap::new();
for class in [ActorClass::Agent, ActorClass::Operator, ActorClass::System] {
actions.insert(class, ACTION_KINDS.to_vec());
}
SafetyEnvelope {
allowed,
actions,
agent_min_interval_s: 0,
}
}
pub struct World {
pub core: Arc<Supervisor>,
pub journal: Arc<Journal>,
pub store: Arc<FakeStore>,
pub printer: Arc<FakePrinter>,
pub vision: Arc<FakeVision>,
pub agent: Arc<FakeSupervisor>,
pub clock: Arc<FakeClock>,
pub turns: Arc<crate::fakes::FakeTurnAuthority>,
pub config: CoreConfig,
}
impl World {
#[must_use]
pub fn new() -> Self {
Self::with_envelope(permissive_envelope())
}
#[must_use]
pub fn with_envelope(envelope: SafetyEnvelope) -> Self {
Self::built(envelope, true)
}
#[must_use]
pub fn with_no_turn_authority() -> Self {
Self::built(permissive_envelope(), false)
}
#[must_use]
pub fn with_camera() -> Self {
Self::configured(permissive_envelope(), true, |config| {
config.camera_snapshot_url =
Some(WebAddress::new(CAMERA_URL).expect("the camera's address is one"));
})
}
#[must_use]
pub fn with_camera_retry(retry: printobserver_core::CameraRetry) -> Self {
Self::configured(permissive_envelope(), true, |config| {
config.camera_snapshot_url =
Some(WebAddress::new(CAMERA_URL).expect("the camera's address is one"));
config.camera_retry = retry;
})
}
#[must_use]
pub fn with_config(envelope: SafetyEnvelope, edit: impl FnOnce(&mut CoreConfig)) -> Self {
Self::configured(envelope, true, edit)
}
#[must_use]
pub fn restarted(&self) -> Arc<Supervisor> {
self.restarted_on(Arc::clone(&self.clock) as Arc<dyn printobserver_core::Clock>)
}
#[must_use]
pub fn restarted_on(&self, clock: Arc<dyn printobserver_core::Clock>) -> Arc<Supervisor> {
let core = Supervisor::new(
self.config.clone(),
Arc::clone(&self.printer) as Arc<dyn printobserver_printer_api::PrinterPort>,
printobserver_core::store::Stores::of(Arc::clone(&self.store)),
Arc::clone(&self.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
Arc::clone(&self.agent) as Arc<dyn printobserver_supervisor_api::SupervisorPort>,
clock,
);
assert!(
core.install_turn_authority(Arc::new(crate::fakes::OpensTurns(Arc::clone(
&self.turns
))))
);
core
}
pub fn restart(&mut self) {
self.restart_on(Arc::clone(&self.clock) as Arc<dyn printobserver_core::Clock>);
}
pub fn restart_on(&mut self, clock: Arc<dyn printobserver_core::Clock>) {
let stopped = Arc::downgrade(&self.core);
self.core = self.restarted_on(clock);
self.agent.attach(&self.core);
wait_until("the first supervisor to stop", || {
stopped.upgrade().is_none()
});
}
fn built(envelope: SafetyEnvelope, authority: bool) -> Self {
Self::configured(envelope, authority, |_| {})
}
fn configured(
envelope: SafetyEnvelope,
authority: bool,
edit: impl FnOnce(&mut CoreConfig),
) -> Self {
let journal = Arc::new(Journal::default());
let clock = Arc::new(FakeClock::new(EPOCH_SECONDS));
let store = Arc::new(FakeStore::new(Arc::clone(&journal), Arc::clone(&clock)));
let printer = Arc::new(FakePrinter::new(Arc::clone(&journal)));
let vision = Arc::new(FakeVision::new(Arc::clone(&journal)));
let agent = Arc::new(FakeSupervisor::new(
Arc::clone(&journal),
Arc::clone(&clock),
));
let mut config = CoreConfig::new(
envelope,
format!(
"printobserver context {}",
printobserver_core::PRINT_ID_PLACEHOLDER
),
);
config.expiry_poll = Duration::from_millis(5);
edit(&mut config);
let core = Supervisor::new(
config.clone(),
Arc::clone(&printer) as Arc<dyn printobserver_printer_api::PrinterPort>,
printobserver_core::store::Stores::of(Arc::clone(&store)),
Arc::clone(&vision) as Arc<dyn printobserver_vision_api::VisionPort>,
Arc::clone(&agent) as Arc<dyn printobserver_supervisor_api::SupervisorPort>,
Arc::clone(&clock) as Arc<dyn printobserver_core::Clock>,
);
agent.attach(&core);
let turns = Arc::new(crate::fakes::FakeTurnAuthority::default());
if authority {
assert!(
core.install_turn_authority(Arc::new(crate::fakes::OpensTurns(Arc::clone(&turns))))
);
}
agent.reads_authority(&turns);
Self {
core,
journal,
store,
printer,
vision,
agent,
clock,
turns,
config,
}
}
pub fn open_print(&self, provider_print_id: i64) -> PrintRecord {
block_on(printobserver_core::store::PrintStore::open_print(
self.store.as_ref(),
Some(provider_print_id),
Some("benchy.gcode".to_owned()),
))
.expect("the store opens a print")
}
pub fn handle(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
block_on(self.core.handle_event(alert))
}
pub fn request(
&self,
print_id: PrintId,
action: PrintAction,
) -> Result<ActionOutcome, CoreError> {
block_on(self.core.request_action(print_id, action))
}
pub fn context(
&self,
print_id: PrintId,
) -> Result<printobserver_core::PrintContext, CoreError> {
block_on(self.core.context(print_id))
}
pub fn agent_context(
&self,
print_id: PrintId,
since: Option<printobserver_types::EventId>,
) -> Result<printobserver_core::AgentContext, CoreError> {
block_on(self.core.agent_context(print_id, since))
}
pub fn wait_until(&self, what: &str, condition: impl FnMut() -> bool) {
let _ = &self.core;
wait_until(what, condition);
}
}
pub fn wait_until(what: &str, mut condition: impl FnMut() -> bool) {
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while std::time::Instant::now() < deadline {
if condition() {
return;
}
std::thread::sleep(Duration::from_millis(2));
}
panic!("{what} did not happen within the deadline");
}
#[track_caller]
pub fn assert_same(actual: f64, expected: f64) {
assert!(
actual.to_bits() == expected.to_bits(),
"expected {expected}, found {actual}"
);
}
impl Default for World {
fn default() -> Self {
Self::new()
}
}
#[must_use]
pub fn at(seconds: i64) -> Timestamp {
Timestamp::from_unix_seconds(EPOCH_SECONDS + seconds).expect("a representable instant")
}
#[must_use]
pub fn agent_actor(print_id: PrintId) -> Actor {
Actor::Agent {
session_name: format!("print-{print_id}"),
}
}
pub const TEST_PROVIDER_SOURCE: &str = "test_provider";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct TestProviderAlert {
pub severity: String,
pub paused: bool,
}
impl EventPayload for TestProviderAlert {
const KIND: &'static str = "test_provider_alert";
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct TestProviderNotification {
pub what: String,
}
impl EventPayload for TestProviderNotification {
const KIND: &'static str = "test_provider_notification";
}
#[must_use]
pub fn alert_kind() -> EventKind {
TestProviderAlert::kind()
}
#[must_use]
pub fn notification_kind() -> EventKind {
TestProviderNotification::kind()
}
#[must_use]
pub fn failure_alert(provider_print_id: i64) -> NormalizedAlert {
NormalizedAlert {
source: EventSource::new(TEST_PROVIDER_SOURCE),
received_at: at(0),
body: EventBody::of(&TestProviderAlert {
severity: "failure".to_owned(),
paused: false,
})
.expect("a payload renders"),
raw: RawBytes::new(br#"{"event":"print_failure"}"#.to_vec()),
image_url: None,
print: Some(ProviderPrint {
id: provider_print_id,
file_name: Some("benchy.gcode".to_owned()),
started_at: None,
}),
detection: None,
signal: None,
}
}
pub const DETECTOR_PRINTER_ID: i64 = 41;
#[must_use]
pub fn detector_paused_alert(provider_print_id: i64) -> NormalizedAlert {
NormalizedAlert {
detection: Some(printobserver_vision_api::Detection {
warning: false,
paused_the_print: true,
provider_printer_id: DETECTOR_PRINTER_ID,
}),
..failure_alert(provider_print_id)
}
}
#[must_use]
pub fn failure_alert_with_image(provider_print_id: i64) -> NormalizedAlert {
NormalizedAlert {
image_url: Some("https://provider.example/snapshot.png".to_owned()),
..failure_alert(provider_print_id)
}
}
#[must_use]
pub fn notification_alert(provider_print_id: i64) -> NormalizedAlert {
NormalizedAlert {
body: EventBody::of(&TestProviderNotification {
what: "paused".to_owned(),
})
.expect("a payload renders"),
..failure_alert(provider_print_id)
}
}
#[must_use]
pub fn unattributed_alert() -> NormalizedAlert {
NormalizedAlert {
body: EventBody::of(&MalformedExternalEventPayload {
detail: "the body is not JSON: expected value at line 1 column 1".to_owned(),
})
.expect("a payload renders"),
print: None,
..failure_alert(7)
}
}
#[must_use]
pub fn manifest(allowed: &[(Adjustable, Range)]) -> JobManifest {
JobManifest {
file_name: "benchy.gcode".to_owned(),
material: "PLA".to_owned(),
nozzle_diameter_mm: 0.4,
slicer_profile: "0.20mm SPEED".to_owned(),
sheet: Some("smooth-pei".to_owned()),
allowed: allowed.iter().copied().collect(),
metadata: BTreeMap::new(),
segment_spools: Vec::new(),
}
}