Initial code commit
CI / test (push) Successful in 5m7s

This commit is contained in:
IxianPixel committed 2026-11-05 14:19:37 +00:00
1 parent f47217d5a3
commit 8ceb3c8be8
60 files changed
+10884

No files matched your search

+208
View File
@@ -0,0 +1,208 @@
//! Persistent state in SQLite (WAL mode).
//!
//! Jobs and exports are stored as JSON documents with a few indexed columns.
//! The schema is deliberately small; the job struct is the source of truth.
use std::path::Path;
use std::sync::{Arc, Mutex};
use jm_core::{Job, JobId};
use rusqlite::{Connection, OptionalExtension, params};
use serde::{Serialize, de::DeserializeOwned};
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
#[error("database error: {0}")]
Sql(#[from] rusqlite::Error),
#[error("corrupt record: {0}")]
Json(#[from] serde_json::Error),
}
type Result<T> = std::result::Result<T, StoreError>;
const MIGRATIONS: &[&str] = &[
// v1
"CREATE TABLE jobs (
id TEXT PRIMARY KEY,
active INTEGER NOT NULL,
created TEXT NOT NULL,
body TEXT NOT NULL
);
CREATE INDEX jobs_active ON jobs(active);
CREATE TABLE exports (
id TEXT PRIMARY KEY,
body TEXT NOT NULL
);",
];
#[derive(Clone)]
pub struct Store {
conn: Arc<Mutex<Connection>>,
}
impl Store {
pub fn open(path: &Path) -> Result<Self> {
Self::init(Connection::open(path)?)
}
pub fn in_memory() -> Result<Self> {
Self::init(Connection::open_in_memory()?)
}
fn init(conn: Connection) -> Result<Self> {
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
let version: i64 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?;
for (i, sql) in MIGRATIONS.iter().enumerate().skip(version as usize) {
conn.execute_batch(sql)?;
conn.pragma_update(None, "user_version", (i + 1) as i64)?;
}
Ok(Self {
conn: Arc::new(Mutex::new(conn)),
})
}
async fn with<T: Send + 'static>(
&self,
f: impl FnOnce(&Connection) -> Result<T> + Send + 'static,
) -> Result<T> {
let conn = self.conn.clone();
tokio::task::spawn_blocking(move || f(&conn.lock().expect("store mutex poisoned")))
.await
.expect("store task panicked")
}
pub async fn put_job(&self, job: &Job) -> Result<()> {
let id = job.id.to_string();
let active = job.status.is_active();
let created = job.created.unix_timestamp().to_string();
let body = serde_json::to_string(job)?;
self.with(move |c| {
c.execute(
"INSERT INTO jobs (id, active, created, body) VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(id) DO UPDATE SET active = excluded.active, body = excluded.body",
params![id, active, created, body],
)?;
Ok(())
})
.await
}
pub async fn get_job(&self, id: JobId) -> Result<Option<Job>> {
let id = id.to_string();
let body: Option<String> = self
.with(move |c| {
Ok(
c.query_row("SELECT body FROM jobs WHERE id = ?1", [id], |r| r.get(0))
.optional()?,
)
})
.await?;
body.map(|b| serde_json::from_str(&b).map_err(Into::into))
.transpose()
}
/// Most recent jobs first.
pub async fn list_jobs(&self, limit: usize) -> Result<Vec<Job>> {
self.query_jobs(
"SELECT body FROM jobs ORDER BY created DESC, rowid DESC LIMIT ?1",
limit,
)
.await
}
/// Jobs that were queued or running, e.g. when the daemon last stopped.
pub async fn active_jobs(&self) -> Result<Vec<Job>> {
self.query_jobs(
"SELECT body FROM jobs WHERE active = 1 ORDER BY created ASC LIMIT ?1",
10_000,
)
.await
}
async fn query_jobs(&self, sql: &'static str, limit: usize) -> Result<Vec<Job>> {
let bodies: Vec<String> = self
.with(move |c| {
let mut stmt = c.prepare(sql)?;
let rows = stmt.query_map([limit as i64], |r| r.get(0))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
})
.await?;
bodies
.iter()
.map(|b| serde_json::from_str(b).map_err(Into::into))
.collect()
}
pub async fn put_export<T: Serialize>(&self, id: &str, export: &T) -> Result<()> {
let id = id.to_string();
let body = serde_json::to_string(export)?;
self.with(move |c| {
c.execute(
"INSERT INTO exports (id, body) VALUES (?1, ?2)
ON CONFLICT(id) DO UPDATE SET body = excluded.body",
params![id, body],
)?;
Ok(())
})
.await
}
pub async fn get_export<T: DeserializeOwned>(&self, id: &str) -> Result<Option<T>> {
let id = id.to_string();
let body: Option<String> = self
.with(move |c| {
Ok(
c.query_row("SELECT body FROM exports WHERE id = ?1", [id], |r| r.get(0))
.optional()?,
)
})
.await?;
body.map(|b| serde_json::from_str(&b).map_err(Into::into))
.transpose()
}
}
#[cfg(test)]
mod tests {
use super::*;
use jm_core::JobStatus;
#[tokio::test]
async fn jobs_roundtrip_and_track_activity() {
let store = Store::in_memory().unwrap();
let mut a = Job::new("1", "A", "cloud", "home", false);
let b = Job::new("2", "B", "cloud", "home", false);
store.put_job(&a).await.unwrap();
store.put_job(&b).await.unwrap();
assert_eq!(store.active_jobs().await.unwrap().len(), 2);
a.status = JobStatus::Done;
store.put_job(&a).await.unwrap();
let active = store.active_jobs().await.unwrap();
assert_eq!(active.len(), 1);
assert_eq!(active[0].name, "B");
let got = store.get_job(a.id).await.unwrap().unwrap();
assert_eq!(got.status, JobStatus::Done);
assert_eq!(store.list_jobs(10).await.unwrap().len(), 2);
}
#[tokio::test]
async fn survives_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("state.db");
let job = Job::new("1", "A", "cloud", "home", false);
{
let s = Store::open(&path).unwrap();
s.put_job(&job).await.unwrap();
s.put_export("e1", &serde_json::json!({"x": 1}))
.await
.unwrap();
}
let s = Store::open(&path).unwrap();
assert!(s.get_job(job.id).await.unwrap().is_some());
let e: serde_json::Value = s.get_export("e1").await.unwrap().unwrap();
assert_eq!(e["x"], 1);
}
}