use crate::records::{AcknowledgementDisposition, Actor, PrintAction, PrintRecord};
use crate::store::{EventDraft, HistoryQuery, ImageLookup};
use printobserver_printer_api::{JobSnapshot, PrinterState};
use printobserver_supervisor_api::{AgentAssessment, Disposition, SessionPhase};
use printobserver_supervisor_api::{SupervisionSessionOpenedPayload, TurnRequest, TurnSituation};
use printobserver_types::EventId;
use printobserver_types::{EventBody, EventRecord, ImageRef, PrintId, Timestamp};
use printobserver_vision_api::NormalizedAlert;
use crate::check_image::{ImageUse, captured_at_of};
use crate::context::{AgentContext, PrintContext, Since, newer_than};
use crate::error::CoreError;
use crate::inbox::{AlertCameraFrame, Arrival};
use crate::kinds::{
AgentAssessmentPayload, AgentStopUnactedPayload, PortFailurePayload, PortFailureSite,
system_source,
};
use crate::listing::{self, ObservedJob, reached_reason};
use crate::look::Frame;
use crate::supervisor::Supervisor;
use crate::watch::{concerns_its_end, noticed_of};
#[derive(Debug, Clone, PartialEq)]
pub struct Received {
pub event: EventRecord,
pub turn: Option<PendingTurn>,
}
enum Supervised {
Ran,
Terminal(PrinterState),
Ended,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PendingTurn {
print: PrintRecord,
arrival: Arrival,
earlier: Vec<Arrival>,
}
impl PendingTurn {
pub(crate) const fn new(print: PrintRecord, arrival: Arrival, earlier: Vec<Arrival>) -> Self {
Self {
print,
arrival,
earlier,
}
}
}
enum Resolution {
NoPrint,
Existing(PrintRecord),
Opened(PrintRecord),
}
impl Resolution {
const fn print(&self) -> Option<&PrintRecord> {
match self {
Self::NoPrint => None,
Self::Existing(print) | Self::Opened(print) => Some(print),
}
}
}
pub const TERMINAL_STATES: [PrinterState; 3] = [
PrinterState::Operational,
PrinterState::Error,
PrinterState::Offline,
];
pub const ALERT_CAMERA_FRAME_NOTE: &str = "panel 1 is the printer's camera's own frame, taken as the detector's alert arrived, not the detector's picture";
impl Supervisor {
pub async fn handle_event(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
let received = self.receive_event(alert).await?;
if let Some(turn) = received.turn {
self.run_supervision(turn).await?;
}
Ok(received.event)
}
pub async fn receive_event(&self, alert: NormalizedAlert) -> Result<Received, CoreError> {
let resolution = self.resolve_print(&alert).await?;
let draft = EventDraft {
print_id: resolution.print().map(|record| record.id),
source: alert.source.clone(),
received_at: alert.received_at,
body: alert.body.clone(),
raw: Some(alert.raw.clone()),
};
let event = self
.stores()
.events
.append_event(draft)
.await
.map_err(CoreError::Store)?;
let print = match resolution {
Resolution::NoPrint => return Ok(Received { event, turn: None }),
Resolution::Existing(print) => print,
Resolution::Opened(print) => {
self.record_print_started(print.id, print.file_name.clone(), None, None)
.await?;
print
}
};
if alert.detection.is_some() {
self.note_flagged(print.id);
}
let (image, frame_captured_at) = self
.write_image(&print, &event, alert.image_url.clone())
.await
.map_or((None, None), |(image, at)| (Some(image), Some(at)));
if print.ended_at.is_some() {
return Ok(Received { event, turn: None });
}
if let Some(signal) = alert.signal {
self.handle_signal(&print, signal, alert.kind()).await?;
}
let mut carried = event.clone();
carried.image = image.or(carried.image);
if let Some(detection) = alert.detection
&& detection.paused_the_print
{
self.note_detector_pause(print.id, event.id, detection);
}
let camera_frame = if alert.detection.is_some() && carried.image.is_some() {
self.alert_camera_frame(&print, &event).await
} else {
AlertCameraFrame::NotAsked
};
let arrival = Arrival {
event: carried,
detection: alert.detection,
frame_captured_at,
camera_frame,
};
let turn = self
.inboxes()
.claim_or_hand_over(print.id, arrival.clone())
.then(|| PendingTurn::new(print, arrival, Vec::new()));
Ok(Received { event, turn })
}
pub async fn run_supervision(&self, turn: PendingTurn) -> Result<(), CoreError> {
let PendingTurn {
print,
arrival,
earlier,
} = turn;
let mut next = Some((arrival, earlier));
while let Some((arrival, earlier)) = next {
let supervised = self.supervise(&print, &arrival, earlier).await;
if !matches!(supervised, Ok(Supervised::Ended)) {
self.resume_adjusted_detector_pause(print.id).await;
}
match supervised {
Ok(Supervised::Ran) => {}
Ok(Supervised::Ended) => {
self.inboxes().release(print.id);
self.forget_detector_pause(print.id);
return Ok(());
}
Ok(Supervised::Terminal(state)) => {
self.inboxes().release(print.id);
let _turn = self.turns().acquire(print.id).await;
return self
.close_out_print(print.id, &state, &reached_reason(&state), None)
.await
.map(drop);
}
Err(error) => {
self.inboxes().release(print.id);
return Err(error);
}
}
next = self
.inboxes()
.next_or_release(print.id)
.and_then(|mut left| left.pop().map(|latest| (latest, left)));
}
Ok(())
}
async fn resolve_print(&self, alert: &NormalizedAlert) -> Result<Resolution, CoreError> {
let Some(provider_print) = &alert.print else {
return Ok(Resolution::NoPrint);
};
let _resolving = self.resolving().await;
if let Some(found) = self
.stores()
.prints
.print_by_provider_id(provider_print.id)
.await?
{
return Ok(Resolution::Existing(found));
}
if let Some(file_name) = &provider_print.file_name {
let unattached = self
.stores()
.prints
.open_prints()
.await?
.into_iter()
.find(|open| {
open.provider_print_id.is_none()
&& open.file_name.as_ref() == Some(file_name)
&& listing::may_have_started_it(open, provider_print.started_at)
});
if let Some(found) = unattached {
let attached = self
.stores()
.prints
.attach_obico_print(found.id, provider_print.id)
.await?;
return Ok(Resolution::Existing(attached));
}
}
let opened = self
.stores()
.prints
.open_print(Some(provider_print.id), provider_print.file_name.clone())
.await?;
Ok(Resolution::Opened(opened))
}
async fn write_image(
&self,
print: &PrintRecord,
event: &EventRecord,
image_url: Option<String>,
) -> Option<(ImageRef, Timestamp)> {
let source_url = image_url?;
let fetched = match self.vision().fetch_image(source_url.clone()).await {
Ok(fetched) => fetched,
Err(error) => {
self.record_port_failure(
print.id,
event.id,
PortFailureSite::ImageWrite,
error.to_string(),
)
.await;
return None;
}
};
let captured_at = fetched.captured_at.unwrap_or_else(|| self.clock().now());
match self
.stores()
.images
.put_image(
print.id,
event.id,
Some(source_url),
fetched.content_type,
fetched.bytes,
)
.await
{
Ok(record) => Some((
ImageRef {
id: record.id,
sha256: record.sha256,
},
captured_at,
)),
Err(error) => {
self.record_port_failure(
print.id,
event.id,
PortFailureSite::ImageWrite,
error.to_string(),
)
.await;
None
}
}
}
async fn alert_camera_frame(
&self,
print: &PrintRecord,
event: &EventRecord,
) -> AlertCameraFrame {
if !self
.check_images
.get()
.is_some_and(|images| images.composes(print.id))
{
return AlertCameraFrame::NotAsked;
}
let image = match self.fetch_configured_frame(Some(print.id)).await {
Some((url, Frame::Good(image))) => (url, image),
Some((_, Frame::Failed(detail))) => return AlertCameraFrame::Missing(detail),
Some((_, Frame::Degraded(degraded))) => {
return AlertCameraFrame::Missing(degraded.detail);
}
None => return AlertCameraFrame::Missing("no camera is configured".to_owned()),
};
let (url, image) = image;
let captured_at = image.captured_at.unwrap_or_else(|| self.clock().now());
match self
.stores()
.images
.put_image(
print.id,
event.id,
Some(url),
image.content_type,
image.bytes,
)
.await
{
Ok(record) => AlertCameraFrame::Had {
image: ImageRef {
id: record.id,
sha256: record.sha256,
},
captured_at,
},
Err(error) => {
let detail = error.to_string();
self.record_port_failure(
print.id,
event.id,
PortFailureSite::ImageWrite,
detail.clone(),
)
.await;
AlertCameraFrame::Missing(detail)
}
}
}
async fn supervise(
&self,
print: &PrintRecord,
arrival: &Arrival,
earlier: Vec<Arrival>,
) -> Result<Supervised, CoreError> {
let event = &arrival.event;
let guard = self.turns().acquire(print.id).await;
let Some(held) = self.stores().prints.print(print.id).await? else {
return Ok(Supervised::Ended);
};
let ended = held.ended_at.is_some();
if ended && !concerns_its_end(event.kind()) {
return Ok(Supervised::Ended);
}
let context = self.gather_context(print, Some(event.id)).await?;
let printer_state = context
.printer
.as_ref()
.map(|snapshot| snapshot.connection.clone());
let terminal = printer_state
.clone()
.filter(|state| TERMINAL_STATES.contains(state));
let (image_path, image, frame_captured_at) = self
.check_image_for(print, arrival, context.job.as_ref())
.await;
let facts = crate::context::turn_facts(&context.for_agent(None));
let situation = TurnSituation {
printer_state,
detector_warned: arrival.detection.map(|detection| detection.warning),
detector_paused_the_print: arrival
.detection
.map(|detection| detection.paused_the_print),
arrived_while_busy: earlier.into_iter().map(|left| left.event).collect(),
noticed: noticed_of(event),
frame_captured_at,
image,
};
let opened = self.open_turn(print.id, image_path.is_some());
self.forget_acknowledged_by_turn(print.id);
let running = situation.printer_state == Some(PrinterState::Printing);
self.forget_stop_asked(print.id);
let access = std::sync::Arc::new(StopAware {
inner: opened.access(),
print_id: print.id,
stops: std::sync::Arc::clone(&self.stopped_by_turn),
});
let turn = self
.agent()
.run_turn(
TurnRequest {
print_id: print.id,
event: event.clone(),
image_path,
context_command: self.config().context_command_for(print.id),
facts,
situation,
},
access,
)
.await;
opened.revoke();
let acknowledged_by_command = self.forget_acknowledged_by_turn(print.id);
let asked_to_stop = self.forget_stop_asked(print.id);
drop(guard);
match turn {
Ok(outcome) => {
let stop_unacted = (running
&& !asked_to_stop
&& outcome.assessment.disposition == Disposition::Stop)
.then(|| {
(
outcome.session.session_name.clone(),
outcome.assessment.summary.clone(),
)
});
self.record_answered(print.id, event.id, outcome, acknowledged_by_command)
.await?;
if let Some(said) = stop_unacted {
self.record_unacted_stop(print.id, event.id, said).await?;
}
}
Err(error) => {
self.record_port_failure(
print.id,
event.id,
PortFailureSite::SupervisionTurn,
error.to_string(),
)
.await;
}
}
Ok(match terminal {
Some(state) if !ended => Supervised::Terminal(state),
_ => Supervised::Ran,
})
}
async fn record_answered(
&self,
print_id: PrintId,
event_id: EventId,
outcome: printobserver_supervisor_api::TurnOutcome,
acknowledged_by_command: bool,
) -> Result<(), CoreError> {
if outcome.phase == SessionPhase::Created {
self.append_system_event(
print_id,
EventBody::of(&SupervisionSessionOpenedPayload {
session_name: outcome.session.session_name.clone(),
harness_identity: outcome.session.harness_identity.clone(),
})?,
)
.await?;
}
let session_name = outcome.session.session_name.clone();
self.stores().sessions.put_session(outcome.session).await?;
let assessment = outcome.assessment;
self.append_system_event(
print_id,
EventBody::of(&AgentAssessmentPayload {
session_name: session_name.clone(),
assessment: assessment.clone(),
})?,
)
.await?;
if !acknowledged_by_command
&& let Err(error) = self
.acknowledge_from_answer(print_id, event_id, session_name, &assessment)
.await
{
self.record_port_failure(
print_id,
event_id,
PortFailureSite::SupervisionTurn,
format!("the answer's acknowledgement could not be made: {error}"),
)
.await;
}
Ok(())
}
async fn record_unacted_stop(
&self,
print_id: PrintId,
event_id: EventId,
(session_name, summary): (String, String),
) -> Result<(), CoreError> {
let open = self
.stores()
.prints
.print(print_id)
.await?
.is_some_and(|print| print.ended_at.is_none());
if !open {
return Ok(());
}
self.append_system_event(
print_id,
EventBody::of(&AgentStopUnactedPayload {
event_id,
session_name,
summary,
})?,
)
.await?;
Ok(())
}
async fn check_image_for(
&self,
print: &PrintRecord,
arrival: &Arrival,
job: Option<&JobSnapshot>,
) -> (
Option<std::path::PathBuf>,
Option<String>,
Option<Timestamp>,
) {
let event = &arrival.event;
let Some(reference) = &event.image else {
return (None, None, arrival.frame_captured_at);
};
let plan = self.plan_position(print, job).await;
if let AlertCameraFrame::Had { image, captured_at } = &arrival.camera_frame {
let shown = self
.shown_image_of(
image,
Some(print.id),
*captured_at,
ImageUse::Check,
plan.clone(),
)
.await;
if let Some(shown) = shown.filter(|shown| shown.composite) {
self.note_check_frame(print, job, *captured_at);
let note = shown
.note
.map(|note| format!("{note}; {ALERT_CAMERA_FRAME_NOTE}"));
return (Some(shown.path), note, Some(*captured_at));
}
}
let captured_at = captured_at_of(event, arrival.frame_captured_at);
self.note_check_frame(print, job, captured_at);
let missing = match &arrival.camera_frame {
AlertCameraFrame::Missing(why) => Some(why.as_str()),
AlertCameraFrame::NotAsked | AlertCameraFrame::Had { .. } => None,
};
self.shown_image_of(
reference,
Some(print.id),
captured_at,
ImageUse::Check,
plan,
)
.await
.map_or((None, None, arrival.frame_captured_at), |shown| {
let note = match (shown.note, missing) {
(Some(note), Some(why)) => Some(format!(
"{note}; the detector's own picture, because the camera gave no frame of its own as the alert arrived: {why}"
)),
(note, _) => note,
};
(Some(shown.path), note, arrival.frame_captured_at)
})
}
fn note_check_frame(
&self,
print: &PrintRecord,
job: Option<&JobSnapshot>,
captured_at: Timestamp,
) {
if let Some(job) = job
&& print.ended_at.is_none()
&& job.file_name.is_some()
&& job.file_name == print.file_name
&& let Some(position) = job.file_position_bytes
{
self.gcode_indexes()
.note_look(print.id, captured_at, position, self.clock().now());
}
}
pub(crate) fn note_stop_asked(&self, print_id: PrintId, action: &PrintAction) {
if action.actor().class() == crate::records::ActorClass::Agent
&& matches!(
action,
PrintAction::Pause { .. } | PrintAction::Cancel { .. }
)
{
self.stopped_by_turn
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(print_id);
}
}
fn forget_stop_asked(&self, print_id: PrintId) -> bool {
self.stopped_by_turn
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(&print_id)
}
pub(crate) fn note_acknowledged_by_turn(&self, print_id: PrintId) {
self.acknowledged_by_turn
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(print_id);
}
fn forget_acknowledged_by_turn(&self, print_id: PrintId) -> bool {
self.acknowledged_by_turn
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(&print_id)
}
async fn acknowledge_from_answer(
&self,
print_id: PrintId,
event_id: EventId,
session_name: String,
assessment: &AgentAssessment,
) -> Result<(), CoreError> {
let open = self
.stores()
.prints
.print(print_id)
.await?
.is_some_and(|print| print.ended_at.is_none());
if !open {
return Ok(());
}
let disposition = match assessment.disposition {
Disposition::Continue => AcknowledgementDisposition::Continue,
Disposition::Watch => AcknowledgementDisposition::Watch,
Disposition::Stop => AcknowledgementDisposition::Stop,
};
self.request_action(
print_id,
PrintAction::AcknowledgeFailure {
event_id,
disposition,
reason: assessment.why.clone(),
actor: Actor::Agent { session_name },
},
)
.await?;
Ok(())
}
pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
let print = self
.stores()
.prints
.print(print_id)
.await?
.ok_or(CoreError::NoSuchPrint { print_id })?;
self.gather_context(&print, None).await
}
pub async fn agent_context(
&self,
print_id: PrintId,
since: Option<printobserver_types::EventId>,
) -> Result<AgentContext, CoreError> {
let context = self.context(print_id).await?;
let Some(event) = since else {
return Ok(context.for_agent(None));
};
let wider;
let newer = if let Some(newer) = newer_than(&context.recent_events, event) {
newer
} else {
wider = self
.recent_events_of(&context.print, crate::store::MAX_HISTORY_LIMIT)
.await?;
newer_than(&wider, event).ok_or_else(|| {
CoreError::Store(crate::store::StoreError::NotFound {
what: format!(
"event {event} among print {print_id}'s latest {} events",
crate::store::MAX_HISTORY_LIMIT
),
})
})?
};
let agent = context.for_agent(Some(Since { event, newer }));
Ok(agent)
}
async fn gather_context(
&self,
print: &PrintRecord,
event_id: Option<printobserver_types::EventId>,
) -> Result<PrintContext, CoreError> {
let printer = match self.read_snapshot().await {
Ok(snapshot) => Some(snapshot),
Err(error) => {
self.record_read_failure(
print.id,
event_id,
PortFailureSite::PrinterSnapshot,
error.to_string(),
)
.await;
None
}
};
let resolving = self.resolving().await;
let job = match self.read_job().await {
Ok(job) => Some(job),
Err(error) => {
self.record_read_failure(
print.id,
event_id,
PortFailureSite::PrinterJob,
error.to_string(),
)
.await;
None
}
};
let print = match &job {
Some(job) if print.ended_at.is_none() => self.settle_for_context(print, job).await?,
_ => print.clone(),
};
drop(resolving);
let print = &print;
let manifest = self.stores().prints.manifest(print.id).await?;
let bounds = self.bounds_for(Some(print), print.id).await?;
let interventions = self.stores().actions.active_interventions(print.id).await?;
let recent_events = self
.recent_events_of(print, self.config().recent_events)
.await?;
let latest_image = recent_events.iter().find_map(|record| record.image.clone());
let slicer = self
.slicer_plan(print, job.as_ref(), &interventions)
.await?;
Ok(PrintContext {
print: print.clone(),
printer,
job,
manifest,
bounds: bounds.effective,
interventions,
recent_events,
latest_image,
detector: self.detector_health_for(print.id),
slicer,
})
}
async fn recent_events_of(
&self,
print: &PrintRecord,
limit: u32,
) -> Result<Vec<EventRecord>, CoreError> {
let mut events = self
.stores()
.events
.history(HistoryQuery {
print_id: print.id,
kinds: Vec::new(),
since: None,
until: None,
limit: Some(limit),
})
.await?;
let kinds = crate::watch::PRINTER_WATCH_KINDS
.iter()
.filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
.collect();
let watched = self
.stores()
.timeline
.timeline(crate::store::TimelineQuery {
kinds,
since: Some(print.opened_at),
until: None,
spool_id: None,
before: None,
limit: Some(limit),
})
.await?;
events.extend(watched.into_iter().filter(|event| event.print_id.is_none()));
events.sort_by_key(|event| core::cmp::Reverse((event.received_at, event.id)));
events.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
Ok(events)
}
pub(crate) async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
match self.stores().images.image(image.id).await {
Ok(ImageLookup::Found { path, .. }) => Some(path),
_ => None,
}
}
async fn settle_for_context(
&self,
print: &PrintRecord,
job: &JobSnapshot,
) -> Result<PrintRecord, CoreError> {
let observed = ObservedJob {
job: job.clone(),
observed_at: self.clock().now(),
};
let settled = self.settle_open_prints(&observed).await?;
match settled.running {
Some(running) if running.id == print.id => Ok(running),
_ if settled.closed.contains(&print.id) => Ok(self
.stores()
.prints
.print(print.id)
.await?
.unwrap_or_else(|| print.clone())),
_ => Ok(print.clone()),
}
}
pub(crate) async fn close_out_print(
&self,
print_id: PrintId,
state: &PrinterState,
reason: &str,
closing_job: Option<&JobSnapshot>,
) -> Result<bool, CoreError> {
let print = match self.stores().prints.print(print_id).await? {
Some(print) if print.ended_at.is_none() => print,
_ => return Ok(false),
};
self.forget_detector_pause(print_id);
self.expire_all_active(print_id).await?;
self.settle_filament(&print, state, reason, closing_job)
.await?;
self.stores()
.prints
.end_print(
print_id,
state.clone(),
self.clock().now(),
reason.to_owned(),
)
.await?;
self.close_session_of(print_id, reason).await?;
self.drop_gcode_spool(print_id);
self.follow_up_end(print_id).await;
Ok(true)
}
pub(crate) async fn append_system_event(
&self,
print_id: PrintId,
body: EventBody,
) -> Result<EventRecord, CoreError> {
self.append_system_event_to(Some(print_id), body).await
}
pub(crate) async fn append_system_event_to(
&self,
print_id: Option<PrintId>,
body: EventBody,
) -> Result<EventRecord, CoreError> {
Ok(self
.stores()
.events
.append_event(EventDraft {
print_id,
source: system_source(),
received_at: self.clock().now(),
body,
raw: None,
})
.await?)
}
async fn record_read_failure(
&self,
print_id: PrintId,
event_id: Option<printobserver_types::EventId>,
site: PortFailureSite,
detail: String,
) {
if let Some(event_id) = event_id {
self.record_port_failure(print_id, event_id, site, detail)
.await;
}
}
pub(crate) async fn record_port_failure(
&self,
print_id: PrintId,
event_id: printobserver_types::EventId,
site: PortFailureSite,
detail: String,
) {
self.record_port_failure_to(Some(print_id), event_id, site, detail)
.await;
}
pub(crate) async fn record_port_failure_to(
&self,
print_id: Option<PrintId>,
event_id: printobserver_types::EventId,
site: PortFailureSite,
detail: String,
) {
let Ok(body) = EventBody::of(&PortFailurePayload {
event_id,
site,
detail,
}) else {
return;
};
let _ = self.append_system_event_to(print_id, body).await;
}
}
struct StopAware {
inner: std::sync::Arc<dyn printobserver_supervisor_api::TurnAccess>,
print_id: PrintId,
stops: std::sync::Arc<std::sync::Mutex<std::collections::BTreeSet<PrintId>>>,
}
impl printobserver_supervisor_api::TurnAccess for StopAware {
fn issue(
&self,
session: &printobserver_supervisor_api::TurnSession,
) -> Result<printobserver_supervisor_api::TurnPass, printobserver_supervisor_api::SupervisorError>
{
self.inner.issue(session)
}
fn asked_to_stop(&self) -> bool {
self.stops
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.contains(&self.print_id)
}
}