use crate::gcode_index::SlicerPlan;
use crate::records::{EffectiveBounds, Intervention, JobManifest, PrintRecord};
use crate::watch::{DetectorHealth, DetectorHealthStatus};
use printobserver_printer_api::{
HeaterSnapshot, JobError, JobSnapshot, PrinterSnapshot, PrinterState,
};
use printobserver_types::EventPayload;
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::serde_json::Value;
use printobserver_types::{
EventId, EventKind, EventRecord, ImageRef, PrintId, Reported, Timestamp,
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PrintContext {
pub print: PrintRecord,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub printer: Option<PrinterSnapshot>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub job: Option<JobSnapshot>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manifest: Option<JobManifest>,
pub bounds: EffectiveBounds,
pub interventions: Vec<Intervention>,
pub recent_events: Vec<EventRecord>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latest_image: Option<ImageRef>,
#[serde(default)]
pub detector: DetectorHealth,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slicer: Option<SlicerPlan>,
}
impl Sample for PrintContext {
fn sample_full() -> Self {
Self {
print: PrintRecord::sample_full(),
printer: Some(PrinterSnapshot::sample_full()),
job: Some(JobSnapshot::sample_full()),
manifest: Some(JobManifest::sample_full()),
bounds: EffectiveBounds::sample_full(),
interventions: vec![Intervention::sample_full()],
recent_events: vec![EventRecord::sample_full()],
latest_image: Some(ImageRef::sample_full()),
detector: DetectorHealth::sample_full(),
slicer: Some(SlicerPlan::sample_full()),
}
}
fn sample_minimal() -> Self {
Self {
print: PrintRecord::sample_minimal(),
printer: None,
job: None,
manifest: None,
bounds: EffectiveBounds::sample_full(),
interventions: vec![],
recent_events: vec![],
latest_image: None,
detector: DetectorHealth::sample_minimal(),
slicer: None,
}
}
}
const UNREAD_PAYLOAD_FIELDS: [&str; 8] = [
"printer",
"job",
"assessment",
"interval_s",
"session_name",
"harness_identity",
"delivered",
"waited_s",
];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentContext {
pub print: AgentPrint,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub printer: Option<AgentPrinter>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub job_error: Option<JobError>,
pub bounds: EffectiveBounds,
pub interventions: Vec<Intervention>,
pub detector: DetectorHealthStatus,
pub recent_events: Vec<AgentEvent>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latest_image: Option<ImageRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub newest_event: Option<EventId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slicer: Option<SlicerPlan>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentPrint {
pub id: PrintId,
pub state: PrinterState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentPrinter {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tools: Vec<AgentHeater>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bed: Option<AgentHeater>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentHeater {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub actual_c: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target_c: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct AgentEvent {
pub id: EventId,
pub kind: EventKind,
pub received_at: Timestamp,
#[serde(default, skip_serializing_if = "is_empty_payload")]
pub payload: Value,
}
fn is_empty_payload(payload: &Value) -> bool {
match payload {
Value::Null => true,
Value::Object(fields) => fields.is_empty(),
_ => false,
}
}
#[derive(Debug, Clone, Copy)]
pub struct Since<'events> {
pub event: EventId,
pub newer: &'events [EventRecord],
}
impl PrintContext {
#[must_use]
pub fn for_agent(&self, since: Option<Since<'_>>) -> AgentContext {
let heater = |heater: &HeaterSnapshot| AgentHeater {
actual_c: in_range(heater.actual_c.as_ref()),
target_c: in_range(heater.target_c.as_ref()),
};
let (events, newest_event) = match since {
Some(since) => (
since.newer,
Some(since.newer.first().map_or(since.event, |newest| newest.id)),
),
None => (
self.recent_events.as_slice(),
self.recent_events.first().map(|newest| newest.id),
),
};
AgentContext {
print: AgentPrint {
id: self.print.id,
state: self.print.state.clone(),
end_reason: self.print.end_reason.clone(),
},
printer: self.printer.as_ref().map(|printer| AgentPrinter {
tools: printer.tools.iter().map(heater).collect(),
bed: printer.bed.as_ref().map(heater),
}),
job_error: self.job.as_ref().and_then(|job| job.error.clone()),
bounds: self.bounds.clone(),
interventions: self.interventions.clone(),
detector: self.detector.status(),
recent_events: events.iter().map(agent_event).collect(),
latest_image: self.latest_image.clone(),
newest_event,
slicer: self.slicer.clone(),
}
}
}
#[must_use]
pub fn turn_facts(
context: &AgentContext,
) -> Option<printobserver_types::serde_json::Map<String, Value>> {
let mut facts = context.clone();
facts.recent_events = unseen_events(&context.recent_events);
match printobserver_types::serde_json::to_value(facts) {
Ok(Value::Object(fields)) => Some(fields),
_ => None,
}
}
#[must_use]
pub fn unseen_events(events: &[AgentEvent]) -> Vec<AgentEvent> {
let is_answer = |event: &AgentEvent| {
event.kind.as_str() == <crate::kinds::AgentAssessmentPayload as EventPayload>::KIND
};
let Some(answered) = events.iter().position(is_answer) else {
return events.to_vec();
};
let (newer, older) = events.split_at(answered);
let older = &older[1..];
let turn = &older[..older.iter().position(is_answer).unwrap_or(older.len())];
let during = events
.iter()
.find_map(agents_acknowledged_event)
.and_then(|answered_event| turn.iter().position(|event| event.id == answered_event))
.map_or(turn, |at| &turn[..at]);
let own: Vec<&Value> = during
.iter()
.filter(|event| is_agents_request(event))
.filter_map(|event| event.payload.get("action_id"))
.collect();
let mut unseen = newer.to_vec();
unseen.extend(
during
.iter()
.filter(|event| {
!TURNS_OWN_KINDS.contains(&event.kind.as_str())
&& !event
.payload
.get("action_id")
.is_some_and(|action| own.contains(&action))
})
.cloned(),
);
unseen
}
const TURNS_OWN_KINDS: [&str; 2] = [
<crate::kinds::CameraLookPayload as EventPayload>::KIND,
<printobserver_supervisor_api::SupervisionSessionOpenedPayload as EventPayload>::KIND,
];
fn is_agents_request(event: &AgentEvent) -> bool {
event.kind.as_str() == <crate::kinds::ActionRequestedPayload as EventPayload>::KIND
&& event
.payload
.get("actor")
.is_some_and(|actor| actor.get("agent").is_some())
}
fn agents_acknowledged_event(event: &AgentEvent) -> Option<EventId> {
if !is_agents_request(event) {
return None;
}
let action = event.payload.get("action")?;
if action.get("action")?.as_str()? != "acknowledge_failure" {
return None;
}
printobserver_types::serde_json::from_value(action.get("event_id")?.clone()).ok()
}
#[must_use]
pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
events
.iter()
.position(|event| event.id == since)
.map(|at| &events[..at])
}
fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
reported
.filter(|reported| !reported.out_of_range())
.map(Reported::value)
}
fn agent_event(event: &EventRecord) -> AgentEvent {
let mut payload = event.body.payload.clone();
if let Value::Object(fields) = &mut payload {
for unread in UNREAD_PAYLOAD_FIELDS {
fields.remove(unread);
}
}
AgentEvent {
id: event.id,
kind: event.kind().clone(),
received_at: event.received_at,
payload,
}
}
impl Sample for AgentContext {
fn sample_full() -> Self {
PrintContext::sample_full().for_agent(None)
}
fn sample_minimal() -> Self {
PrintContext::sample_minimal().for_agent(None)
}
}