use async_trait::async_trait;
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use adk_core::{RunState, UsageVector};
use crate::bus::SpendDelta;
use crate::error::Result;
use crate::partition::PartitionId;
use crate::process::ProcessMeta;
use crate::sched::QueueClass;
use crate::wake::WakeSet;
#[cfg(feature = "firestore")]
mod agenda_firestore;
mod agenda_memory;
#[cfg(feature = "mongodb")]
mod agenda_mongodb;
#[cfg(feature = "neo4j")]
mod agenda_neo4j;
#[cfg(feature = "redis")]
mod agenda_redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod agenda_sql;
#[cfg(feature = "firestore")]
mod agent_firestore;
mod agent_memory;
#[cfg(feature = "mongodb")]
mod agent_mongodb;
#[cfg(feature = "neo4j")]
mod agent_neo4j;
#[cfg(feature = "redis")]
mod agent_redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod agent_sql;
mod bundle;
#[cfg(feature = "charter")]
pub(crate) mod charter_memory;
#[cfg(all(feature = "charter", feature = "redis"))]
pub(crate) mod charter_redis;
#[cfg(all(feature = "charter", any(feature = "sqlite", feature = "postgres")))]
pub(crate) mod charter_sql;
#[cfg(all(feature = "drivers", feature = "firestore"))]
mod driver_firestore;
#[cfg(feature = "drivers")]
mod driver_memory;
#[cfg(all(feature = "drivers", feature = "mongodb"))]
mod driver_mongodb;
#[cfg(all(feature = "drivers", feature = "neo4j"))]
mod driver_neo4j;
#[cfg(all(feature = "drivers", feature = "postgres"))]
mod driver_postgres;
#[cfg(all(feature = "drivers", feature = "redis"))]
mod driver_redis;
#[cfg(all(feature = "drivers", any(feature = "sqlite", feature = "postgres")))]
mod driver_sql;
#[cfg(all(feature = "drivers", feature = "sqlite"))]
mod driver_sqlite;
#[cfg(feature = "firestore")]
mod firestore;
#[cfg(all(feature = "proc", feature = "firestore"))]
mod ledger_firestore;
#[cfg(feature = "proc")]
mod ledger_memory;
#[cfg(all(feature = "proc", feature = "mongodb"))]
mod ledger_mongodb;
#[cfg(all(feature = "proc", feature = "neo4j"))]
mod ledger_neo4j;
#[cfg(all(feature = "proc", feature = "redis"))]
mod ledger_redis;
#[cfg(all(feature = "proc", any(feature = "sqlite", feature = "postgres")))]
pub(crate) mod ledger_sql;
mod memory;
#[cfg(feature = "mongodb")]
mod mongodb;
#[cfg(feature = "neo4j")]
mod neo4j;
#[cfg(feature = "firestore")]
mod partition_firestore;
mod partition_memory;
#[cfg(feature = "mongodb")]
mod partition_mongodb;
#[cfg(feature = "neo4j")]
mod partition_neo4j;
#[cfg(feature = "redis")]
mod partition_redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod partition_sql;
#[cfg(feature = "postgres")]
mod postgres;
#[cfg(feature = "redis")]
mod redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
mod sql;
#[cfg(feature = "sqlite")]
mod sqlite;
#[cfg(feature = "firestore")]
mod watermark_firestore;
mod watermark_memory;
#[cfg(feature = "mongodb")]
mod watermark_mongodb;
#[cfg(feature = "neo4j")]
mod watermark_neo4j;
#[cfg(feature = "redis")]
mod watermark_redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod watermark_sql;
#[cfg(feature = "firestore")]
pub use agenda_firestore::FirestoreAgendaStore;
pub use agenda_memory::InMemoryAgendaStore;
#[cfg(feature = "mongodb")]
pub use agenda_mongodb::MongoAgendaStore;
#[cfg(feature = "neo4j")]
pub use agenda_neo4j::Neo4jAgendaStore;
#[cfg(feature = "redis")]
pub use agenda_redis::RedisAgendaStore;
#[cfg(feature = "postgres")]
pub use agenda_sql::PostgresAgendaStore;
#[cfg(feature = "sqlite")]
pub use agenda_sql::SqliteAgendaStore;
#[cfg(feature = "firestore")]
pub use agent_firestore::FirestoreAgentStore;
pub use agent_memory::InMemoryAgentStore;
#[cfg(feature = "mongodb")]
pub use agent_mongodb::MongoAgentStore;
#[cfg(feature = "neo4j")]
pub use agent_neo4j::Neo4jAgentStore;
#[cfg(feature = "redis")]
pub use agent_redis::RedisAgentStore;
#[cfg(feature = "postgres")]
pub use agent_sql::PostgresAgentStore;
#[cfg(feature = "sqlite")]
pub use agent_sql::SqliteAgentStore;
pub use bundle::{KernelStores, StoreOrigin, StoreUse};
#[cfg(all(feature = "drivers", feature = "firestore"))]
pub use driver_firestore::FirestoreDriverStore;
#[cfg(feature = "drivers")]
pub use driver_memory::InMemoryDriverStore;
#[cfg(all(feature = "drivers", feature = "mongodb"))]
pub use driver_mongodb::MongoDriverStore;
#[cfg(all(feature = "drivers", feature = "neo4j"))]
pub use driver_neo4j::Neo4jDriverStore;
#[cfg(all(feature = "drivers", feature = "postgres"))]
pub use driver_postgres::PostgresDriverStore;
#[cfg(all(feature = "drivers", feature = "redis"))]
pub use driver_redis::RedisDriverStore;
#[cfg(all(feature = "drivers", feature = "sqlite"))]
pub use driver_sqlite::SqliteDriverStore;
#[cfg(feature = "firestore")]
pub use firestore::FirestoreProcessStore;
#[cfg(all(feature = "proc", feature = "firestore"))]
pub use ledger_firestore::FirestoreLedgerStore;
#[cfg(feature = "proc")]
pub use ledger_memory::InMemoryLedgerStore;
#[cfg(all(feature = "proc", feature = "mongodb"))]
pub use ledger_mongodb::MongoLedgerStore;
#[cfg(all(feature = "proc", feature = "neo4j"))]
pub use ledger_neo4j::Neo4jLedgerStore;
#[cfg(all(feature = "proc", feature = "redis"))]
pub use ledger_redis::RedisLedgerStore;
#[cfg(all(feature = "proc", feature = "postgres"))]
pub use ledger_sql::PostgresLedgerStore;
#[cfg(all(feature = "proc", feature = "sqlite"))]
pub use ledger_sql::SqliteLedgerStore;
pub use memory::InMemoryProcessStore;
#[cfg(feature = "mongodb")]
pub use mongodb::MongoProcessStore;
#[cfg(feature = "neo4j")]
pub use neo4j::Neo4jProcessStore;
#[cfg(feature = "firestore")]
pub use partition_firestore::FirestorePartitionStore;
pub use partition_memory::InMemoryPartitionStore;
#[cfg(feature = "mongodb")]
pub use partition_mongodb::MongoPartitionStore;
#[cfg(feature = "neo4j")]
pub use partition_neo4j::Neo4jPartitionStore;
#[cfg(feature = "redis")]
pub use partition_redis::RedisPartitionStore;
#[cfg(feature = "postgres")]
pub use partition_sql::PostgresPartitionStore;
#[cfg(feature = "sqlite")]
pub use partition_sql::SqlitePartitionStore;
#[cfg(feature = "postgres")]
pub use postgres::PostgresProcessStore;
#[cfg(feature = "redis")]
pub use redis::RedisProcessStore;
#[cfg(feature = "sqlite")]
pub use sqlite::SqliteProcessStore;
#[cfg(feature = "firestore")]
pub use watermark_firestore::FirestoreCronWatermarkStore;
pub use watermark_memory::InMemoryCronWatermarkStore;
#[cfg(feature = "mongodb")]
pub use watermark_mongodb::MongoCronWatermarkStore;
#[cfg(feature = "neo4j")]
pub use watermark_neo4j::Neo4jCronWatermarkStore;
#[cfg(feature = "redis")]
pub use watermark_redis::RedisCronWatermarkStore;
#[cfg(feature = "postgres")]
pub use watermark_sql::PostgresCronWatermarkStore;
#[cfg(feature = "sqlite")]
pub use watermark_sql::SqliteCronWatermarkStore;
#[async_trait]
pub trait ProcessStore: Send + Sync {
async fn put(&self, meta: ProcessMeta) -> Result<()>;
async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>>;
async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>>;
async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()>;
async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()>;
async fn delete(&self, pid: &str) -> Result<bool>;
async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()>;
async fn add_spend(
&self,
pid: &str,
partition: &PartitionId,
day: NaiveDate,
delta: SpendDelta,
) -> Result<()>;
async fn spend(
&self,
scope: &SpendScope,
from: NaiveDate,
to_inclusive: NaiveDate,
) -> Result<u64>;
async fn usage(
&self,
scope: &SpendScope,
from: NaiveDate,
to_inclusive: NaiveDate,
) -> Result<UsageTotals>;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct UsageTotals {
pub micro_usd: u64,
pub model_calls: u64,
pub total_tokens: u64,
pub units: UsageVector,
}
impl UsageTotals {
pub fn add(&mut self, delta: &SpendDelta) {
self.micro_usd = self.micro_usd.saturating_add(delta.micro_usd);
self.model_calls = self.model_calls.saturating_add(delta.model_calls);
self.total_tokens = self.total_tokens.saturating_add(delta.total_tokens);
self.units.merge(&delta.units);
}
pub fn merge(&mut self, other: &UsageTotals) {
self.micro_usd = self.micro_usd.saturating_add(other.micro_usd);
self.model_calls = self.model_calls.saturating_add(other.model_calls);
self.total_tokens = self.total_tokens.saturating_add(other.total_tokens);
self.units.merge(&other.units);
}
#[cfg(any(
feature = "sqlite",
feature = "postgres",
feature = "redis",
feature = "mongodb",
feature = "firestore",
feature = "neo4j"
))]
pub(crate) fn add_counter(&mut self, name: &str, amount: u64) {
match name {
MODEL_CALLS_COUNTER => self.model_calls = self.model_calls.saturating_add(amount),
TOTAL_TOKENS_COUNTER => self.total_tokens = self.total_tokens.saturating_add(amount),
unit => {
if let Some(unit) =
adk_core::UsageUnit::ALL.into_iter().find(|known| known.as_str() == unit)
{
self.units.add(unit, amount);
}
}
}
}
}
#[cfg(any(
feature = "sqlite",
feature = "postgres",
feature = "redis",
feature = "mongodb",
feature = "firestore",
feature = "neo4j"
))]
const MODEL_CALLS_COUNTER: &str = "modelCalls";
#[cfg(any(
feature = "sqlite",
feature = "postgres",
feature = "redis",
feature = "mongodb",
feature = "firestore",
feature = "neo4j"
))]
const TOTAL_TOKENS_COUNTER: &str = "totalTokens";
#[cfg(any(
feature = "sqlite",
feature = "postgres",
feature = "redis",
feature = "mongodb",
feature = "firestore",
feature = "neo4j"
))]
pub(crate) fn stored_amount(backend: &'static str, name: &str, amount: u64) -> Result<i64> {
i64::try_from(amount).map_err(|_| crate::KernelError::Store {
backend,
reason: format!("a {name} delta of {amount} exceeds a signed 64-bit integer"),
})
}
#[cfg(any(
feature = "sqlite",
feature = "postgres",
feature = "redis",
feature = "mongodb",
feature = "firestore",
feature = "neo4j"
))]
pub(crate) fn counters(delta: &SpendDelta) -> Vec<(&'static str, u64)> {
[(MODEL_CALLS_COUNTER, delta.model_calls), (TOTAL_TOKENS_COUNTER, delta.total_tokens)]
.into_iter()
.chain(delta.units.iter().map(|(unit, amount)| (unit.as_str(), amount)))
.filter(|(_, amount)| *amount > 0)
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum SpendScope {
Process(String),
Partition(PartitionId),
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProcessFilter {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partition: Option<PartitionId>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub states: Vec<RunState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub queue: Option<QueueClass>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub suspend_requested: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
}
impl ProcessFilter {
#[must_use]
pub fn partition(mut self, partition: impl Into<PartitionId>) -> Self {
self.partition = Some(partition.into());
self
}
#[must_use]
pub fn states(mut self, states: impl IntoIterator<Item = RunState>) -> Self {
self.states = states.into_iter().collect();
self
}
#[must_use]
pub fn queue(mut self, queue: QueueClass) -> Self {
self.queue = Some(queue);
self
}
#[must_use]
pub fn parent(mut self, parent: impl Into<String>) -> Self {
self.parent = Some(parent.into());
self
}
#[must_use]
pub fn suspend_requested(mut self, requested: bool) -> Self {
self.suspend_requested = Some(requested);
self
}
#[must_use]
pub fn target(mut self, target: impl Into<String>) -> Self {
self.target = Some(target.into());
self
}
#[must_use]
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn matches(&self, meta: &ProcessMeta) -> bool {
self.partition.as_ref().is_none_or(|partition| *partition == meta.partition)
&& self.queue.as_ref().is_none_or(|queue| *queue == meta.queue)
&& self.parent.as_ref().is_none_or(|parent| meta.parent.as_ref() == Some(parent))
&& self.suspend_requested.is_none_or(|requested| requested == meta.suspend_requested)
}
}
#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
pub(crate) fn day_number(day: NaiveDate) -> i64 {
i64::from(chrono::Datelike::num_days_from_ce(&day))
}
#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
pub(crate) fn stored_micro_usd(backend: &'static str, delta: &SpendDelta) -> Result<i64> {
i64::try_from(delta.micro_usd).map_err(|_| crate::KernelError::Store {
backend,
reason: format!(
"a spend delta of {} micro-USD exceeds a signed 64-bit integer",
delta.micro_usd
),
})
}
#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
pub(crate) fn stored_total(backend: &'static str, total: i64) -> Result<u64> {
u64::try_from(total).map_err(|_| crate::KernelError::Store {
backend,
reason: format!("the stored spend total {total} is negative"),
})
}