use async_trait::async_trait;
use std::sync::Arc;
use crate::core::{Access, Grant};
use crate::model::{
ClientId, ClientName, Event, EventRequest, ObjectId, ObjectType, Program, ProgramName,
ProgramRequest, Report, ReportRequest, Resource, ResourceName, Subscription,
SubscriptionRequest, Timestamp, Ven, VenName,
};
use crate::vtn::notify::Fanout;
mod memory;
mod outbox;
#[cfg(feature = "postgres")]
mod postgres;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
mod sql;
#[cfg(feature = "sqlite")]
mod sqlite;
#[cfg(test)]
mod suite;
pub use memory::MemoryStorage;
pub use outbox::{
BreakerPolicy, DeadLetter, OutboxId, OutboxStats, Queued, RetryPolicy, SubscriberHealth,
};
#[cfg(feature = "postgres")]
#[cfg_attr(docsrs, doc(cfg(feature = "postgres")))]
pub use postgres::PostgresStorage;
#[cfg(feature = "sqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "sqlite")))]
pub use sqlite::SqliteStorage;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum StorageError {
#[error("{object_type} {id} not found")]
NotFound {
object_type: ObjectType,
id: ObjectId,
},
#[error("{object_type} with {field} {value:?} already exists")]
Conflict {
object_type: ObjectType,
field: &'static str,
value: String,
},
#[error("{field} {value:?} does not reference an existing object")]
DanglingReference {
field: &'static str,
value: String,
},
#[error("storage backend unavailable: {0}")]
Unavailable(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Page {
pub skip: usize,
pub limit: usize,
}
impl Default for Page {
fn default() -> Self {
Self {
skip: 0,
limit: Self::MAX_LIMIT,
}
}
}
impl Page {
pub const MAX_LIMIT: usize = crate::model::MAX_PAGE_LIMIT;
pub fn apply<T: Clone>(&self, items: &[T]) -> Vec<T> {
items
.iter()
.skip(self.skip)
.take(self.limit)
.cloned()
.collect()
}
}
pub fn prefix(kind: ObjectType) -> &'static str {
match kind {
ObjectType::Program => "prg",
ObjectType::Event => "evt",
ObjectType::Report => "rpt",
ObjectType::Subscription => "sub",
ObjectType::Ven => "ven",
ObjectType::Resource => "res",
}
}
pub fn sequenced_id(kind: ObjectType, n: i64) -> ObjectId {
ObjectId::new(format!("{}-{n:08}", prefix(kind))).expect("generated ids are valid")
}
pub fn order_by_creation<T>(items: &mut [T], key: impl Fn(&T) -> (Timestamp, &ObjectId)) {
items.sort_by(|a, b| {
let (a_time, a_id) = key(a);
let (b_time, b_id) = key(b);
a_time.cmp(&b_time).then_with(|| a_id.cmp(b_id))
});
}
#[derive(Debug, Clone)]
pub struct ProgramQuery {
pub program_name: Option<ProgramName>,
pub access: Access,
pub page: Page,
}
#[derive(Debug, Clone)]
pub struct EventQuery {
pub program_id: Option<ObjectId>,
pub active_at: Option<Timestamp>,
pub access: Access,
pub page: Page,
}
#[derive(Debug, Clone)]
pub struct ReportQuery {
pub program_id: Option<ObjectId>,
pub event_id: Option<ObjectId>,
pub client_name: Option<ClientName>,
pub access: Access,
pub page: Page,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OwnerKind {
BusinessLogic,
Ven,
}
impl OwnerKind {
pub const fn as_str(self) -> &'static str {
match self {
OwnerKind::BusinessLogic => "BL",
OwnerKind::Ven => "VEN",
}
}
pub fn from_str_or_ven(raw: &str) -> Self {
if raw == OwnerKind::BusinessLogic.as_str() {
OwnerKind::BusinessLogic
} else {
OwnerKind::Ven
}
}
pub const fn is_business_logic(self) -> bool {
matches!(self, OwnerKind::BusinessLogic)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Subscriber {
pub subscription: Subscription,
pub owner: OwnerKind,
}
#[derive(Debug, Clone)]
pub struct SubscriptionQuery {
pub program_id: Option<ObjectId>,
pub client_name: Option<ClientName>,
pub objects: Vec<ObjectType>,
pub access: Access,
pub page: Page,
}
#[derive(Debug, Clone)]
pub struct VenQuery {
pub ven_name: Option<VenName>,
pub access: Access,
pub page: Page,
}
#[derive(Debug, Clone)]
pub struct ResourceQuery {
pub ven_id: Option<ObjectId>,
pub resource_name: Option<ResourceName>,
pub access: Access,
pub page: Page,
}
#[async_trait]
pub trait Storage: Send + Sync + 'static {
async fn healthy(&self) -> bool;
async fn create_program(
&self,
request: ProgramRequest,
now: Timestamp,
fanout: &Fanout,
) -> Result<Program, StorageError>;
async fn get_program(&self, id: &ObjectId) -> Result<Program, StorageError>;
async fn list_programs(&self, query: &ProgramQuery) -> Result<Vec<Program>, StorageError>;
async fn update_program(
&self,
id: &ObjectId,
request: ProgramRequest,
now: Timestamp,
fanout: &Fanout,
) -> Result<Program, StorageError>;
async fn delete_program(&self, id: &ObjectId, fanout: &Fanout)
-> Result<Program, StorageError>;
async fn create_event(
&self,
request: EventRequest,
now: Timestamp,
fanout: &Fanout,
) -> Result<Event, StorageError>;
async fn get_event(&self, id: &ObjectId) -> Result<Event, StorageError>;
async fn list_events(&self, query: &EventQuery) -> Result<Vec<Event>, StorageError>;
async fn update_event(
&self,
id: &ObjectId,
request: EventRequest,
now: Timestamp,
fanout: &Fanout,
) -> Result<Event, StorageError>;
async fn delete_event(&self, id: &ObjectId, fanout: &Fanout) -> Result<Event, StorageError>;
async fn create_report(
&self,
request: ReportRequest,
owner: Option<ClientId>,
now: Timestamp,
fanout: &Fanout,
) -> Result<Report, StorageError>;
async fn get_report(&self, id: &ObjectId) -> Result<Report, StorageError>;
async fn list_reports(&self, query: &ReportQuery) -> Result<Vec<Report>, StorageError>;
async fn update_report(
&self,
id: &ObjectId,
request: ReportRequest,
now: Timestamp,
fanout: &Fanout,
) -> Result<Report, StorageError>;
async fn delete_report(&self, id: &ObjectId, fanout: &Fanout) -> Result<Report, StorageError>;
async fn create_subscription(
&self,
request: SubscriptionRequest,
owner: ClientId,
owner_kind: OwnerKind,
now: Timestamp,
fanout: &Fanout,
) -> Result<Subscription, StorageError>;
async fn get_subscription(&self, id: &ObjectId) -> Result<Subscription, StorageError>;
async fn list_subscriptions(
&self,
query: &SubscriptionQuery,
) -> Result<Vec<Subscription>, StorageError>;
async fn subscribers(
&self,
object_types: &[ObjectType],
) -> Result<Vec<Subscriber>, StorageError>;
async fn update_subscription(
&self,
id: &ObjectId,
request: SubscriptionRequest,
now: Timestamp,
fanout: &Fanout,
) -> Result<Subscription, StorageError>;
async fn delete_subscription(
&self,
id: &ObjectId,
fanout: &Fanout,
) -> Result<Subscription, StorageError>;
async fn create_ven(&self, ven: Ven, fanout: &Fanout) -> Result<Ven, StorageError>;
async fn get_ven(&self, id: &ObjectId) -> Result<Ven, StorageError>;
async fn get_ven_by_client(&self, client_id: &ClientId) -> Result<Option<Ven>, StorageError>;
async fn list_vens(&self, query: &VenQuery) -> Result<Vec<Ven>, StorageError>;
async fn update_ven(
&self,
id: &ObjectId,
ven: Ven,
fanout: &Fanout,
) -> Result<Ven, StorageError>;
async fn delete_ven(&self, id: &ObjectId, fanout: &Fanout) -> Result<Ven, StorageError>;
async fn create_resource(
&self,
resource: Resource,
fanout: &Fanout,
) -> Result<Resource, StorageError>;
async fn get_resource(&self, id: &ObjectId) -> Result<Resource, StorageError>;
async fn list_resources(&self, query: &ResourceQuery) -> Result<Vec<Resource>, StorageError>;
async fn update_resource(
&self,
id: &ObjectId,
resource: Resource,
fanout: &Fanout,
) -> Result<Resource, StorageError>;
async fn delete_resource(
&self,
id: &ObjectId,
fanout: &Fanout,
) -> Result<Resource, StorageError>;
async fn grant_for(&self, client_id: &ClientId) -> Result<Grant, StorageError>;
async fn all_grants(&self) -> Result<Vec<(ObjectId, ClientId, Grant)>, StorageError>;
async fn enqueue(
&self,
deliveries: Vec<crate::vtn::notify::Delivery>,
now: Timestamp,
) -> Result<(), StorageError>;
async fn claim_due(
&self,
now: Timestamp,
limit: usize,
lease: core::time::Duration,
owner: &str,
) -> Result<Vec<Queued>, StorageError>;
async fn complete(&self, id: OutboxId) -> Result<(), StorageError>;
async fn record_failure(
&self,
id: OutboxId,
failure: &crate::vtn::notify::DeliveryFailure,
now: Timestamp,
policy: &RetryPolicy,
) -> Result<bool, StorageError>;
async fn await_outbox(&self, timeout: core::time::Duration) {
tokio::time::sleep(timeout).await;
}
async fn outbox_stats(&self, now: Timestamp) -> Result<OutboxStats, StorageError>;
async fn dead_letters(&self, limit: usize) -> Result<Vec<DeadLetter>, StorageError>;
async fn revive_dead(&self, now: Timestamp) -> Result<u64, StorageError>;
async fn note_delivery(
&self,
subscription: &ObjectId,
abandoned: bool,
now: Timestamp,
policy: &BreakerPolicy,
error: Option<&str>,
) -> Result<bool, StorageError>;
async fn subscriber_health(&self) -> Result<Vec<SubscriberHealth>, StorageError>;
async fn clear_subscriber_health(&self) -> Result<u64, StorageError>;
async fn purge_reports(&self, before: Timestamp, limit: usize) -> Result<u64, StorageError>;
async fn report_stats(&self, now: Timestamp) -> Result<ReportStats, StorageError>;
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportStats {
pub count: u64,
pub oldest_seconds: Option<i64>,
}
pub type SharedStorage = Arc<dyn Storage>;