use core::future::Future;
use core::pin::Pin;
use std::path::PathBuf;
use std::sync::Arc;
use crate::records::{
ActionId, ActionRecord, ActionRequest, ExecutionOutcome, ImageRecord, Intervention,
InterventionId, InterventionOutcome, JobManifest, ManifestNarrowing, PolicyDecision,
PrintRecord,
};
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 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 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>>;
}
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(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>,
}
impl Stores {
pub fn of<S>(store: Arc<S>) -> Self
where
S: PrintStore + EventStore + ImageStore + ActionStore + SessionStore + '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: store as Arc<dyn SessionStore>,
}
}
}