mod downloads;
mod journal;
mod leases;
mod mirror;
mod owner;
mod resources;
mod rows;
mod runs;
mod schema;
#[cfg(test)]
mod tests;
#[cfg(test)]
pub(crate) use owner::tests::dead_pid;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use rusqlite::{Connection, TransactionBehavior};
use serde::Serialize;
use serde::de::DeserializeOwned;
pub use leases::Reserver;
pub use mirror::{MIRROR_FILE, Recovered};
pub use owner::Owner;
pub use rows::{
CopyName, Ended, EventCursor, EventPage, Lease, LeaseOutcome, Lifetime, NewResource, NotPerCopy, OperationId, OperationRow, Outcome, PortReservation,
ResourceId, ResourceKind, ResourceRow, ResourceState, RunRow, Scope,
};
use crate::Result;
use crate::error::{Error, ErrorCode};
pub(crate) const DB_FILE: &str = "state.db";
const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
pub struct Store {
conn: Mutex<Connection>,
path: PathBuf,
mirror: PathBuf,
mirrored: AtomicI64,
recovered: Option<Recovered>,
}
impl std::fmt::Debug for Store {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Store").field("path", &self.path).finish_non_exhaustive()
}
}
pub struct Tx<'c> {
tx: rusqlite::Transaction<'c>,
}
impl Store {
pub fn open(home: &Path) -> Result<Store> {
let home = &std::path::absolute(home).map_err(Error::io(home, "made absolute"))?;
crate::store::create_dir(home)?;
let path = home.join(DB_FILE);
let mirror = home.join(MIRROR_FILE);
match Store::open_checked(&path, &mirror, Fresh::Suspect) {
Ok(store) => {
store.sync_mirror();
Ok(store)
}
Err(e) if e.code() == ErrorCode::StoreCorrupt => Store::rebuild(&path, &mirror, &e),
Err(e) => Err(e),
}
}
fn open_checked(path: &Path, mirror: &Path, fresh: Fresh) -> Result<Store> {
let conn = connect(path)?;
quick_check(&conn)?;
let store = Store {
conn: Mutex::new(conn),
path: path.to_path_buf(),
mirror: mirror.to_path_buf(),
mirrored: AtomicI64::new(-1),
recovered: None,
};
let was = store.migrate()?;
if was == 0 && fresh == Fresh::Suspect && mirror::read(mirror).is_some_and(|m| m.holds_rows()) {
return Err(Error::Store {
action: "opened",
code: ErrorCode::StoreCorrupt,
reason: "its file is empty, but its mirror holds runs, operations or resources".to_owned(),
});
}
Ok(store)
}
pub fn read_existing<T>(home: &Path, f: impl FnOnce(&Tx<'_>) -> Result<T>) -> Result<Option<T>> {
let path = home.join(DB_FILE);
if !path.is_file() {
return Ok(None);
}
let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX;
let conn = Connection::open_with_flags(&path, flags).map_err(failed("opened"))?;
conn.busy_timeout(BUSY_TIMEOUT).map_err(failed("opened"))?;
let store = Store {
conn: Mutex::new(conn),
path,
mirror: home.join(MIRROR_FILE),
mirrored: AtomicI64::new(-1),
recovered: None,
};
store.read(f).map(Some)
}
fn rebuild(path: &Path, mirror: &Path, cause: &Error) -> Result<Store> {
let damaged = |reason: String| Error::Store {
action: "opened",
code: ErrorCode::StoreCorrupt,
reason,
};
let Some(copy) = mirror::read(mirror) else {
return Err(damaged(format!("{cause}; and there is no mirror to rebuild it from")));
};
let known = i64::try_from(schema::MIGRATIONS.len()).unwrap_or(i64::MAX);
if copy.schema() != known {
return Err(damaged(format!("{cause}; and its mirror is of schema {}, not {known}", copy.schema())));
}
let kept = set_aside(path)?;
tracing::warn!(error = %cause, kept = %kept.display(), "the store was damaged: rebuilt from its mirror");
let mut store = Store::open_checked(path, mirror, Fresh::Expected)?;
{
let mut conn = store.conn.lock().unwrap_or_else(PoisonError::into_inner);
copy.restore(&mut conn)?;
}
store.sync_mirror();
store.recovered = Some(Recovered {
corrupt_kept_at: kept,
mirror_written_at: copy.written_at().to_owned(),
reason: cause.to_string(),
});
Ok(store)
}
#[must_use]
pub fn recovered(&self) -> Option<&Recovered> {
self.recovered.as_ref()
}
fn sync_mirror(&self) {
let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
match conn.transaction_with_behavior(TransactionBehavior::Deferred) {
Ok(tx) => self.mirror_within(&tx),
Err(e) => tracing::warn!(error = %e, "the store's mirror wasn't written"),
}
}
fn mirror_within(&self, conn: &Connection) {
let written = mirror::generation(conn).map_err(failed("read")).and_then(|n| {
if n == self.mirrored.load(Ordering::SeqCst) {
Ok(None)
} else {
mirror::write(conn, n, &self.mirror).map(|()| Some(n))
}
});
match written {
Ok(Some(n)) => self.mirrored.store(n, Ordering::SeqCst),
Ok(None) => {}
Err(e) => {
self.mirrored.store(-1, Ordering::SeqCst);
tracing::warn!(error = %e, "the store's mirror wasn't written");
}
}
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn read<T>(&self, f: impl FnOnce(&Tx<'_>) -> Result<T>) -> Result<T> {
let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
let tx = conn.transaction_with_behavior(TransactionBehavior::Deferred).map_err(failed("read"))?;
let tx = Tx { tx };
let value = f(&tx)?;
tx.tx.finish().map_err(failed("read"))?;
Ok(value)
}
pub fn write<T>(&self, f: impl FnOnce(&mut Tx<'_>) -> Result<T>) -> Result<T> {
let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
let committed = {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(failed("written"))?;
let mut tx = Tx { tx };
let value = f(&mut tx)?;
self.mirror_within(&tx.tx);
tx.tx.commit().map(|()| value)
};
committed.map_err(|e| {
self.mirrored.store(-1, Ordering::SeqCst);
drop(conn);
self.sync_mirror();
failed("written")(e)
})
}
fn migrate(&self) -> Result<i64> {
let mut conn = self.conn.lock().unwrap_or_else(PoisonError::into_inner);
conn.execute_batch("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)")
.map_err(failed("migrated"))?;
let applied: i64 = conn
.query_row("SELECT COALESCE(MAX(version), 0) FROM schema_migrations", [], |r| r.get(0))
.map_err(failed("migrated"))?;
let known = i64::try_from(schema::MIGRATIONS.len()).unwrap_or(i64::MAX);
if applied > known {
return Err(Error::Store {
action: "opened",
code: ErrorCode::StoreVersion,
reason: format!("its schema is version {applied}, newer than this runner's {known}: a newer runner wrote it"),
});
}
for (version, sql) in (1..).zip(schema::MIGRATIONS).skip(usize::try_from(applied).unwrap_or(0)) {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate).map_err(failed("migrated"))?;
tx.execute_batch(sql).map_err(failed("migrated"))?;
tx.execute(
"INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)",
rusqlite::params![version, now()],
)
.map_err(failed("migrated"))?;
tx.commit().map_err(failed("migrated"))?;
}
Ok(applied)
}
}
impl Tx<'_> {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Fresh {
Suspect,
Expected,
}
fn connect(path: &Path) -> Result<Connection> {
let conn = Connection::open(path).map_err(failed("opened"))?;
#[cfg(unix)]
restrict(path)?;
conn.busy_timeout(BUSY_TIMEOUT).map_err(failed("opened"))?;
conn.pragma_update(None, "journal_mode", "WAL").map_err(failed("opened"))?;
conn.pragma_update(None, "foreign_keys", "ON").map_err(failed("opened"))?;
conn.pragma_update(None, "synchronous", "NORMAL").map_err(failed("opened"))?;
Ok(conn)
}
const FINDINGS_SAID: usize = 3;
fn quick_check(conn: &Connection) -> Result<()> {
let mut stmt = conn.prepare("PRAGMA quick_check").map_err(failed("checked"))?;
let findings: Vec<String> = stmt
.query_map([], |r| r.get::<_, String>(0))
.map_err(failed("checked"))?
.collect::<rusqlite::Result<_>>()
.map_err(failed("checked"))?;
if findings.iter().all(|f| f == "ok") {
return Ok(());
}
let said: Vec<&str> = findings.iter().take(FINDINGS_SAID).map(String::as_str).collect();
Err(Error::Store {
action: "checked",
code: ErrorCode::StoreCorrupt,
reason: format!("its integrity check failed ({} findings): {}", findings.len(), said.join("; ")),
})
}
fn set_aside(path: &Path) -> Result<PathBuf> {
let kept = path.with_file_name(format!("{DB_FILE}.corrupt-{}", epoch_now()));
for suffix in ["", "-wal", "-shm"] {
let with = |p: &Path| {
let mut name = p.as_os_str().to_owned();
name.push(suffix);
PathBuf::from(name)
};
let (from, to) = (with(path), with(&kept));
if from.exists() {
std::fs::rename(&from, &to).map_err(Error::io(&from, "moved aside"))?;
}
}
Ok(kept)
}
pub(crate) fn failed(action: &'static str) -> impl Fn(rusqlite::Error) -> Error {
move |e| {
let code = match e.sqlite_error_code() {
Some(rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked) => ErrorCode::Locked,
Some(rusqlite::ErrorCode::NotADatabase | rusqlite::ErrorCode::DatabaseCorrupt) => ErrorCode::StoreCorrupt,
_ => ErrorCode::Io,
};
Error::Store {
action,
code,
reason: e.to_string(),
}
}
}
pub(crate) fn corrupt(what: &str, value: &str) -> Error {
Error::Store {
action: "read",
code: ErrorCode::StoreCorrupt,
reason: format!("a {what} column holds `{value}`, which this runner doesn't write"),
}
}
pub(crate) fn word<T: Serialize>(value: &T) -> String {
crate::encoding::wire_name(value)
}
pub(crate) fn from_word<T: DeserializeOwned>(what: &str, word: &str) -> Result<T> {
crate::encoding::from_wire_name(word).ok_or_else(|| corrupt(what, word))
}
pub(crate) fn to_json<T: Serialize>(value: &T) -> Result<String> {
serde_json::to_string(value).map_err(|e| Error::Store {
action: "written",
code: ErrorCode::Io,
reason: e.to_string(),
})
}
pub(crate) fn from_json<T: DeserializeOwned>(what: &str, text: &str) -> Result<T> {
serde_json::from_str(text).map_err(|e| Error::Store {
action: "read",
code: ErrorCode::StoreCorrupt,
reason: format!("its {what} doesn't parse: {e}"),
})
}
pub(crate) fn now() -> String {
crate::clock::rfc3339(std::time::SystemTime::now())
}
pub(crate) fn epoch_now() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs())
}
#[cfg(unix)]
fn restrict(path: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(Error::io(path, "made owner-only"))
}