a2a_protocol_server/tool_loop/journal/
sqlite.rs1use a2a_protocol_types::error::{A2aError, A2aResult};
8use sqlx::Row;
9use sqlx::sqlite::{SqlitePool, SqliteRow};
10
11use super::{JournalEntry, JournalError, JournalFuture, RunOwner, RunSummary, StepJournal};
12
13const CREATE_TABLE_SQL: &str = "CREATE TABLE IF NOT EXISTS a2a_run_journal (
14 run_key TEXT PRIMARY KEY,
15 revision INTEGER NOT NULL,
16 body TEXT NOT NULL,
17 updated_at INTEGER NOT NULL
18)";
19
20const OWNER_COLUMNS: [(&str, &str); 4] = [
23 ("tenant", "TEXT"),
24 ("principal", "TEXT"),
25 ("task", "TEXT"),
26 ("completed", "INTEGER NOT NULL DEFAULT 0"),
27];
28
29const INDEX_SQL: [&str; 2] = [
30 "CREATE INDEX IF NOT EXISTS idx_a2a_run_journal_principal ON a2a_run_journal(principal, tenant)",
31 "CREATE INDEX IF NOT EXISTS idx_a2a_run_journal_updated ON a2a_run_journal(completed, updated_at)",
32];
33
34const COLUMNS: &str = "run_key, revision, body, updated_at, tenant, principal, task, completed";
35
36#[derive(Debug, Clone)]
38pub struct SqliteStepJournal {
39 pool: SqlitePool,
40}
41
42impl SqliteStepJournal {
43 pub async fn new(url: &str) -> A2aResult<Self> {
51 let pool = crate::sqlite_pool::sqlite_pool(url)
52 .await
53 .map_err(|e| A2aError::internal(format!("run journal open: {e}")))?;
54 Self::from_pool(pool).await
55 }
56
57 pub async fn from_pool(pool: SqlitePool) -> A2aResult<Self> {
64 let migrate = |e: sqlx::Error| A2aError::internal(format!("run journal migrate: {e}"));
65 sqlx::query(CREATE_TABLE_SQL)
66 .execute(&pool)
67 .await
68 .map_err(migrate)?;
69 for (column, kind) in OWNER_COLUMNS {
70 let present: i64 = sqlx::query_scalar(
71 "SELECT count(*) FROM pragma_table_info('a2a_run_journal') WHERE name = ?1",
72 )
73 .bind(column)
74 .fetch_one(&pool)
75 .await
76 .map_err(migrate)?;
77 if present == 0 {
78 sqlx::query(sqlx::AssertSqlSafe(format!(
80 "ALTER TABLE a2a_run_journal ADD COLUMN {column} {kind}"
81 )))
82 .execute(&pool)
83 .await
84 .map_err(migrate)?;
85 }
86 }
87 for ddl in INDEX_SQL {
88 sqlx::query(ddl).execute(&pool).await.map_err(migrate)?;
89 }
90 Ok(Self { pool })
91 }
92}
93
94fn failed(what: &str, e: &sqlx::Error) -> JournalError {
95 JournalError::Store(format!("{what}: {e}"))
96}
97
98fn revision_of(r: u64) -> Result<i64, JournalError> {
99 i64::try_from(r).map_err(|_| JournalError::Store("a revision past i64".to_owned()))
100}
101
102fn entry_of(row: &SqliteRow) -> (String, JournalEntry) {
104 let entry = JournalEntry::new(
105 u64::try_from(row.get::<i64, _>(1)).unwrap_or(0),
106 RunOwner::new(row.get(4), row.get(5), row.get(6)),
107 row.get::<i64, _>(7) != 0,
108 row.get(3),
109 row.get(2),
110 );
111 (row.get(0), entry)
112}
113
114impl StepJournal for SqliteStepJournal {
115 fn load<'a>(&'a self, key: &'a str) -> JournalFuture<'a, Option<JournalEntry>> {
116 Box::pin(async move {
117 let row = sqlx::query(sqlx::AssertSqlSafe(format!(
118 "SELECT {COLUMNS} FROM a2a_run_journal WHERE run_key = ?1"
119 )))
120 .bind(key)
121 .fetch_optional(&self.pool)
122 .await
123 .map_err(|e| failed("load", &e))?;
124 Ok(row.map(|r| entry_of(&r).1))
125 })
126 }
127
128 fn save<'a>(&'a self, key: &'a str, entry: &'a JournalEntry) -> JournalFuture<'a, ()> {
129 Box::pin(async move {
130 let revision = revision_of(entry.revision)?;
131 let owner = &entry.owner;
132 let written = if revision == 1 {
135 sqlx::query(
136 "INSERT INTO a2a_run_journal
137 (run_key, revision, body, updated_at, tenant, principal, task, completed)
138 VALUES (?1, 1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT (run_key) DO NOTHING",
139 )
140 .bind(key)
141 .bind(&entry.body)
142 .bind(entry.updated_at_ms)
143 .bind(&owner.tenant)
144 .bind(&owner.principal)
145 .bind(&owner.task)
146 .bind(i64::from(entry.completed))
147 .execute(&self.pool)
148 .await
149 } else {
150 sqlx::query(
151 "UPDATE a2a_run_journal SET revision = ?2, body = ?3, updated_at = ?4,
152 tenant = ?5, principal = ?6, task = ?7, completed = ?8
153 WHERE run_key = ?1 AND revision = ?9",
154 )
155 .bind(key)
156 .bind(revision)
157 .bind(&entry.body)
158 .bind(entry.updated_at_ms)
159 .bind(&owner.tenant)
160 .bind(&owner.principal)
161 .bind(&owner.task)
162 .bind(i64::from(entry.completed))
163 .bind(revision - 1)
164 .execute(&self.pool)
165 .await
166 }
167 .map_err(|e| failed("save", &e))?;
168 if written.rows_affected() == 1 {
169 Ok(())
170 } else {
171 Err(JournalError::Conflict)
172 }
173 })
174 }
175
176 fn clear<'a>(&'a self, key: &'a str, revision: u64) -> JournalFuture<'a, ()> {
177 Box::pin(async move {
178 let revision = revision_of(revision)?;
179 let done =
182 sqlx::query("DELETE FROM a2a_run_journal WHERE run_key = ?1 AND revision = ?2")
183 .bind(key)
184 .bind(revision)
185 .execute(&self.pool)
186 .await
187 .map_err(|e| failed("clear", &e))?;
188 if done.rows_affected() == 1 {
189 return Ok(());
190 }
191 let other: Option<i64> =
192 sqlx::query_scalar("SELECT revision FROM a2a_run_journal WHERE run_key = ?1")
193 .bind(key)
194 .fetch_optional(&self.pool)
195 .await
196 .map_err(|e| failed("clear", &e))?;
197 other.map_or(Ok(()), |_| Err(JournalError::Conflict))
198 })
199 }
200
201 fn sweep(&self, completed_before_ms: i64, unfinished_before_ms: i64) -> JournalFuture<'_, u64> {
202 Box::pin(async move {
203 let done = sqlx::query(
204 "DELETE FROM a2a_run_journal
205 WHERE (completed != 0 AND updated_at < ?1) OR (completed = 0 AND updated_at < ?2)",
206 )
207 .bind(completed_before_ms)
208 .bind(unfinished_before_ms)
209 .execute(&self.pool)
210 .await
211 .map_err(|e| failed("sweep", &e))?;
212 Ok(done.rows_affected())
213 })
214 }
215
216 fn runs_of<'a>(
217 &'a self,
218 principal: &'a str,
219 tenant: Option<&'a str>,
220 ) -> JournalFuture<'a, Vec<RunSummary>> {
221 Box::pin(async move {
222 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
223 "SELECT {COLUMNS} FROM a2a_run_journal
224 WHERE principal = ?1 AND (?2 IS NULL OR tenant = ?2) ORDER BY run_key"
225 )))
226 .bind(principal)
227 .bind(tenant)
228 .fetch_all(&self.pool)
229 .await
230 .map_err(|e| failed("runs_of", &e))?;
231 Ok(rows
232 .iter()
233 .map(|r| {
234 let (key, entry) = entry_of(r);
235 entry.summary(&key)
236 })
237 .collect())
238 })
239 }
240
241 fn erase<'a>(&'a self, principal: &'a str, tenant: Option<&'a str>) -> JournalFuture<'a, u64> {
242 Box::pin(async move {
243 let mut conn = self.pool.acquire().await.map_err(|e| failed("erase", &e))?;
244 sqlx::query("PRAGMA secure_delete = ON")
246 .execute(&mut *conn)
247 .await
248 .map_err(|e| failed("erase", &e))?;
249 let done = sqlx::query(
250 "DELETE FROM a2a_run_journal WHERE principal = ?1 AND (?2 IS NULL OR tenant = ?2)",
251 )
252 .bind(principal)
253 .bind(tenant)
254 .execute(&mut *conn)
255 .await
256 .map_err(|e| failed("erase", &e))?;
257 Ok(done.rows_affected())
258 })
259 }
260}