use async_trait::async_trait;
use thiserror::Error;
use time::{Date, Duration, OffsetDateTime};
use crate::domain::{
CrossBorderSnapshot, ForecastPoint, Granularity, IntensityStats, LoadRecord, Measurement,
Region, RollupBucket, SpotPrice, Subscription, TimeRange, VisitStats, WeatherForecast,
};
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SourceError {
#[error("aucune donnée disponible pour la région {0}")]
NoData(Region),
#[error("source indisponible : {0}")]
Unavailable(String),
#[error("réponse de la source invalide : {0}")]
Invalid(String),
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum RepositoryError {
#[error("erreur de stockage : {0}")]
Backend(String),
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ForecastError {
#[error("prévision indisponible : {0}")]
Unavailable(String),
#[error("données insuffisantes pour prévoir")]
NotEnoughData,
}
#[async_trait]
pub trait Eco2mixSource: Send + Sync {
async fn latest(&self, region: Region) -> Result<Measurement, SourceError>;
async fn range(
&self,
region: Region,
range: TimeRange,
) -> Result<Vec<Measurement>, SourceError>;
}
#[async_trait]
pub trait Eco2mixArchive: Send + Sync {
async fn export_national(&self, range: TimeRange) -> Result<Vec<Measurement>, SourceError>;
async fn export_national_loads(&self, range: TimeRange)
-> Result<Vec<LoadRecord>, SourceError>;
async fn export_regional(&self, _range: TimeRange) -> Result<Vec<Measurement>, SourceError> {
Err(SourceError::Unavailable(
"export régional non pris en charge par cette archive".into(),
))
}
}
#[async_trait]
pub trait IntensityRepository: Send + Sync {
async fn upsert_many(&self, measurements: &[Measurement]) -> Result<usize, RepositoryError>;
async fn latest(
&self,
region: Region,
methodology_id: &str,
) -> Result<Option<Measurement>, RepositoryError>;
async fn latest_all(&self, methodology_id: &str) -> Result<Vec<Measurement>, RepositoryError> {
let mut out = Vec::with_capacity(1 + Region::METROPOLITAN.len());
for region in std::iter::once(Region::National).chain(Region::METROPOLITAN) {
if let Some(measurement) = self.latest(region, methodology_id).await? {
out.push(measurement);
}
}
Ok(out)
}
async fn range(
&self,
region: Region,
methodology_id: &str,
range: TimeRange,
) -> Result<Vec<Measurement>, RepositoryError>;
async fn stats(
&self,
region: Region,
methodology_id: &str,
range: TimeRange,
) -> Result<Option<IntensityStats>, RepositoryError>;
async fn rollup(
&self,
region: Region,
methodology_id: &str,
range: TimeRange,
granularity: Granularity,
) -> Result<Vec<RollupBucket>, RepositoryError>;
async fn refresh_rollups(&self) -> Result<(), RepositoryError>;
}
#[async_trait]
pub trait ConsumptionRepository: Send + Sync {
async fn upsert_loads(&self, loads: &[LoadRecord]) -> Result<usize, RepositoryError>;
async fn load_range(
&self,
region: Region,
range: TimeRange,
) -> Result<Vec<LoadRecord>, RepositoryError>;
}
#[async_trait]
pub trait ConsumptionSource: Send + Sync {
async fn recent_loads(&self, region: Region) -> Result<Vec<LoadRecord>, SourceError>;
}
#[async_trait]
pub trait WeatherRepository: Send + Sync {
async fn upsert_weather(&self, forecasts: &[WeatherForecast])
-> Result<usize, RepositoryError>;
async fn weather_range(
&self,
valid: TimeRange,
) -> Result<Vec<WeatherForecast>, RepositoryError>;
async fn weather_latest(
&self,
valid: TimeRange,
) -> Result<Vec<WeatherForecast>, RepositoryError>;
}
#[async_trait]
pub trait WeatherForecastSource: Send + Sync {
async fn current_forecast(&self) -> Result<Vec<WeatherForecast>, SourceError>;
}
#[async_trait]
pub trait CrossBorderSource: Send + Sync {
async fn recent_flows(&self) -> Result<Vec<CrossBorderSnapshot>, SourceError>;
}
#[async_trait]
pub trait CrossBorderRepository: Send + Sync {
async fn upsert_flows(
&self,
snapshots: &[CrossBorderSnapshot],
) -> Result<usize, RepositoryError>;
async fn flows_at(
&self,
at: OffsetDateTime,
) -> Result<Option<CrossBorderSnapshot>, RepositoryError>;
async fn flows_range(
&self,
range: TimeRange,
) -> Result<Vec<CrossBorderSnapshot>, RepositoryError>;
}
#[async_trait]
pub trait SpotPriceSource: Send + Sync {
async fn recent_prices(&self) -> Result<Vec<SpotPrice>, SourceError>;
}
#[async_trait]
pub trait SpotPriceRepository: Send + Sync {
async fn upsert_prices(&self, prices: &[SpotPrice]) -> Result<usize, RepositoryError>;
async fn price_at(&self, at: OffsetDateTime) -> Result<Option<SpotPrice>, RepositoryError>;
async fn price_range(&self, range: TimeRange) -> Result<Vec<SpotPrice>, RepositoryError>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApiTier {
Free,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiKeyRecord {
pub tier: ApiTier,
pub label: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiKeySummary {
pub key_hash: String,
pub tier: Option<ApiTier>,
pub label: String,
pub created_at: OffsetDateTime,
pub subscriptions: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyRevocation {
pub subscriptions_removed: u64,
}
#[async_trait]
pub trait ApiKeyRepository: Send + Sync {
async fn resolve(&self, key_hash: &str) -> Result<Option<ApiKeyRecord>, RepositoryError>;
async fn insert_key(
&self,
key_hash: &str,
tier: ApiTier,
label: &str,
) -> Result<(), RepositoryError>;
async fn list_keys(&self) -> Result<Vec<ApiKeySummary>, RepositoryError>;
async fn revoke_key(&self, key_hash: &str) -> Result<Option<KeyRevocation>, RepositoryError>;
}
#[async_trait]
pub trait SubscriptionRepository: Send + Sync {
async fn create(
&self,
subscription: &Subscription,
max_per_owner: usize,
) -> Result<bool, RepositoryError>;
async fn list_for_owner(
&self,
owner_key_hash: &str,
) -> Result<Vec<Subscription>, RepositoryError>;
async fn delete(&self, id: &str, owner_key_hash: &str) -> Result<bool, RepositoryError>;
async fn active(&self) -> Result<Vec<Subscription>, RepositoryError>;
async fn record_delivery(
&self,
id: &str,
delivered: bool,
max_consecutive_failures: u32,
) -> Result<bool, RepositoryError>;
async fn purge_disabled(&self, disabled_before: OffsetDateTime)
-> Result<u64, RepositoryError>;
}
#[derive(Debug, Clone)]
pub struct WebhookDelivery {
pub url: String,
pub body: String,
pub signature: String,
}
#[async_trait]
pub trait Notifier: Send + Sync {
async fn deliver(&self, delivery: &WebhookDelivery) -> Result<(), SourceError>;
}
#[async_trait]
pub trait VisitCounter: Send + Sync {
async fn record_visit(&self, visitor: &str, day: Date) -> Result<VisitStats, RepositoryError>;
async fn visit_stats(&self) -> Result<VisitStats, RepositoryError>;
}
#[async_trait]
pub trait ForecastModel: Send + Sync {
async fn forecast(
&self,
region: Region,
methodology_id: &str,
from: OffsetDateTime,
horizon: Duration,
) -> Result<Vec<ForecastPoint>, ForecastError>;
}
pub trait Clock: Send + Sync {
fn now(&self) -> OffsetDateTime;
}