use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use crate::records::{ActionRecord, ActionRequest, ExecutionOutcome, PolicyDecision, PrintAction};
use printobserver_printer_api::{
FileFacts, JobSnapshot, PrinterError, PrinterPort, PrinterSnapshot, ToolFilament,
};
use printobserver_supervisor_api::SupervisorPort;
use printobserver_types::{FileName, PrintId, Timestamp};
use printobserver_vision_api::VisionPort;
use crate::store::{StoreError, Stores};
use crate::block_on::block_on;
use crate::clock::Clock;
use crate::config::CoreConfig;
use crate::detector::DetectorPauses;
use crate::inbox::Inboxes;
use crate::turn_access::{NoAccess, OpenedTurn, TurnAuthority};
use crate::turn_lock::TurnLocks;
#[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,
}
}
}
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, Timestamp>>,
inboxes: Inboxes,
detector_pauses: Mutex<DetectorPauses>,
turn_authority: std::sync::OnceLock<Arc<dyn TurnAuthority>>,
}
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 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()),
inboxes: Inboxes::default(),
detector_pauses: Mutex::new(BTreeMap::new()),
turn_authority: std::sync::OnceLock::new(),
});
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(crate) fn open_turn(&self, print_id: PrintId) -> OpenedTurn {
self.turn_authority
.get()
.map_or_else(NoAccess::opened, |authority| authority.open(print_id))
}
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 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: Timestamp) {
self.last_agent_action
.lock()
.expect("the agent's own record is not poisoned")
.insert(print_id, at);
}
pub(crate) fn last_agent_action(&self, print_id: PrintId) -> Option<Timestamp> {
self.last_agent_action
.lock()
.expect("the agent's own record is not poisoned")
.get(&print_id)
.copied()
}
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_printed_files(&self) -> Result<Vec<FileFacts>, PrinterError> {
self.printer.printed_files().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,
request: ActionRequest,
decision: PolicyDecision,
) -> Result<Issued, StoreError> {
let record = self
.stores
.actions
.record_action(request.clone(), decision.clone())
.await?;
if decision != PolicyDecision::Accepted {
return Ok(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 { .. } => Ok(()),
};
let outcome = match &executed {
Ok(()) => ExecutionOutcome::Succeeded,
Err(error) => ExecutionOutcome::Failed {
reason: error.to_string(),
},
};
let record = self
.stores
.actions
.record_execution(record.id, outcome)
.await?;
Ok(Issued {
record,
executed: Some(executed),
})
}
}