Skip to main content

adk_kernel/stores/
mod.rs

1//! The kernel-owned stores and their backends (spec 3.2 §7.1, §7.3, §13 Q8).
2//!
3//! Phase 1 has one kernel-owned store, the [`ProcessStore`] side table, with the kernel's
4//! daily spend totals per process (the phase-1 source of `ProcessView::spend_today` and
5//! `spend_7d`). It runs on every
6//! backend that holds the run, schedule and governance stores, with one conformance suite
7//! (`process_store_conformance_tests!`, feature `conformance`):
8//!
9//! | Backend | Type | Feature | Opened from |
10//! |---|---|---|---|
11//! | In-memory | [`InMemoryProcessStore`] | — | — |
12//! | SQLite | `SqliteProcessStore` | `sqlite` (default) | the pool of `harness.db`, with its own migration table |
13//! | PostgreSQL | `PostgresProcessStore` | `postgres` | the URL of `adk-rust serve --store` |
14//! | Redis | `RedisProcessStore` | `redis` | the URL of `adk-rust serve --store` |
15//!
16//! Phase 2 adds the [`AgendaStore`](crate::AgendaStore) on the same four backends
17//! ([`InMemoryAgendaStore`], `SqliteAgendaStore`, `PostgresAgendaStore`, `RedisAgendaStore`,
18//! suite `agenda_store_conformance_tests!`).
19//!
20//! The driver store (`drivers::DriverStore`, feature `drivers`) runs on
21//! the same four backends: `InMemoryDriverStore`, `SqliteDriverStore`,
22//! `PostgresDriverStore` and `RedisDriverStore` (spec 3.2 §7.7).
23//!
24//! The ledger store (`proc::LedgerStore`, feature `proc`) runs on the same four backends:
25//! `InMemoryLedgerStore`, `SqliteLedgerStore`, `PostgresLedgerStore` and `RedisLedgerStore`
26//! (spec 3.2 §7.10, suite `ledger_store_conformance_tests!`).
27//!
28//! The [`PartitionStore`](crate::PartitionStore) — the partition table and the crossing
29//! ledger (§7.8) — runs on in-memory, SQLite, PostgreSQL and Redis
30//! ([`InMemoryPartitionStore`], `SqlitePartitionStore`, `PostgresPartitionStore`,
31//! `RedisPartitionStore`, suite `partition_store_conformance_tests!`).
32//!
33//! Phase 4 adds these stores on MongoDB, Firestore and Neo4j (§13 Q8), each checked by its
34//! conformance suite against a live server in CI:
35//!
36//! | Store | MongoDB (`mongodb`) | Firestore (`firestore`) | Neo4j (`neo4j`) |
37//! |---|---|---|---|
38//! | [`ProcessStore`] | `MongoProcessStore` | `FirestoreProcessStore` | `Neo4jProcessStore` |
39//! | [`AgendaStore`](crate::AgendaStore) | `MongoAgendaStore` | `FirestoreAgendaStore` | `Neo4jAgendaStore` |
40//! | `drivers::DriverStore` (with `drivers`) | `MongoDriverStore` | `FirestoreDriverStore` | `Neo4jDriverStore` |
41//! | `proc::LedgerStore` (with `proc`) | `MongoLedgerStore` | `FirestoreLedgerStore` | `Neo4jLedgerStore` |
42//! | [`PartitionStore`](crate::PartitionStore) | `MongoPartitionStore` | `FirestorePartitionStore` | `Neo4jPartitionStore` |
43//! | [`CronWatermarkStore`](crate::CronWatermarkStore) | `MongoCronWatermarkStore` | `FirestoreCronWatermarkStore` | `Neo4jCronWatermarkStore` |
44//!
45//! The [`CronWatermarkStore`](crate::CronWatermarkStore) — where each cron wake source left
46//! off (§7.4) — runs on in-memory, SQLite, PostgreSQL and Redis
47//! ([`InMemoryCronWatermarkStore`], `SqliteCronWatermarkStore`, `PostgresCronWatermarkStore`,
48//! `RedisCronWatermarkStore`, suite `cron_watermark_store_conformance_tests!`), and on
49//! MongoDB, Firestore and Neo4j.
50//!
51//! The [`AgentStore`](crate::agents::AgentStore) — the agents a person adds (spec 3.3 §5.7,
52//! §10 K7) — runs on every backend: [`InMemoryAgentStore`], `SqliteAgentStore`,
53//! `PostgresAgentStore`, `RedisAgentStore`, `MongoAgentStore`, `FirestoreAgentStore` and
54//! `Neo4jAgentStore`, suite `agent_store_conformance_tests!`.
55//!
56//! There is no file backend and no Vertex AI backend (§13 Q8): no durable store on `main` is file-backed, and
57//! Vertex AI holds sessions only.
58
59use 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/// The kernel's side table of process metadata, keyed by run id (spec 3.2 §7.3, §6 D-2).
263///
264/// `RunRecord` has no metadata field, so the kernel keeps what the run store does not here
265/// instead of changing the run store's schema across six backends. Rows of runs the run
266/// store has pruned are deleted with [`delete`](Self::delete).
267///
268/// # Example
269///
270/// ```rust
271/// use adk_kernel::{InMemoryProcessStore, ProcessKind, ProcessMeta, ProcessStore, QueueClass};
272///
273/// # #[tokio::main(flavor = "current_thread")]
274/// # async fn main() -> adk_kernel::Result<()> {
275/// let store = InMemoryProcessStore::new();
276/// store.put(ProcessMeta::new("run-1", QueueClass::Background, ProcessKind::Goal)).await?;
277/// store.set_queue("run-1", QueueClass::Interactive).await?;
278/// assert_eq!(store.get("run-1").await?.unwrap().queue, QueueClass::Interactive);
279/// # Ok(())
280/// # }
281/// ```
282#[async_trait]
283pub trait ProcessStore: Send + Sync {
284    /// Inserts `meta`, or replaces the row with the same `pid`.
285    ///
286    /// # Errors
287    ///
288    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
289    async fn put(&self, meta: ProcessMeta) -> Result<()>;
290
291    /// The row of `pid`, or `None`.
292    ///
293    /// # Errors
294    ///
295    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
296    async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>>;
297
298    /// The rows `filter` selects by partition, queue, parent and pending suspension request,
299    /// ordered by `pid`, at most
300    /// `filter.limit`. `filter.states` is a run-store field and is applied by
301    /// [`ProcessTable::ps`](crate::ProcessTable::ps), not here.
302    ///
303    /// # Errors
304    ///
305    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
306    async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>>;
307
308    /// Sets or clears the wake set of `pid`.
309    ///
310    /// # Errors
311    ///
312    /// Returns [`KernelError::NotFound`](crate::KernelError::NotFound) when no row has
313    /// `pid`, or [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
314    async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()>;
315
316    /// Sets the queue class of `pid`.
317    ///
318    /// # Errors
319    ///
320    /// Returns [`KernelError::NotFound`](crate::KernelError::NotFound) when no row has
321    /// `pid`, or [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
322    async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()>;
323
324    /// Deletes the row of `pid`; `false` when there was none.
325    ///
326    /// # Errors
327    ///
328    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
329    async fn delete(&self, pid: &str) -> Result<bool>;
330
331    /// Sets or clears the pending suspension request of `pid`
332    /// ([`ProcessMeta::suspend_requested`]).
333    ///
334    /// # Errors
335    ///
336    /// Returns [`KernelError::NotFound`](crate::KernelError::NotFound) when no row has
337    /// `pid`, or [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
338    async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()>;
339
340    /// Adds `delta` — its cost, model calls, total tokens and units — to the totals of `pid`
341    /// in `partition` on the UTC day `day`. Additions from concurrent writers all count.
342    ///
343    /// # Errors
344    ///
345    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
346    async fn add_spend(
347        &self,
348        pid: &str,
349        partition: &PartitionId,
350        day: NaiveDate,
351        delta: SpendDelta,
352    ) -> Result<()>;
353
354    /// The spend `scope` recorded from `from` through `to_inclusive`, in micro-USD; 0 when
355    /// none was.
356    ///
357    /// # Errors
358    ///
359    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
360    async fn spend(
361        &self,
362        scope: &SpendScope,
363        from: NaiveDate,
364        to_inclusive: NaiveDate,
365    ) -> Result<u64>;
366
367    /// What `scope` used from `from` through `to_inclusive`: the cost, model calls, total
368    /// tokens and units [`add_spend`](Self::add_spend) recorded; zero when none was.
369    ///
370    /// # Errors
371    ///
372    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
373    async fn usage(
374        &self,
375        scope: &SpendScope,
376        from: NaiveDate,
377        to_inclusive: NaiveDate,
378    ) -> Result<UsageTotals>;
379}
380
381/// What a process or a partition used over a span of UTC days ([`ProcessStore::usage`]).
382///
383/// # Example
384///
385/// ```rust
386/// use adk_core::{UsageUnit, UsageVector};
387/// use adk_kernel::SpendDelta;
388/// use adk_kernel::stores::UsageTotals;
389///
390/// let mut totals = UsageTotals::default();
391/// totals.add(&SpendDelta::new(10_000).with_units(UsageVector::new().with(UsageUnit::Images, 1)));
392/// totals.add(&SpendDelta::new(500).with_model_calls(1).with_total_tokens(900));
393/// assert_eq!(totals.micro_usd, 10_500);
394/// assert_eq!((totals.model_calls, totals.total_tokens), (1, 900));
395/// assert_eq!(totals.units.get(UsageUnit::Images), 1);
396/// ```
397#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
398#[serde(rename_all = "camelCase")]
399#[non_exhaustive]
400pub struct UsageTotals {
401    /// Cost, in micro-USD.
402    pub micro_usd: u64,
403    /// Model calls.
404    pub model_calls: u64,
405    /// Input plus output tokens.
406    pub total_tokens: u64,
407    /// Usage per unit.
408    pub units: UsageVector,
409}
410
411impl UsageTotals {
412    /// Adds `delta`, saturating.
413    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    /// Adds every total of `other`, saturating.
421    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    /// Adds `amount` to the counter a durable backend stores as `name` ([`counters`]); an
429    /// unknown name, written by a later version, is skipped.
430    #[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/// The counter name of [`SpendDelta::model_calls`] in the durable backends.
454#[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/// The counter name of [`SpendDelta::total_tokens`] in the durable backends.
465#[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/// A counter amount as a durable backend stores it, a signed 64-bit integer.
476#[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/// The named counters a durable backend stores beside a delta's micro-USD: model calls,
492/// total tokens and each unit by its wire name, the zero ones left out.
493#[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/// Whose spend [`ProcessStore::spend`] sums (spec 3.2 §7.3, §7.10).
510///
511/// # Example
512///
513/// ```rust
514/// use adk_kernel::stores::SpendScope;
515///
516/// let scope = SpendScope::Process("run-1".into());
517/// assert_eq!(serde_json::to_value(&scope).unwrap()["process"], "run-1");
518/// ```
519#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
520#[serde(rename_all = "camelCase")]
521#[non_exhaustive]
522pub enum SpendScope {
523    /// One process.
524    Process(String),
525    /// Every process of a partition.
526    Partition(PartitionId),
527}
528
529/// Which processes `ps` lists (spec 3.2 §7.3, §8.1 `adk-rust ps [--partition P] [--state S]`).
530///
531/// An empty field matches everything.
532///
533/// # Example
534///
535/// ```rust
536/// use adk_core::RunState;
537/// use adk_kernel::{ProcessFilter, ProcessKind, ProcessMeta, QueueClass};
538///
539/// let filter = ProcessFilter::default().partition("default").states([RunState::Waiting]).limit(20);
540/// let meta = ProcessMeta::new("run-1", QueueClass::Background, ProcessKind::Goal);
541/// assert!(filter.matches(&meta));
542/// assert!(!filter.clone().queue(QueueClass::Interactive).matches(&meta));
543/// ```
544#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
545#[serde(rename_all = "camelCase")]
546#[non_exhaustive]
547pub struct ProcessFilter {
548    /// Only processes in this partition.
549    #[serde(default, skip_serializing_if = "Option::is_none")]
550    pub partition: Option<PartitionId>,
551    /// Only processes whose run is in one of these states.
552    #[serde(default, skip_serializing_if = "Vec::is_empty")]
553    pub states: Vec<RunState>,
554    /// Only processes in this queue class.
555    #[serde(default, skip_serializing_if = "Option::is_none")]
556    pub queue: Option<QueueClass>,
557    /// Only processes this run caused.
558    #[serde(default, skip_serializing_if = "Option::is_none")]
559    pub parent: Option<String>,
560    /// Only processes whose [`ProcessMeta::suspend_requested`] is this.
561    #[serde(default, skip_serializing_if = "Option::is_none")]
562    pub suspend_requested: Option<bool>,
563    /// Only processes whose run's target is this: an agent's id (spec 3.3 §5.7).
564    #[serde(default, skip_serializing_if = "Option::is_none")]
565    pub target: Option<String>,
566    /// At most this many processes.
567    #[serde(default, skip_serializing_if = "Option::is_none")]
568    pub limit: Option<usize>,
569}
570
571impl ProcessFilter {
572    /// Only processes in `partition`.
573    #[must_use]
574    pub fn partition(mut self, partition: impl Into<PartitionId>) -> Self {
575        self.partition = Some(partition.into());
576        self
577    }
578
579    /// Only processes whose run is in one of `states`.
580    #[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    /// Only processes in `queue`.
587    #[must_use]
588    pub fn queue(mut self, queue: QueueClass) -> Self {
589        self.queue = Some(queue);
590        self
591    }
592
593    /// Only processes `parent` caused.
594    #[must_use]
595    pub fn parent(mut self, parent: impl Into<String>) -> Self {
596        self.parent = Some(parent.into());
597        self
598    }
599
600    /// Only processes whose pending suspension request is `requested`.
601    #[must_use]
602    pub fn suspend_requested(mut self, requested: bool) -> Self {
603        self.suspend_requested = Some(requested);
604        self
605    }
606
607    /// Only processes whose run's target is `target`, such as an added agent's id (spec 3.3
608    /// §5.7). Like `states`, it is a run-record field, applied by
609    /// [`ProcessTable::ps`](crate::ProcessTable::ps) rather than by the store.
610    #[must_use]
611    pub fn target(mut self, target: impl Into<String>) -> Self {
612        self.target = Some(target.into());
613        self
614    }
615
616    /// At most `limit` processes.
617    #[must_use]
618    pub fn limit(mut self, limit: usize) -> Self {
619        self.limit = Some(limit);
620        self
621    }
622
623    /// Whether `meta` passes the side-table fields: partition, queue, parent and the
624    /// pending suspension request. `states`, `target` and `limit` are not checked here.
625    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/// The stored form of a UTC day in the document and graph backends: its number of days from
634/// the common era, as the SQL backends store it, so a range compares as integers.
635#[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/// A spend delta as the document and graph backends store it, a signed 64-bit integer.
641#[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/// A summed spend total as returned.
653#[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}