use std::{collections::HashSet, path::PathBuf};
use super::{
KeySegments, LocalFsBlob, LocalFsBlobError, LocalFsBlobRecord, LocalFsStore, MAX_PATH_LEN,
MAX_SEGMENT_LEN, RESERVED, Segments, blob_address, is_verbatim, render_segment,
};
use crate::{
AsyncBlobEngine, AsyncLocate, BlobRecord, Connected, Identifiable, Transformer, TypedId,
};
fn block_on<F: Future>(future: F) -> F::Output {
use core::{
pin::pin,
task::{Context, Poll, Waker},
};
let mut future = pin!(future);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
}
}
const SLOT: &str = "thumbnail";
struct ThumbKey {
media: String,
frame: i64,
}
impl ThumbKey {
fn new(media: &str, frame: i64) -> Self {
Self {
media: media.to_owned(),
frame,
}
}
}
impl KeySegments for ThumbKey {
fn segments(&self, out: &mut Segments) {
out.push(&self.media);
out.push(&self.frame);
}
}
struct Thumbnail {
key: ThumbKey,
bytes: Vec<u8>,
}
struct ThumbLineage {
#[expect(
dead_code,
reason = "the address binding names the type; no blob seam projects the lineage half"
)]
media: String,
}
impl Identifiable for Thumbnail {
type Id = i64;
fn id_ref(&self) -> &i64 {
&self.key.frame
}
}
impl Transformer for Thumbnail {
type Key = ThumbKey;
type Lineage = ThumbLineage;
type Record = Self;
type Graphql = ();
fn key(&self) -> ThumbKey {
ThumbKey::new(&self.key.media, self.key.frame)
}
}
impl BlobRecord for Thumbnail {
type Bytes = Vec<u8>;
fn bytes(&self) -> &Vec<u8> {
&self.bytes
}
fn extension() -> Option<&'static str> {
Some("png")
}
}
struct TypedThumbKey {
media: String,
frame: TypedId<i64, TypedThumb>,
}
impl TypedThumbKey {
fn new(media: &str, frame: i64) -> Self {
Self {
media: media.to_owned(),
frame: TypedId::new(frame),
}
}
}
impl KeySegments for TypedThumbKey {
fn segments(&self, out: &mut Segments) {
out.push(&self.media);
out.push(&self.frame);
}
}
struct TypedThumb {
key: TypedThumbKey,
}
impl Identifiable for TypedThumb {
type Id = TypedId<i64, TypedThumb>;
fn id_ref(&self) -> &Self::Id {
&self.key.frame
}
}
impl Transformer for TypedThumb {
type Key = TypedThumbKey;
type Lineage = ThumbLineage;
type Record = Self;
type Graphql = ();
fn key(&self) -> TypedThumbKey {
TypedThumbKey::new(&self.key.media, self.key.frame.id())
}
}
impl BlobRecord for TypedThumb {
type Bytes = Vec<u8>;
fn bytes(&self) -> &Vec<u8> {
unreachable!("the typed twin is only addressed, never written")
}
fn extension() -> Option<&'static str> {
Some("png")
}
}
struct Waveform;
impl Identifiable for Waveform {
type Id = i64;
fn id_ref(&self) -> &i64 {
&12
}
}
impl Transformer for Waveform {
type Key = ThumbKey;
type Lineage = ThumbLineage;
type Record = Self;
type Graphql = ();
fn key(&self) -> ThumbKey {
ThumbKey::new("clip_42", 12)
}
}
impl BlobRecord for Waveform {
type Bytes = Vec<u8>;
fn bytes(&self) -> &Vec<u8> {
unreachable!("the extensionless record is only addressed, never written")
}
}
struct SlugKey {
media: String,
slug: String,
}
impl SlugKey {
fn new(media: &str, slug: &str) -> Self {
Self {
media: media.to_owned(),
slug: slug.to_owned(),
}
}
}
impl KeySegments for SlugKey {
fn segments(&self, out: &mut Segments) {
out.push(&self.media);
out.push(&self.slug);
}
}
struct Slugged {
key: SlugKey,
}
impl Identifiable for Slugged {
type Id = String;
fn id_ref(&self) -> &String {
&self.key.slug
}
}
impl Transformer for Slugged {
type Key = SlugKey;
type Lineage = ThumbLineage;
type Record = Self;
type Graphql = ();
fn key(&self) -> SlugKey {
SlugKey::new(&self.key.media, &self.key.slug)
}
}
impl BlobRecord for Slugged {
type Bytes = Vec<u8>;
fn bytes(&self) -> &Vec<u8> {
unreachable!("the text-leafed record is only addressed, never written")
}
fn extension() -> Option<&'static str> {
Some("png")
}
}
struct DeepKey(Vec<String>);
impl KeySegments for DeepKey {
fn segments(&self, out: &mut Segments) {
for level in &self.0 {
out.push(level);
}
}
}
struct Deep;
impl Identifiable for Deep {
type Id = ();
fn id_ref(&self) -> &() {
&()
}
}
impl Transformer for Deep {
type Key = DeepKey;
type Lineage = ThumbLineage;
type Record = Self;
type Graphql = ();
fn key(&self) -> DeepKey {
DeepKey(Vec::new())
}
}
impl BlobRecord for Deep {
type Bytes = Vec<u8>;
fn bytes(&self) -> &Vec<u8> {
unreachable!("the deep record is only addressed, never written")
}
}
fn open_store() -> (tempfile::TempDir, LocalFsStore) {
let dir = tempfile::tempdir().expect("a temp dir");
let store = LocalFsStore::open(dir.path()).expect("the store opens");
(dir, store)
}
fn try_locate<R>(
store: &LocalFsStore,
slot: &str,
key: &R::Key,
) -> Result<PathBuf, LocalFsBlobError>
where
R: LocalFsBlobRecord,
R::Bytes: AsRef<[u8]>,
{
AsyncLocate::<R>::locate(
&LocalFsBlob::new(slot),
Connected::new(store, ()),
key,
R::extension(),
)
}
fn locate<R>(store: &LocalFsStore, key: &R::Key) -> PathBuf
where
R: LocalFsBlobRecord,
R::Bytes: AsRef<[u8]>,
{
try_locate::<R>(store, SLOT, key).expect("the address renders")
}
fn slot_entries(dir: &tempfile::TempDir) -> Vec<String> {
let mut names: Vec<_> = std::fs::read_dir(dir.path().join(SLOT))
.expect("the slot directory")
.map(|entry| {
entry
.expect("an entry")
.file_name()
.into_string()
.expect("a utf-8 name")
})
.collect();
names.sort();
names
}
#[test]
fn a_two_level_key_renders_its_address_byte_exactly() {
let (dir, store) = open_store();
let key = ThumbKey::new("clip_42", 12);
assert_eq!(
locate::<Thumbnail>(&store, &key),
dir.path().join("thumbnail/clip_42/12.png")
);
assert_eq!(
locate::<Waveform>(&store, &key),
dir.path().join("thumbnail/clip_42/12")
);
}
#[test]
fn a_negative_integer_renders_verbatim_with_its_sign() {
let (dir, store) = open_store();
assert_eq!(
locate::<Thumbnail>(&store, &ThumbKey::new("clip", -7)),
dir.path().join("thumbnail/clip/-7.png")
);
assert!(is_verbatim("-7"));
}
#[test]
fn a_text_id_that_escapes_renders_its_base32() {
let (dir, store) = open_store();
assert_eq!(
locate::<Thumbnail>(&store, &ThumbKey::new("a/b", 1)),
dir.path().join("thumbnail/=mexwe/1.png")
);
}
#[test]
fn text_ids_differing_only_by_case_never_collide() {
let (dir, store) = open_store();
let leaf = |media: &str| locate::<Thumbnail>(&store, &ThumbKey::new(media, 1));
let lower = leaf("alice");
let upper = leaf("Alice");
assert_eq!(lower, dir.path().join("thumbnail/alice/1.png"));
assert_ne!(lower, upper);
assert_ne!(
lower.to_str().expect("utf-8").to_lowercase(),
upper.to_str().expect("utf-8").to_lowercase()
);
let a = leaf("Bob Smith");
let b = leaf("bob smith");
assert_ne!(a, b);
assert_ne!(
a.to_str().expect("utf-8").to_lowercase(),
b.to_str().expect("utf-8").to_lowercase()
);
}
#[test]
fn a_case_pair_writes_two_files_that_coexist() {
let (dir, store) = open_store();
let handle = LocalFsBlob::new(SLOT);
let put = |media: &str, byte: u8| {
block_on(handle.put(
Connected::new(&store, ()),
&Thumbnail {
key: ThumbKey::new(media, 1),
bytes: vec![byte],
},
))
.expect("the put")
};
let get = |media: &str| {
block_on(AsyncBlobEngine::<Thumbnail>::get(
&handle,
Connected::new(&store, ()),
&ThumbKey::new(media, 1),
))
.expect("the read")
};
put("abc", 1);
put("Abc", 2);
assert_eq!(get("abc"), vec![1]);
assert_eq!(get("Abc"), vec![2]);
let lower = locate::<Thumbnail>(&store, &ThumbKey::new("abc", 1));
let upper = locate::<Thumbnail>(&store, &ThumbKey::new("Abc", 1));
assert!(lower.exists() && upper.exists());
assert_ne!(
lower.to_str().expect("utf-8").to_lowercase(),
upper.to_str().expect("utf-8").to_lowercase()
);
assert_eq!(slot_entries(&dir), ["=ifrgg", "abc"]);
}
#[test]
fn every_text_id_renders_and_none_collides() {
let long = "x".repeat(300);
let adversarial = [
"",
".",
"..",
"...",
".hidden",
"a.b",
"a.",
".a",
"1.2.3.4",
"1.2.3.5",
"255.255.255.255",
"CON",
"con",
"NUL",
"nul",
"com1",
"lpt9",
"aux",
"prn",
"a/b",
"a\\b",
"a:b",
"a\0b",
"=already",
"=",
" ",
" ",
"\n",
"Ünïcødé",
"日本語",
"🎬",
"Alice",
"alice",
"ALICE",
"a-b_c",
"-",
"_",
"0",
&long,
];
let mut folded = HashSet::new();
for id in adversarial {
let mut rendered = String::new();
render_segment(id, &mut rendered);
assert!(
!rendered.is_empty(),
"the id {id:?} rendered to an empty segment"
);
assert!(
folded.insert(rendered.to_lowercase()),
"the id {id:?} collided at {rendered:?}"
);
assert!(!rendered.contains('/'), "{id:?} rendered a separator");
assert!(!rendered.contains('\\'), "{id:?} rendered a separator");
assert!(!rendered.contains('\0'), "{id:?} rendered a NUL");
assert!(rendered != "." && rendered != "..", "{id:?} rendered a dot");
}
}
#[test]
fn the_pure_dot_segments_escape_and_their_neighbours_do_not() {
for dots in [".", ".."] {
assert!(!is_verbatim(dots), "{dots:?} must not render verbatim");
let mut rendered = String::new();
render_segment(dots, &mut rendered);
assert!(rendered.starts_with('='), "{dots:?} did not escape");
}
assert!(is_verbatim("..."));
assert!(is_verbatim(".hidden"));
assert!(is_verbatim("a.b"));
assert!(is_verbatim("1.2.3.4"));
assert!(is_verbatim("a."));
}
#[test]
fn a_text_id_shaped_like_an_address_is_just_text() {
let mut text = Segments::new();
text.push(&"1.2.3.4".to_owned());
let mut ip = Segments::new();
ip.push(&core::net::Ipv4Addr::new(1, 2, 3, 4));
assert_eq!(text.as_slice(), ip.as_slice());
assert_eq!(text.as_slice(), ["1.2.3.4"]);
}
#[test]
fn the_network_family_renders_verbatim() {
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
let v6 = Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 1);
let mut segments = Segments::new();
segments.push(&Ipv4Addr::new(1, 2, 3, 4));
segments.push(&v6);
segments.push(&IpAddr::V4(Ipv4Addr::new(255, 255, 255, 255)));
segments.push(&IpAddr::V6(v6));
segments.push(&SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 8080));
segments.push(&SocketAddrV6::new(v6, 8080, 0, 0));
segments.push(&SocketAddrV6::new(v6, 8080, 7, 9));
segments.push(&SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::new(1, 2, 3, 4),
80,
)));
assert_eq!(
segments.as_slice(),
[
"1.2.3.4",
"20010db8000000000000000000000001",
"255.255.255.255",
"20010db8000000000000000000000001",
"1.2.3.4_8080",
"20010db8000000000000000000000001_8080_0_0",
"20010db8000000000000000000000001_8080_7_9",
"1.2.3.4_80",
]
);
for rendered in segments.as_slice() {
assert!(is_verbatim(rendered), "{rendered:?} should be verbatim");
}
}
#[test]
fn a_socket_v6_addresses_its_flowinfo_and_scope_id() {
use core::net::{Ipv6Addr, SocketAddrV6};
let ip = Ipv6Addr::LOCALHOST;
let base = SocketAddrV6::new(ip, 80, 0, 0);
let flow = SocketAddrV6::new(ip, 80, 1, 0);
let scope = SocketAddrV6::new(ip, 80, 0, 1);
assert_ne!(base, flow);
assert_ne!(base, scope);
assert_ne!(flow, scope);
let render = |addr: &SocketAddrV6| {
let mut out = Segments::new();
out.push(addr);
out.as_slice()[0].clone()
};
let (b, f, s) = (render(&base), render(&flow), render(&scope));
assert_ne!(b, f);
assert_ne!(b, s);
assert_ne!(f, s);
}
#[test]
fn a_pointer_addresses_what_its_pointee_does() {
fn one<I: super::Segment>(id: &I) -> String {
let mut out = Segments::new();
out.push(id);
out.as_slice()[0].clone()
}
let bare = one(&9u64);
assert_eq!(one(&std::sync::Arc::new(9u64)), bare);
assert_eq!(one(&std::rc::Rc::new(9u64)), bare);
assert_eq!(one(&Box::new(9u64)), bare);
let uuid = uuid::Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").expect("a uuid");
assert_eq!(one(&std::sync::Arc::new(uuid)), one(&uuid));
let text = "Ünïcødé".to_owned();
assert_eq!(one(&std::sync::Arc::new(text.clone())), one(&text));
assert_eq!(one(&std::sync::Arc::new(Box::new(9u64))), bare);
}
#[test]
fn a_typed_id_addresses_what_its_bare_id_does() {
let (dir, store) = open_store();
let bare = locate::<Thumbnail>(&store, &ThumbKey::new("clip_42", 12));
let typed = locate::<TypedThumb>(&store, &TypedThumbKey::new("clip_42", 12));
assert_eq!(typed, bare);
assert_eq!(typed, dir.path().join("thumbnail/clip_42/12.png"));
}
#[test]
fn a_typed_text_id_escapes_exactly_as_its_bare_id_does() {
struct Slug {
id: TypedId<String, Slug>,
}
impl Identifiable for Slug {
type Id = TypedId<String, Slug>;
fn id_ref(&self) -> &Self::Id {
&self.id
}
}
fn one<I: super::Segment>(id: &I) -> String {
let mut out = Segments::new();
out.push(id);
out.as_slice()[0].clone()
}
let text = "Ünïcødé".to_owned();
assert_eq!(one(&TypedId::<String, Slug>::new(text.clone())), one(&text));
assert!(one(&TypedId::<String, Slug>::new(text)).starts_with('='));
}
#[test]
fn every_reserved_device_name_escapes_in_either_case() {
for name in RESERVED {
for spelling in [name.to_owned(), name.to_uppercase()] {
assert!(
!is_verbatim(&spelling),
"{spelling:?} is a reserved device name and must not render verbatim"
);
let mut rendered = String::new();
render_segment(&spelling, &mut rendered);
assert!(rendered.starts_with('='), "{spelling:?} did not escape");
}
}
assert!(is_verbatim("console"));
assert!(is_verbatim("com10"));
assert!(is_verbatim("com0"));
assert!(is_verbatim("nullable"));
}
#[test]
fn a_reserved_name_is_a_file_beside_an_ordinary_one() {
let (dir, store) = open_store();
let handle = LocalFsBlob::new(SLOT);
let put = |media: &str, byte: u8| {
block_on(handle.put(
Connected::new(&store, ()),
&Thumbnail {
key: ThumbKey::new(media, 1),
bytes: vec![byte],
},
))
.expect("the put")
};
let get = |media: &str| {
block_on(AsyncBlobEngine::<Thumbnail>::get(
&handle,
Connected::new(&store, ()),
&ThumbKey::new(media, 1),
))
.expect("the read")
};
put("con", 1);
put("console", 2);
assert_eq!(get("con"), vec![1]);
assert_eq!(get("console"), vec![2]);
assert_eq!(slot_entries(&dir), ["=mnxw4", "console"]);
}
#[test]
fn a_put_reads_back_and_a_second_put_replaces_it() {
let (_dir, store) = open_store();
let handle = LocalFsBlob::new(SLOT);
let read = || {
block_on(AsyncBlobEngine::<Thumbnail>::get(
&handle,
Connected::new(&store, ()),
&ThumbKey::new("clip", 3),
))
.expect("the read")
};
block_on(handle.put(
Connected::new(&store, ()),
&Thumbnail {
key: ThumbKey::new("clip", 3),
bytes: vec![1, 2, 3],
},
))
.expect("the first put");
assert_eq!(read(), vec![1, 2, 3]);
block_on(handle.put(
Connected::new(&store, ()),
&Thumbnail {
key: ThumbKey::new("clip", 3),
bytes: vec![9],
},
))
.expect("the second put");
assert_eq!(read(), vec![9]);
}
#[test]
fn a_publish_leaves_no_tmp_behind() {
let (dir, store) = open_store();
block_on(LocalFsBlob::new(SLOT).put(
Connected::new(&store, ()),
&Thumbnail {
key: ThumbKey::new("clip", 1),
bytes: vec![7],
},
))
.expect("the put");
let entries: Vec<_> = std::fs::read_dir(dir.path().join("thumbnail/clip"))
.expect("the key directory")
.map(|entry| entry.expect("an entry").file_name())
.collect();
assert_eq!(entries, vec![std::ffi::OsString::from("1.png")]);
}
#[test]
fn an_escaped_text_id_round_trips_through_the_filesystem() {
let (dir, store) = open_store();
let handle = LocalFsBlob::new(SLOT);
block_on(handle.put(
Connected::new(&store, ()),
&Thumbnail {
key: ThumbKey::new("Ünïcødé", 1),
bytes: vec![4, 2],
},
))
.expect("the put");
assert_eq!(
block_on(AsyncBlobEngine::<Thumbnail>::get(
&handle,
Connected::new(&store, ()),
&ThumbKey::new("Ünïcødé", 1),
))
.expect("the read"),
vec![4, 2]
);
assert!(
locate::<Thumbnail>(&store, &ThumbKey::new("Ünïcødé", 1))
.strip_prefix(dir.path())
.expect("under the root")
.to_str()
.expect("utf-8")
.starts_with("thumbnail/=")
);
}
#[test]
fn a_missing_blob_is_a_typed_miss() {
let (dir, store) = open_store();
let err = block_on(AsyncBlobEngine::<Thumbnail>::get(
&LocalFsBlob::new(SLOT),
Connected::new(&store, ()),
&ThumbKey::new("absent", 1),
))
.expect_err("the miss");
assert!(
matches!(&err, LocalFsBlobError::Missing(path) if path == &dir.path().join("thumbnail/absent/1.png"))
);
assert!(err.to_string().starts_with("no blob stored at "));
}
#[test]
fn a_malformed_slot_is_refused_where_an_id_never_is() {
let (_dir, store) = open_store();
let err = AsyncLocate::<Thumbnail>::locate(
&LocalFsBlob::new("../etc"),
Connected::new(&store, ()),
&ThumbKey::new("a/b", 1),
Thumbnail::extension(),
)
.expect_err("the slot is refused");
assert!(matches!(err, LocalFsBlobError::InvalidSlot(_)));
assert!(err.to_string().contains("is not a valid slot"));
}
#[test]
fn a_key_with_no_fields_is_refused() {
struct Empty;
impl KeySegments for Empty {
fn segments(&self, _out: &mut Segments) {}
}
struct Nothing;
impl Identifiable for Nothing {
type Id = ();
fn id_ref(&self) -> &() {
&()
}
}
impl Transformer for Nothing {
type Key = Empty;
type Lineage = ();
type Record = Self;
type Graphql = ();
fn key(&self) -> Empty {
Empty
}
}
impl BlobRecord for Nothing {
type Bytes = Vec<u8>;
fn bytes(&self) -> &Vec<u8> {
unreachable!("no address, so no write")
}
}
let (_dir, store) = open_store();
let err = AsyncLocate::<Nothing>::locate(
&LocalFsBlob::new(SLOT),
Connected::new(&store, ()),
&Empty,
None,
)
.expect_err("an empty key is refused");
assert!(matches!(err, LocalFsBlobError::EmptyKey));
}
#[test]
fn a_segment_past_the_ceiling_is_refused_by_name() {
let (_dir, store) = open_store();
let at = "a".repeat(MAX_SEGMENT_LEN);
let over = "a".repeat(MAX_SEGMENT_LEN + 1);
let err = try_locate::<Thumbnail>(&store, SLOT, &ThumbKey::new(&over, 1)).expect_err("refused");
let LocalFsBlobError::SegmentTooLong(refusal) = &err else {
panic!("expected a SegmentTooLong, got {err:?}");
};
assert_eq!(refusal.position(), 1);
assert_eq!(refusal.got(), MAX_SEGMENT_LEN + 1);
assert_eq!(refusal.limit(), MAX_SEGMENT_LEN);
assert!(
err
.to_string()
.starts_with("component 1 of the blob address renders to 256 bytes")
);
assert!(try_locate::<Thumbnail>(&store, SLOT, &ThumbKey::new(&at, 1)).is_ok());
}
#[test]
fn a_leaf_is_measured_with_its_extension() {
let (_dir, store) = open_store();
let extension = ".png".len();
let at = "b".repeat(MAX_SEGMENT_LEN - extension);
let over = "b".repeat(MAX_SEGMENT_LEN - extension + 1);
assert!(over.len() <= MAX_SEGMENT_LEN);
let err = try_locate::<Slugged>(&store, SLOT, &SlugKey::new("clip", &over)).expect_err("refused");
let LocalFsBlobError::SegmentTooLong(refusal) = &err else {
panic!("expected a SegmentTooLong, got {err:?}");
};
assert_eq!(refusal.position(), 2);
assert_eq!(refusal.got(), MAX_SEGMENT_LEN + 1);
assert_eq!(refusal.limit(), MAX_SEGMENT_LEN);
let path = try_locate::<Slugged>(&store, SLOT, &SlugKey::new("clip", &at)).expect("resolves");
assert_eq!(
path
.file_name()
.expect("a file name")
.to_str()
.expect("utf-8")
.len(),
MAX_SEGMENT_LEN
);
}
#[test]
fn an_over_long_slot_is_the_zeroth_component() {
let (_dir, store) = open_store();
let slot = "s".repeat(MAX_SEGMENT_LEN + 1);
assert!(crate::slot::is_identifier(slot.as_bytes()));
let err = try_locate::<Thumbnail>(&store, &slot, &ThumbKey::new("clip", 1)).expect_err("refused");
let LocalFsBlobError::SegmentTooLong(refusal) = &err else {
panic!("expected a SegmentTooLong, got {err:?}");
};
assert_eq!(refusal.position(), 0);
}
#[test]
fn a_path_past_the_ceiling_is_refused_by_name() {
let (_dir, store) = open_store();
let level = "c".repeat(200);
let deep = DeepKey(core::iter::repeat_n(level.clone(), 6).collect());
assert!(level.len() < MAX_SEGMENT_LEN);
let err = try_locate::<Deep>(&store, SLOT, &deep).expect_err("refused");
let LocalFsBlobError::PathTooLong(refusal) = &err else {
panic!("expected a PathTooLong, got {err:?}");
};
assert_eq!(refusal.got(), refusal.path().as_os_str().len());
assert!(refusal.got() > MAX_PATH_LEN);
assert_eq!(refusal.limit(), MAX_PATH_LEN);
assert!(err.to_string().ends_with("a portable path may take"));
assert!(try_locate::<Deep>(&store, SLOT, &DeepKey(vec![level; 2])).is_ok());
}
#[test]
fn a_length_refusal_reaches_the_put_before_any_io() {
let (dir, store) = open_store();
let err = block_on(LocalFsBlob::new(SLOT).put(
Connected::new(&store, ()),
&Thumbnail {
key: ThumbKey::new(&"a".repeat(MAX_SEGMENT_LEN + 1), 1),
bytes: vec![7],
},
))
.expect_err("refused");
assert!(matches!(err, LocalFsBlobError::SegmentTooLong(_)));
assert!(!dir.path().join(SLOT).exists());
}
#[test]
fn every_non_text_member_renders_verbatim() {
let uuid = uuid::Uuid::parse_str("67E55044-10B1-426F-9247-BB680E5FE0C8").expect("a uuid");
let mut segments = Segments::new();
segments.push(&7i64);
segments.push(&-7i64);
segments.push(&u64::MAX);
segments.push(&core::num::NonZeroU64::new(9).expect("nonzero"));
segments.push(&uuid);
segments.push(&[0xde_u8, 0xad, 0xbe, 0xef]);
assert_eq!(
segments.as_slice(),
[
"7",
"-7",
"18446744073709551615",
"9",
"67e55044-10b1-426f-9247-bb680e5fe0c8",
"deadbeef",
]
);
for rendered in segments.as_slice() {
assert!(is_verbatim(rendered), "{rendered:?} should be verbatim");
}
}
#[test]
fn a_nonzero_addresses_what_its_integer_does() {
let mut wrapped = Segments::new();
wrapped.push(&core::num::NonZeroI32::new(-42).expect("nonzero"));
let mut bare = Segments::new();
bare.push(&-42i32);
assert_eq!(wrapped.as_slice(), bare.as_slice());
}
#[test]
fn a_resolved_path_renders_to_its_address() {
let (dir, store) = open_store();
let path = locate::<Thumbnail>(&store, &ThumbKey::new("clip", 1));
assert_eq!(
blob_address(&path).expect("a utf-8 address"),
dir
.path()
.join("thumbnail/clip/1.png")
.to_str()
.expect("a utf-8 temp dir")
);
}
#[test]
fn the_filesystem_location_is_the_address_and_nothing_it_would_have_to_stat_for() {
let (dir, store) = open_store();
let handle = LocalFsBlob::new("thumbnail");
let path = locate::<Thumbnail>(&store, &ThumbKey::new("clip", 1));
let location =
AsyncLocate::<Thumbnail>::location(&handle, path).expect("the address renders to a location");
assert_eq!(
location.address(),
dir
.path()
.join("thumbnail/clip/1.png")
.to_str()
.expect("a utf-8 temp dir")
);
assert_eq!(location.content_type(), None);
assert_eq!(location.size(), None);
}
#[test]
fn locate_resolves_without_an_existence_check() {
let (dir, store) = open_store();
assert_eq!(
locate::<Thumbnail>(&store, &ThumbKey::new("never_written", 99)),
dir.path().join("thumbnail/never_written/99.png")
);
assert!(!dir.path().join("thumbnail").exists());
}