pub mod bundle;
pub mod cite;
mod methods;
mod shared;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use rusqlite::{Connection, OptionalExtension, params};
pub use cite::Citation;
pub use methods::{Gap, Group, Methods, Noticed, methods};
use crate::canon::Note;
use crate::dim::ReferenceId;
use crate::hash::ContentHash;
use crate::key::StepKey;
use crate::store::BlobStore;
use crate::store::published;
use crate::types::{DataKind, Origin, RemoteVerdict};
pub const PROV_VERSION: u32 = 2;
const DATABASE: &str = "provenance.sqlite";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InputRecord {
pub param: String,
pub kind: DataKind,
pub path: PathBuf,
pub bytes: ContentHash,
pub canonical: ContentHash,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReferenceRecord {
pub param: String,
pub path: PathBuf,
pub build: Option<String>,
pub accession: Option<String>,
pub contigs: usize,
pub length: u64,
pub checksum: Option<String>,
pub fingerprint: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Record {
pub key: StepKey,
pub step: String,
pub code: String,
pub command: Option<String>,
pub output_kind: DataKind,
pub output_bytes: ContentHash,
pub output_canonical: ContentHash,
pub output_notes: Vec<Note>,
pub parameters: Vec<(String, String)>,
pub inputs: Vec<InputRecord>,
pub references: Vec<ReferenceRecord>,
pub remotes: Vec<Origin>,
pub tools: Vec<(String, String)>,
pub engine: String,
pub platform: String,
pub recorded_at: i64,
pub duration_ms: u64,
}
#[derive(Debug)]
pub enum ProvError {
Io {
path: PathBuf,
source: io::Error,
},
Database(rusqlite::Error),
Poisoned,
Corrupt {
detail: String,
},
}
impl fmt::Display for ProvError {
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, "provenance: {error}"),
Self::Poisoned => f.write_str("provenance was left locked by a panicking thread"),
Self::Corrupt { detail } => write!(f, "a provenance record is damaged: {detail}"),
}
}
}
impl std::error::Error for ProvError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Database(error) => Some(error),
Self::Poisoned | Self::Corrupt { .. } => None,
}
}
}
impl From<rusqlite::Error> for ProvError {
fn from(error: rusqlite::Error) -> Self {
Self::Database(error)
}
}
#[derive(Debug)]
pub struct Prov {
database: Mutex<Connection>,
}
impl Prov {
pub fn open(root: &Path) -> Result<Self, ProvError> {
std::fs::create_dir_all(root).map_err(|source| ProvError::Io {
path: root.to_path_buf(),
source,
})?;
let database = Connection::open(root.join(DATABASE))?;
database.pragma_update(None, "journal_mode", "WAL")?;
database.busy_timeout(std::time::Duration::from_secs(30))?;
prepare(&database)?;
Ok(Self {
database: Mutex::new(database),
})
}
pub fn record(&self, record: &Record) -> Result<(), ProvError> {
let key = record.key.to_hex();
let mut guard = self.database.lock().map_err(|_| ProvError::Poisoned)?;
let transaction = guard.transaction()?;
transaction.execute(
"INSERT OR REPLACE INTO produced
(key, step, code, command, output_kind, output_bytes,
output_canonical, engine, platform, recorded_at, duration_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
params![
key,
record.step,
record.code,
record.command,
record.output_kind.name(),
record.output_bytes.to_hex(),
record.output_canonical.to_hex(),
record.engine,
record.platform,
record.recorded_at,
i64::try_from(record.duration_ms).unwrap_or(i64::MAX),
],
)?;
for table in [
"parameters",
"inputs",
"references",
"remotes",
"tools",
"notes",
] {
transaction.execute(
&format!("DELETE FROM produced_{table} WHERE key = ?1"),
params![key],
)?;
}
for (position, (name, value)) in record.parameters.iter().enumerate() {
transaction.execute(
"INSERT INTO produced_parameters (key, position, name, value)
VALUES (?1, ?2, ?3, ?4)",
params![key, position_of(position), name, value],
)?;
}
for (position, input) in record.inputs.iter().enumerate() {
transaction.execute(
"INSERT INTO produced_inputs
(key, position, param, kind, path, bytes, canonical)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
key,
position_of(position),
input.param,
input.kind.name(),
input.path.to_string_lossy(),
input.bytes.to_hex(),
input.canonical.to_hex(),
],
)?;
}
for (position, reference) in record.references.iter().enumerate() {
transaction.execute(
"INSERT INTO produced_references
(key, position, param, path, build, accession, contigs,
length, checksum, fingerprint)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
params![
key,
position_of(position),
reference.param,
reference.path.to_string_lossy(),
reference.build,
reference.accession,
position_of(reference.contigs),
i64::try_from(reference.length).unwrap_or(i64::MAX),
reference.checksum,
reference.fingerprint,
],
)?;
}
for (position, remote) in record.remotes.iter().enumerate() {
transaction.execute(
"INSERT INTO produced_remotes
(key, position, locator, digest, bytes, fetched_at, verdict)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
key,
position_of(position),
remote.locator,
remote.digest.to_hex(),
remote.bytes.to_hex(),
remote.fetched_at,
remote.verdict.to_string(),
],
)?;
}
for (position, (tool, version)) in record.tools.iter().enumerate() {
transaction.execute(
"INSERT INTO produced_tools (key, position, tool, version)
VALUES (?1, ?2, ?3, ?4)",
params![key, position_of(position), tool, version],
)?;
}
for (position, note) in record.output_notes.iter().enumerate() {
transaction.execute(
"INSERT INTO produced_notes (key, position, code, value)
VALUES (?1, ?2, ?3, ?4)",
params![key, position_of(position), note.code(), note.value()],
)?;
}
transaction.commit()?;
Ok(())
}
pub fn publish(&self, store: &dyn BlobStore, key: StepKey) -> Result<(), ProvError> {
let Some(record) = self.lookup(key)? else {
return Ok(());
};
published::publish(
store,
shared::PROV,
&key.to_hex(),
&[shared::encode(&record)],
)
.map_err(|error| ProvError::Io {
path: PathBuf::from("store"),
source: io::Error::other(error.to_string()),
})
}
pub fn adopt(&self, store: &dyn BlobStore, key: StepKey) -> Result<Option<Record>, ProvError> {
let fields = published::fetch(store, shared::PROV, &key.to_hex()).map_err(|error| {
ProvError::Io {
path: PathBuf::from("store"),
source: io::Error::other(error.to_string()),
}
})?;
let Some([document]) = fields.as_deref() else {
return Ok(None);
};
let Some(record) = shared::decode(key, document)? else {
return Ok(None);
};
self.record(&record)?;
Ok(Some(record))
}
pub fn lookup(&self, key: StepKey) -> Result<Option<Record>, ProvError> {
let hex = key.to_hex();
let guard = self.database.lock().map_err(|_| ProvError::Poisoned)?;
let head: Option<Head> = guard
.query_row(
"SELECT step, code, command, output_kind, output_bytes,
output_canonical, engine, platform, recorded_at, duration_ms
FROM produced WHERE key = ?1",
params![hex],
|row| {
Ok(Head {
step: row.get(0)?,
code: row.get(1)?,
command: row.get(2)?,
output_kind: row.get(3)?,
output_bytes: row.get(4)?,
output_canonical: row.get(5)?,
engine: row.get(6)?,
platform: row.get(7)?,
recorded_at: row.get(8)?,
duration_ms: row.get(9)?,
})
},
)
.optional()?;
let Some(head) = head else {
return Ok(None);
};
let mut parameters = Vec::new();
{
let mut statement = guard.prepare(
"SELECT name, value FROM produced_parameters
WHERE key = ?1 ORDER BY position",
)?;
let rows = statement.query_map(params![hex], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
for row in rows {
parameters.push(row?);
}
}
let mut inputs = Vec::new();
{
let mut statement = guard.prepare(
"SELECT param, kind, path, bytes, canonical FROM produced_inputs
WHERE key = ?1 ORDER BY position",
)?;
let rows = statement.query_map(params![hex], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
row.get::<_, String>(4)?,
))
})?;
for row in rows {
let (param, kind, path, bytes, canonical) = row?;
inputs.push(InputRecord {
param,
kind: kind_of(&kind)?,
path: PathBuf::from(path),
bytes: hash_of(&bytes)?,
canonical: hash_of(&canonical)?,
});
}
}
let mut references = Vec::new();
{
let mut statement = guard.prepare(
"SELECT param, path, build, accession, contigs, length,
checksum, fingerprint
FROM produced_references WHERE key = ?1 ORDER BY position",
)?;
let rows = statement.query_map(params![hex], |row| {
Ok(ReferenceRecord {
param: row.get(0)?,
path: PathBuf::from(row.get::<_, String>(1)?),
build: row.get(2)?,
accession: row.get(3)?,
contigs: usize::try_from(row.get::<_, i64>(4)?).unwrap_or_default(),
length: u64::try_from(row.get::<_, i64>(5)?).unwrap_or_default(),
checksum: row.get(6)?,
fingerprint: row.get(7)?,
})
})?;
for row in rows {
references.push(row?);
}
}
let mut remotes = Vec::new();
{
let mut statement = guard.prepare(
"SELECT locator, digest, bytes, fetched_at, verdict FROM produced_remotes
WHERE key = ?1 ORDER BY position",
)?;
let rows = statement.query_map(params![hex], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, i64>(3)?,
row.get::<_, String>(4)?,
))
})?;
for row in rows {
let (locator, digest, bytes, fetched_at, verdict) = row?;
let (Some(digest), Some(bytes)) =
(ContentHash::parse(&digest), ContentHash::parse(&bytes))
else {
continue;
};
let verdict = match verdict.as_str() {
"pinned" => RemoteVerdict::Pinned,
"replayed" => RemoteVerdict::Replayed,
"live" => RemoteVerdict::Live,
_ => continue,
};
remotes.push(Origin {
locator,
digest,
bytes,
fetched_at,
verdict,
});
}
}
let mut tools = Vec::new();
{
let mut statement = guard.prepare(
"SELECT tool, version FROM produced_tools
WHERE key = ?1 ORDER BY position",
)?;
let rows = statement.query_map(params![hex], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
for row in rows {
tools.push(row?);
}
}
let mut output_notes = Vec::new();
{
let mut statement = guard.prepare(
"SELECT code, value FROM produced_notes
WHERE key = ?1 ORDER BY position",
)?;
let rows = statement.query_map(params![hex], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
for row in rows {
let (code, value) = row?;
if let Some(note) = Note::parse(&code, &value) {
output_notes.push(note);
}
}
}
Ok(Some(Record {
key,
step: head.step,
code: head.code,
command: head.command,
output_kind: kind_of(&head.output_kind)?,
output_bytes: hash_of(&head.output_bytes)?,
output_canonical: hash_of(&head.output_canonical)?,
output_notes,
parameters,
inputs,
references,
remotes,
tools,
engine: head.engine,
platform: head.platform,
recorded_at: head.recorded_at,
duration_ms: u64::try_from(head.duration_ms).unwrap_or_default(),
}))
}
}
struct Head {
step: String,
code: String,
command: Option<String>,
output_kind: String,
output_bytes: String,
output_canonical: String,
engine: String,
platform: String,
recorded_at: i64,
duration_ms: i64,
}
fn hash_of(text: &str) -> Result<ContentHash, ProvError> {
ContentHash::parse(text).ok_or_else(|| ProvError::Corrupt {
detail: format!("`{text}` is not a content hash"),
})
}
fn kind_of(text: &str) -> Result<DataKind, ProvError> {
DataKind::from_name(text).ok_or_else(|| ProvError::Corrupt {
detail: format!("`{text}` is not a kind of data"),
})
}
#[must_use]
pub fn pin(param: &str, path: &Path, identity: &ReferenceId) -> ReferenceRecord {
let contigs = identity.contigs();
let single = match contigs {
[only] => Some(only),
_ => None,
};
ReferenceRecord {
param: param.to_owned(),
path: path.to_path_buf(),
build: identity.label().map(str::to_owned),
accession: single
.map(|contig| contig.name.as_str())
.filter(|name| is_accession(name))
.map(str::to_owned),
contigs: contigs.len(),
length: contigs.iter().filter_map(|contig| contig.length).sum(),
checksum: single.and_then(|contig| contig.md5.clone()),
fingerprint: identity.fingerprint(),
}
}
fn is_accession(name: &str) -> bool {
let (body, version) = match name.split_once('.') {
Some((body, version)) => (body, Some(version)),
None => (name, None),
};
if let Some(version) = version
&& (version.is_empty() || !version.bytes().all(|byte| byte.is_ascii_digit()))
{
return false;
}
let letters = body
.bytes()
.take_while(|byte| byte.is_ascii_uppercase())
.count();
if letters == 0 || letters > 6 {
return false;
}
let rest = &body[letters..];
let digits = rest.strip_prefix('_').unwrap_or(rest);
(5..=10).contains(&digits.len()) && digits.bytes().all(|byte| byte.is_ascii_digit())
}
#[must_use]
pub fn platform() -> String {
let (os, arch) = (std::env::consts::OS, std::env::consts::ARCH);
format!("{os}-{arch}")
}
#[must_use]
pub fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| i64::try_from(since.as_secs()).unwrap_or(i64::MAX))
.unwrap_or_default()
}
#[must_use]
pub fn day(epoch_seconds: i64) -> String {
const MONTHS: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
let days = epoch_seconds.div_euclid(86_400);
let shifted = days + 719_468;
let era = shifted.div_euclid(146_097);
let day_of_era = shifted.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let year = year_of_era + era * 400;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_prime = (5 * day_of_year + 2) / 153;
let day_of_month = day_of_year - (153 * month_prime + 2) / 5 + 1;
let month = if month_prime < 10 {
month_prime + 3
} else {
month_prime - 9
};
let year = if month <= 2 { year + 1 } else { year };
let name = MONTHS
.get(usize::try_from(month - 1).unwrap_or_default())
.copied()
.unwrap_or("January");
format!("{day_of_month} {name} {year}")
}
fn position_of(position: usize) -> i64 {
i64::try_from(position).unwrap_or(i64::MAX)
}
fn prepare(database: &Connection) -> Result<(), ProvError> {
database.execute(
"CREATE TABLE IF NOT EXISTS meta (name TEXT PRIMARY KEY, value TEXT NOT NULL)",
[],
)?;
database.execute(
"INSERT OR REPLACE INTO meta (name, value) VALUES ('prov_version', ?1)",
params![PROV_VERSION.to_string()],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS produced (
key TEXT PRIMARY KEY,
step TEXT NOT NULL,
code TEXT NOT NULL,
command TEXT,
output_kind TEXT NOT NULL,
output_bytes TEXT NOT NULL,
output_canonical TEXT NOT NULL,
engine TEXT NOT NULL,
platform TEXT NOT NULL,
recorded_at INTEGER NOT NULL,
duration_ms INTEGER NOT NULL
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS produced_parameters (
key TEXT NOT NULL,
position INTEGER NOT NULL,
name TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (key, position)
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS produced_inputs (
key TEXT NOT NULL,
position INTEGER NOT NULL,
param TEXT NOT NULL,
kind TEXT NOT NULL,
path TEXT NOT NULL,
bytes TEXT NOT NULL,
canonical TEXT NOT NULL,
PRIMARY KEY (key, position)
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS produced_references (
key TEXT NOT NULL,
position INTEGER NOT NULL,
param TEXT NOT NULL,
path TEXT NOT NULL,
build TEXT,
accession TEXT,
contigs INTEGER NOT NULL,
length INTEGER NOT NULL,
checksum TEXT,
fingerprint TEXT NOT NULL,
PRIMARY KEY (key, position)
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS produced_remotes (
key TEXT NOT NULL,
position INTEGER NOT NULL,
locator TEXT NOT NULL,
digest TEXT NOT NULL,
bytes TEXT NOT NULL,
fetched_at INTEGER NOT NULL,
verdict TEXT NOT NULL,
PRIMARY KEY (key, position)
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS produced_tools (
key TEXT NOT NULL,
position INTEGER NOT NULL,
tool TEXT NOT NULL,
version TEXT NOT NULL,
PRIMARY KEY (key, position)
)",
[],
)?;
database.execute(
"CREATE TABLE IF NOT EXISTS produced_notes (
key TEXT NOT NULL,
position INTEGER NOT NULL,
code TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (key, position)
)",
[],
)?;
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn a_date_reads_as_a_sentence_does() {
assert_eq!(day(1_792_627_200), "22 October 2026");
assert_eq!(day(1_792_713_599), "22 October 2026");
assert_eq!(day(1_792_713_600), "23 October 2026");
}
#[test]
fn the_epoch_and_the_leap_days_around_it_are_right() {
assert_eq!(day(0), "1 January 1970");
assert_eq!(day(1_709_164_800), "29 February 2024");
assert_eq!(day(951_782_400), "29 February 2000");
assert_eq!(day(-2_203_891_200), "1 March 1900");
}
#[test]
fn a_clock_that_is_badly_wrong_gives_a_wrong_date_rather_than_a_panic() {
let _ = day(i64::MIN);
let _ = day(i64::MAX);
}
#[test]
fn an_accession_is_recognised_by_its_shape() {
assert!(is_accession("K03455.1"), "INSDC, with a version");
assert!(is_accession("K03455"), "INSDC, without one");
assert!(is_accession("NC_001802.1"), "RefSeq");
assert!(is_accession("CP001187"), "two letters, six digits");
}
#[test]
fn a_sequence_name_is_not_an_accession() {
assert!(!is_accession("chr1"), "too few digits");
assert!(!is_accession("1"), "no letters");
assert!(!is_accession("chrX"), "no digits");
assert!(!is_accession("K03455.x"), "a version is digits");
assert!(!is_accession("SCAF_00012345678"), "too many digits");
assert!(!is_accession("scaffold1"), "an accession is uppercase");
assert!(!is_accession(""), "nothing at all");
}
}