use std::fmt;
use std::path::PathBuf;
use crate::cache::{Cache, CacheError, RemoteFile, RemoteRow};
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::Request;
use crate::store::{BlobStore, ObjectKey, StoreError};
use crate::types::{DataKind, Origin, RemoteVerdict};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Source {
Store,
Network,
}
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Store => "from the store",
Self::Network => "fetched",
})
}
}
#[derive(Clone, Debug)]
pub struct Resolved {
pub paths: Vec<PathBuf>,
pub digest: ContentHash,
pub record: Record,
pub from: Source,
pub notes: Vec<Note>,
}
impl Resolved {
#[must_use]
pub fn origin(&self) -> Origin {
Origin {
locator: self.record.locator.clone(),
digest: self.record.digest,
bytes: self.record.bytes,
fetched_at: self.record.fetched_at,
verdict: RemoteVerdict::Pinned,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Record {
pub locator: String,
pub kind: DataKind,
pub digest: ContentHash,
pub bytes: ContentHash,
pub files: Vec<RemoteFile>,
pub fetched_at: i64,
}
#[derive(Debug)]
pub enum RemoteError {
Locator(LocatorError),
Fetch {
locator: String,
source: FetchError,
},
Moved {
locator: String,
expected: ContentHash,
found: ContentHash,
cosmetic: bool,
},
Unreadable {
locator: String,
kind: DataKind,
why: String,
},
Cache(CacheError),
Store(StoreError),
}
impl fmt::Display for RemoteError {
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::Moved {
locator,
expected,
found,
cosmetic,
} => {
write!(
f,
"the remote `{locator}` has moved: it was pinned to {} \
and it is now {}.",
expected.to_hex(),
found.to_hex()
)?;
if *cosmetic {
return f.write_str(
" Only its bytes differ; what it means is unchanged, \
so the pin can be updated without the result moving.",
);
}
f.write_str(
" This is a change in what the data means, not a \
reformatting, so check what changed at the source \
before updating the pin.",
)
}
Self::Unreadable { locator, kind, why } => write!(
f,
"`{locator}` was fetched but cannot be read as {}: {why}. A \
200 is not a promise about the body -- an archive asked for \
an accession 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 RemoteError {
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::Moved { .. } | Self::Unreadable { .. } => None,
}
}
}
impl From<CacheError> for RemoteError {
fn from(error: CacheError) -> Self {
Self::Cache(error)
}
}
impl From<StoreError> for RemoteError {
fn from(error: StoreError) -> Self {
Self::Store(error)
}
}
impl From<LocatorError> for RemoteError {
fn from(error: LocatorError) -> Self {
Self::Locator(error)
}
}
pub fn resolve(
locator: &Locator,
kind: DataKind,
declared: Option<ContentHash>,
cache: &Cache,
transport: &dyn Transport,
) -> Result<Resolved, RemoteError> {
let written = locator.to_string();
if let Some(resolved) = from_store(&written, kind, declared, cache)? {
return Ok(resolved);
}
let previous = cache.remote(&written, kind)?;
let fetched = fetch_all(locator, &written, kind, cache, transport)?;
if let Some(expected) = declared
&& fetched.digest != expected
{
cache.forget_remote(&written, kind)?;
return Err(RemoteError::Moved {
locator: written,
expected,
found: fetched.digest,
cosmetic: false,
});
}
let mut notes = Vec::new();
if let Some(previous) = previous
&& previous.digest == fetched.digest
&& previous.bytes != fetched.bytes
{
notes.push(Note::RemoteRewritten {
locator: written.clone(),
});
}
let row = RemoteRow {
digest: fetched.digest,
bytes: fetched.bytes,
files: fetched.files.clone(),
fetched_at: crate::prov::now(),
};
for (staged, file) in fetched.staged.iter().zip(&fetched.files) {
cache.objects().put_file_as(staged, &file.key)?;
}
cache.record_remote(&written, kind, &row)?;
Ok(Resolved {
paths: paths_of(cache, &row)?,
digest: row.digest,
record: record_of(&written, kind, &row),
from: Source::Network,
notes,
})
}
fn from_store(
written: &str,
kind: DataKind,
declared: Option<ContentHash>,
cache: &Cache,
) -> Result<Option<Resolved>, RemoteError> {
let Some(row) = cache.remote(written, kind)? else {
return Ok(None);
};
if declared.is_some_and(|expected| expected != row.digest) {
return Ok(None);
}
if row.files.is_empty() {
return Ok(None);
}
let mut paths = Vec::with_capacity(row.files.len());
for file in &row.files {
match cache.objects().local_path(&file.key)? {
Some(path) => paths.push(path),
None => return Ok(None),
}
}
Ok(Some(Resolved {
paths,
digest: row.digest,
record: record_of(written, kind, &row),
from: Source::Store,
notes: Vec::new(),
}))
}
struct Fetched {
staged: Vec<PathBuf>,
files: Vec<RemoteFile>,
digest: ContentHash,
bytes: ContentHash,
}
fn fetch_all(
locator: &Locator,
written: &str,
kind: DataKind,
cache: &Cache,
transport: &dyn Transport,
) -> Result<Fetched, RemoteError> {
let urls = locator.urls()?;
let suffixes = locator.suffixes();
let mut staged = Vec::with_capacity(urls.len());
let mut files = Vec::with_capacity(urls.len());
let mut meanings = Vec::with_capacity(urls.len());
let mut byte_hashes = Vec::with_capacity(urls.len());
for (at, url) in urls.iter().enumerate() {
let suffix = suffixes.get(at).cloned().unwrap_or_default();
let into = cache.scratch(&format!(
"fetch-{}-{at}{suffix}",
ContentHash::of_bytes(written.as_bytes()).to_hex()
));
let fetched = transport
.fetch(&Request::get(url), &into)
.map_err(|source| RemoteError::Fetch {
locator: written.to_owned(),
source,
})?;
let bytes = ContentHash::of_file(&into).map_err(|source| {
RemoteError::Cache(CacheError::Io {
path: into.clone(),
source,
})
})?;
byte_hashes.push(bytes);
let canonical = cache
.semantic(kind, &into)
.map_err(|error| RemoteError::Unreadable {
locator: written.to_owned(),
kind,
why: error.to_string(),
})?;
if canonical.form == Form::Raw {
return Err(RemoteError::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(),
});
}
meanings.push(canonical.hash);
files.push(RemoteFile {
key: ObjectKey::new(bytes, &suffix),
url: fetched.url,
bytes: fetched.bytes,
});
staged.push(into);
}
Ok(Fetched {
digest: ContentHash::of_hashes(&meanings),
bytes: ContentHash::of_hashes(&byte_hashes),
staged,
files,
})
}
fn paths_of(cache: &Cache, row: &RemoteRow) -> Result<Vec<PathBuf>, RemoteError> {
row.files
.iter()
.map(|file| {
cache
.objects()
.local_path(&file.key)
.map_err(RemoteError::Store)
.map(|found| found.unwrap_or_else(|| cache.objects().path_of(&file.key)))
})
.collect()
}
fn record_of(written: &str, kind: DataKind, row: &RemoteRow) -> Record {
Record {
locator: written.to_owned(),
kind,
digest: row.digest,
bytes: row.bytes,
files: row.files.clone(),
fetched_at: row.fetched_at,
}
}