1use async_trait::async_trait;
60use chrono::NaiveDate;
61use serde::{Deserialize, Serialize};
62
63use adk_core::{RunState, UsageVector};
64
65use crate::bus::SpendDelta;
66use crate::error::Result;
67use crate::partition::PartitionId;
68use crate::process::ProcessMeta;
69use crate::sched::QueueClass;
70use crate::wake::WakeSet;
71
72#[cfg(feature = "firestore")]
73mod agenda_firestore;
74mod agenda_memory;
75#[cfg(feature = "mongodb")]
76mod agenda_mongodb;
77#[cfg(feature = "neo4j")]
78mod agenda_neo4j;
79#[cfg(feature = "redis")]
80mod agenda_redis;
81#[cfg(any(feature = "sqlite", feature = "postgres"))]
82pub(crate) mod agenda_sql;
83#[cfg(feature = "firestore")]
84mod agent_firestore;
85mod agent_memory;
86#[cfg(feature = "mongodb")]
87mod agent_mongodb;
88#[cfg(feature = "neo4j")]
89mod agent_neo4j;
90#[cfg(feature = "redis")]
91mod agent_redis;
92#[cfg(any(feature = "sqlite", feature = "postgres"))]
93pub(crate) mod agent_sql;
94mod bundle;
95#[cfg(feature = "charter")]
96pub(crate) mod charter_memory;
97#[cfg(all(feature = "charter", feature = "redis"))]
98pub(crate) mod charter_redis;
99#[cfg(all(feature = "charter", any(feature = "sqlite", feature = "postgres")))]
100pub(crate) mod charter_sql;
101#[cfg(all(feature = "drivers", feature = "firestore"))]
102mod driver_firestore;
103#[cfg(feature = "drivers")]
104mod driver_memory;
105#[cfg(all(feature = "drivers", feature = "mongodb"))]
106mod driver_mongodb;
107#[cfg(all(feature = "drivers", feature = "neo4j"))]
108mod driver_neo4j;
109#[cfg(all(feature = "drivers", feature = "postgres"))]
110mod driver_postgres;
111#[cfg(all(feature = "drivers", feature = "redis"))]
112mod driver_redis;
113#[cfg(all(feature = "drivers", any(feature = "sqlite", feature = "postgres")))]
114mod driver_sql;
115#[cfg(all(feature = "drivers", feature = "sqlite"))]
116mod driver_sqlite;
117#[cfg(feature = "firestore")]
118mod firestore;
119#[cfg(all(feature = "proc", feature = "firestore"))]
120mod ledger_firestore;
121#[cfg(feature = "proc")]
122mod ledger_memory;
123#[cfg(all(feature = "proc", feature = "mongodb"))]
124mod ledger_mongodb;
125#[cfg(all(feature = "proc", feature = "neo4j"))]
126mod ledger_neo4j;
127#[cfg(all(feature = "proc", feature = "redis"))]
128mod ledger_redis;
129#[cfg(all(feature = "proc", any(feature = "sqlite", feature = "postgres")))]
130pub(crate) mod ledger_sql;
131mod memory;
132#[cfg(feature = "mongodb")]
133mod mongodb;
134#[cfg(feature = "neo4j")]
135mod neo4j;
136#[cfg(feature = "firestore")]
137mod partition_firestore;
138mod partition_memory;
139#[cfg(feature = "mongodb")]
140mod partition_mongodb;
141#[cfg(feature = "neo4j")]
142mod partition_neo4j;
143#[cfg(feature = "redis")]
144mod partition_redis;
145#[cfg(any(feature = "sqlite", feature = "postgres"))]
146pub(crate) mod partition_sql;
147#[cfg(feature = "postgres")]
148mod postgres;
149#[cfg(feature = "redis")]
150mod redis;
151#[cfg(any(feature = "sqlite", feature = "postgres"))]
152mod sql;
153#[cfg(feature = "sqlite")]
154mod sqlite;
155#[cfg(feature = "firestore")]
156mod watermark_firestore;
157mod watermark_memory;
158#[cfg(feature = "mongodb")]
159mod watermark_mongodb;
160#[cfg(feature = "neo4j")]
161mod watermark_neo4j;
162#[cfg(feature = "redis")]
163mod watermark_redis;
164#[cfg(any(feature = "sqlite", feature = "postgres"))]
165pub(crate) mod watermark_sql;
166
167#[cfg(feature = "firestore")]
168pub use agenda_firestore::FirestoreAgendaStore;
169pub use agenda_memory::InMemoryAgendaStore;
170#[cfg(feature = "mongodb")]
171pub use agenda_mongodb::MongoAgendaStore;
172#[cfg(feature = "neo4j")]
173pub use agenda_neo4j::Neo4jAgendaStore;
174#[cfg(feature = "redis")]
175pub use agenda_redis::RedisAgendaStore;
176#[cfg(feature = "postgres")]
177pub use agenda_sql::PostgresAgendaStore;
178#[cfg(feature = "sqlite")]
179pub use agenda_sql::SqliteAgendaStore;
180#[cfg(feature = "firestore")]
181pub use agent_firestore::FirestoreAgentStore;
182pub use agent_memory::InMemoryAgentStore;
183#[cfg(feature = "mongodb")]
184pub use agent_mongodb::MongoAgentStore;
185#[cfg(feature = "neo4j")]
186pub use agent_neo4j::Neo4jAgentStore;
187#[cfg(feature = "redis")]
188pub use agent_redis::RedisAgentStore;
189#[cfg(feature = "postgres")]
190pub use agent_sql::PostgresAgentStore;
191#[cfg(feature = "sqlite")]
192pub use agent_sql::SqliteAgentStore;
193pub use bundle::{KernelStores, StoreOrigin, StoreUse};
194#[cfg(all(feature = "drivers", feature = "firestore"))]
195pub use driver_firestore::FirestoreDriverStore;
196#[cfg(feature = "drivers")]
197pub use driver_memory::InMemoryDriverStore;
198#[cfg(all(feature = "drivers", feature = "mongodb"))]
199pub use driver_mongodb::MongoDriverStore;
200#[cfg(all(feature = "drivers", feature = "neo4j"))]
201pub use driver_neo4j::Neo4jDriverStore;
202#[cfg(all(feature = "drivers", feature = "postgres"))]
203pub use driver_postgres::PostgresDriverStore;
204#[cfg(all(feature = "drivers", feature = "redis"))]
205pub use driver_redis::RedisDriverStore;
206#[cfg(all(feature = "drivers", feature = "sqlite"))]
207pub use driver_sqlite::SqliteDriverStore;
208#[cfg(feature = "firestore")]
209pub use firestore::FirestoreProcessStore;
210#[cfg(all(feature = "proc", feature = "firestore"))]
211pub use ledger_firestore::FirestoreLedgerStore;
212#[cfg(feature = "proc")]
213pub use ledger_memory::InMemoryLedgerStore;
214#[cfg(all(feature = "proc", feature = "mongodb"))]
215pub use ledger_mongodb::MongoLedgerStore;
216#[cfg(all(feature = "proc", feature = "neo4j"))]
217pub use ledger_neo4j::Neo4jLedgerStore;
218#[cfg(all(feature = "proc", feature = "redis"))]
219pub use ledger_redis::RedisLedgerStore;
220#[cfg(all(feature = "proc", feature = "postgres"))]
221pub use ledger_sql::PostgresLedgerStore;
222#[cfg(all(feature = "proc", feature = "sqlite"))]
223pub use ledger_sql::SqliteLedgerStore;
224pub use memory::InMemoryProcessStore;
225#[cfg(feature = "mongodb")]
226pub use mongodb::MongoProcessStore;
227#[cfg(feature = "neo4j")]
228pub use neo4j::Neo4jProcessStore;
229#[cfg(feature = "firestore")]
230pub use partition_firestore::FirestorePartitionStore;
231pub use partition_memory::InMemoryPartitionStore;
232#[cfg(feature = "mongodb")]
233pub use partition_mongodb::MongoPartitionStore;
234#[cfg(feature = "neo4j")]
235pub use partition_neo4j::Neo4jPartitionStore;
236#[cfg(feature = "redis")]
237pub use partition_redis::RedisPartitionStore;
238#[cfg(feature = "postgres")]
239pub use partition_sql::PostgresPartitionStore;
240#[cfg(feature = "sqlite")]
241pub use partition_sql::SqlitePartitionStore;
242#[cfg(feature = "postgres")]
243pub use postgres::PostgresProcessStore;
244#[cfg(feature = "redis")]
245pub use redis::RedisProcessStore;
246#[cfg(feature = "sqlite")]
247pub use sqlite::SqliteProcessStore;
248#[cfg(feature = "firestore")]
249pub use watermark_firestore::FirestoreCronWatermarkStore;
250pub use watermark_memory::InMemoryCronWatermarkStore;
251#[cfg(feature = "mongodb")]
252pub use watermark_mongodb::MongoCronWatermarkStore;
253#[cfg(feature = "neo4j")]
254pub use watermark_neo4j::Neo4jCronWatermarkStore;
255#[cfg(feature = "redis")]
256pub use watermark_redis::RedisCronWatermarkStore;
257#[cfg(feature = "postgres")]
258pub use watermark_sql::PostgresCronWatermarkStore;
259#[cfg(feature = "sqlite")]
260pub use watermark_sql::SqliteCronWatermarkStore;
261
262#[async_trait]
283pub trait ProcessStore: Send + Sync {
284 async fn put(&self, meta: ProcessMeta) -> Result<()>;
290
291 async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>>;
297
298 async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>>;
307
308 async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()>;
315
316 async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()>;
323
324 async fn delete(&self, pid: &str) -> Result<bool>;
330
331 async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()>;
339
340 async fn add_spend(
347 &self,
348 pid: &str,
349 partition: &PartitionId,
350 day: NaiveDate,
351 delta: SpendDelta,
352 ) -> Result<()>;
353
354 async fn spend(
361 &self,
362 scope: &SpendScope,
363 from: NaiveDate,
364 to_inclusive: NaiveDate,
365 ) -> Result<u64>;
366
367 async fn usage(
374 &self,
375 scope: &SpendScope,
376 from: NaiveDate,
377 to_inclusive: NaiveDate,
378 ) -> Result<UsageTotals>;
379}
380
381#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
398#[serde(rename_all = "camelCase")]
399#[non_exhaustive]
400pub struct UsageTotals {
401 pub micro_usd: u64,
403 pub model_calls: u64,
405 pub total_tokens: u64,
407 pub units: UsageVector,
409}
410
411impl UsageTotals {
412 pub fn add(&mut self, delta: &SpendDelta) {
414 self.micro_usd = self.micro_usd.saturating_add(delta.micro_usd);
415 self.model_calls = self.model_calls.saturating_add(delta.model_calls);
416 self.total_tokens = self.total_tokens.saturating_add(delta.total_tokens);
417 self.units.merge(&delta.units);
418 }
419
420 pub fn merge(&mut self, other: &UsageTotals) {
422 self.micro_usd = self.micro_usd.saturating_add(other.micro_usd);
423 self.model_calls = self.model_calls.saturating_add(other.model_calls);
424 self.total_tokens = self.total_tokens.saturating_add(other.total_tokens);
425 self.units.merge(&other.units);
426 }
427
428 #[cfg(any(
431 feature = "sqlite",
432 feature = "postgres",
433 feature = "redis",
434 feature = "mongodb",
435 feature = "firestore",
436 feature = "neo4j"
437 ))]
438 pub(crate) fn add_counter(&mut self, name: &str, amount: u64) {
439 match name {
440 MODEL_CALLS_COUNTER => self.model_calls = self.model_calls.saturating_add(amount),
441 TOTAL_TOKENS_COUNTER => self.total_tokens = self.total_tokens.saturating_add(amount),
442 unit => {
443 if let Some(unit) =
444 adk_core::UsageUnit::ALL.into_iter().find(|known| known.as_str() == unit)
445 {
446 self.units.add(unit, amount);
447 }
448 }
449 }
450 }
451}
452
453#[cfg(any(
455 feature = "sqlite",
456 feature = "postgres",
457 feature = "redis",
458 feature = "mongodb",
459 feature = "firestore",
460 feature = "neo4j"
461))]
462const MODEL_CALLS_COUNTER: &str = "modelCalls";
463
464#[cfg(any(
466 feature = "sqlite",
467 feature = "postgres",
468 feature = "redis",
469 feature = "mongodb",
470 feature = "firestore",
471 feature = "neo4j"
472))]
473const TOTAL_TOKENS_COUNTER: &str = "totalTokens";
474
475#[cfg(any(
477 feature = "sqlite",
478 feature = "postgres",
479 feature = "redis",
480 feature = "mongodb",
481 feature = "firestore",
482 feature = "neo4j"
483))]
484pub(crate) fn stored_amount(backend: &'static str, name: &str, amount: u64) -> Result<i64> {
485 i64::try_from(amount).map_err(|_| crate::KernelError::Store {
486 backend,
487 reason: format!("a {name} delta of {amount} exceeds a signed 64-bit integer"),
488 })
489}
490
491#[cfg(any(
494 feature = "sqlite",
495 feature = "postgres",
496 feature = "redis",
497 feature = "mongodb",
498 feature = "firestore",
499 feature = "neo4j"
500))]
501pub(crate) fn counters(delta: &SpendDelta) -> Vec<(&'static str, u64)> {
502 [(MODEL_CALLS_COUNTER, delta.model_calls), (TOTAL_TOKENS_COUNTER, delta.total_tokens)]
503 .into_iter()
504 .chain(delta.units.iter().map(|(unit, amount)| (unit.as_str(), amount)))
505 .filter(|(_, amount)| *amount > 0)
506 .collect()
507}
508
509#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
520#[serde(rename_all = "camelCase")]
521#[non_exhaustive]
522pub enum SpendScope {
523 Process(String),
525 Partition(PartitionId),
527}
528
529#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
545#[serde(rename_all = "camelCase")]
546#[non_exhaustive]
547pub struct ProcessFilter {
548 #[serde(default, skip_serializing_if = "Option::is_none")]
550 pub partition: Option<PartitionId>,
551 #[serde(default, skip_serializing_if = "Vec::is_empty")]
553 pub states: Vec<RunState>,
554 #[serde(default, skip_serializing_if = "Option::is_none")]
556 pub queue: Option<QueueClass>,
557 #[serde(default, skip_serializing_if = "Option::is_none")]
559 pub parent: Option<String>,
560 #[serde(default, skip_serializing_if = "Option::is_none")]
562 pub suspend_requested: Option<bool>,
563 #[serde(default, skip_serializing_if = "Option::is_none")]
565 pub target: Option<String>,
566 #[serde(default, skip_serializing_if = "Option::is_none")]
568 pub limit: Option<usize>,
569}
570
571impl ProcessFilter {
572 #[must_use]
574 pub fn partition(mut self, partition: impl Into<PartitionId>) -> Self {
575 self.partition = Some(partition.into());
576 self
577 }
578
579 #[must_use]
581 pub fn states(mut self, states: impl IntoIterator<Item = RunState>) -> Self {
582 self.states = states.into_iter().collect();
583 self
584 }
585
586 #[must_use]
588 pub fn queue(mut self, queue: QueueClass) -> Self {
589 self.queue = Some(queue);
590 self
591 }
592
593 #[must_use]
595 pub fn parent(mut self, parent: impl Into<String>) -> Self {
596 self.parent = Some(parent.into());
597 self
598 }
599
600 #[must_use]
602 pub fn suspend_requested(mut self, requested: bool) -> Self {
603 self.suspend_requested = Some(requested);
604 self
605 }
606
607 #[must_use]
611 pub fn target(mut self, target: impl Into<String>) -> Self {
612 self.target = Some(target.into());
613 self
614 }
615
616 #[must_use]
618 pub fn limit(mut self, limit: usize) -> Self {
619 self.limit = Some(limit);
620 self
621 }
622
623 pub fn matches(&self, meta: &ProcessMeta) -> bool {
626 self.partition.as_ref().is_none_or(|partition| *partition == meta.partition)
627 && self.queue.as_ref().is_none_or(|queue| *queue == meta.queue)
628 && self.parent.as_ref().is_none_or(|parent| meta.parent.as_ref() == Some(parent))
629 && self.suspend_requested.is_none_or(|requested| requested == meta.suspend_requested)
630 }
631}
632
633#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
636pub(crate) fn day_number(day: NaiveDate) -> i64 {
637 i64::from(chrono::Datelike::num_days_from_ce(&day))
638}
639
640#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
642pub(crate) fn stored_micro_usd(backend: &'static str, delta: &SpendDelta) -> Result<i64> {
643 i64::try_from(delta.micro_usd).map_err(|_| crate::KernelError::Store {
644 backend,
645 reason: format!(
646 "a spend delta of {} micro-USD exceeds a signed 64-bit integer",
647 delta.micro_usd
648 ),
649 })
650}
651
652#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
654pub(crate) fn stored_total(backend: &'static str, total: i64) -> Result<u64> {
655 u64::try_from(total).map_err(|_| crate::KernelError::Store {
656 backend,
657 reason: format!("the stored spend total {total} is negative"),
658 })
659}