use core::time::Duration;
use std::collections::BTreeMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::records::{
Actor, Intervention, InterventionId, InterventionOutcome, PolicyDecision, PrintAction,
RejectionReason,
};
use printobserver_printer_api::Adjustable;
use printobserver_types::{PrintId, Timestamp};
use crate::clock::ClockReading;
use crate::decision::{DecisionInput, decide};
use crate::error::CoreError;
use crate::store::{EventDraft, SettleOutcome};
use crate::supervisor::Supervisor;
#[derive(Debug, Default)]
pub(crate) struct Deadlines {
counting: Mutex<BTreeMap<InterventionId, (Intervention, Duration)>>,
adopted: AtomicBool,
}
impl Deadlines {
fn count(&self, intervention: &Intervention, reading: ClockReading) {
let due = reading.elapsed_at(intervention.expires_at);
self.counting()
.insert(intervention.id, (intervention.clone(), due));
}
fn adopt(&self, intervention: &Intervention, reading: ClockReading) {
let due = reading.elapsed_at(intervention.expires_at);
self.counting()
.entry(intervention.id)
.or_insert_with(|| (intervention.clone(), due));
}
fn forget(&self, intervention_id: InterventionId) {
self.counting().remove(&intervention_id);
}
fn due(&self, elapsed: Duration) -> Vec<Intervention> {
let mut due: Vec<(Duration, Intervention)> = self
.counting()
.values()
.filter(|(_, at)| *at <= elapsed)
.map(|(intervention, at)| (*at, intervention.clone()))
.collect();
due.sort_by_key(|(at, _)| *at);
due.into_iter()
.map(|(_, intervention)| intervention)
.collect()
}
fn counting(
&self,
) -> std::sync::MutexGuard<'_, BTreeMap<InterventionId, (Intervention, Duration)>> {
self.counting
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
const RESTORE_REASON: &str = "the bounded intervention expired";
#[must_use]
pub fn restoring_action(adjustable: Adjustable, prior_value: f64) -> PrintAction {
match adjustable {
Adjustable::Feedrate => PrintAction::SetFeedrateFactor {
factor: prior_value,
duration_s: None,
reason: RESTORE_REASON.to_owned(),
actor: Actor::System,
},
Adjustable::Flowrate => PrintAction::SetFlowrateFactor {
factor: prior_value,
duration_s: None,
reason: RESTORE_REASON.to_owned(),
actor: Actor::System,
},
Adjustable::ToolTarget { tool } => PrintAction::SetToolTargetC {
tool,
target_c: prior_value,
duration_s: None,
reason: RESTORE_REASON.to_owned(),
actor: Actor::System,
},
Adjustable::BedTarget => PrintAction::SetBedTargetC {
target_c: prior_value,
duration_s: None,
reason: RESTORE_REASON.to_owned(),
actor: Actor::System,
},
Adjustable::Fan => PrintAction::SetFanPercent {
percent: prior_value,
duration_s: None,
reason: RESTORE_REASON.to_owned(),
actor: Actor::System,
},
}
}
#[must_use]
pub fn rejection_detail(reason: &RejectionReason) -> String {
match reason {
RejectionReason::OutOfBounds {
adjustable,
requested,
allowed,
} => format!(
"{requested} is outside the {} to {} allowed for {adjustable}",
allowed.min, allowed.max
),
RejectionReason::ActorMayNotRequest {
actor_class,
action,
} => format!("{actor_class:?} may not request {action:?}"),
RejectionReason::NoActivePrint => "there is no active print to act on".to_owned(),
RejectionReason::InvalidFromState { state } => {
format!("this is not valid from {state:?}")
}
RejectionReason::MinIntervalNotElapsed {
interval_s,
since_last_s,
} => format!(
"the agent last acted {since_last_s}s ago and its minimum interval is {interval_s}s"
),
RejectionReason::UnsupportedAdjustable { adjustable } => {
format!("this printer has no {adjustable}")
}
RejectionReason::InsufficientFilament {
tool,
spool_name,
required_g,
buffer_g,
remaining_g,
..
} => format!(
"spool {spool_name} on tool {tool} holds {remaining_g}g, and the print needs \
{required_g}g and a {buffer_g}g buffer"
),
RejectionReason::UnverifiedSpool {
tool, spool_name, ..
} => format!("spool {spool_name} on tool {tool} is unverified"),
RejectionReason::AnalysisUnavailable {
file_name,
waited_s,
} => format!("{file_name} had no analysis after waiting {waited_s}s for one"),
RejectionReason::SpoolRefused { message, .. } => message.clone(),
RejectionReason::PrintAlreadyEnded => "this print's record has already ended".to_owned(),
RejectionReason::PrintStillActive { state } => {
format!("the printer shows this print's file still {state:?}")
}
RejectionReason::InterventionStillActive { intervention_id } => {
format!("intervention {intervention_id} has neither expired nor been restored")
}
RejectionReason::PrintNotResumable { recovery_event_id } => format!(
"recovery event {recovery_event_id} moved the printer while this print was paused, \
and resuming would print the rest of the layer at the wrong height"
),
}
}
impl Supervisor {
pub async fn sweep_expired(&self) -> Result<(), CoreError> {
self.adopt_left_active().await?;
for intervention in self.deadlines().due(self.clock().elapsed()) {
let _ = self.expire_intervention(&intervention).await;
}
Ok(())
}
async fn adopt_left_active(&self) -> Result<(), CoreError> {
let deadlines = self.deadlines();
if deadlines.adopted.load(Ordering::Acquire) {
return Ok(());
}
for intervention in self
.stores()
.actions
.due_interventions(Timestamp::latest())
.await?
{
deadlines.adopt(&intervention, self.started());
}
deadlines.adopted.store(true, Ordering::Release);
Ok(())
}
pub(crate) fn count_down(&self, intervention: &Intervention) {
self.deadlines()
.count(intervention, ClockReading::of(self.clock().as_ref()));
}
pub(crate) fn stop_counting_down(&self, intervention_id: InterventionId) {
self.deadlines().forget(intervention_id);
}
pub(crate) async fn expire_all_active(&self, print_id: PrintId) -> Result<(), CoreError> {
for intervention in self.stores().actions.active_interventions(print_id).await? {
let _ = self.expire_intervention(&intervention).await;
}
Ok(())
}
pub async fn expire_intervention(
&self,
intervention: &Intervention,
) -> Result<InterventionOutcome, CoreError> {
let outcome = self.expire_once(intervention).await?;
self.deadlines().forget(intervention.id);
Ok(outcome)
}
async fn expire_once(
&self,
intervention: &Intervention,
) -> Result<InterventionOutcome, CoreError> {
if intervention.outcome != InterventionOutcome::StillActive {
return Ok(intervention.outcome.clone());
}
let _expiring = self.expiring().acquire(intervention.print_id).await;
let still_active = self
.stores()
.actions
.active_interventions(intervention.print_id)
.await?
.iter()
.any(|active| active.id == intervention.id);
if !still_active {
return self
.settle(intervention, InterventionOutcome::RestoreUnavailable)
.await;
}
let Some(prior_value) = intervention.prior_value else {
return self
.settle(intervention, InterventionOutcome::RestoreUnavailable)
.await;
};
let outcome = self.restore(intervention, prior_value).await?;
self.settle(intervention, outcome).await
}
async fn restore(
&self,
intervention: &Intervention,
prior_value: f64,
) -> Result<InterventionOutcome, CoreError> {
let requested_at = self.clock().now();
let action = restoring_action(intervention.adjustable, prior_value);
let actor = action.actor().clone();
let print = self.stores().prints.print(intervention.print_id).await?;
let bounds = self
.bounds_for(print.as_ref(), intervention.print_id)
.await?;
let decision = decide(&DecisionInput {
action: &action,
actor: &actor,
requested_at,
print: print.as_ref(),
printer_state: None,
bounds: &bounds.effective,
envelope: &self.config().envelope,
since_last_agent_action: None,
});
let request = crate::records::ActionRequest {
action,
actor,
requested_at,
};
let issued = self.issue_action(request, decision, None).await?;
if let PolicyDecision::Rejected(reason) = &issued.record.decision {
return Ok(InterventionOutcome::RestoreFailed {
reason: rejection_detail(reason),
});
}
if let Some(error) = issued.printer_error() {
return Ok(InterventionOutcome::RestoreFailed {
reason: error.to_string(),
});
}
Ok(InterventionOutcome::Restored)
}
async fn settle(
&self,
intervention: &Intervention,
outcome: InterventionOutcome,
) -> Result<InterventionOutcome, CoreError> {
let settled = self
.stores()
.actions
.settle_intervention(intervention.id, outcome)
.await?;
Ok(match settled {
SettleOutcome::Settled {
intervention: settled,
} => {
self.append_expiry_event(intervention, settled.outcome.clone())
.await?;
settled.outcome
}
SettleOutcome::AlreadySettled { outcome } => outcome,
})
}
async fn append_expiry_event(
&self,
intervention: &Intervention,
outcome: InterventionOutcome,
) -> Result<(), CoreError> {
self.stores()
.events
.append_event(EventDraft {
print_id: Some(intervention.print_id),
source: crate::kinds::system_source(),
received_at: self.clock().now(),
body: printobserver_types::EventBody::of(
&crate::kinds::InterventionExpiredPayload {
intervention_id: intervention.id,
adjustable: intervention.adjustable,
outcome,
},
)?,
raw: None,
})
.await?;
Ok(())
}
}