use std::sync::Arc;
use printobserver_core::store::{ActionStore, EventDraft, EventStore, PrintStore, SessionStore};
use printobserver_core::{CoreError, Supervisor, system_source};
use printobserver_core::{Intervention, InterventionId, InterventionOutcome};
use printobserver_printer_api::Adjustable;
use printobserver_types::contract::Sample;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{EventBody, EventPayload, PrintId, Timestamp};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
rename_all = "snake_case",
deny_unknown_fields
)]
#[schemars(crate = "printobserver_types::schemars")]
pub enum StartupOutcome {
PrintAdopted,
SessionResumed {
session_name: String,
},
InterventionExpired {
intervention_id: InterventionId,
adjustable: Adjustable,
outcome: InterventionOutcome,
},
}
impl Sample for StartupOutcome {
fn sample_full() -> Self {
Self::InterventionExpired {
intervention_id: InterventionId::sample_full(),
adjustable: Adjustable::Fan,
outcome: InterventionOutcome::Restored,
}
}
fn sample_alternates() -> Vec<Self> {
vec![
Self::PrintAdopted,
Self::SessionResumed {
session_name: "watch-4211".to_owned(),
},
]
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct StartupReconciliationPayload {
pub print_id: PrintId,
pub outcome: StartupOutcome,
}
impl EventPayload for StartupReconciliationPayload {
const KIND: &'static str = "startup_reconciliation";
}
impl Sample for StartupReconciliationPayload {
fn sample_full() -> Self {
Self {
print_id: PrintId::sample_full(),
outcome: StartupOutcome::sample_full(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Reconciliation {
pub adopted: Vec<PrintId>,
pub resumed: Vec<PrintId>,
pub expired: Vec<InterventionId>,
}
pub async fn overdue(
actions: &Arc<dyn ActionStore>,
at: Timestamp,
) -> Result<Vec<Intervention>, CoreError> {
Ok(actions.due_interventions(at).await?)
}
#[derive(Clone)]
pub struct ReconcileStores {
pub prints: Arc<dyn PrintStore>,
pub sessions: Arc<dyn SessionStore>,
pub events: Arc<dyn EventStore>,
}
pub async fn reconcile(
supervisor: &Arc<Supervisor>,
stores: &ReconcileStores,
overdue: Vec<Intervention>,
) -> Result<Reconciliation, CoreError> {
let mut found = Reconciliation::default();
for print in stores.prints.open_prints().await? {
record(&stores.events, print.id, StartupOutcome::PrintAdopted).await?;
found.adopted.push(print.id);
let Some(session) = stores.sessions.session(print.id).await? else {
continue;
};
if session.closed_at.is_some() {
continue;
}
record(
&stores.events,
print.id,
StartupOutcome::SessionResumed {
session_name: session.session_name,
},
)
.await?;
found.resumed.push(print.id);
}
for intervention in overdue {
let outcome = supervisor.expire_intervention(&intervention).await?;
record(
&stores.events,
intervention.print_id,
StartupOutcome::InterventionExpired {
intervention_id: intervention.id,
adjustable: intervention.adjustable,
outcome,
},
)
.await?;
found.expired.push(intervention.id);
}
Ok(found)
}
async fn record(
events: &Arc<dyn EventStore>,
print_id: PrintId,
outcome: StartupOutcome,
) -> Result<(), CoreError> {
events
.append_event(EventDraft {
print_id: Some(print_id),
source: system_source(),
received_at: Timestamp::now(),
body: EventBody::of(&StartupReconciliationPayload { print_id, outcome })?,
raw: None,
})
.await?;
Ok(())
}