use printobserver_store_api::HistoryQuery;
use printobserver_supervisor_api::TurnRequest;
use printobserver_types::{
EventPayload, EventRecord, EventSource, ImageRef, PortFailurePayload, PortFailureSite,
PrintContext, PrintId, PrintRecord, PrinterState, SessionPhase,
SupervisionSessionClosedPayload, SupervisionSessionOpenedPayload,
};
use printobserver_vision_api::NormalizedAlert;
use crate::error::CoreError;
use crate::supervisor::Supervisor;
pub const TERMINAL_STATES: [PrinterState; 3] = [
PrinterState::Operational,
PrinterState::Error,
PrinterState::Offline,
];
fn obico_print_id(payload: &EventPayload) -> Option<i64> {
match payload {
EventPayload::ObicoFailureAlert(alert) => alert.obico_print_id,
EventPayload::ObicoPrinterNotification(notification) => notification.obico_print_id,
_ => None,
}
}
fn alert_file_name(payload: &EventPayload) -> Option<String> {
match payload {
EventPayload::ObicoFailureAlert(alert) => alert.file_name.clone(),
EventPayload::ObicoPrinterNotification(notification) => notification.file_name.clone(),
_ => None,
}
}
impl Supervisor {
pub async fn handle_event(&self, alert: NormalizedAlert) -> Result<EventRecord, CoreError> {
let print = self.resolve_print(&alert).await?;
let draft = printobserver_store_api::EventDraft {
print_id: print.as_ref().map(|record| record.id),
source: alert.source,
received_at: alert.received_at,
payload: alert.payload.clone(),
raw: Some(alert.raw.clone()),
};
let event = self
.store()
.append_event(draft)
.await
.map_err(CoreError::Store)?;
let Some(print) = print else {
return Ok(event);
};
let image = self
.write_image(&print, &event, alert.image_url.clone())
.await;
let terminal = self.supervise(&print, &event, image).await?;
if let Some(state) = terminal {
self.close_out_print(&print, &state).await?;
}
Ok(event)
}
async fn resolve_print(
&self,
alert: &NormalizedAlert,
) -> Result<Option<PrintRecord>, CoreError> {
let Some(obico_print_id) = obico_print_id(&alert.payload) else {
return Ok(None);
};
if let Some(found) = self.store().print_by_obico_id(obico_print_id).await? {
return Ok(Some(found));
}
let opened = self
.store()
.open_print(Some(obico_print_id), alert_file_name(&alert.payload))
.await?;
Ok(Some(opened))
}
async fn write_image(
&self,
print: &PrintRecord,
event: &EventRecord,
image_url: Option<String>,
) -> Option<ImageRef> {
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;
}
};
match self
.store()
.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,
}),
Err(error) => {
self.record_port_failure(
print.id,
event.id,
PortFailureSite::ImageWrite,
error.to_string(),
)
.await;
None
}
}
}
async fn supervise(
&self,
print: &PrintRecord,
event: &EventRecord,
image: Option<ImageRef>,
) -> Result<Option<PrinterState>, CoreError> {
let guard = self.turns().acquire(print.id).await;
let context = self.gather_context(print, Some(event.id)).await?;
let terminal = context
.printer
.as_ref()
.map(|snapshot| snapshot.connection.clone())
.filter(|state| TERMINAL_STATES.contains(state));
let image_path = match &image {
Some(reference) => self.image_path(reference).await,
None => None,
};
let mut carried = event.clone();
carried.image = image.or(carried.image);
self.hold_context(print.id, context);
let turn = self
.agent()
.run_turn(TurnRequest {
print_id: print.id,
event: carried,
image_path,
context_command: self.config().context_command_for(print.id),
})
.await;
self.drop_context(print.id);
drop(guard);
match turn {
Ok(outcome) => {
if outcome.phase == SessionPhase::Created {
self.append_system_event(
print.id,
EventPayload::SupervisionSessionOpened(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.store().put_session(outcome.session).await?;
self.append_system_event(
print.id,
EventPayload::AgentAssessment(printobserver_types::AgentAssessmentPayload {
session_name,
assessment: outcome.assessment,
}),
)
.await?;
}
Err(error) => {
self.record_port_failure(
print.id,
event.id,
PortFailureSite::SupervisionTurn,
error.to_string(),
)
.await;
}
}
Ok(terminal)
}
pub async fn context(&self, print_id: PrintId) -> Result<PrintContext, CoreError> {
if let Some(held) = self.held_context(print_id) {
return Ok(held);
}
let print = self
.store()
.print(print_id)
.await?
.ok_or(CoreError::NoSuchPrint { print_id })?;
self.gather_context(&print, None).await
}
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 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 manifest = self.store().manifest(print.id).await?;
let bounds = self.bounds_for(Some(print), print.id).await?;
let interventions = self.store().active_interventions(print.id).await?;
let recent_events = self
.store()
.history(HistoryQuery {
print_id: print.id,
kinds: Vec::new(),
since: None,
until: None,
limit: Some(self.config().recent_events),
})
.await?;
let latest_image = recent_events.iter().find_map(|record| record.image.clone());
Ok(PrintContext {
print: print.clone(),
printer,
job,
manifest,
bounds: bounds.effective,
interventions,
recent_events,
latest_image,
})
}
async fn image_path(&self, image: &ImageRef) -> Option<std::path::PathBuf> {
match self.store().image(image.id).await {
Ok(printobserver_store_api::ImageLookup::Found { path, .. }) => Some(path),
_ => None,
}
}
async fn close_out_print(
&self,
print: &PrintRecord,
state: &PrinterState,
) -> Result<(), CoreError> {
let reason = format!("the print reached {state:?}");
self.expire_all_active(print.id).await?;
self.store()
.end_print(print.id, state.clone(), self.clock().now(), reason.clone())
.await?;
let _ = self.agent().close_session(print.id, reason.clone()).await;
if let Some(session) = self.store().session(print.id).await? {
self.append_system_event(
print.id,
EventPayload::SupervisionSessionClosed(SupervisionSessionClosedPayload {
session_name: session.session_name,
close_reason: reason,
}),
)
.await?;
}
Ok(())
}
async fn append_system_event(
&self,
print_id: PrintId,
payload: EventPayload,
) -> Result<EventRecord, CoreError> {
Ok(self
.store()
.append_event(printobserver_store_api::EventDraft {
print_id: Some(print_id),
source: EventSource::System,
received_at: self.clock().now(),
payload,
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;
}
}
async fn record_port_failure(
&self,
print_id: PrintId,
event_id: printobserver_types::EventId,
site: PortFailureSite,
detail: String,
) {
let _ = self
.append_system_event(
print_id,
EventPayload::PortFailure(PortFailurePayload {
event_id,
site,
detail,
}),
)
.await;
}
}