use std::path::{Path, PathBuf};
use std::sync::Arc;
use atproto_dasl::cid::{CidCore, RAW_CODEC, RawCidHasher, SHA256_CODE};
use atproto_identity::validation::{is_valid_did_method_plc, is_valid_did_method_web};
use futures::StreamExt;
use tokio::io::AsyncWriteExt;
use crate::context::ServerContext;
use crate::errors::{ResourceError, ToolError};
use crate::proto::serve::RequestCtx;
pub const SCHEME: &str = "atpmcp";
pub const NAMESPACE_PUBLIC: &str = "public";
pub const URI_TEMPLATE: &str = "atpmcp://public/blob/{+did}/{cid}";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlobUri {
pub did: String,
pub cid: String,
}
impl BlobUri {
#[must_use]
pub fn new(did: impl Into<String>, cid: impl Into<String>) -> Self {
Self {
did: did.into(),
cid: cid.into(),
}
}
#[must_use]
pub fn to_uri(&self) -> String {
format!(
"{SCHEME}://{NAMESPACE_PUBLIC}/blob/{}/{}",
self.did, self.cid
)
}
pub fn parse(uri: &str) -> Result<Self, ResourceError> {
let malformed = |reason: &str| ResourceError::MalformedUri {
uri: uri.to_string(),
reason: reason.to_string(),
};
if uri.contains('?') {
return Err(malformed("a blob URI carries no query string"));
}
if uri.contains('#') {
return Err(malformed("a blob URI carries no fragment"));
}
let prefix = format!("{SCHEME}://");
let Some(rest) = uri.strip_prefix(&prefix) else {
return Err(ResourceError::UnsupportedScheme {
uri: uri.to_string(),
});
};
let segments: Vec<&str> = rest.split('/').collect();
let [namespace, kind, did, cid] = segments.as_slice() else {
return Err(malformed(
"expected exactly atpmcp://public/blob/{did}/{cid}",
));
};
if *namespace != NAMESPACE_PUBLIC {
return Err(ResourceError::UnsupportedScheme {
uri: uri.to_string(),
});
}
if *kind != "blob" {
return Err(ResourceError::UnsupportedScheme {
uri: uri.to_string(),
});
}
if !is_supported_did(did) {
return Err(malformed("the DID is not a valid did:plc or did:web"));
}
validate_blob_cid(cid).map_err(|reason| malformed(&reason))?;
Ok(Self::new(*did, *cid))
}
}
#[must_use]
pub fn is_supported_did(did: &str) -> bool {
is_valid_did_method_plc(did) || is_valid_did_method_web(did, false)
}
pub fn validate_blob_cid(cid: &str) -> Result<(), String> {
let parsed: CidCore = cid.parse().map_err(|error| format!("not a CID: {error}"))?;
if parsed.version() != atproto_dasl::CidVersion::V1 {
return Err("a blob CID must be CIDv1".to_string());
}
if parsed.codec() != RAW_CODEC {
return Err(format!(
"a blob CID must use the raw codec (0x55), got 0x{:x}; a dag-cbor CID addresses a record, not a blob",
parsed.codec()
));
}
let hash = parsed.hash();
if hash.code() != SHA256_CODE {
return Err("a blob CID must use SHA-256".to_string());
}
if hash.digest().len() != 32 {
return Err("a blob CID must carry a 32-byte digest".to_string());
}
if parsed.to_string() != cid {
return Err("the CID is not in its canonical base32 form".to_string());
}
Ok(())
}
#[derive(Debug)]
pub struct VerifiedBlob {
pub path: PathBuf,
pub size: u64,
pub mime_type: String,
pub mime_disagreement: Option<String>,
pub cached: bool,
cid: String,
file: Option<tokio::fs::File>,
ephemeral: bool,
}
impl VerifiedBlob {
pub async fn bytes(&mut self) -> Result<Vec<u8>, ToolError> {
use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};
let failed = |reason: String| ToolError::BlobReadBackFailed {
path: self.path.display().to_string(),
reason,
};
let Some(file) = self.file.as_mut() else {
return Err(failed("the verified file is already closed".to_string()));
};
file.rewind()
.await
.map_err(|error| failed(error.to_string()))?;
let capacity = usize::try_from(self.size).unwrap_or(usize::MAX);
let mut data = Vec::with_capacity(capacity);
file.take(self.size.saturating_add(1))
.read_to_end(&mut data)
.await
.map_err(|error| failed(error.to_string()))?;
if data.len() as u64 != self.size {
return Err(failed(format!(
"it no longer holds the {} bytes that were verified; it was changed after it \
was verified",
self.size
)));
}
let computed = atproto_dasl::compute_raw_cid(&data).to_string();
if computed != self.cid {
tracing::warn!(
path = %self.path.display(),
expected = %self.cid,
computed = %computed,
"A verified blob changed on disk before it was read back."
);
return Err(failed(format!(
"it now hashes to {computed}, not {}; it was changed after it was verified",
self.cid
)));
}
Ok(data)
}
pub fn keep(&mut self) -> PathBuf {
self.ephemeral = false;
self.path.clone()
}
}
impl Drop for VerifiedBlob {
fn drop(&mut self) {
self.file = None;
if self.ephemeral {
let _ = std::fs::remove_file(&self.path);
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Expected {
pub size: Option<u64>,
pub mime_type: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Locator {
pub did: String,
pub cid: String,
pub endpoint: Option<String>,
}
pub async fn fetch(
ctx: &Arc<ServerContext>,
rctx: &mut RequestCtx,
locator: &Locator,
expected: &Expected,
max_bytes: u64,
) -> Result<VerifiedBlob, ToolError> {
if let Some(size) = expected.size
&& size > max_bytes
{
return Err(ToolError::BlobTooLarge {
size,
limit: max_bytes,
});
}
if let Some(mut cached) = ctx.cache.get(&locator.cid).await {
if cached.size > max_bytes {
return Err(ToolError::BlobTooLarge {
size: cached.size,
limit: max_bytes,
});
}
if let Some(declared) = expected.size
&& declared != cached.size
{
return Err(ToolError::BlobSizeMismatch {
declared,
actual: cached.size,
at_least: false,
});
}
let decided = decide_type(
cached.mime_type.as_deref(),
expected.mime_type.as_deref(),
&mut cached.file,
)
.await;
tracing::debug!(cid = %locator.cid, "Serving a blob from cache.");
return Ok(VerifiedBlob {
path: cached.path,
size: cached.size,
mime_type: decided.value,
mime_disagreement: decided.disagreement,
cached: true,
cid: locator.cid.clone(),
file: Some(cached.file),
ephemeral: false,
});
}
if rctx.cancel.is_cancelled() {
return Err(ToolError::BlobDownloadFailed {
reason: "cancelled".to_string(),
});
}
let endpoint = match locator.endpoint.as_deref() {
Some(endpoint) => endpoint.to_string(),
None => resolve_endpoint(ctx, &locator.did).await?,
};
rctx.report_progress(0, &format!("Fetching {} from {endpoint}", locator.cid));
let streamed = tokio::select! {
biased;
() = rctx.cancel.cancelled() => {
return Err(ToolError::BlobDownloadFailed { reason: "cancelled".to_string() });
}
result = stream_and_verify(ctx, &endpoint, &locator.did, &locator.cid, expected, max_bytes) => result?,
};
rctx.set_progress_total(Some(streamed.size));
rctx.finish_progress(streamed.size, &format!("Fetched {} bytes", streamed.size));
Ok(VerifiedBlob {
path: streamed.path,
size: streamed.size,
mime_type: streamed.mime_type.value,
mime_disagreement: streamed.mime_type.disagreement,
cached: false,
cid: locator.cid.clone(),
file: Some(streamed.file),
ephemeral: streamed.ephemeral,
})
}
const SNIFF_BYTES: u64 = 8 * 1024;
async fn decide_type(
served: Option<&str>,
declared: Option<&str>,
file: &mut tokio::fs::File,
) -> crate::mime::ServedType {
use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};
let mut sniffed = None;
if crate::mime::wants_sniff(served, declared) {
let mut prefix = Vec::new();
let read = async {
file.rewind().await?;
(&mut *file)
.take(SNIFF_BYTES)
.read_to_end(&mut prefix)
.await
}
.await;
if read.is_ok() {
sniffed = crate::mime::sniff(&prefix);
}
}
crate::mime::resolve_served(served, declared, sniffed)
}
struct StreamedBlob {
path: PathBuf,
size: u64,
mime_type: crate::mime::ServedType,
ephemeral: bool,
file: tokio::fs::File,
}
async fn stream_and_verify(
ctx: &Arc<ServerContext>,
endpoint: &str,
did: &str,
cid: &str,
expected: &Expected,
max_bytes: u64,
) -> Result<StreamedBlob, ToolError> {
let limit = expected.size.map_or(max_bytes, |size| size.min(max_bytes));
let mismatch = |error: ToolError| match (error, expected.size) {
(ToolError::BlobDownloadTooLarge { size, .. }, Some(declared)) if declared <= max_bytes => {
ToolError::BlobSizeMismatch {
declared,
actual: size,
at_least: true,
}
}
(error, _) => error,
};
let url = atproto_identity::url::build_url(
endpoint,
"/xrpc/com.atproto.sync.getBlob",
[("did", did), ("cid", cid)],
)
.map_err(|error| ToolError::BlobDownloadFailed {
reason: format!("could not build a request URL for {endpoint}: {error}"),
})?;
let response = ctx
.blob_client
.get(url.as_str())
.send()
.await
.map_err(|error| ToolError::BlobDownloadFailed {
reason: format!("request to {endpoint} failed: {error}"),
})?;
let status = response.status();
if !status.is_success() {
return Err(ToolError::BlobErrorResponse {
endpoint: endpoint.to_string(),
status: status.as_u16(),
body: error_body(response).await,
});
}
let served_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(str::to_string);
let declared = response.content_length();
if let Some(declared) = declared
&& declared > limit
{
return Err(mismatch(ToolError::BlobDownloadTooLarge {
size: declared,
limit,
}));
}
let (temp_path, final_target) = match ctx.cache.prepare_write(cid, declared).await {
Ok(Some(target)) => (target.temp_path.clone(), Some(target)),
Ok(None) => (scratch_path(cid), None),
Err(error) => {
tracing::warn!(
error = ?error,
"Could not prepare the cache for a streamed blob; using scratch space."
);
(scratch_path(cid), None)
}
};
let write_result = write_hashed(&temp_path, response.bytes_stream(), limit).await;
let (size, computed, mut file) = match write_result {
Ok(written) => written,
Err(error) => {
discard_temp(ctx, &temp_path, final_target.as_ref()).await;
return Err(mismatch(error));
}
};
if computed != cid {
tracing::warn!(
requested = %cid,
computed = %computed,
endpoint = %endpoint,
"A repository served bytes that do not match the requested CID."
);
discard_temp(ctx, &temp_path, final_target.as_ref()).await;
return Err(ToolError::BlobCidMismatch {
requested: cid.to_string(),
computed,
});
}
if let Some(declared) = expected.size
&& declared != size
{
discard_temp(ctx, &temp_path, final_target.as_ref()).await;
return Err(ToolError::BlobSizeMismatch {
declared,
actual: size,
at_least: false,
});
}
let mime_type = decide_type(
served_type.as_deref(),
expected.mime_type.as_deref(),
&mut file,
)
.await;
let (path, file, ephemeral) = match final_target {
Some(target) if !ctx.cache.admits(size) => {
tracing::debug!(
cid = %cid,
size,
"A blob that declared no length is larger than the cache; keeping it as a scratch file."
);
let (path, file) = move_to_scratch(ctx, &target, cid, file).await?;
(path, file, true)
}
Some(target) => match ctx
.cache
.commit_write(&target, Some(&mime_type.value))
.await
{
Ok(()) => (target.final_path, file, false),
Err(error) => {
tracing::warn!(
error = ?error,
"Failed to publish a streamed blob into the cache; keeping it as a scratch file."
);
let (path, file) = move_to_scratch(ctx, &target, cid, file).await?;
(path, file, true)
}
},
None => (temp_path, file, true),
};
Ok(StreamedBlob {
path,
size,
mime_type,
ephemeral,
file,
})
}
async fn write_hashed(
path: &Path,
mut chunks: impl futures::Stream<Item = reqwest::Result<bytes::Bytes>> + Unpin,
max_bytes: u64,
) -> Result<(u64, String, tokio::fs::File), ToolError> {
let mut file = tokio::fs::OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(path)
.await
.map_err(|error| ToolError::BlobDownloadFailed {
reason: format!("could not create {}: {error}", path.display()),
})?;
let mut hasher = RawCidHasher::new();
let mut written: u64 = 0;
while let Some(chunk) = chunks.next().await {
let chunk = chunk.map_err(|error| ToolError::BlobDownloadFailed {
reason: format!("reading the response body failed: {error}"),
})?;
written += chunk.len() as u64;
if written > max_bytes {
return Err(ToolError::BlobDownloadTooLarge {
size: written,
limit: max_bytes,
});
}
hasher.update(&chunk);
file.write_all(&chunk)
.await
.map_err(|error| ToolError::BlobDownloadFailed {
reason: format!("writing {}: {error}", path.display()),
})?;
}
file.flush()
.await
.map_err(|error| ToolError::BlobDownloadFailed {
reason: format!("flushing {}: {error}", path.display()),
})?;
Ok((written, hasher.finalize().to_string(), file))
}
const ERROR_BODY_LIMIT: usize = 1024;
async fn error_body(response: reqwest::Response) -> String {
if response.status().is_redirection() {
let location = response
.headers()
.get(reqwest::header::LOCATION)
.and_then(|value| value.to_str().ok())
.map(|location| format!(" to {location}"))
.unwrap_or_default();
return format!("a redirect{location}, which is not followed for a blob");
}
let mut chunks = response.bytes_stream();
let mut collected: Vec<u8> = Vec::new();
let mut truncated = false;
while let Some(Ok(chunk)) = chunks.next().await {
let room = ERROR_BODY_LIMIT - collected.len();
if chunk.len() > room {
collected.extend_from_slice(&chunk[..room]);
truncated = true;
break;
}
collected.extend_from_slice(&chunk);
}
if collected.is_empty() {
return "(no body)".to_string();
}
if !truncated && let Ok(value) = serde_json::from_slice::<serde_json::Value>(&collected) {
return value.to_string();
}
let mut text = String::from_utf8_lossy(&collected).into_owned();
if truncated {
text.push_str(&format!(" … (truncated at {ERROR_BODY_LIMIT} bytes)"));
}
text
}
async fn discard_temp(
ctx: &Arc<ServerContext>,
temp_path: &Path,
target: Option<&crate::cache::WriteTarget>,
) {
match target {
Some(target) => ctx.cache.abort_write(target).await,
None => {
let _ = tokio::fs::remove_file(temp_path).await;
}
}
}
async fn move_to_scratch(
ctx: &Arc<ServerContext>,
target: &crate::cache::WriteTarget,
cid: &str,
file: tokio::fs::File,
) -> Result<(PathBuf, tokio::fs::File), ToolError> {
let scratch = scratch_path(cid);
let renamed = match tokio::fs::rename(&target.temp_path, &scratch).await {
Ok(()) => return Ok((scratch, file)),
Err(error) => error,
};
let copied = copy_verified(file, &scratch, cid).await;
ctx.cache.abort_write(target).await;
match copied {
Ok(file) => Ok((scratch, file)),
Err(reason) => Err(ToolError::BlobDownloadFailed {
reason: format!(
"could not move the verified blob out of the cache to {}: renaming it failed \
({renamed}), and so did copying it ({reason})",
scratch.display()
),
}),
}
}
async fn copy_verified(
mut from: tokio::fs::File,
to: &Path,
cid: &str,
) -> Result<tokio::fs::File, String> {
use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};
let mut out = tokio::fs::OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(to)
.await
.map_err(|error| format!("could not create {}: {error}", to.display()))?;
let copied = async {
from.rewind().await?;
let mut hasher = RawCidHasher::new();
let mut buffer = vec![0u8; 64 * 1024];
loop {
let read = from.read(&mut buffer).await?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
out.write_all(&buffer[..read]).await?;
}
out.flush().await?;
Ok::<_, std::io::Error>(hasher.finalize().to_string())
}
.await;
let failure = match copied {
Ok(computed) if computed == cid => return Ok(out),
Ok(computed) => format!("the copy hashes to {computed}, not {cid}"),
Err(error) => format!("copying into {}: {error}", to.display()),
};
drop(out);
let _ = tokio::fs::remove_file(to).await;
Err(failure)
}
fn scratch_path(cid: &str) -> PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
std::env::temp_dir().join(format!(
"atpmcp-blob-{cid}-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
))
}
async fn resolve_endpoint(ctx: &Arc<ServerContext>, did: &str) -> Result<String, ToolError> {
let document =
ctx.resolver
.resolve(did)
.await
.map_err(|error| ToolError::BlobDownloadFailed {
reason: format!("failed to resolve {did}: {error:#}"),
})?;
crate::host_policy::pds_endpoint(&document, false).map_err(|unusable| {
ToolError::BlobDownloadFailed {
reason: unusable.tool_reason(did, Some("endpoint")),
}
})
}
#[cfg(test)]
mod tests {
use super::*;
const DID: &str = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
fn blob_cid() -> String {
atproto_dasl::compute_raw_cid(b"some blob bytes").to_string()
}
fn record_cid() -> String {
atproto_dasl::compute_cid_for(&serde_json::json!({ "a": 1 }))
.unwrap()
.to_string()
}
#[test]
fn round_trips_a_uri() {
let cid = blob_cid();
let uri = BlobUri::new(DID, &cid);
let text = uri.to_uri();
assert_eq!(text, format!("atpmcp://public/blob/{DID}/{cid}"));
assert_eq!(BlobUri::parse(&text).unwrap(), uri);
}
#[test]
fn a_did_keeps_its_colons_unescaped() {
let uri = BlobUri::new(DID, blob_cid()).to_uri();
assert!(uri.contains("did:plc:"), "colons must stay literal: {uri}");
assert!(!uri.contains("%3A"));
}
#[test]
fn the_template_uses_reserved_expansion_for_the_did() {
assert!(URI_TEMPLATE.contains("{+did}"));
assert!(!URI_TEMPLATE.contains("{did}"));
let cid = blob_cid();
let expanded = URI_TEMPLATE.replace("{+did}", DID).replace("{cid}", &cid);
assert_eq!(expanded, BlobUri::new(DID, &cid).to_uri());
}
#[test]
fn rejects_a_foreign_scheme() {
let cid = blob_cid();
for uri in [
format!("atproto://public/blob/{DID}/{cid}"),
format!("https://public/blob/{DID}/{cid}"),
format!("at://{DID}/blob/{cid}"),
] {
assert!(
matches!(
BlobUri::parse(&uri),
Err(ResourceError::UnsupportedScheme { .. })
),
"should reject {uri}"
);
}
}
#[test]
fn rejects_a_foreign_namespace_or_kind() {
let cid = blob_cid();
for uri in [
format!("atpmcp://private/blob/{DID}/{cid}"),
format!("atpmcp://public/record/{DID}/{cid}"),
] {
assert!(matches!(
BlobUri::parse(&uri),
Err(ResourceError::UnsupportedScheme { .. })
));
}
}
#[test]
fn rejects_extra_or_missing_segments() {
let cid = blob_cid();
for uri in [
format!("atpmcp://public/blob/{DID}"),
format!("atpmcp://public/blob/{DID}/{cid}/extra"),
"atpmcp://public/blob".to_string(),
] {
assert!(BlobUri::parse(&uri).is_err(), "should reject {uri}");
}
}
#[test]
fn rejects_a_query_or_fragment() {
let cid = blob_cid();
for uri in [
format!("atpmcp://public/blob/{DID}/{cid}?download=1"),
format!("atpmcp://public/blob/{DID}/{cid}#top"),
] {
assert!(matches!(
BlobUri::parse(&uri),
Err(ResourceError::MalformedUri { .. })
));
}
}
#[test]
fn rejects_an_invalid_did() {
let cid = blob_cid();
for did in ["not-a-did", "did:unknown:abc", "alice.bsky.social"] {
let uri = format!("atpmcp://public/blob/{did}/{cid}");
assert!(BlobUri::parse(&uri).is_err(), "should reject did {did}");
}
}
#[test]
fn rejects_a_record_cid() {
let uri = format!("atpmcp://public/blob/{DID}/{}", record_cid());
let error = BlobUri::parse(&uri).expect_err("a dag-cbor CID is not a blob CID");
assert!(error.to_string().contains("raw codec"));
}
#[test]
fn rejects_a_cidv0() {
let uri =
format!("atpmcp://public/blob/{DID}/QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR");
assert!(BlobUri::parse(&uri).is_err());
}
#[test]
fn rejects_a_non_canonical_cid_rendering() {
let cid = blob_cid().to_uppercase();
let uri = format!("atpmcp://public/blob/{DID}/{cid}");
assert!(BlobUri::parse(&uri).is_err());
}
#[test]
fn errors_carry_the_uri_and_the_right_code() {
let error = BlobUri::parse("atpmcp://public/blob/bad").unwrap_err();
assert_eq!(error.code(), crate::proto::INVALID_PARAMS);
assert_eq!(error.uri(), Some("atpmcp://public/blob/bad"));
}
#[test]
fn supported_did_methods() {
assert!(is_supported_did(DID));
assert!(is_supported_did("did:web:example.com"));
assert!(!is_supported_did("did:key:z6Mk"));
assert!(!is_supported_did(""));
}
use crate::tools::test_support::{
one_shot_server, test_context, test_context_with_cache, test_request,
};
fn dir_entries(dir: &Path) -> Vec<String> {
std::fs::read_dir(dir)
.map(|entries| {
entries
.filter_map(Result::ok)
.map(|entry| entry.file_name().to_string_lossy().to_string())
.collect()
})
.unwrap_or_default()
}
#[tokio::test]
async fn a_fresh_fetch_streams_to_its_cache_path() {
let ctx = test_context_with_cache();
let mut rctx = test_request();
let body = b"a freshly fetched blob, never held in one buffer".to_vec();
let cid = atproto_dasl::compute_raw_cid(&body).to_string();
let base_url = one_shot_server(200, body.clone(), true).await;
let locator = Locator {
did: DID.to_string(),
cid: cid.clone(),
endpoint: Some(base_url),
};
let blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect("fetch succeeds");
assert!(!blob.cached);
assert!(
!blob.ephemeral,
"a working cache should land the blob at its real path, not scratch"
);
assert_eq!(blob.size, body.len() as u64);
assert_eq!(blob.path, ctx.cache.path_for(&cid).unwrap());
assert_eq!(std::fs::read(&blob.path).unwrap(), body);
if let Some(dir) = ctx.cache.dir() {
let _ = std::fs::remove_dir_all(dir);
}
}
#[tokio::test]
async fn a_cache_hit_over_max_bytes_is_refused_like_a_fetch() {
let ctx = test_context_with_cache();
let mut rctx = test_request();
let body = vec![4u8; 4096];
let cid = atproto_dasl::compute_raw_cid(&body).to_string();
ctx.cache.put(&cid, &body, None).await.unwrap();
let locator = Locator {
did: DID.to_string(),
cid: cid.clone(),
endpoint: Some("https://127.0.0.1:1".to_string()),
};
let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect_err("a hit over max_bytes must be refused");
assert!(
matches!(
error,
ToolError::BlobTooLarge {
size: 4096,
limit: 1024
}
),
"expected the exact size and the limit, got {error}"
);
let blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 4096)
.await
.expect("a hit within max_bytes is served");
assert!(blob.cached);
assert_eq!(blob.size, 4096);
if let Some(dir) = ctx.cache.dir() {
let _ = std::fs::remove_dir_all(dir);
}
}
#[tokio::test]
async fn a_cid_mismatch_deletes_the_partial_file_and_leaves_no_cache_entry() {
let ctx = test_context_with_cache();
let mut rctx = test_request();
let served = b"bytes the server actually sends".to_vec();
let requested_cid =
atproto_dasl::compute_raw_cid(b"a completely different blob").to_string();
let base_url = one_shot_server(200, served, true).await;
let locator = Locator {
did: DID.to_string(),
cid: requested_cid.clone(),
endpoint: Some(base_url),
};
let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect_err("a mismatch must fail the fetch");
assert!(
matches!(error, ToolError::BlobCidMismatch { .. }),
"expected BlobCidMismatch, got {error}"
);
let dir = ctx.cache.dir().expect("cache dir configured").to_path_buf();
assert_eq!(
dir_entries(&dir),
Vec::<String>::new(),
"no partial or final file may survive a CID mismatch"
);
assert!(ctx.cache.get(&requested_cid).await.is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn an_oversize_body_is_refused_on_the_running_total_and_leaves_no_partial_file() {
let ctx = test_context_with_cache();
let mut rctx = test_request();
let body = vec![7u8; 4096];
let cid = atproto_dasl::compute_raw_cid(&body).to_string();
let base_url = one_shot_server(200, body, false).await;
let locator = Locator {
did: DID.to_string(),
cid,
endpoint: Some(base_url),
};
let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect_err("a body over max_bytes must be refused");
let message = error.to_string();
match error {
ToolError::BlobDownloadTooLarge { size, limit } => {
assert_eq!(limit, 1024);
assert!(size > limit, "the reported size must exceed the limit");
assert!(size <= 4096, "and cannot exceed what was sent");
}
other => panic!("expected BlobDownloadTooLarge, got {other}"),
}
assert!(message.starts_with("error-atpmcp-tool-20 "), "{message}");
assert!(message.contains("at least"), "{message}");
let dir = ctx.cache.dir().expect("cache dir configured").to_path_buf();
assert_eq!(
dir_entries(&dir),
Vec::<String>::new(),
"a size refusal must not leave a partial file behind to fill the disk"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn an_error_status_is_reported_as_the_answer_and_never_hashed() {
let ctx = test_context_with_cache();
let mut rctx = test_request();
let cid = blob_cid();
let base_url = one_shot_server(
400,
br#"{"error":"BlobNotFound","message":"Blob not found"}"#.to_vec(),
true,
)
.await;
let locator = Locator {
did: DID.to_string(),
cid: cid.clone(),
endpoint: Some(base_url.clone()),
};
let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect_err("an error answer is not the blob");
match &error {
ToolError::BlobErrorResponse {
endpoint,
status,
body,
} => {
assert_eq!(endpoint, &base_url);
assert_eq!(*status, 400);
assert_eq!(
body,
r#"{"error":"BlobNotFound","message":"Blob not found"}"#
);
}
other => panic!("expected BlobErrorResponse, got {other}"),
}
let message = error.to_string();
assert!(message.starts_with("error-atpmcp-tool-19 "), "{message}");
assert!(!message.contains("mismatch"), "{message}");
let dir = ctx.cache.dir().expect("cache dir configured").to_path_buf();
assert_eq!(dir_entries(&dir), Vec::<String>::new());
assert!(ctx.cache.get(&cid).await.is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn a_redirect_is_named_and_never_hashed() {
let ctx = test_context();
let mut rctx = test_request();
let base_url = one_shot_server(302, Vec::new(), true).await;
let locator = Locator {
did: DID.to_string(),
cid: blob_cid(),
endpoint: Some(base_url),
};
let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect_err("a redirect is not the blob");
let ToolError::BlobErrorResponse { status, body, .. } = &error else {
panic!("expected BlobErrorResponse, got {error}");
};
assert_eq!(*status, 302);
assert!(body.contains("redirect"), "{body}");
assert!(body.contains("not followed"), "{body}");
}
#[tokio::test]
async fn a_large_error_page_is_an_error_answer_quoted_in_part() {
let ctx = test_context_with_cache();
let mut rctx = test_request();
let mut page = b"<html><body>Bad Gateway".to_vec();
page.resize(8192, b'x');
let base_url = one_shot_server(502, page, true).await;
let locator = Locator {
did: DID.to_string(),
cid: blob_cid(),
endpoint: Some(base_url),
};
let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect_err("a 502 is not the blob");
let ToolError::BlobErrorResponse { status, body, .. } = &error else {
panic!("expected BlobErrorResponse, got {error}");
};
assert_eq!(*status, 502);
assert!(body.starts_with("<html><body>Bad Gateway"), "{body}");
assert!(body.ends_with("(truncated at 1024 bytes)"), "{body}");
assert!(body.len() < 1024 + 64, "{} bytes quoted", body.len());
if let Some(dir) = ctx.cache.dir() {
let _ = std::fs::remove_dir_all(dir);
}
}
#[tokio::test]
async fn an_oversize_declared_content_length_is_refused_before_writing_anything() {
let ctx = test_context_with_cache();
let mut rctx = test_request();
let body = vec![9u8; 4096];
let cid = atproto_dasl::compute_raw_cid(&body).to_string();
let base_url = one_shot_server(200, body, true).await;
let locator = Locator {
did: DID.to_string(),
cid,
endpoint: Some(base_url),
};
let error = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect_err("an over-declared Content-Length must be refused");
assert!(
matches!(
error,
ToolError::BlobDownloadTooLarge {
size: 4096,
limit: 1024
}
),
"expected BlobDownloadTooLarge, got {error}"
);
assert!(error.to_string().contains("at least 4096 bytes"), "{error}");
let dir = ctx.cache.dir().expect("cache dir configured").to_path_buf();
assert_eq!(dir_entries(&dir), Vec::<String>::new());
let _ = std::fs::remove_dir_all(&dir);
}
fn png() -> Vec<u8> {
let mut data = vec![
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
0x44, 0x52,
];
data.extend_from_slice(&[1u8; 64]);
data
}
fn expecting(size: Option<u64>, mime_type: Option<&str>) -> Expected {
Expected {
size,
mime_type: mime_type.map(str::to_string),
}
}
async fn fetch_served(
ctx: &Arc<ServerContext>,
body: &[u8],
declare_length: bool,
content_type: Option<&str>,
expected: &Expected,
) -> Result<VerifiedBlob, ToolError> {
let base_url = crate::tools::test_support::one_shot_server_typed(
200,
body.to_vec(),
declare_length,
content_type,
)
.await;
let locator = Locator {
did: DID.to_string(),
cid: atproto_dasl::compute_raw_cid(body).to_string(),
endpoint: Some(base_url),
};
fetch(ctx, &mut test_request(), &locator, expected, 1024).await
}
#[tokio::test]
async fn an_octet_stream_png_is_a_png_and_is_cached_as_one() {
let ctx = test_context_with_cache();
let data = png();
let blob = fetch_served(
&ctx,
&data,
true,
Some("application/octet-stream"),
&Expected::default(),
)
.await
.expect("fetch succeeds");
assert_eq!(blob.mime_type, "image/png");
assert!(blob.mime_disagreement.is_none());
drop(blob);
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
let cached = ctx.cache.get(&cid).await.expect("cached");
assert_eq!(cached.mime_type.as_deref(), Some("image/png"));
let _ = std::fs::remove_dir_all(ctx.cache.dir().unwrap());
}
#[tokio::test]
async fn a_declared_type_is_used_and_cached_over_a_generic_one() {
for served in [Some("application/octet-stream"), None] {
let ctx = test_context_with_cache();
let data = format!("plain text, served as {served:?}").into_bytes();
let blob = fetch_served(
&ctx,
&data,
true,
served,
&expecting(None, Some("text/plain")),
)
.await
.expect("fetch succeeds");
assert_eq!(blob.mime_type, "text/plain", "{served:?}");
drop(blob);
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
let cached = ctx.cache.get(&cid).await.expect("cached");
assert_eq!(
cached.mime_type.as_deref(),
Some("text/plain"),
"{served:?}"
);
let _ = std::fs::remove_dir_all(ctx.cache.dir().unwrap());
}
}
#[tokio::test]
async fn a_specific_served_type_stands_and_a_disagreement_is_reported() {
let ctx = test_context();
let blob = fetch_served(
&ctx,
&png(),
true,
Some("image/webp"),
&expecting(None, Some("image/png")),
)
.await
.expect("a disagreement is not a refusal");
assert_eq!(blob.mime_type, "image/webp");
let note = blob.mime_disagreement.as_deref().expect("reported");
assert!(note.contains("the host served 'image/webp'"), "{note}");
}
#[tokio::test]
async fn a_hit_that_recorded_octet_stream_is_sniffed() {
let ctx = test_context_with_cache();
let data = png();
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
ctx.cache
.put(&cid, &data, Some("application/octet-stream"))
.await
.unwrap();
let locator = Locator {
did: DID.to_string(),
cid,
endpoint: Some("https://127.0.0.1:1".to_string()),
};
let blob = fetch(
&ctx,
&mut test_request(),
&locator,
&Expected::default(),
1024,
)
.await
.expect("a hit");
assert!(blob.cached);
assert_eq!(blob.mime_type, "image/png");
drop(blob);
let _ = std::fs::remove_dir_all(ctx.cache.dir().unwrap());
}
#[tokio::test]
async fn a_blob_shorter_than_its_declared_size_is_refused_and_discarded() {
let ctx = test_context_with_cache();
let data = b"forty-odd bytes of a blob with a wrong size".to_vec();
let declared = data.len() as u64 + 10;
let error = fetch_served(&ctx, &data, true, None, &expecting(Some(declared), None))
.await
.expect_err("a size mismatch is refused");
match &error {
ToolError::BlobSizeMismatch {
declared: said,
actual,
at_least,
} => {
assert_eq!(*said, declared);
assert_eq!(*actual, data.len() as u64);
assert!(!at_least);
}
other => panic!("expected BlobSizeMismatch, got {other}"),
}
let message = error.to_string();
assert!(message.starts_with("error-atpmcp-tool-22 "), "{message}");
assert!(
message.contains(&format!("the blob is {}", data.len())),
"{message}"
);
let dir = ctx.cache.dir().unwrap().to_path_buf();
assert_eq!(dir_entries(&dir), Vec::<String>::new());
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn a_blob_longer_than_its_declared_size_is_refused_at_that_size() {
for declare_length in [true, false] {
let ctx = test_context_with_cache();
let data = vec![5u8; 900];
let error = fetch_served(
&ctx,
&data,
declare_length,
None,
&expecting(Some(100), None),
)
.await
.expect_err("a size mismatch is refused");
let message = error.to_string();
match error {
ToolError::BlobSizeMismatch {
declared,
actual,
at_least,
} => {
assert_eq!(declared, 100);
assert!(actual > 100, "{actual}");
assert!(at_least, "{declare_length}");
}
other => panic!("expected BlobSizeMismatch, got {other}"),
}
assert!(message.contains("the host sent at least"), "{message}");
let dir = ctx.cache.dir().unwrap().to_path_buf();
assert_eq!(dir_entries(&dir), Vec::<String>::new());
let _ = std::fs::remove_dir_all(&dir);
}
}
#[tokio::test]
async fn a_blob_of_its_declared_size_is_served() {
let ctx = test_context();
let data = png();
let blob = fetch_served(
&ctx,
&data,
false,
Some("image/png"),
&expecting(Some(data.len() as u64), Some("image/png")),
)
.await
.expect("fetch succeeds");
assert_eq!(blob.size, data.len() as u64);
assert!(blob.mime_disagreement.is_none());
}
#[tokio::test]
async fn a_declared_size_over_max_bytes_is_refused_before_fetching() {
let ctx = test_context();
let locator = Locator {
did: DID.to_string(),
cid: blob_cid(),
endpoint: Some("https://127.0.0.1:1".to_string()),
};
let error = fetch(
&ctx,
&mut test_request(),
&locator,
&expecting(Some(4096), None),
1024,
)
.await
.expect_err("refused");
assert!(
matches!(
error,
ToolError::BlobTooLarge {
size: 4096,
limit: 1024
}
),
"{error}"
);
}
#[tokio::test]
async fn a_hit_of_another_size_is_refused_and_kept() {
let ctx = test_context_with_cache();
let data = vec![6u8; 64];
let cid = atproto_dasl::compute_raw_cid(&data).to_string();
ctx.cache.put(&cid, &data, None).await.unwrap();
let locator = Locator {
did: DID.to_string(),
cid: cid.clone(),
endpoint: Some("https://127.0.0.1:1".to_string()),
};
let error = fetch(
&ctx,
&mut test_request(),
&locator,
&expecting(Some(65), None),
1024,
)
.await
.expect_err("refused");
assert!(
matches!(
error,
ToolError::BlobSizeMismatch {
declared: 65,
actual: 64,
at_least: false
}
),
"{error}"
);
assert!(ctx.cache.get(&cid).await.is_some(), "the entry is kept");
let _ = std::fs::remove_dir_all(ctx.cache.dir().unwrap());
}
async fn a_verified_hit(data: &[u8]) -> (Arc<ServerContext>, VerifiedBlob) {
let ctx = test_context_with_cache();
let mut rctx = test_request();
let cid = atproto_dasl::compute_raw_cid(data).to_string();
ctx.cache.put(&cid, data, None).await.unwrap();
let locator = Locator {
did: DID.to_string(),
cid,
endpoint: Some("https://127.0.0.1:1".to_string()),
};
let blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024 * 1024)
.await
.expect("a cache hit");
assert!(blob.cached);
(ctx, blob)
}
fn remove_cache(ctx: &Arc<ServerContext>) {
if let Some(dir) = ctx.cache.dir() {
let _ = std::fs::remove_dir_all(dir);
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_file_replaced_after_verification_reads_back_as_the_verified_bytes() {
let original = b"the bytes that were verified".to_vec();
let (ctx, mut blob) = a_verified_hit(&original).await;
let impostor = blob.path.with_extension("impostor");
std::fs::write(&impostor, b"the bytes put there afterwards").unwrap();
std::fs::rename(&impostor, &blob.path).unwrap();
let data = blob.bytes().await.expect("the verified file is still open");
assert_eq!(data, original, "never the bytes that replaced it");
drop(blob);
remove_cache(&ctx);
}
#[cfg(unix)]
#[tokio::test]
async fn a_file_removed_after_verification_still_reads_back() {
let original = b"evicted between verification and the inline read".to_vec();
let (ctx, mut blob) = a_verified_hit(&original).await;
std::fs::remove_file(&blob.path).unwrap();
let data = blob.bytes().await.expect("the verified file is still open");
assert_eq!(data, original);
drop(blob);
remove_cache(&ctx);
}
#[tokio::test]
async fn a_file_rewritten_in_place_after_verification_is_refused() {
use std::io::Write as _;
let original = b"the bytes that were verified".to_vec();
let (ctx, mut blob) = a_verified_hit(&original).await;
let mut tampered = original.clone();
tampered[4] ^= 0x20;
let mut file = std::fs::OpenOptions::new()
.write(true)
.open(&blob.path)
.unwrap();
file.write_all(&tampered).unwrap();
drop(file);
let error = blob.bytes().await.expect_err("changed bytes are refused");
assert!(
matches!(&error, ToolError::BlobReadBackFailed { reason, .. } if reason.contains("hashes to")),
"{error}"
);
assert!(
error.to_string().starts_with("error-atpmcp-tool-21 "),
"{error}"
);
drop(blob);
remove_cache(&ctx);
}
#[tokio::test]
async fn a_file_grown_after_verification_is_refused_without_reading_it_all() {
use std::io::Write as _;
let original = b"the bytes that were verified".to_vec();
let (ctx, mut blob) = a_verified_hit(&original).await;
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(&blob.path)
.unwrap();
file.write_all(&vec![0u8; 1024 * 1024]).unwrap();
drop(file);
let error = blob.bytes().await.expect_err("a grown file is refused");
assert!(
matches!(&error, ToolError::BlobReadBackFailed { reason, .. }
if reason.contains(&format!("{} bytes", original.len()))),
"{error}"
);
drop(blob);
remove_cache(&ctx);
}
#[tokio::test]
async fn a_disabled_cache_streams_to_a_scratch_file_cleaned_up_on_drop() {
let ctx = test_context(); let mut rctx = test_request();
let body = b"scratch-only blob".to_vec();
let cid = atproto_dasl::compute_raw_cid(&body).to_string();
let base_url = one_shot_server(200, body.clone(), true).await;
let locator = Locator {
did: DID.to_string(),
cid,
endpoint: Some(base_url),
};
let blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect("fetch succeeds even with no persistent cache");
assert!(blob.ephemeral);
let path = blob.path.clone();
assert!(
path.exists(),
"the scratch file exists while `blob` is alive"
);
assert_eq!(std::fs::read(&path).unwrap(), body);
drop(blob);
assert!(
!path.exists(),
"an ephemeral scratch file must not outlive its VerifiedBlob"
);
}
#[tokio::test]
async fn a_kept_scratch_file_outlives_its_verified_blob() {
let ctx = test_context(); let mut rctx = test_request();
let body = b"kept scratch blob".to_vec();
let cid = atproto_dasl::compute_raw_cid(&body).to_string();
let base_url = one_shot_server(200, body.clone(), true).await;
let locator = Locator {
did: DID.to_string(),
cid,
endpoint: Some(base_url),
};
let mut blob = fetch(&ctx, &mut rctx, &locator, &Expected::default(), 1024)
.await
.expect("fetch succeeds even with no persistent cache");
assert!(blob.ephemeral);
let path = blob.keep();
assert!(!blob.ephemeral);
drop(blob);
assert_eq!(
std::fs::read(&path).unwrap(),
body,
"a kept scratch file survives the drop with the verified bytes"
);
let _ = std::fs::remove_file(&path);
}
async fn a_verified_temp_file(
ctx: &Arc<ServerContext>,
data: &[u8],
) -> (String, crate::cache::WriteTarget, tokio::fs::File) {
let cid = atproto_dasl::compute_raw_cid(data).to_string();
let target = ctx
.cache
.prepare_write(&cid, None)
.await
.unwrap()
.expect("a cache to write into");
let chunks = futures::stream::iter(vec![Ok(bytes::Bytes::copy_from_slice(data))]);
let (_, computed, file) = write_hashed(&target.temp_path, chunks, 1024 * 1024)
.await
.unwrap();
assert_eq!(computed, cid);
(cid, target, file)
}
#[tokio::test]
async fn a_blob_moved_to_scratch_leaves_nothing_in_the_cache() {
let ctx = test_context_with_cache();
let data = b"moved out of the cache directory".to_vec();
let (cid, target, file) = a_verified_temp_file(&ctx, &data).await;
let (path, file) = move_to_scratch(&ctx, &target, &cid, file)
.await
.expect("moved");
let dir = ctx.cache.dir().unwrap().to_path_buf();
assert!(!path.starts_with(&dir), "{}", path.display());
assert_eq!(std::fs::read(&path).unwrap(), data);
assert_eq!(dir_entries(&dir), Vec::<String>::new());
let mut blob = VerifiedBlob {
path: path.clone(),
size: data.len() as u64,
mime_type: crate::mime::OCTET_STREAM.to_string(),
mime_disagreement: None,
cached: false,
cid,
file: Some(file),
ephemeral: true,
};
assert_eq!(blob.bytes().await.unwrap(), data);
drop(blob);
assert!(
!path.exists(),
"an ephemeral scratch file goes with its value"
);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[tokio::test]
async fn a_blob_that_cannot_be_renamed_to_scratch_is_copied_through_its_handle() {
let ctx = test_context_with_cache();
let data = vec![3u8; 200_000];
let (cid, target, file) = a_verified_temp_file(&ctx, &data).await;
std::fs::remove_file(&target.temp_path).unwrap();
let (path, mut file) = move_to_scratch(&ctx, &target, &cid, file)
.await
.expect("copied");
assert_eq!(std::fs::read(&path).unwrap(), data);
use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};
let mut through_handle = Vec::new();
file.rewind().await.unwrap();
file.read_to_end(&mut through_handle).await.unwrap();
assert_eq!(through_handle, data, "the handle returned is the copy's");
let _ = std::fs::remove_file(&path);
remove_cache(&ctx);
}
#[tokio::test]
async fn a_copy_refuses_an_existing_path_and_one_that_does_not_verify() {
let ctx = test_context_with_cache();
let data = b"copied and hashed again".to_vec();
let (cid, target, file) = a_verified_temp_file(&ctx, &data).await;
let existing = scratch_path(&cid);
std::fs::write(&existing, b"someone else's file").unwrap();
let error = copy_verified(file, &existing, &cid)
.await
.expect_err("an existing path is refused");
assert!(error.contains("could not create"), "{error}");
assert_eq!(std::fs::read(&existing).unwrap(), b"someone else's file");
let _ = std::fs::remove_file(&existing);
let file = tokio::fs::File::open(&target.temp_path).await.unwrap();
let other = atproto_dasl::compute_raw_cid(b"different bytes").to_string();
let to = scratch_path(&other);
let error = copy_verified(file, &to, &other)
.await
.expect_err("a copy that does not verify is refused");
assert!(error.contains("hashes to"), "{error}");
assert!(!to.exists(), "and deleted");
remove_cache(&ctx);
}
#[tokio::test]
async fn a_streamed_write_refuses_an_existing_path() {
let path = std::env::temp_dir().join(format!(
"atpmcp-existing-{}-{}",
std::process::id(),
line!()
));
std::fs::write(&path, b"someone else's file").unwrap();
let chunks = futures::stream::iter(vec![Ok(bytes::Bytes::from_static(b"blob bytes"))]);
let result = write_hashed(&path, chunks, 1024).await;
assert!(result.is_err(), "an existing path must be refused");
assert_eq!(
std::fs::read(&path).unwrap(),
b"someone else's file",
"and left exactly as it was"
);
let _ = std::fs::remove_file(&path);
}
#[tokio::test]
async fn a_verified_fetch_is_not_visible_at_its_cache_path_before_it_completes() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
let ctx = test_context_with_cache();
let body = vec![5u8; 65536];
let cid = atproto_dasl::compute_raw_cid(&body).to_string();
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
let addr = listener.local_addr().expect("addr");
let server_body = body.clone();
tokio::spawn(async move {
let Ok((mut socket, _)) = listener.accept().await else {
return;
};
let mut raw = Vec::new();
let mut buffer = [0u8; 4096];
loop {
let Ok(read) = socket.read(&mut buffer).await else {
return;
};
if read == 0 {
break;
}
raw.extend_from_slice(&buffer[..read]);
if raw.windows(4).any(|w| w == b"\r\n\r\n") {
break;
}
}
let mut response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n",
server_body.len()
);
response.push_str("Connection: close\r\n\r\n");
let _ = socket.write_all(response.as_bytes()).await;
let (first, second) = server_body.split_at(server_body.len() / 2);
let _ = socket.write_all(first).await;
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
let _ = socket.write_all(second).await;
let _ = socket.shutdown().await;
});
let locator = Locator {
did: DID.to_string(),
cid: cid.clone(),
endpoint: Some(format!("http://{addr}")),
};
let ctx_bg = Arc::clone(&ctx);
let locator_bg = locator.clone();
let handle = tokio::spawn(async move {
let mut rctx = test_request();
fetch(
&ctx_bg,
&mut rctx,
&locator_bg,
&Expected::default(),
1024 * 1024,
)
.await
});
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
assert!(
ctx.cache
.path_for(&cid)
.filter(|path| path.exists())
.is_none(),
"an in-flight fetch must not be visible at its final cache path yet"
);
let result = handle.await.unwrap();
assert!(
result.is_ok(),
"fetch should eventually succeed: {result:?}"
);
assert!(
ctx.cache
.path_for(&cid)
.filter(|path| path.exists())
.is_some(),
"once complete, the verified blob must be at its real cache path"
);
if let Some(dir) = ctx.cache.dir() {
let _ = std::fs::remove_dir_all(dir);
}
}
}