adk_kernel/stores/
agent_sql.rs1use crate::agents::AgentRecord;
14use crate::error::{KernelError, Result};
15
16pub(crate) const AGENT_REGISTRY_TABLE: &str = "_adk_kernel_agent_migrations";
18
19#[cfg(feature = "sqlite")]
21const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[(
22 1,
23 "create the kernel agent table",
24 "\
25CREATE TABLE IF NOT EXISTS adk_kernel_agents (\
26 id TEXT PRIMARY KEY, \
27 version BIGINT NOT NULL, \
28 state TEXT NOT NULL, \
29 record TEXT NOT NULL\
30);",
31)];
32
33#[cfg(feature = "postgres")]
36const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[(
37 1,
38 "create the kernel agent table",
39 "\
40CREATE TABLE IF NOT EXISTS adk_kernel_agents (\
41 id TEXT COLLATE \"C\" PRIMARY KEY, \
42 version BIGINT NOT NULL, \
43 state TEXT NOT NULL, \
44 record TEXT NOT NULL\
45);",
46)];
47
48pub(crate) const INSERT: &str = "\
49INSERT INTO adk_kernel_agents (id, version, state, record) VALUES ($1, $2, $3, $4) \
50ON CONFLICT (id) DO NOTHING";
51
52pub(crate) const UPDATE: &str = "\
53UPDATE adk_kernel_agents SET version = $1, state = $2, record = $3 \
54WHERE id = $4 AND version = $5";
55
56pub(crate) const GET: &str = "SELECT record FROM adk_kernel_agents WHERE id = $1";
57
58pub(crate) const LIST: &str = "SELECT record FROM adk_kernel_agents ORDER BY id";
59
60pub(crate) const DELETE: &str =
61 "DELETE FROM adk_kernel_agents WHERE id = $1 AND state = 'proposed'";
62
63pub(crate) fn stored_version(backend: &'static str, version: u64) -> Result<i64> {
65 i64::try_from(version).map_err(|_| KernelError::Store {
66 backend,
67 reason: format!("agent version {version} exceeds a signed 64-bit integer"),
68 })
69}
70
71pub(crate) fn decode(backend: &'static str, record: &str) -> Result<AgentRecord> {
73 serde_json::from_str(record).map_err(|error| KernelError::Store {
74 backend,
75 reason: format!("a stored agent is corrupt: {error}"),
76 })
77}
78
79pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
81 KernelError::Store { backend, reason: format!("could not {action} the agent table: {error}") }
82}
83
84macro_rules! sql_agent_store {
87 ($store:ty, $backend:literal) => {
88 #[async_trait::async_trait]
89 impl $crate::agents::AgentStore for $store {
90 async fn put_if_version(
91 &self,
92 record: $crate::agents::AgentRecord,
93 expected: u64,
94 ) -> $crate::error::Result<bool> {
95 let json = serde_json::to_string(&record)?;
96 let version = $crate::stores::agent_sql::stored_version($backend, record.version)?;
97 let done = if expected == 0 {
98 sqlx::query($crate::stores::agent_sql::INSERT)
99 .bind(&record.id)
100 .bind(version)
101 .bind(record.state.as_str())
102 .bind(json)
103 .execute(&self.pool)
104 .await
105 } else {
106 let expected = $crate::stores::agent_sql::stored_version($backend, expected)?;
107 sqlx::query($crate::stores::agent_sql::UPDATE)
108 .bind(version)
109 .bind(record.state.as_str())
110 .bind(json)
111 .bind(&record.id)
112 .bind(expected)
113 .execute(&self.pool)
114 .await
115 }
116 .map_err(|e| $crate::stores::agent_sql::db_error($backend, "write", &e))?;
117 Ok(done.rows_affected() > 0)
118 }
119
120 async fn get(
121 &self,
122 id: &str,
123 ) -> $crate::error::Result<Option<$crate::agents::AgentRecord>> {
124 let row: Option<(String,)> = sqlx::query_as($crate::stores::agent_sql::GET)
125 .bind(id)
126 .fetch_optional(&self.pool)
127 .await
128 .map_err(|e| $crate::stores::agent_sql::db_error($backend, "read", &e))?;
129 row.map(|(record,)| $crate::stores::agent_sql::decode($backend, &record))
130 .transpose()
131 }
132
133 async fn list(&self) -> $crate::error::Result<Vec<$crate::agents::AgentRecord>> {
134 let rows: Vec<(String,)> = sqlx::query_as($crate::stores::agent_sql::LIST)
135 .fetch_all(&self.pool)
136 .await
137 .map_err(|e| $crate::stores::agent_sql::db_error($backend, "list", &e))?;
138 rows.iter()
139 .map(|(record,)| $crate::stores::agent_sql::decode($backend, record))
140 .collect()
141 }
142
143 async fn delete(&self, id: &str) -> $crate::error::Result<bool> {
144 let done = sqlx::query($crate::stores::agent_sql::DELETE)
145 .bind(id)
146 .execute(&self.pool)
147 .await
148 .map_err(|e| {
149 $crate::stores::agent_sql::db_error($backend, "delete from", &e)
150 })?;
151 Ok(done.rows_affected() > 0)
152 }
153 }
154 };
155}
156
157#[cfg(feature = "sqlite")]
185#[derive(Debug, Clone)]
186pub struct SqliteAgentStore {
187 pool: sqlx::SqlitePool,
188}
189
190#[cfg(feature = "sqlite")]
191impl SqliteAgentStore {
192 pub fn new(pool: sqlx::SqlitePool) -> Self {
194 Self { pool }
195 }
196
197 pub fn pool(&self) -> &sqlx::SqlitePool {
199 &self.pool
200 }
201
202 pub async fn migrate(&self) -> Result<()> {
210 adk_session::migration::sqlite_runner::run_sql_migrations(
211 &self.pool,
212 AGENT_REGISTRY_TABLE,
213 SQLITE_MIGRATIONS,
214 || async { Ok(false) },
215 )
216 .await
217 .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
218 }
219}
220
221#[cfg(feature = "sqlite")]
222sql_agent_store!(SqliteAgentStore, "sqlite");
223
224#[cfg(feature = "postgres")]
241#[derive(Debug, Clone)]
242pub struct PostgresAgentStore {
243 pool: sqlx::PgPool,
244}
245
246#[cfg(feature = "postgres")]
247impl PostgresAgentStore {
248 pub fn new(pool: sqlx::PgPool) -> Self {
250 Self { pool }
251 }
252
253 pub fn pool(&self) -> &sqlx::PgPool {
255 &self.pool
256 }
257
258 pub async fn connect(database_url: &str) -> Result<Self> {
264 let pool =
265 sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
266 backend: "postgres",
267 reason: format!("could not connect: {error}"),
268 })?;
269 Ok(Self::new(pool))
270 }
271
272 pub async fn migrate(&self) -> Result<()> {
280 super::postgres::migrate_locked(
281 self.pool.clone(),
282 AGENT_REGISTRY_TABLE,
283 POSTGRES_MIGRATIONS,
284 )
285 .await
286 }
287}
288
289#[cfg(feature = "postgres")]
290sql_agent_store!(PostgresAgentStore, "postgres");