use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use rusqlite::{Connection, OptionalExtension, params};
use crate::canon::{self, CANON_VERSION, Canonical, Form, Note};
use crate::hash::ContentHash;
use crate::key::{KEY_VERSION, StepKey};
use crate::remote::request::Method;
use crate::store::published::{self, REMOTES, STEPS};
use crate::store::{BlobStore, ObjectKey, StoreError, TieredStore, suffix_of as suffix};
use crate::types::DataKind;
const SCHEMA_VERSION: u32 = 5;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stored {
pub hash: ContentHash,
pub path: PathBuf,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
pub output: Stored,
pub duration_ms: u64,
pub notes: Vec<Note>,
}
#[derive(Clone, Copy, Debug)]
pub struct Recording<'a> {
pub key: StepKey,
pub step: &'a str,
pub output: &'a Stored,
pub canonical: ContentHash,
pub tools: &'a str,
pub duration_ms: u64,
pub notes: &'a [Note],
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Recorded {
Fresh,
Superseded {
canonical: ContentHash,
},
}
struct StepRow<'a> {
fields: &'a [String],
canonical: ContentHash,
}
fn read_step_row(fields: &[String]) -> Option<StepRow<'_>> {
let [_hash, _suffix, _duration, _notes, canonical] = fields else {
return None;
};
Some(StepRow {
fields,
canonical: ContentHash::parse(canonical)?,
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteFile {
pub key: ObjectKey,
pub url: String,
pub bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteRow {
pub digest: ContentHash,
pub bytes: ContentHash,
pub files: Vec<RemoteFile>,
pub fetched_at: i64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryRecord {
pub request: ContentHash,
pub revision: u32,
pub recorded_at: i64,
pub locator: String,
pub kind: DataKind,
pub method: Method,
pub url: String,
pub status: u16,
pub body: ObjectKey,
pub digest: ContentHash,
pub notes: Vec<Note>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CacheStats {
pub hashed: u64,
pub prefiltered: u64,
pub canonicalised: u64,
}
#[derive(Debug)]
pub enum CacheError {
Io {
path: PathBuf,
source: io::Error,
},
Database(rusqlite::Error),
Poisoned,
Store(StoreError),
}
impl fmt::Display for CacheError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
Self::Database(error) => write!(f, "cache metadata: {error}"),
Self::Poisoned => f.write_str("the cache was left locked by a panicking thread"),
Self::Store(error) => error.fmt(f),
}
}
}
impl std::error::Error for CacheError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Database(error) => Some(error),
Self::Poisoned => None,
Self::Store(error) => Some(error),
}
}
}
impl From<rusqlite::Error> for CacheError {
fn from(error: rusqlite::Error) -> Self {
Self::Database(error)
}
}
impl From<StoreError> for CacheError {
fn from(error: StoreError) -> Self {
Self::Store(error)
}
}
#[derive(Debug)]
pub struct Cache {
root: PathBuf,
objects: TieredStore,
database: Mutex<Connection>,
hashed: AtomicU64,
prefiltered: AtomicU64,
canonicalised: AtomicU64,
}
impl Cache {
pub fn open(root: &Path) -> Result<Self, CacheError> {
Self::open_with(root, crate::store::configured().as_deref())
}
pub fn open_with(root: &Path, store: Option<&str>) -> Result<Self, CacheError> {
create_dir(root)?;
let objects = TieredStore::open(&root.join("store"), store)?;
create_dir(&root.join("tmp"))?;
let database = Connection::open(root.join("cache.sqlite")).map_err(CacheError::from)?;
database.pragma_update(None, "journal_mode", "WAL")?;
database.busy_timeout(std::time::Duration::from_secs(30))?;
prepare(&database)?;
Ok(Self {
root: root.to_path_buf(),
objects,
database: Mutex::new(database),
hashed: AtomicU64::new(0),
prefiltered: AtomicU64::new(0),
canonicalised: AtomicU64::new(0),
})
}
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
#[must_use]
pub fn stats(&self) -> CacheStats {
CacheStats {
hashed: self.hashed.load(Ordering::Relaxed),
prefiltered: self.prefiltered.load(Ordering::Relaxed),
canonicalised: self.canonicalised.load(Ordering::Relaxed),
}
}
pub fn semantic_hash(&self, kind: DataKind, path: &Path) -> Result<ContentHash, CacheError> {
Ok(self.semantic(kind, path)?.hash)
}
pub fn semantic(&self, kind: DataKind, path: &Path) -> Result<Canonical, CacheError> {
let raw = self.content_hash(path)?;
if let Some(known) = self.remembered_canonical(raw, kind)? {
return Ok(known);
}
let canonical = canon::hash(kind, path, raw).map_err(|source| CacheError::Io {
path: path.to_path_buf(),
source,
})?;
self.canonicalised.fetch_add(1, Ordering::Relaxed);
self.remember_canonical(raw, kind, &canonical)?;
Ok(canonical)
}
pub fn content_hash(&self, path: &Path) -> Result<ContentHash, CacheError> {
let before = stat(path)?;
let key = path.to_string_lossy().into_owned();
if let Some(known) = self.remembered_hash(&key, before)? {
self.prefiltered.fetch_add(1, Ordering::Relaxed);
return Ok(known);
}
let hash = ContentHash::of_file(path).map_err(|source| CacheError::Io {
path: path.to_path_buf(),
source,
})?;
self.hashed.fetch_add(1, Ordering::Relaxed);
let after = stat(path)?;
if after == before {
self.remember_hash(&key, before, hash)?;
}
Ok(hash)
}
pub fn store(&self, staged: &Path) -> Result<Stored, CacheError> {
let key = self.objects.put_file(staged, &suffix(staged))?;
Ok(Stored {
hash: key.hash,
path: self.objects.path_of(&key),
})
}
pub fn remote(&self, locator: &str, kind: DataKind) -> Result<Option<RemoteRow>, CacheError> {
let row: Option<(String, String, String, i64)> = self.with_database(|database| {
database
.query_row(
"SELECT digest, bytes, files, fetched_at FROM remotes
WHERE locator = ?1 AND kind = ?2",
params![locator, kind.name()],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
)
.optional()
})??;
let (row, from_store) = match row {
Some(row) => (Some(row), false),
None => (self.published_remote(locator, kind)?, true),
};
let Some((digest, bytes, files, fetched_at)) = row else {
return Ok(None);
};
let Some(digest) = ContentHash::parse(&digest) else {
return Ok(None);
};
let Some(bytes) = ContentHash::parse(&bytes) else {
return Ok(None);
};
let row = RemoteRow {
digest,
bytes,
files: decode_remote_files(&files),
fetched_at,
};
if from_store {
self.remember_remote(locator, kind, &row)?;
}
Ok(Some(row))
}
fn published_remote(
&self,
locator: &str,
kind: DataKind,
) -> Result<Option<(String, String, String, i64)>, CacheError> {
let Some(fields) =
published::fetch(&self.objects, REMOTES, &remote_row_key(locator, kind))?
else {
return Ok(None);
};
let [digest, bytes, files, fetched_at] = fields.as_slice() else {
return Ok(None);
};
Ok(Some((
digest.clone(),
bytes.clone(),
files.clone(),
fetched_at.parse().unwrap_or_default(),
)))
}
pub fn record_remote(
&self,
locator: &str,
kind: DataKind,
row: &RemoteRow,
) -> Result<(), CacheError> {
self.remember_remote(locator, kind, row)?;
published::put(
&self.objects,
REMOTES,
&remote_row_key(locator, kind),
&[
row.digest.to_hex(),
row.bytes.to_hex(),
encode_remote_files(&row.files),
row.fetched_at.to_string(),
],
)?;
Ok(())
}
fn remember_remote(
&self,
locator: &str,
kind: DataKind,
row: &RemoteRow,
) -> Result<(), CacheError> {
self.with_database(|database| {
database.execute(
"INSERT OR REPLACE INTO remotes
(locator, kind, digest, bytes, files, fetched_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
locator,
kind.name(),
row.digest.to_hex(),
row.bytes.to_hex(),
encode_remote_files(&row.files),
row.fetched_at,
],
)
})??;
Ok(())
}
pub fn forget_remote(&self, locator: &str, kind: DataKind) -> Result<(), CacheError> {
self.with_database(|database| {
database.execute(
"DELETE FROM remotes WHERE locator = ?1 AND kind = ?2",
params![locator, kind.name()],
)
})??;
Ok(())
}
pub fn query_records(&self, request: ContentHash) -> Result<Vec<QueryRecord>, CacheError> {
let rows: Vec<Row> = self.with_database(|database| {
let mut statement = database.prepare(
"SELECT revision, recorded_at, locator, kind, method, url, status,
body, suffix, digest, notes
FROM records WHERE request = ?1 ORDER BY revision",
)?;
statement
.query_map(params![request.to_hex()], |row| -> rusqlite::Result<Row> {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
row.get(5)?,
row.get(6)?,
row.get(7)?,
row.get(8)?,
row.get(9)?,
row.get(10)?,
))
})?
.collect::<rusqlite::Result<Vec<Row>>>()
})??;
Ok(rows
.into_iter()
.filter_map(|row| decode_query_record(request, row))
.collect())
}
pub fn query_record(&self, request: ContentHash) -> Result<Option<QueryRecord>, CacheError> {
Ok(self.query_records(request)?.pop())
}
pub fn record_query(&self, record: &QueryRecord) -> Result<QueryRecord, CacheError> {
let next = self
.query_records(record.request)?
.last()
.map_or(1, |previous| previous.revision + 1);
let written = QueryRecord {
revision: next,
..record.clone()
};
self.with_database(|database| {
database.execute(
"INSERT INTO records
(request, revision, recorded_at, locator, kind, method, url,
status, body, suffix, digest, notes)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
params![
written.request.to_hex(),
written.revision,
written.recorded_at,
written.locator,
written.kind.name(),
written.method.name(),
written.url,
written.status,
written.body.hash.to_hex(),
written.body.suffix,
written.digest.to_hex(),
encode_notes(&written.notes),
],
)
})??;
Ok(written)
}
pub fn all_query_records(&self) -> Result<Vec<QueryRecord>, CacheError> {
let requests: Vec<String> = self.with_database(|database| {
let mut statement =
database.prepare("SELECT DISTINCT request FROM records ORDER BY request")?;
statement
.query_map([], |row| row.get::<_, String>(0))?
.collect::<rusqlite::Result<Vec<String>>>()
})??;
let mut records = Vec::new();
for request in requests {
let Some(request) = ContentHash::parse(&request) else {
continue;
};
records.extend(self.query_records(request)?);
}
Ok(records)
}
#[must_use]
pub fn objects(&self) -> &TieredStore {
&self.objects
}
pub fn referenced_objects(&self) -> Result<Vec<ObjectKey>, CacheError> {
let mut keys = Vec::new();
let steps: Vec<(String, String)> = self.with_database(|database| {
let mut statement = database.prepare("SELECT output_hash, suffix FROM steps")?;
statement
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
.collect::<rusqlite::Result<Vec<_>>>()
})??;
for (hex, suffix) in steps {
if let Some(hash) = ContentHash::parse(&hex) {
keys.push(ObjectKey::new(hash, &suffix));
}
}
let remotes: Vec<String> = self.with_database(|database| {
let mut statement = database.prepare("SELECT files FROM remotes")?;
statement
.query_map([], |row| row.get::<_, String>(0))?
.collect::<rusqlite::Result<Vec<_>>>()
})??;
for files in remotes {
keys.extend(decode_remote_files(&files).into_iter().map(|file| file.key));
}
let bodies: Vec<(String, String)> = self.with_database(|database| {
let mut statement = database.prepare("SELECT body, suffix FROM records")?;
statement
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
.collect::<rusqlite::Result<Vec<_>>>()
})??;
for (hex, suffix) in bodies {
if let Some(hash) = ContentHash::parse(&hex) {
keys.push(ObjectKey::new(hash, &suffix));
}
}
keys.sort_unstable();
keys.dedup();
Ok(keys)
}
#[must_use]
pub fn staging(&self, key: StepKey, suffix: &str) -> PathBuf {
self.root.join("tmp").join(format!("{key}{suffix}"))
}
#[must_use]
pub fn scratch(&self, name: &str) -> PathBuf {
self.root.join("tmp").join(name)
}
pub fn lookup(&self, key: StepKey) -> Result<Option<Entry>, CacheError> {
let row: Option<(String, String, i64, String)> = self.with_database(|database| {
database
.query_row(
"SELECT output_hash, suffix, duration_ms, notes FROM steps WHERE key = ?1",
params![key.to_hex()],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
)
.optional()
})??;
let (row, from_store) = match row {
Some(row) => (Some(row), false),
None => (self.published_entry(key)?, true),
};
let Some((hex, suffix, duration_ms, notes)) = row else {
return Ok(None);
};
let Some(hash) = ContentHash::parse(&hex) else {
self.forget(key)?;
return Ok(None);
};
let object = ObjectKey::new(hash, &suffix);
let path = match self.objects.local_path(&object) {
Ok(Some(path)) => path,
Ok(None) | Err(StoreError::Mismatch { .. }) => {
self.forget(key)?;
return Ok(None);
}
Err(error) => return Err(error.into()),
};
if from_store {
self.remember_published(key, &hex, &suffix, duration_ms, ¬es)?;
}
Ok(Some(Entry {
output: Stored { hash, path },
duration_ms: duration_ms.try_into().unwrap_or_default(),
notes: decode_notes(¬es),
}))
}
fn published_entry(
&self,
key: StepKey,
) -> Result<Option<(String, String, i64, String)>, CacheError> {
let Some(fields) = published::fetch(&self.objects, STEPS, &key.to_hex())? else {
return Ok(None);
};
let [hash, suffix, duration, notes, _canonical] = fields.as_slice() else {
return Ok(None);
};
Ok(Some((
hash.clone(),
suffix.clone(),
duration.parse().unwrap_or_default(),
notes.clone(),
)))
}
fn remember_published(
&self,
key: StepKey,
hash: &str,
suffix: &str,
duration_ms: i64,
notes: &str,
) -> Result<(), CacheError> {
self.with_database(|database| {
database.execute(
"INSERT OR REPLACE INTO steps
(key, step, output_hash, suffix, tools, duration_ms, created_at, notes)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
params![
key.to_hex(),
"(from the store)",
hash,
suffix,
"",
duration_ms,
now(),
notes,
],
)
})??;
Ok(())
}
pub fn record(&self, made: &Recording<'_>) -> Result<Recorded, CacheError> {
let (key, output) = (made.key, made.output);
let duration = i64::try_from(made.duration_ms).unwrap_or(i64::MAX);
let mine = [
output.hash.to_hex(),
suffix(&output.path),
duration.to_string(),
encode_notes(made.notes),
made.canonical.to_hex(),
];
published::put(&self.objects, STEPS, &key.to_hex(), &mine)?;
let theirs = self
.objects
.shared()
.and_then(|shared| {
published::fetch(shared, STEPS, &key.to_hex())
.ok()
.flatten()
})
.filter(|theirs| theirs != &mine);
let (fields, verdict) = match theirs.as_deref().and_then(read_step_row) {
Some(theirs) => (
theirs.fields,
Recorded::Superseded {
canonical: theirs.canonical,
},
),
None => (&mine[..], Recorded::Fresh),
};
let [hash, row_suffix, row_duration, row_notes, ..] = fields else {
return Err(CacheError::Store(StoreError::Impostor {
at: key.to_hex(),
claims: "a step row with too few fields".to_owned(),
}));
};
self.with_database(|database| {
database.execute(
"INSERT OR REPLACE INTO steps
(key, step, output_hash, suffix, tools, duration_ms, created_at, notes)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
params![
key.to_hex(),
made.step,
hash,
row_suffix,
made.tools,
row_duration.parse::<i64>().unwrap_or(duration),
now(),
row_notes,
],
)
})??;
Ok(verdict)
}
fn forget(&self, key: StepKey) -> Result<(), CacheError> {
self.with_database(|database| {
database.execute("DELETE FROM steps WHERE key = ?1", params![key.to_hex()])
})??;
Ok(())
}
fn remembered_hash(&self, path: &str, stat: Stat) -> Result<Option<ContentHash>, CacheError> {
let hex: Option<String> = self.with_database(|database| {
database
.query_row(
"SELECT hash FROM files
WHERE path = ?1 AND size = ?2 AND mtime_ns = ?3",
params![path, stat.size, stat.mtime_ns],
|row| row.get(0),
)
.optional()
})??;
Ok(hex.as_deref().and_then(ContentHash::parse))
}
fn remembered_canonical(
&self,
raw: ContentHash,
kind: DataKind,
) -> Result<Option<Canonical>, CacheError> {
let held: Option<(String, String, String)> = self.with_database(|database| {
database
.query_row(
"SELECT canonical, form, notes FROM canonical
WHERE raw = ?1 AND kind = ?2",
params![raw.to_hex(), kind.name()],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.optional()
})??;
let Some((hex, form, notes)) = held else {
return Ok(None);
};
let Some(form) = Form::parse(&form) else {
return Ok(None);
};
Ok(ContentHash::parse(&hex).map(|hash| Canonical {
hash,
form,
notes: decode_notes(¬es),
}))
}
fn remember_canonical(
&self,
raw: ContentHash,
kind: DataKind,
canonical: &Canonical,
) -> Result<(), CacheError> {
self.with_database(|database| {
database.execute(
"INSERT OR REPLACE INTO canonical (raw, kind, canonical, form, notes)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![
raw.to_hex(),
kind.name(),
canonical.hash.to_hex(),
canonical.form.to_string(),
encode_notes(&canonical.notes),
],
)
})??;
Ok(())
}
fn remember_hash(&self, path: &str, stat: Stat, hash: ContentHash) -> Result<(), CacheError> {
self.with_database(|database| {
database.execute(
"INSERT OR REPLACE INTO files (path, size, mtime_ns, hash)
VALUES (?1, ?2, ?3, ?4)",
params![path, stat.size, stat.mtime_ns, hash.to_hex()],
)
})??;
Ok(())
}
fn with_database<T>(&self, work: impl FnOnce(&Connection) -> T) -> Result<T, CacheError> {
let database = self.database.lock().map_err(|_| CacheError::Poisoned)?;
Ok(work(&database))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Stat {
size: i64,
mtime_ns: i64,
}
fn stat(path: &Path) -> Result<Stat, CacheError> {
let metadata = fs::metadata(path).map_err(|source| CacheError::Io {
path: path.to_path_buf(),
source,
})?;
let mtime_ns = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.and_then(|since| i64::try_from(since.as_nanos()).ok())
.unwrap_or(-1);
Ok(Stat {
size: i64::try_from(metadata.len()).unwrap_or(i64::MAX),
mtime_ns,
})
}
fn now() -> String {
let seconds = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
seconds.to_string()
}
fn create_dir(path: &Path) -> Result<(), CacheError> {
fs::create_dir_all(path).map_err(|source| CacheError::Io {
path: path.to_path_buf(),
source,
})
}
type Row = (
u32,
i64,
String,
String,
String,
String,
u16,
String,
String,
String,
String,
);
fn decode_query_record(request: ContentHash, row: Row) -> Option<QueryRecord> {
let (revision, recorded_at, locator, kind, method, url, status, body, suffix, digest, notes) =
row;
Some(QueryRecord {
request,
revision,
recorded_at,
locator,
kind: DataKind::ALL
.iter()
.copied()
.find(|known| known.name() == kind)?,
method: Method::parse(&method)?,
url,
status,
body: ObjectKey::new(ContentHash::parse(&body)?, &suffix),
digest: ContentHash::parse(&digest)?,
notes: decode_notes(¬es),
})
}
fn encode_remote_files(files: &[RemoteFile]) -> String {
files
.iter()
.map(|file| format!("{}\t{}\t{}", file.key, file.url, file.bytes))
.collect::<Vec<_>>()
.join("\n")
}
fn decode_remote_files(column: &str) -> Vec<RemoteFile> {
column
.lines()
.filter_map(|line| {
let mut parts = line.split('\t');
let key = parts.next()?;
let url = parts.next()?;
let bytes = parts.next()?.parse().ok()?;
let hash = ContentHash::parse(key.get(..64)?)?;
Some(RemoteFile {
key: ObjectKey::new(hash, key.get(64..).unwrap_or_default()),
url: url.to_owned(),
bytes,
})
})
.collect()
}
fn remote_row_key(locator: &str, kind: DataKind) -> String {
format!("{locator}\t{}", kind.name())
}
fn encode_notes(notes: &[Note]) -> String {
notes
.iter()
.map(|note| format!("{}\t{}", note.code(), note.value()))
.collect::<Vec<_>>()
.join("\n")
}
fn decode_notes(column: &str) -> Vec<Note> {
column
.lines()
.filter_map(|line| line.split_once('\t'))
.filter_map(|(code, value)| Note::parse(code, value))
.collect()
}
fn prepare(database: &Connection) -> Result<(), CacheError> {
database.execute(
"CREATE TABLE IF NOT EXISTS meta (name TEXT PRIMARY KEY, value TEXT NOT NULL)",
[],
)?;
let schema: Option<String> = database
.query_row(
"SELECT value FROM meta WHERE name = 'schema_version'",
[],
|row| row.get(0),
)
.optional()?;
if schema.is_some_and(|version| version != SCHEMA_VERSION.to_string()) {
database.execute("DROP TABLE IF EXISTS files", [])?;
database.execute("DROP TABLE IF EXISTS steps", [])?;
database.execute("DROP TABLE IF EXISTS canonical", [])?;
database.execute("DROP TABLE IF EXISTS remotes", [])?;
database.execute("DROP TABLE IF EXISTS records", [])?;
}
database.execute(
"CREATE TABLE IF NOT EXISTS files (
path TEXT PRIMARY KEY,
size INTEGER NOT NULL,
mtime_ns INTEGER NOT NULL,
hash TEXT NOT NULL
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS steps (
key TEXT PRIMARY KEY,
step TEXT NOT NULL,
output_hash TEXT NOT NULL,
suffix TEXT NOT NULL,
tools TEXT NOT NULL,
duration_ms INTEGER NOT NULL,
created_at TEXT NOT NULL,
notes TEXT NOT NULL DEFAULT ''
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS remotes (
locator TEXT NOT NULL,
kind TEXT NOT NULL,
digest TEXT NOT NULL,
bytes TEXT NOT NULL,
files TEXT NOT NULL,
fetched_at INTEGER NOT NULL,
PRIMARY KEY (locator, kind)
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS records (
request TEXT NOT NULL,
revision INTEGER NOT NULL,
recorded_at INTEGER NOT NULL,
locator TEXT NOT NULL,
kind TEXT NOT NULL,
method TEXT NOT NULL,
url TEXT NOT NULL,
status INTEGER NOT NULL,
body TEXT NOT NULL,
suffix TEXT NOT NULL,
digest TEXT NOT NULL,
notes TEXT NOT NULL DEFAULT '',
PRIMARY KEY (request, revision)
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS canonical (
raw TEXT NOT NULL,
kind TEXT NOT NULL,
canonical TEXT NOT NULL,
form TEXT NOT NULL,
notes TEXT NOT NULL DEFAULT '',
PRIMARY KEY (raw, kind)
)",
[],
)?;
let keys: Option<String> = database
.query_row(
"SELECT value FROM meta WHERE name = 'key_version'",
[],
|row| row.get(0),
)
.optional()?;
if keys.is_some_and(|version| version != KEY_VERSION.to_string()) {
database.execute("DELETE FROM steps", [])?;
}
let canon: Option<String> = database
.query_row(
"SELECT value FROM meta WHERE name = 'canon_version'",
[],
|row| row.get(0),
)
.optional()?;
if canon.is_some_and(|version| version != CANON_VERSION.to_string()) {
database.execute("DELETE FROM canonical", [])?;
database.execute("DELETE FROM steps", [])?;
}
database.execute(
"INSERT OR REPLACE INTO meta (name, value) VALUES
('schema_version', ?1), ('key_version', ?2), ('canon_version', ?3)",
params![
SCHEMA_VERSION.to_string(),
KEY_VERSION.to_string(),
CANON_VERSION.to_string(),
],
)?;
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn a_suffix_keeps_every_extension_a_tool_reads() {
assert_eq!(suffix(Path::new("out.bam")), ".bam");
assert_eq!(suffix(Path::new("out.vcf.gz")), ".vcf.gz");
assert_eq!(suffix(Path::new("out")), "");
assert_eq!(suffix(Path::new("/tmp/a.b/out.tsv")), ".tsv");
}
}