use core::time::Duration;
use std::time::Instant;
use printobserver_core::store::StoredQuery;
use printobserver_core::{
CameraRetryPayload, PeriodicObservationPayload, PortFailurePayload, PortFailureSite,
};
use printobserver_types::{EventPayload as _, EventRecord, PrintId};
use crate::agent::StandInAgent;
use crate::printer::RecordingPrinter;
use crate::world::{World, set};
pub const INTERVAL_S: i64 = 1;
pub const PATIENCE: Duration = Duration::from_secs(60);
pub async fn checking(url: String) -> World {
checking_over(url, |stores| stores).await
}
pub async fn checking_over(
url: String,
between: impl FnOnce(printobserver_core::store::Stores) -> printobserver_core::store::Stores,
) -> World {
World::configured_over(
RecordingPrinter::printing(),
StandInAgent::new(),
|document| {
set(
document,
"supervisor.observation_interval_s",
toml::Value::Integer(INTERVAL_S),
);
let mut table = toml::Table::new();
table.insert("snapshot_url".to_owned(), toml::Value::String(url));
set(document, "camera", toml::Value::Table(table));
},
between,
)
.await
}
pub async fn stored(world: &World, print_id: PrintId) -> Vec<EventRecord> {
world
.stores
.events
.stored_after(StoredQuery {
after: None,
print_id: Some(print_id),
limit: Some(500),
})
.await
.expect("the log reads")
}
#[derive(Debug)]
pub struct FirstCheck {
pub observation: EventRecord,
pub retries: Vec<CameraRetryPayload>,
pub seen: Instant,
}
impl FirstCheck {
pub async fn of(world: &World, print_id: PrintId) -> Self {
let deadline = Instant::now() + PATIENCE;
loop {
let events = stored(world, print_id).await;
if let Some(at) = events
.iter()
.position(|event| event.kind().as_str() == PeriodicObservationPayload::KIND)
{
let retries = events[..at]
.iter()
.filter_map(EventRecord::payload_as::<CameraRetryPayload>)
.map(|retry| retry.expect("a retry reads as one"))
.collect();
return Self {
observation: events[at].clone(),
retries,
seen: Instant::now(),
};
}
assert!(
Instant::now() < deadline,
"no scheduled check was stored within {PATIENCE:?}"
);
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
pub async fn failures(&self, world: &World) -> Vec<PortFailurePayload> {
tokio::time::sleep(Duration::from_millis(300)).await;
let print_id = self.observation.print_id.expect("a check is a print's");
stored(world, print_id)
.await
.iter()
.filter_map(EventRecord::payload_as::<PortFailurePayload>)
.map(|failure| failure.expect("a failure reads as one"))
.filter(|failure| failure.event_id == self.observation.id)
.collect()
}
pub async fn camera_failure(&self, world: &World) -> PortFailurePayload {
let mut failures = self.failures(world).await;
assert_eq!(failures.len(), 1, "{failures:?}");
let failure = failures.remove(0);
assert_eq!(failure.site, PortFailureSite::CameraLook, "{failure:?}");
failure
}
}