#[cfg(feature = "channels")]
mod approvals;
#[cfg(feature = "client-events")]
mod client_events;
pub mod maintenance;
mod migrations;
#[cfg(feature = "channels")]
pub use approvals::SqliteApprovalStore;
#[cfg(feature = "client-events")]
pub use client_events::{ClientEventRow, DeviceRow, PairingRow, SqliteClientEventLog};
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;
use aidaemon_core::{Event, RunId, RunState, RunStatus, RunStore, StoreError};
use async_trait::async_trait;
use serde_json::Value;
use sqlx::Row;
use sqlx::sqlite::{
SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions, SqliteSynchronous,
};
pub use migrations::{MIGRATIONS, Migration, latest_version};
const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("sqlite: {0}")]
Sqlx(#[from] sqlx::Error),
#[error("json: {0}")]
Json(#[from] serde_json::Error),
#[error(
"database schema version {found} is newer than this build supports ({supported}); \
upgrade aidaemon-store-sqlite or use a different database file"
)]
SchemaTooNew { found: i64, supported: i64 },
#[error("migration {version} ({name}) failed: {source}")]
Migration {
version: i64,
name: &'static str,
source: sqlx::Error,
},
}
impl From<Error> for StoreError {
fn from(err: Error) -> Self {
StoreError(err.to_string())
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct StoredEvent {
pub run_id: String,
pub seq: i64,
pub event_type: String,
pub payload: Value,
pub created_at: String,
}
impl StoredEvent {
pub fn event(&self) -> Result<Event, serde_json::Error> {
serde_json::from_value(self.payload.clone())
}
}
#[derive(Debug, Clone)]
pub struct SqliteStore {
pool: SqlitePool,
}
impl SqliteStore {
pub async fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
let options = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true)
.journal_mode(SqliteJournalMode::Wal)
.synchronous(SqliteSynchronous::Normal)
.foreign_keys(true)
.busy_timeout(Duration::from_secs(10))
.pragma("cache_size", "-65536")
.pragma("mmap_size", "268435456")
.pragma("temp_store", "MEMORY");
let pool = SqlitePoolOptions::new()
.max_connections(8)
.connect_with(options)
.await?;
let store = Self::from_pool(pool).await?;
maintenance::optimize(&store.pool, maintenance::Optimize::AtOpen).await?;
Ok(store)
}
pub async fn open_in_memory() -> Result<Self, Error> {
let options = SqliteConnectOptions::from_str("sqlite::memory:")?.foreign_keys(true);
let pool = SqlitePoolOptions::new()
.max_connections(1)
.min_connections(1)
.idle_timeout(None)
.max_lifetime(None)
.connect_with(options)
.await?;
Self::from_pool(pool).await
}
pub async fn from_pool(pool: SqlitePool) -> Result<Self, Error> {
migrations::run(&pool).await?;
Ok(Self { pool })
}
pub fn pool(&self) -> &SqlitePool {
&self.pool
}
pub async fn schema_version(&self) -> Result<i64, Error> {
migrations::current_version(&self.pool).await
}
pub async fn append(&self, run_id: RunId, event: &Event) -> Result<i64, Error> {
let payload = serde_json::to_value(event)?;
let event_type = payload
.get("type")
.and_then(Value::as_str)
.unwrap_or("unknown")
.to_string();
let run_id = run_id.to_string();
let seq: i64 = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
"INSERT INTO run_events (run_id, seq, event_type, payload, created_at)
SELECT ?1, COALESCE(MAX(seq), 0) + 1, ?2, ?3, {NOW}
FROM run_events WHERE run_id = ?1
RETURNING seq"
)))
.bind(&run_id)
.bind(event_type)
.bind(payload.to_string())
.fetch_one(&self.pool)
.await?;
Ok(seq)
}
pub async fn run_ended(&self, run_id: RunId) -> Result<bool, Error> {
let last: Option<(String, String)> = sqlx::query_as(
"SELECT event_type, payload FROM run_events WHERE run_id = ? \
ORDER BY seq DESC LIMIT 1",
)
.bind(run_id.to_string())
.fetch_optional(&self.pool)
.await?;
let Some((event_type, payload)) = last else {
return Ok(false);
};
if event_type != "finished" {
return Ok(false);
}
let paused = serde_json::from_str::<Event>(&payload).is_ok_and(|event| {
matches!(
event,
Event::Finished {
status: RunStatus::Interrupted { .. },
..
}
)
});
Ok(!paused)
}
pub async fn events(&self, run_id: RunId) -> Result<Vec<Event>, Error> {
self.raw_events(run_id)
.await?
.iter()
.map(|e| e.event().map_err(Error::from))
.collect()
}
pub async fn raw_events(&self, run_id: RunId) -> Result<Vec<StoredEvent>, Error> {
let rows = sqlx::query(
"SELECT run_id, seq, event_type, payload, created_at
FROM run_events WHERE run_id = ? ORDER BY seq",
)
.bind(run_id.to_string())
.fetch_all(&self.pool)
.await?;
rows.into_iter()
.map(|row| {
let payload: String = row.try_get("payload")?;
Ok(StoredEvent {
run_id: row.try_get("run_id")?,
seq: row.try_get("seq")?,
event_type: row.try_get("event_type")?,
payload: serde_json::from_str(&payload)?,
created_at: row.try_get("created_at")?,
})
})
.collect()
}
pub async fn upsert_state(&self, state: &RunState) -> Result<(), Error> {
let json = serde_json::to_string(state)?;
sqlx::query(sqlx::AssertSqlSafe(format!(
"INSERT INTO run_states (run_id, agent_id, session_id, state, updated_at)
VALUES (?, ?, ?, ?, {NOW})
ON CONFLICT (run_id) DO UPDATE SET
agent_id = excluded.agent_id,
session_id = excluded.session_id,
state = excluded.state,
updated_at = excluded.updated_at"
)))
.bind(state.run_id.to_string())
.bind(&state.agent_id)
.bind(&state.session_id)
.bind(json)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn state(&self, run_id: RunId) -> Result<Option<RunState>, Error> {
let row: Option<String> =
sqlx::query_scalar("SELECT state FROM run_states WHERE run_id = ?")
.bind(run_id.to_string())
.fetch_optional(&self.pool)
.await?;
row.map(|s| serde_json::from_str(&s).map_err(Error::from))
.transpose()
}
pub async fn runs_for_session(&self, session_id: &str) -> Result<Vec<RunState>, Error> {
self.states_where("session_id = ?", Some(session_id), false, None)
.await
}
pub async fn latest_state_for_session(
&self,
session_id: &str,
) -> Result<Option<RunState>, Error> {
let mut states = self
.states_where("session_id = ?", Some(session_id), true, Some(1))
.await?;
Ok(states.pop())
}
pub async fn interrupted_runs(&self) -> Result<Vec<RunState>, Error> {
self.states_where(
"json_extract(state, '$.pending') IS NOT NULL \
AND json_extract(state, '$.parent_run') IS NULL",
None,
false,
None,
)
.await
}
pub async fn in_flight_runs(&self) -> Result<Vec<RunState>, Error> {
self.states_where(
"json_extract(state, '$.in_flight') IS NOT NULL",
None,
false,
None,
)
.await
}
pub async fn clock(&self) -> Result<String, Error> {
let now: String = sqlx::query_scalar(sqlx::AssertSqlSafe(format!("SELECT {NOW}")))
.fetch_one(&self.pool)
.await?;
Ok(now)
}
pub async fn unfinished_runs_since(&self, since: &str) -> Result<Vec<RunState>, Error> {
let candidates = self
.states_where_since(
"json_extract(state, '$.parent_run') IS NULL AND updated_at >= ?",
since,
)
.await?;
let mut unfinished = Vec::new();
for state in candidates {
if self.run_ended(state.run_id).await? {
continue;
}
let latest = self.latest_state_for_session(&state.session_id).await?;
if latest.is_some_and(|latest| latest.run_id == state.run_id) {
unfinished.push(state);
}
}
Ok(unfinished)
}
pub async fn unfinished_background_runs_since(
&self,
since: &str,
) -> Result<Vec<RunState>, Error> {
let candidates = self
.states_where_since(
"json_extract(state, '$.parent_run') IS NOT NULL AND updated_at >= ?",
since,
)
.await?;
let mut unfinished = Vec::new();
for state in candidates {
let Some(parent) = state.parent_run else {
continue;
};
if self.run_ended(state.run_id).await? || !self.run_ended(parent).await? {
continue;
}
unfinished.push(state);
}
Ok(unfinished)
}
async fn states_where_since(
&self,
predicate: &str,
since: &str,
) -> Result<Vec<RunState>, Error> {
let sql =
format!("SELECT state FROM run_states WHERE {predicate} ORDER BY updated_at, rowid");
sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*sql))
.bind(since)
.fetch_all(&self.pool)
.await?
.iter()
.map(|s| serde_json::from_str(s).map_err(Error::from))
.collect()
}
async fn states_where(
&self,
predicate: &str,
bind: Option<&str>,
newest_first: bool,
limit: Option<u32>,
) -> Result<Vec<RunState>, Error> {
let dir = if newest_first { "DESC" } else { "ASC" };
let limit = limit.map(|n| format!(" LIMIT {n}")).unwrap_or_default();
let sql = format!(
"SELECT state FROM run_states WHERE {predicate}
ORDER BY updated_at {dir}, rowid {dir}{limit}"
);
let mut query = sqlx::query_scalar::<_, String>(sqlx::AssertSqlSafe(&*sql));
if let Some(value) = bind {
query = query.bind(value);
}
query
.fetch_all(&self.pool)
.await?
.iter()
.map(|s| serde_json::from_str(s).map_err(Error::from))
.collect()
}
pub async fn close(&self) {
self.pool.close().await;
}
}
#[async_trait]
impl RunStore for SqliteStore {
async fn append_event(&self, run_id: RunId, event: &Event) -> Result<(), StoreError> {
self.append(run_id, event).await?;
Ok(())
}
async fn save_state(&self, state: &RunState) -> Result<(), StoreError> {
Ok(self.upsert_state(state).await?)
}
async fn load_state(&self, run_id: RunId) -> Result<Option<RunState>, StoreError> {
Ok(self.state(run_id).await?)
}
}
pub async fn erase_session_in_tx(
tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
session_id: &str,
) -> Result<(), Error> {
let journaled: Option<String> = sqlx::query_scalar(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'run_states'",
)
.fetch_optional(&mut **tx)
.await?;
if journaled.is_none() {
return Ok(());
}
sqlx::query("DROP TRIGGER IF EXISTS run_events_no_delete")
.execute(&mut **tx)
.await?;
sqlx::query(
"DELETE FROM run_events
WHERE run_id IN (SELECT run_id FROM run_states WHERE session_id = ?)",
)
.bind(session_id)
.execute(&mut **tx)
.await?;
sqlx::query(
"CREATE TRIGGER run_events_no_delete BEFORE DELETE ON run_events
BEGIN SELECT RAISE(ABORT, 'run_events is append-only'); END",
)
.execute(&mut **tx)
.await?;
sqlx::query("DELETE FROM run_states WHERE session_id = ?")
.bind(session_id)
.execute(&mut **tx)
.await?;
Ok(())
}