use core::future::Future;
use core::pin::Pin;
use std::path::PathBuf;
use std::sync::Arc;
use crate::records::{
ActionId, ActionRecord, ActionRequest, Actor, ChargeKey, ChargedFilament, ExecutionOutcome,
FilePosition, ImageRecord, Intervention, InterventionId, InterventionOutcome, JobManifest,
ManifestNarrowing, PendingCharge, PolicyDecision, PrintOutcome, PrintRecord, SpoolId,
SpoolRecord, SpoolTrust, UnverifiedReason, UnverifiedReasonKind,
};
use printobserver_printer_api::{Adjustable, PrinterState};
use printobserver_supervisor_api::SupervisionSession;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_types::{
EventBody, EventId, EventKind, EventRecord, EventSource, ImageId, PrintId, RawBytes, Timestamp,
};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub const DEFAULT_HISTORY_WINDOW: u32 = 100;
pub const MAX_HISTORY_LIMIT: u32 = 1_000;
pub fn resolve_history_limit(limit: Option<u32>) -> Result<u32, StoreError> {
match limit {
None => Ok(DEFAULT_HISTORY_WINDOW),
Some(asked_for) if asked_for <= MAX_HISTORY_LIMIT => Ok(asked_for),
Some(asked_for) => Err(StoreError::LimitRefused {
limit: MAX_HISTORY_LIMIT,
asked_for,
}),
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub struct EventDraft {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub print_id: Option<PrintId>,
pub source: EventSource,
pub received_at: Timestamp,
#[serde(flatten)]
pub body: EventBody,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub raw: Option<RawBytes>,
}
impl EventDraft {
#[must_use]
pub const fn kind(&self) -> &EventKind {
&self.body.kind
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct HistoryQuery {
pub print_id: PrintId,
pub kinds: Vec<EventKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub since: Option<Timestamp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub until: Option<Timestamp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<u32>,
}
impl HistoryQuery {
pub fn resolved_limit(&self) -> Result<u32, StoreError> {
resolve_history_limit(self.limit)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoredQuery {
pub after: Option<EventId>,
pub print_id: Option<PrintId>,
pub limit: Option<u32>,
}
impl StoredQuery {
pub fn resolved_limit(&self) -> Result<u32, StoreError> {
resolve_history_limit(self.limit)
}
}
pub type StoredSignal = Arc<dyn Fn() + Send + Sync>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImageLookup {
Found {
record: ImageRecord,
path: PathBuf,
},
FileMissing {
record: ImageRecord,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum SettleOutcome {
Settled {
intervention: Intervention,
},
AlreadySettled {
outcome: InterventionOutcome,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct AuditPage {
pub events: Vec<EventRecord>,
pub next: Option<EventId>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StoreError {
ConstraintRefused {
constraint: String,
},
NotFound {
what: String,
},
LimitRefused {
limit: u32,
asked_for: u32,
},
Database {
detail: String,
},
Io {
detail: String,
},
}
impl core::fmt::Display for StoreError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::ConstraintRefused { constraint } => {
write!(formatter, "the constraint {constraint} refused the write")
}
Self::NotFound { what } => write!(formatter, "there is no {what}"),
Self::LimitRefused { limit, asked_for } => {
write!(
formatter,
"{asked_for} was asked for, and the limit is {limit}"
)
}
Self::Database { detail } => write!(formatter, "the database failed: {detail}"),
Self::Io { detail } => write!(formatter, "reading or writing failed: {detail}"),
}
}
}
impl core::error::Error for StoreError {}
pub trait PrintStore: Send + Sync {
fn open_print(
&self,
provider_print_id: Option<i64>,
file_name: Option<String>,
) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
fn print(&self, print_id: PrintId) -> BoxFuture<'_, Result<Option<PrintRecord>, StoreError>>;
fn open_prints(&self) -> BoxFuture<'_, Result<Vec<PrintRecord>, StoreError>>;
fn prints(&self) -> BoxFuture<'_, Result<Vec<PrintRecord>, StoreError>>;
fn attach_obico_print(
&self,
print_id: PrintId,
obico_print_id: i64,
) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
fn record_job_sighting(
&self,
print_id: PrintId,
job_started_at: Timestamp,
job_print_time_s: Option<i64>,
) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
fn print_by_provider_id(
&self,
provider_print_id: i64,
) -> BoxFuture<'_, Result<Option<PrintRecord>, StoreError>>;
fn end_print(
&self,
print_id: PrintId,
state: PrinterState,
ended_at: Timestamp,
reason: String,
) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
fn record_narrowing(
&self,
print_id: PrintId,
narrowing: ManifestNarrowing,
) -> BoxFuture<'_, Result<PrintRecord, StoreError>>;
fn put_manifest(
&self,
print_id: PrintId,
manifest: JobManifest,
) -> BoxFuture<'_, Result<(), StoreError>>;
fn manifest(&self, print_id: PrintId)
-> BoxFuture<'_, Result<Option<JobManifest>, StoreError>>;
}
pub trait EventStore: Send + Sync {
fn append_event(&self, draft: EventDraft) -> BoxFuture<'_, Result<EventRecord, StoreError>>;
fn history(&self, query: HistoryQuery) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
fn audit_page(
&self,
print_id: PrintId,
after: Option<EventId>,
page_size: u32,
) -> BoxFuture<'_, Result<AuditPage, StoreError>>;
fn stored_after(
&self,
query: StoredQuery,
) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
fn newest_stored(&self) -> BoxFuture<'_, Result<Option<EventId>, StoreError>>;
fn on_stored(&self, signal: StoredSignal);
}
pub trait ImageStore: Send + Sync {
fn put_image(
&self,
print_id: PrintId,
event_id: EventId,
source_url: Option<String>,
content_type: String,
bytes: RawBytes,
) -> BoxFuture<'_, Result<ImageRecord, StoreError>>;
fn image(&self, image_id: ImageId) -> BoxFuture<'_, Result<ImageLookup, StoreError>>;
}
pub trait ActionStore: Send + Sync {
fn record_action(
&self,
request: ActionRequest,
decision: PolicyDecision,
) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
fn record_execution(
&self,
action_id: ActionId,
outcome: ExecutionOutcome,
) -> BoxFuture<'_, Result<ActionRecord, StoreError>>;
fn open_intervention(
&self,
action_id: ActionId,
adjustable: Adjustable,
prior_value: Option<f64>,
applied_value: f64,
applied_at: Timestamp,
expires_at: Timestamp,
) -> BoxFuture<'_, Result<Intervention, StoreError>>;
fn settle_intervention(
&self,
intervention_id: InterventionId,
outcome: InterventionOutcome,
) -> BoxFuture<'_, Result<SettleOutcome, StoreError>>;
fn due_interventions(
&self,
at: Timestamp,
) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
fn active_interventions(
&self,
print_id: PrintId,
) -> BoxFuture<'_, Result<Vec<Intervention>, StoreError>>;
}
pub trait SessionStore: Send + Sync {
fn put_session(&self, session: SupervisionSession) -> BoxFuture<'_, Result<(), StoreError>>;
fn session(
&self,
print_id: PrintId,
) -> BoxFuture<'_, Result<Option<SupervisionSession>, StoreError>>;
}
#[derive(Debug, Clone, PartialEq)]
pub struct NewSpool {
pub name: String,
pub material: String,
pub color: Option<String>,
pub diameter_mm: f64,
pub density_g_cm3: f64,
pub initial_g: f64,
pub remaining_g: f64,
pub tare_g: Option<f64>,
pub loaded_on_tool: Option<i64>,
pub trust: SpoolTrust,
pub registered_at: Timestamp,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChargeIdentity {
key: ChargeKey,
linked_print: Option<PrintId>,
}
impl ChargeIdentity {
#[must_use]
pub const fn of(key: ChargeKey) -> Self {
Self {
key,
linked_print: None,
}
}
pub const fn linked(key: ChargeKey, print_id: PrintId) -> Result<Self, ChargeKey> {
match key {
ChargeKey::Print { .. } => Err(key),
ChargeKey::Unobserved { .. } => Ok(Self {
key,
linked_print: Some(print_id),
}),
}
}
#[must_use]
pub const fn key(&self) -> &ChargeKey {
&self.key
}
#[must_use]
pub const fn tool(&self) -> i64 {
self.key.tool()
}
#[must_use]
pub const fn print_id(&self) -> Option<PrintId> {
match self.key.watched_print() {
Some(print_id) => Some(print_id),
None => self.linked_print,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Charge {
pub identity: ChargeIdentity,
pub length_mm: f64,
pub charged: Option<ChargedFilament>,
pub at: Timestamp,
pub event: EventDraft,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ChargeRecord {
pub identity: ChargeIdentity,
pub length_mm: f64,
pub charged: Option<ChargedFilament>,
pub at: Timestamp,
pub event_id: EventId,
}
impl ChargeRecord {
#[must_use]
pub fn spool_id(&self) -> Option<SpoolId> {
self.charged.as_ref().map(|charged| charged.spool_id)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Pend {
pub pending: PendingCharge,
pub event: EventDraft,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SpoolMutation {
pub spool_id: SpoolId,
pub change: SpoolChange,
pub at: Timestamp,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SpoolChange {
Load {
tool: i64,
event: EventDraft,
},
Unload {
event: EventDraft,
},
SetRemaining {
remaining_g: f64,
event: EventDraft,
},
MarkUnverified {
reason: UnverifiedReason,
event: EventDraft,
},
ClearMarks {
kinds: Vec<UnverifiedReasonKind>,
},
Retire {
event: EventDraft,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct SpoolWrite {
pub spools: Vec<SpoolRecord>,
pub events: Vec<EventRecord>,
pub charges: Vec<ChargeRecord>,
pub pending: Vec<PendingCharge>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Settlement {
Settled {
at: Timestamp,
events: Vec<EventRecord>,
},
AlreadySettled {
at: Timestamp,
outcome: PrintOutcome,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileTally {
pub file_name: String,
pub origin: String,
pub generation: u32,
pub successes: i64,
pub failures: i64,
pub observed_at: Timestamp,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimelineQuery {
pub kinds: Vec<EventKind>,
pub since: Option<Timestamp>,
pub until: Option<Timestamp>,
pub spool_id: Option<SpoolId>,
pub before: Option<EventId>,
pub limit: Option<u32>,
}
impl TimelineQuery {
pub fn resolved_limit(&self) -> Result<u32, StoreError> {
resolve_history_limit(self.limit)
}
pub fn resolved_kinds(&self) -> Result<Vec<EventKind>, StoreError> {
let refused = || StoreError::ConstraintRefused {
constraint: "timeline.kinds".to_owned(),
};
if self.kinds.is_empty() {
return crate::kinds::TIMELINE_KINDS
.iter()
.map(|kind| EventKind::new(*kind).map_err(|_| refused()))
.collect();
}
if self
.kinds
.iter()
.any(|kind| !crate::kinds::TIMELINE_KINDS.contains(&kind.as_str()))
{
return Err(refused());
}
Ok(self.kinds.clone())
}
}
pub trait FilamentStore: Send + Sync {
fn register_spool(
&self,
spool: NewSpool,
source: EventSource,
actor: Actor,
reason: String,
) -> BoxFuture<'_, Result<(SpoolRecord, EventRecord), StoreError>>;
fn apply_spool_changes(
&self,
changes: Vec<SpoolMutation>,
charges: Vec<Charge>,
pends: Vec<Pend>,
) -> BoxFuture<'_, Result<SpoolWrite, StoreError>>;
fn settle_print(
&self,
print_id: PrintId,
outcome: PrintOutcome,
ended: EventDraft,
charges: Vec<Charge>,
pends: Vec<Pend>,
marks: Vec<SpoolMutation>,
) -> BoxFuture<'_, Result<Settlement, StoreError>>;
fn print_settlement(
&self,
print_id: PrintId,
) -> BoxFuture<'_, Result<Option<(Timestamp, PrintOutcome)>, StoreError>>;
fn charges(&self, print_id: PrintId) -> BoxFuture<'_, Result<Vec<ChargeRecord>, StoreError>>;
fn pending_charges(
&self,
tool: Option<i64>,
) -> BoxFuture<'_, Result<Vec<PendingCharge>, StoreError>>;
fn spool(&self, id: SpoolId) -> BoxFuture<'_, Result<Option<SpoolRecord>, StoreError>>;
fn spools(&self, include_retired: bool) -> BoxFuture<'_, Result<Vec<SpoolRecord>, StoreError>>;
fn loaded_spools(&self) -> BoxFuture<'_, Result<Vec<SpoolRecord>, StoreError>>;
fn record_file_position(
&self,
print_id: PrintId,
position: FilePosition,
) -> BoxFuture<'_, Result<(), StoreError>>;
fn file_position(
&self,
print_id: PrintId,
) -> BoxFuture<'_, Result<Option<FilePosition>, StoreError>>;
fn file_tallies(&self) -> BoxFuture<'_, Result<Vec<FileTally>, StoreError>>;
fn account_tallies(
&self,
tallies: Vec<FileTally>,
charges: Vec<Charge>,
marks: Vec<SpoolMutation>,
events: Vec<EventDraft>,
) -> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
}
pub trait TimelineStore: Send + Sync {
fn timeline(&self, query: TimelineQuery)
-> BoxFuture<'_, Result<Vec<EventRecord>, StoreError>>;
}
#[derive(Clone)]
pub struct Stores {
pub prints: Arc<dyn PrintStore>,
pub events: Arc<dyn EventStore>,
pub images: Arc<dyn ImageStore>,
pub actions: Arc<dyn ActionStore>,
pub sessions: Arc<dyn SessionStore>,
pub filament: Arc<dyn FilamentStore>,
pub timeline: Arc<dyn TimelineStore>,
}
impl Stores {
pub fn of<S>(store: Arc<S>) -> Self
where
S: PrintStore
+ EventStore
+ ImageStore
+ ActionStore
+ SessionStore
+ FilamentStore
+ TimelineStore
+ 'static,
{
Self {
prints: Arc::clone(&store) as Arc<dyn PrintStore>,
events: Arc::clone(&store) as Arc<dyn EventStore>,
images: Arc::clone(&store) as Arc<dyn ImageStore>,
actions: Arc::clone(&store) as Arc<dyn ActionStore>,
sessions: Arc::clone(&store) as Arc<dyn SessionStore>,
filament: Arc::clone(&store) as Arc<dyn FilamentStore>,
timeline: store as Arc<dyn TimelineStore>,
}
}
}