use std::fmt;
use std::path::PathBuf;
use crate::cache::{Cache, CacheError, QueryRecord};
use crate::canon::Form;
use crate::hash::ContentHash;
use crate::note::Note;
use crate::remote::fetch::{FetchError, Transport};
use crate::remote::locator::{Locator, LocatorError};
use crate::remote::request::{Auth, CanonicalRequest, Request};
use crate::remote::response;
use crate::store::{BlobStore, ObjectKey, StoreError};
use crate::types::{DataKind, Origin, RemoteVerdict};
pub const MAX_RECORDED_BYTES: u64 = 32 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mode {
#[default]
Auto,
Replay,
Refresh,
}
impl fmt::Display for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Auto => "auto",
Self::Replay => "replay",
Self::Refresh => "refresh",
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Drift {
First,
Unchanged,
Changed {
was: ContentHash,
now: ContentHash,
previous: u32,
revision: u32,
previous_at: i64,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Served {
Recorded,
Replayed {
at: i64,
revision: u32,
},
Refreshed {
drift: Drift,
},
}
impl Served {
#[must_use]
pub const fn verdict(&self) -> RemoteVerdict {
match self {
Self::Recorded | Self::Refreshed { .. } => RemoteVerdict::Live,
Self::Replayed { .. } => RemoteVerdict::Replayed,
}
}
}
impl fmt::Display for Served {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Recorded => f.write_str("recorded"),
Self::Replayed { at, .. } => {
write!(f, "replayed from record of {}", crate::prov::day(*at))
}
Self::Refreshed { drift } => match drift {
Drift::First => f.write_str("refreshed: a first record, so nothing to compare"),
Drift::Unchanged => f.write_str("refreshed: unchanged"),
Drift::Changed {
previous,
revision,
previous_at,
..
} => write!(
f,
"refreshed: changed since the record of {} \
(revision {previous} kept, revision {revision} written)",
crate::prov::day(*previous_at)
),
},
}
}
}
#[derive(Clone, Debug)]
pub struct ResolvedQuery {
pub path: PathBuf,
pub digest: ContentHash,
pub record: QueryRecord,
pub served: Served,
pub notes: Vec<Note>,
}
impl ResolvedQuery {
#[must_use]
pub fn origin(&self) -> Origin {
Origin {
locator: self.record.locator.clone(),
digest: self.record.digest,
bytes: self.record.body.hash,
fetched_at: self.record.recorded_at,
verdict: self.served.verdict(),
}
}
}
#[derive(Debug)]
pub enum QueryError {
Locator(LocatorError),
Fetch {
locator: String,
source: FetchError,
},
NoRecord {
locator: String,
request: ContentHash,
},
TooLarge {
locator: String,
limit: u64,
},
Unreadable {
locator: String,
kind: DataKind,
why: String,
},
Cache(CacheError),
Store(StoreError),
}
impl fmt::Display for QueryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Locator(error) => error.fmt(f),
Self::Fetch { locator, source } => {
write!(f, "`{locator}` could not be fetched: {source}")
}
Self::NoRecord { locator, request } => write!(
f,
"this run may only replay, and there is no record of \
`{locator}` (request {}). Run it once without `--replay` to \
make the record, or point it at a store or a bundle that \
has one -- a run that replayed some of its queries and \
fetched the rest would be reporting a result nobody can \
repeat",
request.to_hex()
),
Self::TooLarge { locator, limit } => write!(
f,
"`{locator}` answered with more than the {limit} bytes a \
recorded response may hold. An answer that large is a \
dataset rather than a query result, and a dataset has a \
version: pin this as a release instead, with \
`lg.remote(..., digest=...)`, which is reproducible from \
the source rather than from a copy in every bundle"
),
Self::Unreadable { locator, kind, why } => write!(
f,
"`{locator}` answered but the answer cannot be read as {}: \
{why}. A 200 is not a promise about the body -- an API \
asked for something it does not have will answer with an \
error page",
kind.name()
),
Self::Cache(error) => error.fmt(f),
Self::Store(error) => error.fmt(f),
}
}
}
impl std::error::Error for QueryError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Locator(error) => Some(error),
Self::Fetch { source, .. } => Some(source),
Self::Cache(error) => Some(error),
Self::Store(error) => Some(error),
Self::NoRecord { .. } | Self::TooLarge { .. } | Self::Unreadable { .. } => None,
}
}
}
impl From<CacheError> for QueryError {
fn from(error: CacheError) -> Self {
Self::Cache(error)
}
}
impl From<StoreError> for QueryError {
fn from(error: StoreError) -> Self {
Self::Store(error)
}
}
impl From<LocatorError> for QueryError {
fn from(error: LocatorError) -> Self {
Self::Locator(error)
}
}
pub fn resolve(
locator: &Locator,
kind: DataKind,
auth: Option<Auth>,
mode: Mode,
cache: &Cache,
transport: &dyn Transport,
) -> Result<ResolvedQuery, QueryError> {
let written = locator.to_string();
let url = locator
.urls()?
.into_iter()
.next()
.ok_or_else(|| LocatorError::Empty {
locator: written.clone(),
})?;
let request = Request::get(&url).with_auth(auth);
let canonical = CanonicalRequest::of(&request);
let id = canonical.hash();
let held = cache.query_records(id)?;
let current = held.last();
match mode {
Mode::Replay => {
let Some(record) = current.filter(|record| is_held(cache, record)) else {
return Err(QueryError::NoRecord {
locator: written,
request: id,
});
};
replay(cache, record)
}
Mode::Auto => match current.filter(|record| is_held(cache, record)) {
Some(record) => replay(cache, record),
None => {
let written_record = record(&written, kind, id, &request, cache, transport)?;
Ok(ResolvedQuery {
path: path_of(cache, &written_record.record)?,
digest: written_record.record.digest,
served: Served::Recorded,
notes: written_record.record.notes.clone(),
record: written_record.record,
})
}
},
Mode::Refresh => {
let previous = current.cloned();
let fetched = fetch(&written, kind, &request, cache, transport)?;
if let Some(previous) = &previous
&& previous.body.hash == fetched.key.hash
{
let mut served = replay(cache, previous)?;
served.served = Served::Refreshed {
drift: Drift::Unchanged,
};
return Ok(served);
}
let stored = keep(cache, id, &written, kind, &request, fetched)?;
let drift = match &previous {
None => Drift::First,
Some(previous) => Drift::Changed {
was: previous.body.hash,
now: stored.digest_of_body(),
previous: previous.revision,
revision: stored.record.revision,
previous_at: previous.recorded_at,
},
};
let mut notes = stored.record.notes.clone();
if let Drift::Changed { was, now, .. } = &drift {
notes.push(Note::QueryDrifted {
locator: written.clone(),
was: was.to_hex(),
now: now.to_hex(),
});
}
Ok(ResolvedQuery {
path: path_of(cache, &stored.record)?,
digest: stored.record.digest,
served: Served::Refreshed { drift },
notes,
record: stored.record,
})
}
}
}
fn is_held(cache: &Cache, record: &QueryRecord) -> bool {
cache.objects().has(&record.body).unwrap_or(false)
}
fn replay(cache: &Cache, record: &QueryRecord) -> Result<ResolvedQuery, QueryError> {
if cache.objects().checked_get(&record.body)?.is_none() {
return Err(QueryError::NoRecord {
locator: record.locator.clone(),
request: record.request,
});
}
Ok(ResolvedQuery {
path: path_of(cache, record)?,
digest: record.digest,
served: Served::Replayed {
at: record.recorded_at,
revision: record.revision,
},
notes: record.notes.clone(),
record: record.clone(),
})
}
struct Canonicalised {
key: ObjectKey,
bytes: Vec<u8>,
url: String,
status: u16,
digest: ContentHash,
notes: Vec<Note>,
}
struct Written {
record: QueryRecord,
}
impl Written {
const fn digest_of_body(&self) -> ContentHash {
self.record.body.hash
}
}
fn fetch(
written: &str,
kind: DataKind,
request: &Request,
cache: &Cache,
transport: &dyn Transport,
) -> Result<Canonicalised, QueryError> {
let staged = cache.scratch(&format!(
"query-{}",
ContentHash::of_bytes(request.url.as_bytes()).to_hex()
));
let fetched = transport
.fetch(request, &staged)
.map_err(|source| match source {
FetchError::TooLarge { .. } => QueryError::TooLarge {
locator: written.to_owned(),
limit: MAX_RECORDED_BYTES,
},
source => QueryError::Fetch {
locator: written.to_owned(),
source,
},
})?;
if fetched.bytes > MAX_RECORDED_BYTES {
let _ = std::fs::remove_file(&staged);
return Err(QueryError::TooLarge {
locator: written.to_owned(),
limit: MAX_RECORDED_BYTES,
});
}
let body = std::fs::read(&staged).map_err(|source| {
QueryError::Cache(CacheError::Io {
path: staged.clone(),
source,
})
})?;
let _ = std::fs::remove_file(&staged);
let canonical = response::canonicalise(written, &body);
let probe = cache.scratch(&format!(
"query-canonical-{}",
ContentHash::of_bytes(&canonical.bytes).to_hex()
));
if let Some(parent) = probe.parent() {
std::fs::create_dir_all(parent).map_err(|source| {
QueryError::Cache(CacheError::Io {
path: parent.to_path_buf(),
source,
})
})?;
}
std::fs::write(&probe, &canonical.bytes).map_err(|source| {
QueryError::Cache(CacheError::Io {
path: probe.clone(),
source,
})
})?;
let meaning = cache.semantic(kind, &probe);
let _ = std::fs::remove_file(&probe);
let meaning = meaning.map_err(|error| QueryError::Unreadable {
locator: written.to_owned(),
kind,
why: error.to_string(),
})?;
if meaning.form == Form::Raw {
return Err(QueryError::Unreadable {
locator: written.to_owned(),
kind,
why: "it does not parse as that kind, so its bytes would have \
had to stand in for what it means"
.to_owned(),
});
}
Ok(Canonicalised {
key: ObjectKey::of_bytes(&canonical.bytes, &suffix_for(kind)),
bytes: canonical.bytes,
url: fetched.url,
status: fetched.status,
digest: meaning.hash,
notes: canonical.notes,
})
}
fn keep(
cache: &Cache,
id: ContentHash,
written: &str,
kind: DataKind,
request: &Request,
fetched: Canonicalised,
) -> Result<Written, QueryError> {
cache.objects().put(&fetched.key, &fetched.bytes)?;
let record = cache.record_query(&QueryRecord {
request: id,
revision: 0,
recorded_at: crate::prov::now(),
locator: written.to_owned(),
kind,
method: request.method,
url: fetched.url,
status: fetched.status,
body: fetched.key,
digest: fetched.digest,
notes: fetched.notes,
})?;
Ok(Written { record })
}
fn record(
written: &str,
kind: DataKind,
id: ContentHash,
request: &Request,
cache: &Cache,
transport: &dyn Transport,
) -> Result<Written, QueryError> {
let fetched = fetch(written, kind, request, cache, transport)?;
keep(cache, id, written, kind, request, fetched)
}
fn path_of(cache: &Cache, record: &QueryRecord) -> Result<PathBuf, QueryError> {
Ok(cache
.objects()
.local_path(&record.body)?
.unwrap_or_else(|| cache.objects().path_of(&record.body)))
}
fn suffix_for(kind: DataKind) -> String {
match kind {
DataKind::EntitySet | DataKind::RankedList => ".tsv".to_owned(),
DataKind::Reference => ".fasta".to_owned(),
DataKind::Variants => ".vcf".to_owned(),
DataKind::Intervals => ".bed".to_owned(),
DataKind::Alignment => ".sam".to_owned(),
DataKind::Reads => ".fastq".to_owned(),
DataKind::ResistanceReport => String::new(),
}
}