1use workspace_hack as _;
44
45#[cfg(feature = "channels")]
46mod approvals;
47#[cfg(feature = "client-events")]
48mod client_events;
49pub mod maintenance;
50mod migrations;
51
52#[cfg(feature = "channels")]
53pub use approvals::SqliteApprovalStore;
54#[cfg(feature = "client-events")]
55pub use client_events::{ClientEventRow, DeviceRow, PairingRow, SqliteClientEventLog};
56
57use std::path::Path;
58use std::str::FromStr;
59use std::time::Duration;
60
61use aidaemon_core::{Event, RunId, RunState, RunStatus, RunStore, StoreError};
62use async_trait::async_trait;
63use serde_json::Value;
64use sqlx::Row;
65use sqlx::sqlite::{
66 SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions, SqliteSynchronous,
67};
68
69pub use migrations::{
70 MIGRATIONS, MigrateError, Migration, apply as apply_migrations, latest_version,
71 recorded_version,
72};
73
74const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
75
76#[derive(Debug, thiserror::Error)]
78pub enum Error {
79 #[error("sqlite: {0}")]
80 Sqlx(#[from] sqlx::Error),
81 #[error("json: {0}")]
82 Json(#[from] serde_json::Error),
83 #[error(
84 "database schema version {found} is newer than this build supports ({supported}); \
85 upgrade aidaemon-store-sqlite or use a different database file"
86 )]
87 SchemaTooNew { found: i64, supported: i64 },
88 #[error("migration {version} ({name}) failed: {source}")]
89 Migration {
90 version: i64,
91 name: &'static str,
92 source: sqlx::Error,
93 },
94}
95
96impl From<Error> for StoreError {
97 fn from(err: Error) -> Self {
98 StoreError(err.to_string())
99 }
100}
101
102#[derive(Debug, Clone, PartialEq)]
104pub struct StoredEvent {
105 pub run_id: String,
106 pub seq: i64,
108 pub event_type: String,
110 pub payload: Value,
111 pub created_at: String,
113}
114
115impl StoredEvent {
116 pub fn event(&self) -> Result<Event, serde_json::Error> {
118 serde_json::from_value(self.payload.clone())
119 }
120}
121
122#[derive(Debug, Clone)]
124pub struct SqliteStore {
125 pool: SqlitePool,
126}
127
128impl SqliteStore {
129 pub async fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
133 let options = SqliteConnectOptions::new()
134 .filename(path)
135 .create_if_missing(true)
136 .journal_mode(SqliteJournalMode::Wal)
137 .synchronous(SqliteSynchronous::Normal)
138 .foreign_keys(true)
139 .busy_timeout(Duration::from_secs(10))
140 .pragma("cache_size", "-65536")
143 .pragma("mmap_size", "268435456")
144 .pragma("temp_store", "MEMORY");
145 let pool = SqlitePoolOptions::new()
146 .max_connections(8)
147 .connect_with(options)
148 .await?;
149 let store = Self::from_pool(pool).await?;
150 maintenance::optimize(&store.pool, maintenance::Optimize::AtOpen).await?;
151 Ok(store)
152 }
153
154 pub async fn open_in_memory() -> Result<Self, Error> {
157 let options = SqliteConnectOptions::from_str("sqlite::memory:")?.foreign_keys(true);
158 let pool = SqlitePoolOptions::new()
159 .max_connections(1)
160 .min_connections(1)
161 .idle_timeout(None)
162 .max_lifetime(None)
163 .connect_with(options)
164 .await?;
165 Self::from_pool(pool).await
166 }
167
168 pub async fn from_pool(pool: SqlitePool) -> Result<Self, Error> {
171 migrations::run(&pool).await?;
172 Ok(Self { pool })
173 }
174
175 pub fn pool(&self) -> &SqlitePool {
176 &self.pool
177 }
178
179 pub async fn schema_version(&self) -> Result<i64, Error> {
181 migrations::current_version(&self.pool).await
182 }
183
184 pub async fn append(&self, run_id: RunId, event: &Event) -> Result<i64, Error> {
188 let payload = serde_json::to_value(event)?;
189 let event_type = payload
190 .get("type")
191 .and_then(Value::as_str)
192 .unwrap_or("unknown")
193 .to_string();
194 let run_id = run_id.to_string();
195 let seq: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
196 "INSERT INTO run_events (run_id, seq, event_type, payload, created_at)
197 SELECT ?1, COALESCE(MAX(seq), 0) + 1, ?2, ?3, {NOW}
198 FROM run_events WHERE run_id = ?1
199 RETURNING seq"
200 )))
201 .bind(&run_id)
202 .bind(event_type)
203 .bind(payload.to_string())
204 .fetch_one(&self.pool)
205 .await?;
206 Ok(seq)
207 }
208
209 pub async fn run_ended(&self, run_id: RunId) -> Result<bool, Error> {
214 let last: Option<(String, String)> = sqlx::query_as(
215 "SELECT event_type, payload FROM run_events WHERE run_id = ? \
216 ORDER BY seq DESC LIMIT 1",
217 )
218 .bind(run_id.to_string())
219 .fetch_optional(&self.pool)
220 .await?;
221 let Some((event_type, payload)) = last else {
222 return Ok(false);
223 };
224 if event_type != "finished" {
225 return Ok(false);
226 }
227 let paused = serde_json::from_str::<Event>(&payload).is_ok_and(|event| {
228 matches!(
229 event,
230 Event::Finished {
231 status: RunStatus::Interrupted { .. },
232 ..
233 }
234 )
235 });
236 Ok(!paused)
237 }
238
239 pub async fn events(&self, run_id: RunId) -> Result<Vec<Event>, Error> {
241 self.raw_events(run_id)
242 .await?
243 .iter()
244 .map(|e| e.event().map_err(Error::from))
245 .collect()
246 }
247
248 pub async fn raw_events(&self, run_id: RunId) -> Result<Vec<StoredEvent>, Error> {
250 let rows = sqlx::query(
251 "SELECT run_id, seq, event_type, payload, created_at
252 FROM run_events WHERE run_id = ? ORDER BY seq",
253 )
254 .bind(run_id.to_string())
255 .fetch_all(&self.pool)
256 .await?;
257 rows.into_iter()
258 .map(|row| {
259 let payload: String = row.try_get("payload")?;
260 Ok(StoredEvent {
261 run_id: row.try_get("run_id")?,
262 seq: row.try_get("seq")?,
263 event_type: row.try_get("event_type")?,
264 payload: serde_json::from_str(&payload)?,
265 created_at: row.try_get("created_at")?,
266 })
267 })
268 .collect()
269 }
270
271 pub async fn upsert_state(&self, state: &RunState) -> Result<(), Error> {
273 let json = serde_json::to_string(state)?;
274 sqlx::query(sqlx::AssertSqlSafe(format!(
275 "INSERT INTO run_states (run_id, agent_id, session_id, state, updated_at)
276 VALUES (?, ?, ?, ?, {NOW})
277 ON CONFLICT (run_id) DO UPDATE SET
278 agent_id = excluded.agent_id,
279 session_id = excluded.session_id,
280 state = excluded.state,
281 updated_at = excluded.updated_at"
282 )))
283 .bind(state.run_id.to_string())
284 .bind(&state.agent_id)
285 .bind(&state.session_id)
286 .bind(json)
287 .execute(&self.pool)
288 .await?;
289 Ok(())
290 }
291
292 pub async fn state(&self, run_id: RunId) -> Result<Option<RunState>, Error> {
294 let row: Option<String> =
295 sqlx::query_scalar("SELECT state FROM run_states WHERE run_id = ?")
296 .bind(run_id.to_string())
297 .fetch_optional(&self.pool)
298 .await?;
299 row.map(|s| serde_json::from_str(&s).map_err(Error::from))
300 .transpose()
301 }
302
303 pub async fn runs_for_session(&self, session_id: &str) -> Result<Vec<RunState>, Error> {
305 self.states_where("session_id = ?", Some(session_id), false, None)
306 .await
307 }
308
309 pub async fn latest_state_for_session(
311 &self,
312 session_id: &str,
313 ) -> Result<Option<RunState>, Error> {
314 let mut states = self
315 .states_where("session_id = ?", Some(session_id), true, Some(1))
316 .await?;
317 Ok(states.pop())
318 }
319
320 pub async fn interrupted_runs(&self) -> Result<Vec<RunState>, Error> {
326 self.states_where(
327 "json_extract(state, '$.pending') IS NOT NULL \
328 AND json_extract(state, '$.parent_run') IS NULL",
329 None,
330 false,
331 None,
332 )
333 .await
334 }
335
336 pub async fn in_flight_runs(&self) -> Result<Vec<RunState>, Error> {
341 self.states_where(
342 "json_extract(state, '$.in_flight') IS NOT NULL",
343 None,
344 false,
345 None,
346 )
347 .await
348 }
349
350 pub async fn clock(&self) -> Result<String, Error> {
354 let now: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!("SELECT {NOW}")))
355 .fetch_one(&self.pool)
356 .await?;
357 Ok(now)
358 }
359
360 pub async fn unfinished_runs_since(&self, since: &str) -> Result<Vec<RunState>, Error> {
365 let candidates = self
366 .states_where_since(
367 "json_extract(state, '$.parent_run') IS NULL AND updated_at >= ?",
368 since,
369 )
370 .await?;
371 let mut unfinished = Vec::new();
372 for state in candidates {
373 if self.run_ended(state.run_id).await? {
374 continue;
375 }
376 let latest = self.latest_state_for_session(&state.session_id).await?;
377 if latest.is_some_and(|latest| latest.run_id == state.run_id) {
378 unfinished.push(state);
379 }
380 }
381 Ok(unfinished)
382 }
383
384 pub async fn unfinished_background_runs_since(
389 &self,
390 since: &str,
391 ) -> Result<Vec<RunState>, Error> {
392 let candidates = self
393 .states_where_since(
394 "json_extract(state, '$.parent_run') IS NOT NULL AND updated_at >= ?",
395 since,
396 )
397 .await?;
398 let mut unfinished = Vec::new();
399 for state in candidates {
400 let Some(parent) = state.parent_run else {
401 continue;
402 };
403 if self.run_ended(state.run_id).await? || !self.run_ended(parent).await? {
404 continue;
405 }
406 unfinished.push(state);
407 }
408 Ok(unfinished)
409 }
410
411 async fn states_where_since(
412 &self,
413 predicate: &str,
414 since: &str,
415 ) -> Result<Vec<RunState>, Error> {
416 let sql =
418 format!("SELECT state FROM run_states WHERE {predicate} ORDER BY updated_at, rowid");
419 sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*sql))
420 .bind(since)
421 .fetch_all(&self.pool)
422 .await?
423 .iter()
424 .map(|s| serde_json::from_str(s).map_err(Error::from))
425 .collect()
426 }
427
428 async fn states_where(
429 &self,
430 predicate: &str,
431 bind: Option<&str>,
432 newest_first: bool,
433 limit: Option<u32>,
434 ) -> Result<Vec<RunState>, Error> {
435 let dir = if newest_first { "DESC" } else { "ASC" };
437 let limit = limit.map(|n| format!(" LIMIT {n}")).unwrap_or_default();
438 let sql = format!(
439 "SELECT state FROM run_states WHERE {predicate}
440 ORDER BY updated_at {dir}, rowid {dir}{limit}"
441 );
442 let mut query = sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*sql));
443 if let Some(value) = bind {
444 query = query.bind(value);
445 }
446 query
447 .fetch_all(&self.pool)
448 .await?
449 .iter()
450 .map(|s| serde_json::from_str(s).map_err(Error::from))
451 .collect()
452 }
453
454 pub async fn close(&self) {
456 self.pool.close().await;
457 }
458}
459
460#[async_trait]
461impl RunStore for SqliteStore {
462 async fn append_event(&self, run_id: RunId, event: &Event) -> Result<(), StoreError> {
463 self.append(run_id, event).await?;
464 Ok(())
465 }
466
467 async fn save_state(&self, state: &RunState) -> Result<(), StoreError> {
468 Ok(self.upsert_state(state).await?)
469 }
470
471 async fn load_state(&self, run_id: RunId) -> Result<Option<RunState>, StoreError> {
472 Ok(self.state(run_id).await?)
473 }
474}
475
476pub async fn erase_session_in_tx(
484 tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
485 session_id: &str,
486) -> Result<(), Error> {
487 let journaled: Option<String> = sqlx::query_scalar(
490 "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'run_states'",
491 )
492 .fetch_optional(&mut **tx)
493 .await?;
494 if journaled.is_none() {
495 return Ok(());
496 }
497 sqlx::query("DROP TRIGGER IF EXISTS run_events_no_delete")
498 .execute(&mut **tx)
499 .await?;
500 sqlx::query(
501 "DELETE FROM run_events
502 WHERE run_id IN (SELECT run_id FROM run_states WHERE session_id = ?)",
503 )
504 .bind(session_id)
505 .execute(&mut **tx)
506 .await?;
507 sqlx::query(
508 "CREATE TRIGGER run_events_no_delete BEFORE DELETE ON run_events
509 BEGIN SELECT RAISE(ABORT, 'run_events is append-only'); END",
510 )
511 .execute(&mut **tx)
512 .await?;
513 sqlx::query("DELETE FROM run_states WHERE session_id = ?")
514 .bind(session_id)
515 .execute(&mut **tx)
516 .await?;
517 Ok(())
518}