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, EventId, 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 closed: Vec<PrintId>,
pub adopted: Vec<PrintId>,
pub resumed: Vec<PrintId>,
pub expired: Vec<InterventionId>,
pub unobserved: UnobservedAccounting,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnobservedAccounting {
Accounted(Vec<EventId>),
Skipped(String),
}
impl Default for UnobservedAccounting {
fn default() -> Self {
Self::Accounted(Vec::new())
}
}
impl UnobservedAccounting {
#[must_use]
pub fn accounted(&self) -> &[EventId] {
match self {
Self::Accounted(written) => written,
Self::Skipped(_) => &[],
}
}
#[must_use]
pub fn skipped(&self) -> Option<&str> {
match self {
Self::Accounted(_) => None,
Self::Skipped(why) => Some(why),
}
}
}
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 {
closed: supervisor.settle_with_printer().await?.closed,
..Reconciliation::default()
};
match supervisor.account_unobserved_prints().await {
Ok(written) => {
found.unobserved =
UnobservedAccounting::Accounted(written.iter().map(|event| event.id).collect());
}
Err(CoreError::Printer(error)) => {
found.unobserved = UnobservedAccounting::Skipped(format!(
"the printer could not be read ({error}), so the prints it counted while \
nothing was watching were not accounted on this start; the next start that \
reaches it accounts them"
));
}
Err(error) => return Err(error),
}
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
.into_iter()
.filter(|overdue| !found.closed.contains(&overdue.print_id))
{
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(())
}