use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use std::time::Duration;
use crate::records::{
ActionId, ActionRecord, ActionRequest, ActorClass, ExecutionOutcome, PolicyDecision,
PrintAction, RecoveryDecision, RecoveryRejection, ZTrust,
};
use printobserver_printer_api::{
AxisPosition, FileFacts, JobSnapshot, PrintedExtent, PrinterCommand, PrinterError, PrinterPort,
PrinterSnapshot, ToolFilament,
};
use printobserver_supervisor_api::SupervisorPort;
use printobserver_types::{EventPayload as _, EventRecord, FileName, PrintId, Timestamp};
use printobserver_vision_api::VisionPort;
use crate::store::{HistoryQuery, MAX_HISTORY_LIMIT, Stores};
use crate::block_on::block_on;
use crate::clock::{Clock, ClockReading};
use crate::config::CoreConfig;
use crate::decision::changes_the_machine;
use crate::detector::DetectorPauses;
use crate::error::CoreError;
use crate::expiry::Deadlines;
use crate::inbox::Inboxes;
use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload, RecoveryRequestedPayload};
use crate::turn_access::{NoAccess, OpenedTurn, TurnAuthority};
use crate::turn_lock::TurnLocks;
use crate::watch::WatchState;
#[derive(Debug, Clone, PartialEq)]
pub struct Issued {
pub record: ActionRecord,
pub executed: Option<Result<(), PrinterError>>,
}
impl Issued {
#[must_use]
pub fn succeeded(&self) -> bool {
matches!(self.executed, Some(Ok(())))
}
#[must_use]
pub fn printer_error(&self) -> Option<&PrinterError> {
match &self.executed {
Some(Err(error)) => Some(error),
_ => None,
}
}
}
const NOT_SUPPORTED: u16 = 501;
fn recovery_decision_of(
action: crate::records::RecoveryActionKind,
executed: Result<(), PrinterError>,
first: bool,
) -> RecoveryDecision {
match executed {
Ok(()) => RecoveryDecision::Executed(ExecutionOutcome::Succeeded),
Err(PrinterError::Refused {
status: NOT_SUPPORTED,
detail,
}) if first => {
RecoveryDecision::Rejected(RecoveryRejection::PrinterCannot { action, detail })
}
failed @ Err(_) => RecoveryDecision::Executed(outcome_of(&failed)),
}
}
fn outcome_of(executed: &Result<(), PrinterError>) -> ExecutionOutcome {
match executed {
Ok(()) => ExecutionOutcome::Succeeded,
Err(error) => ExecutionOutcome::Failed {
reason: error.to_string(),
},
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum PortCall {
ToolTarget {
tool: i64,
target_c: f64,
},
BedTarget {
target_c: f64,
},
Fan {
percent: f64,
},
Command(PrinterCommand),
}
#[derive(Debug, Clone)]
pub(crate) enum Decided {
Action {
request: Box<ActionRequest>,
decision: PolicyDecision,
against: Option<PrintId>,
},
Recovery {
requested: Box<RecoveryRequestedPayload>,
calls: Result<Vec<PortCall>, RecoveryRejection>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum IssuedAs {
Action(Issued),
Recovery(RecoveryIssued),
}
#[derive(Debug, Clone, PartialEq)]
pub struct RecoveryIssued {
pub decision: RecoveryDecision,
pub requested: EventRecord,
pub settled: EventRecord,
}
pub struct Supervisor {
printer: Arc<dyn PrinterPort>,
stores: Stores,
vision: Arc<dyn VisionPort>,
agent: Arc<dyn SupervisorPort>,
clock: Arc<dyn Clock>,
config: CoreConfig,
turns: TurnLocks,
resolving: TurnLocks,
resolving_key: PrintId,
expiring: TurnLocks,
spool_writes: TurnLocks,
seen_running: Mutex<BTreeSet<PrintId>>,
last_agent_action: Mutex<BTreeMap<PrintId, Option<AgentAction>>>,
started: ClockReading,
deadlines: Deadlines,
inboxes: Inboxes,
detector_pauses: Mutex<DetectorPauses>,
turn_authority: std::sync::OnceLock<Arc<dyn TurnAuthority>>,
scoring_probe: std::sync::OnceLock<Arc<dyn crate::scoring::ScoringProbe>>,
pub(crate) check_images: std::sync::OnceLock<Arc<dyn crate::check_image::CheckImages>>,
pub(crate) acknowledged_by_turn: Mutex<BTreeSet<PrintId>>,
pub(crate) stopped_by_turn: Arc<Mutex<BTreeSet<PrintId>>>,
pub(crate) watch: Mutex<WatchState>,
z_trust: Mutex<ZTrust>,
recovery_extents: Mutex<Option<RecoveryExtent>>,
moved_while_paused: Mutex<BTreeMap<PrintId, printobserver_types::EventId>>,
gcode_indexes: crate::gcode_index::GcodeIndexes,
}
type RecoveryExtent = ((PrintId, i64), Option<PrintedExtent>);
#[derive(Debug, Clone, Copy)]
struct AgentAction {
seen_at: Duration,
already: Duration,
}
impl core::fmt::Debug for Supervisor {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("Supervisor")
.field("config", &self.config)
.finish_non_exhaustive()
}
}
impl Supervisor {
#[must_use]
pub fn new(
config: CoreConfig,
printer: Arc<dyn PrinterPort>,
stores: Stores,
vision: Arc<dyn VisionPort>,
agent: Arc<dyn SupervisorPort>,
clock: Arc<dyn Clock>,
) -> Arc<Self> {
let poll = config.expiry_poll;
let started = ClockReading::of(clock.as_ref());
let supervisor = Arc::new(Self {
printer,
stores,
vision,
agent,
clock,
config,
turns: TurnLocks::default(),
resolving: TurnLocks::default(),
resolving_key: PrintId::new(),
expiring: TurnLocks::default(),
spool_writes: TurnLocks::default(),
seen_running: Mutex::new(BTreeSet::new()),
last_agent_action: Mutex::new(BTreeMap::new()),
started,
deadlines: Deadlines::default(),
inboxes: Inboxes::default(),
detector_pauses: Mutex::new(BTreeMap::new()),
turn_authority: std::sync::OnceLock::new(),
scoring_probe: std::sync::OnceLock::new(),
check_images: std::sync::OnceLock::new(),
acknowledged_by_turn: Mutex::new(BTreeSet::new()),
stopped_by_turn: Arc::new(Mutex::new(BTreeSet::new())),
watch: Mutex::new(WatchState::default()),
z_trust: Mutex::new(ZTrust::Untrusted(
crate::recovery::UNTRUSTED_AT_START.to_owned(),
)),
recovery_extents: Mutex::new(None),
moved_while_paused: Mutex::new(BTreeMap::new()),
gcode_indexes: crate::gcode_index::GcodeIndexes::default(),
});
let weak: Weak<Self> = Arc::downgrade(&supervisor);
std::thread::Builder::new()
.name("printobserver-expiry".to_owned())
.spawn(move || {
while let Some(supervisor) = weak.upgrade() {
let _ = block_on(supervisor.sweep_expired());
block_on(supervisor.resume_due_detector_pauses());
drop(supervisor);
std::thread::sleep(poll);
}
})
.expect("the expiry driver thread starts");
supervisor
}
pub fn install_turn_authority(&self, authority: Arc<dyn TurnAuthority>) -> bool {
self.turn_authority.set(authority).is_ok()
}
pub fn install_scoring_probe(&self, probe: Arc<dyn crate::scoring::ScoringProbe>) -> bool {
self.scoring_probe.set(probe).is_ok()
}
pub(crate) fn scoring_probe(&self) -> Option<Arc<dyn crate::scoring::ScoringProbe>> {
self.scoring_probe.get().cloned()
}
pub(crate) fn z_trust_held(&self) -> MutexGuard<'_, ZTrust> {
self.z_trust
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn recovery_extents(&self) -> MutexGuard<'_, Option<RecoveryExtent>> {
self.recovery_extents
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn moved_while_paused(
&self,
) -> MutexGuard<'_, BTreeMap<PrintId, printobserver_types::EventId>> {
self.moved_while_paused
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn open_turn(&self, print_id: PrintId, handed_image: bool) -> OpenedTurn {
self.turn_authority
.get()
.map_or_else(NoAccess::opened, |authority| {
authority.open(print_id, handed_image)
})
}
pub(crate) const fn gcode_indexes(&self) -> &crate::gcode_index::GcodeIndexes {
&self.gcode_indexes
}
pub(crate) const fn stores(&self) -> &Stores {
&self.stores
}
pub(crate) fn vision(&self) -> &Arc<dyn VisionPort> {
&self.vision
}
pub(crate) fn agent(&self) -> &Arc<dyn SupervisorPort> {
&self.agent
}
pub(crate) fn clock(&self) -> &Arc<dyn Clock> {
&self.clock
}
#[must_use]
pub const fn config(&self) -> &CoreConfig {
&self.config
}
pub(crate) const fn turns(&self) -> &TurnLocks {
&self.turns
}
pub(crate) const fn expiring(&self) -> &TurnLocks {
&self.expiring
}
pub(crate) const fn started(&self) -> ClockReading {
self.started
}
pub(crate) const fn deadlines(&self) -> &Deadlines {
&self.deadlines
}
pub(crate) const fn inboxes(&self) -> &Inboxes {
&self.inboxes
}
pub(crate) fn detector_pauses(&self) -> MutexGuard<'_, DetectorPauses> {
self.detector_pauses
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) async fn resolving(&self) -> crate::turn_lock::TurnGuard<'_> {
self.resolving.acquire(self.resolving_key).await
}
pub(crate) async fn spool_writes(&self) -> crate::turn_lock::TurnGuard<'_> {
self.spool_writes.acquire(self.resolving_key).await
}
pub(crate) fn note_seen_running(&self, print_id: PrintId) {
self.seen_running
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(print_id);
}
pub(crate) fn was_seen_running(&self, print_id: PrintId) -> bool {
self.seen_running
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.contains(&print_id)
}
pub(crate) fn note_agent_action(&self, print_id: PrintId, at: Duration) {
self.last_agents_actions().insert(
print_id,
Some(AgentAction {
seen_at: at,
already: Duration::ZERO,
}),
);
}
pub(crate) async fn since_last_agent_action(
&self,
print_id: PrintId,
) -> Result<Option<Duration>, CoreError> {
let known = self.last_agents_actions().get(&print_id).copied();
let last = if let Some(last) = known {
last
} else {
let started = self.started;
let recorded = self
.recorded_agent_action(print_id)
.await?
.map(|at| AgentAction {
seen_at: started.elapsed,
already: started
.wall
.as_utc()
.signed_duration_since(*at.as_utc())
.to_std()
.unwrap_or_default(),
});
*self
.last_agents_actions()
.entry(print_id)
.or_insert(recorded)
};
Ok(last.map(|action| {
self.clock()
.paced()
.saturating_sub(action.seen_at)
.saturating_add(action.already)
}))
}
async fn recorded_agent_action(
&self,
print_id: PrintId,
) -> Result<Option<Timestamp>, CoreError> {
let history = self
.stores()
.events
.history(HistoryQuery {
print_id,
kinds: vec![
ActionRequestedPayload::kind(),
ActionExecutedPayload::kind(),
],
since: None,
until: None,
limit: Some(MAX_HISTORY_LIMIT),
})
.await?;
let executed: BTreeSet<ActionId> = history
.iter()
.filter_map(EventRecord::payload_as::<ActionExecutedPayload>)
.filter_map(Result::ok)
.map(|payload| payload.action_id)
.collect();
Ok(history.iter().find_map(|event| {
let requested = event.payload_as::<ActionRequestedPayload>()?.ok()?;
(executed.contains(&requested.action_id)
&& requested.actor.class() == ActorClass::Agent
&& changes_the_machine(requested.action.kind()))
.then_some(event.received_at)
}))
}
fn last_agents_actions(&self) -> MutexGuard<'_, BTreeMap<PrintId, Option<AgentAction>>> {
self.last_agent_action
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) async fn read_snapshot(&self) -> Result<PrinterSnapshot, PrinterError> {
self.printer.snapshot().await
}
pub(crate) async fn read_job(&self) -> Result<JobSnapshot, PrinterError> {
self.printer.job().await
}
pub(crate) async fn read_file_facts(
&self,
file_name: FileName,
) -> Result<FileFacts, PrinterError> {
self.printer.file_facts(file_name).await
}
pub(crate) async fn read_filament_types(
&self,
file_name: FileName,
) -> Result<Vec<Option<String>>, PrinterError> {
self.printer.filament_types(file_name).await
}
pub(crate) async fn read_printed_files(&self) -> Result<Vec<FileFacts>, PrinterError> {
self.printer.printed_files().await
}
pub(crate) async fn read_printed_extent(
&self,
file_name: FileName,
position_bytes: i64,
) -> Result<Option<PrintedExtent>, PrinterError> {
self.printer.printed_extent(file_name, position_bytes).await
}
pub(crate) async fn read_gcode(
&self,
file_name: FileName,
sink: &mut dyn printobserver_printer_api::GcodeSink,
) -> Result<(), PrinterError> {
self.printer.read_gcode(file_name, sink).await
}
pub(crate) async fn read_position(&self) -> Result<AxisPosition, PrinterError> {
self.printer.read_position().await
}
pub(crate) async fn read_extruded_to(
&self,
file_name: FileName,
position_bytes: i64,
) -> Result<Vec<ToolFilament>, PrinterError> {
self.printer.extruded_to(file_name, position_bytes).await
}
pub(crate) async fn issue_decided_action(
&self,
decided: Decided,
) -> Result<IssuedAs, CoreError> {
let (request, decision, against) = match decided {
Decided::Action {
request,
decision,
against,
} => (*request, decision, against),
Decided::Recovery { requested, calls } => {
let requested_event = self.write_recovery_request(&requested).await?;
let decision = match calls {
Err(rejection) => RecoveryDecision::Rejected(rejection),
Ok(calls) => {
let (mut executed, mut first) = (Ok(()), true);
for call in calls {
executed = match call {
PortCall::ToolTarget { tool, target_c } => {
self.printer.set_tool_target_c(tool, target_c).await
}
PortCall::BedTarget { target_c } => {
self.printer.set_bed_target_c(target_c).await
}
PortCall::Fan { percent } => {
self.printer.set_fan_percent(percent).await
}
PortCall::Command(command) => {
self.printer.send_command(command).await
}
};
if executed.is_err() {
break;
}
first = false;
}
recovery_decision_of(requested.action.kind(), executed, first)
}
};
return self
.recovery_settled(*requested, requested_event, decision)
.await
.map(IssuedAs::Recovery);
}
};
let actions = &self.stores.actions;
let record = match (&request.action, against) {
(PrintAction::ClosePrint { .. }, Some(print_id)) => {
actions
.record_action_against(print_id, request.clone(), decision.clone())
.await?
}
_ => {
actions
.record_action(request.clone(), decision.clone())
.await?
}
};
if decision != PolicyDecision::Accepted {
return Ok(IssuedAs::Action(Issued {
record,
executed: None,
}));
}
let executed = match &request.action {
PrintAction::Pause { .. } => self.printer.pause().await,
PrintAction::Resume { .. } => self.printer.resume().await,
PrintAction::Cancel { .. } => self.printer.cancel().await,
PrintAction::StartPrint { file_name, .. } => {
self.printer.start(file_name.clone()).await
}
PrintAction::SetFeedrateFactor { factor, .. } => {
self.printer.set_feedrate_factor(*factor).await
}
PrintAction::SetFlowrateFactor { factor, .. } => {
self.printer.set_flowrate_factor(*factor).await
}
PrintAction::SetToolTargetC { tool, target_c, .. } => {
self.printer.set_tool_target_c(*tool, *target_c).await
}
PrintAction::SetBedTargetC { target_c, .. } => {
self.printer.set_bed_target_c(*target_c).await
}
PrintAction::SetFanPercent { percent, .. } => {
self.printer.set_fan_percent(*percent).await
}
PrintAction::AcknowledgeFailure { .. } | PrintAction::ClosePrint { .. } => Ok(()),
};
let outcome = outcome_of(&executed);
let record = self
.stores
.actions
.record_execution(record.id, outcome)
.await?;
Ok(IssuedAs::Action(Issued {
record,
executed: Some(executed),
}))
}
pub(crate) async fn issue_action(
&self,
request: ActionRequest,
decision: PolicyDecision,
against: Option<PrintId>,
) -> Result<Issued, CoreError> {
match self
.issue_decided_action(Decided::Action {
request: Box::new(request),
decision,
against,
})
.await?
{
IssuedAs::Action(issued) => Ok(issued),
IssuedAs::Recovery(_) => Err(CoreError::Unrepresentable {
detail: "a print action was answered as a recovery".to_owned(),
}),
}
}
}