khive_storage/blob.rs
1//! Blob storage capability — content-addressed binary object CRUD.
2//!
3//! `BlobStore` is the trait family added by khive#292: bytes that do not
4//! belong inside the primary SQLite database (source PDFs, images, large
5//! opaque payloads) are stored by a dedicated backend and referenced from
6//! the graph by an opaque [`ContentRef`]. Per ADR-005's "zero
7//! implementations" constraint, this module defines the contract only — the
8//! first backend (filesystem, BLAKE3-addressed) lives in `khive-db`.
9
10use std::collections::HashSet;
11
12use async_trait::async_trait;
13use serde::{Deserialize, Serialize};
14
15use crate::capability::StorageCapability;
16use crate::error::StorageError;
17use crate::types::StorageResult;
18
19/// Number of hex characters in a BLAKE3-256 digest (32 bytes -> 64 hex chars).
20const CONTENT_REF_HEX_LEN: usize = 64;
21
22/// An opaque, content-addressed reference to a stored blob.
23///
24/// Backed by a lowercase-hex BLAKE3 digest of the blob's bytes: identical
25/// content always produces the same `ContentRef`, so storing the same bytes
26/// twice is a no-op after the first write. Callers must treat the value as
27/// opaque — the backend, not the caller, decides how a `ContentRef` maps to
28/// physical storage.
29///
30/// `Deserialize` is hand-written (below) to reject any string that is not 64
31/// lowercase hex characters — a naive derive would let an unvalidated value
32/// panic later in `shard_path`'s slicing.
33/// See `crates/khive-storage/docs/api/blob-store.md` for the full rationale.
34#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
35#[serde(transparent)]
36pub struct ContentRef(String);
37
38impl<'de> Deserialize<'de> for ContentRef {
39 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
40 where
41 D: serde::Deserializer<'de>,
42 {
43 let raw = String::deserialize(deserializer)?;
44 ContentRef::from_hex(raw).map_err(serde::de::Error::custom)
45 }
46}
47
48impl ContentRef {
49 /// Parse a `ContentRef` from a caller-supplied hex string.
50 ///
51 /// Rejects anything that is not exactly 64 lowercase hex characters.
52 /// Uppercase is rejected (not normalized) to keep one canonical string
53 /// form per digest — see `docs/api/blob-store.md`.
54 pub fn from_hex(hex: impl Into<String>) -> Result<Self, String> {
55 let hex = hex.into();
56 if hex.len() != CONTENT_REF_HEX_LEN {
57 return Err(format!(
58 "content_ref must be {CONTENT_REF_HEX_LEN} hex characters, got length {} ({hex:?})",
59 hex.len()
60 ));
61 }
62 if !hex
63 .bytes()
64 .all(|b| b.is_ascii_digit() || (b.is_ascii_lowercase() && b.is_ascii_hexdigit()))
65 {
66 return Err(format!(
67 "content_ref must be lowercase hex (0-9, a-f), got {hex:?}"
68 ));
69 }
70 Ok(Self(hex))
71 }
72
73 /// Construct a `ContentRef` directly from a BLAKE3 digest's raw bytes.
74 pub fn from_digest_bytes(digest: &[u8; 32]) -> Self {
75 Self(hex_encode(digest))
76 }
77
78 /// Borrow the underlying hex string.
79 pub fn as_str(&self) -> &str {
80 &self.0
81 }
82}
83
84impl std::fmt::Display for ContentRef {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 f.write_str(&self.0)
87 }
88}
89
90impl AsRef<str> for ContentRef {
91 fn as_ref(&self) -> &str {
92 &self.0
93 }
94}
95
96fn hex_encode(bytes: &[u8]) -> String {
97 const HEX: &[u8; 16] = b"0123456789abcdef";
98 let mut out = String::with_capacity(bytes.len() * 2);
99 for &b in bytes {
100 out.push(HEX[(b >> 4) as usize] as char);
101 out.push(HEX[(b & 0x0f) as usize] as char);
102 }
103 out
104}
105
106/// Configuration for [`BlobStore::orphan_sweep`].
107///
108/// `live_refs` is a point-in-time snapshot the caller assembles (this trait
109/// has no visibility into SQL substrates — ADR-005 constraint 4), not a live
110/// query. See [`BlobStore::orphan_sweep`] for the concurrency hazard this
111/// implies, and `crates/khive-storage/docs/api/blob-store.md` for the full
112/// rationale.
113#[derive(Clone, Debug, Default, Serialize, Deserialize)]
114pub struct BlobOrphanSweepConfig {
115 /// Content refs currently referenced by at least one live row somewhere
116 /// in the system, as of when the caller assembled this set. Anything
117 /// this backend stores that is NOT in this set is treated as orphaned
118 /// and deleted (or reported, in `dry_run` mode) — including a
119 /// `content_ref` that becomes live after this snapshot was taken.
120 pub live_refs: HashSet<ContentRef>,
121 /// When `true`, report what would be deleted without deleting anything.
122 pub dry_run: bool,
123}
124
125/// Result of a [`BlobStore::orphan_sweep`] call.
126#[derive(Clone, Debug, Default, Serialize, Deserialize)]
127pub struct BlobOrphanSweepResult {
128 /// Total objects examined in this backend.
129 pub scanned: u64,
130 /// Objects actually deleted (always 0 when `dry_run = true`).
131 pub deleted: u64,
132 /// Objects that are orphaned (would be deleted whether or not `dry_run`
133 /// is set — populated in both modes so a dry run reports the same count
134 /// a real run would delete).
135 pub would_delete: u64,
136}
137
138/// Content-addressed binary object CRUD.
139///
140/// Every method is backend-agnostic: the filesystem backend
141/// (`khive-db::stores::blob::FsBlobStore`) is the first implementation, and
142/// any future backend (object storage, a different CAS layout) implements
143/// the same operations. Per ADR-005 constraint 4, a `BlobStore` instance
144/// talks to exactly one backend.
145// `Debug` is a supertrait so boot-path tests can distinguish which concrete
146// backend was installed behind `Arc<dyn BlobStore>` via `format!("{:?}", ..)`
147// without adding a downcast/type-name method to the production surface.
148#[async_trait]
149pub trait BlobStore: Send + Sync + std::fmt::Debug + 'static {
150 /// Store `bytes`, returning the content-addressed reference under which
151 /// they are now retrievable. Storing byte-identical content more than
152 /// once returns the same `ContentRef` and does not re-write the object.
153 async fn put(&self, bytes: Vec<u8>) -> StorageResult<ContentRef>;
154
155 /// Fetch the bytes stored under `content_ref`.
156 ///
157 /// Returns `StorageError::NotFound` (capability `Blob`) if no object
158 /// exists for this reference.
159 async fn get(&self, content_ref: &ContentRef) -> StorageResult<Vec<u8>>;
160
161 /// Whether an object currently exists for `content_ref`.
162 async fn exists(&self, content_ref: &ContentRef) -> StorageResult<bool>;
163
164 /// Remove the object stored under `content_ref`.
165 ///
166 /// Returns `true` when an object was actually removed, `false` when
167 /// none existed — deleting an absent object is not an error.
168 ///
169 /// # Safety / concurrency hazard (ADR-111 §8, amended)
170 ///
171 /// Unconditional physical removal with **no coordination against any
172 /// entity that might reference `content_ref`**. Safe to call only when
173 /// the caller has independently quiesced whatever writer could attach a
174 /// new `content_ref` to an entity for the duration of the call — this
175 /// trait does not detect or prevent a race. Offline-maintenance-only.
176 /// See `crates/khive-storage/docs/api/blob-store.md`.
177 async fn delete(&self, content_ref: &ContentRef) -> StorageResult<bool>;
178
179 /// Enumerate every object this backend holds and delete (or, in
180 /// `dry_run` mode, report) those absent from `config.live_refs`.
181 /// Operator-side GC path (khive#292 deliverable 5) — admin-only, not an
182 /// MCP verb. Default returns `StorageError::Unsupported`; the filesystem
183 /// backend overrides it with a real directory walk.
184 ///
185 /// # Safety / concurrency hazard (ADR-111 §8, amended)
186 ///
187 /// `config.live_refs` is a **snapshot**; a `content_ref` that becomes
188 /// newly live between the snapshot and the sweep is deleted anyway.
189 /// **Callers MUST quiesce entity writes** for the duration of
190 /// snapshot-plus-sweep. See `crates/khive-storage/docs/api/blob-store.md`
191 /// for the race repro and the tracked transactional-sweep follow-up
192 /// (khive#924).
193 async fn orphan_sweep(
194 &self,
195 config: &BlobOrphanSweepConfig,
196 ) -> StorageResult<BlobOrphanSweepResult> {
197 let _ = config;
198 Err(StorageError::Unsupported {
199 capability: StorageCapability::Blob,
200 operation: "orphan_sweep".into(),
201 message: "this backend does not support orphan sweep".into(),
202 })
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn from_hex_accepts_valid_lowercase_digest() {
212 let hex = "a".repeat(64);
213 let cref = ContentRef::from_hex(hex.clone()).unwrap();
214 assert_eq!(cref.as_str(), hex);
215 assert_eq!(cref.to_string(), hex);
216 }
217
218 #[test]
219 fn from_hex_rejects_short_string() {
220 let err = ContentRef::from_hex("abc").unwrap_err();
221 assert!(
222 err.contains("64"),
223 "error must mention expected length: {err}"
224 );
225 }
226
227 #[test]
228 fn from_hex_rejects_long_string() {
229 let err = ContentRef::from_hex("a".repeat(65)).unwrap_err();
230 assert!(
231 err.contains("64"),
232 "error must mention expected length: {err}"
233 );
234 }
235
236 #[test]
237 fn from_hex_rejects_uppercase() {
238 let err = ContentRef::from_hex("A".repeat(64)).unwrap_err();
239 assert!(
240 err.contains("lowercase"),
241 "error must mention lowercase requirement: {err}"
242 );
243 }
244
245 #[test]
246 fn from_hex_rejects_non_hex_characters() {
247 let mut hex = "a".repeat(63);
248 hex.push('z');
249 let err = ContentRef::from_hex(hex).unwrap_err();
250 assert!(
251 err.contains("lowercase hex"),
252 "error must mention hex requirement: {err}"
253 );
254 }
255
256 #[test]
257 fn from_digest_bytes_matches_known_blake3_hash() {
258 // BLAKE3("") -> af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262
259 let hash = blake3_hash_of_empty();
260 let cref = ContentRef::from_digest_bytes(&hash);
261 assert_eq!(
262 cref.as_str(),
263 "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"
264 );
265 }
266
267 // hand-rolled BLAKE3("") vector (see docs/api/blob-store.md)
268 fn blake3_hash_of_empty() -> [u8; 32] {
269 let hex = "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";
270 let mut out = [0u8; 32];
271 for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
272 let s = std::str::from_utf8(chunk).unwrap();
273 out[i] = u8::from_str_radix(s, 16).unwrap();
274 }
275 out
276 }
277
278 #[test]
279 fn deserialize_accepts_a_valid_lowercase_digest() {
280 let hex = "d".repeat(64);
281 let json = serde_json::to_string(&hex).unwrap();
282 let cref: ContentRef = serde_json::from_str(&json).unwrap();
283 assert_eq!(cref.as_str(), hex);
284 }
285
286 #[test]
287 fn deserialize_rejects_short_string() {
288 let err = serde_json::from_str::<ContentRef>("\"x\"").unwrap_err();
289 assert!(
290 err.to_string().contains("64"),
291 "deserialize error must mention the expected length: {err}"
292 );
293 }
294
295 #[test]
296 fn deserialize_rejects_uppercase() {
297 let hex = "A".repeat(64);
298 let json = serde_json::to_string(&hex).unwrap();
299 let err = serde_json::from_str::<ContentRef>(&json).unwrap_err();
300 assert!(
301 err.to_string().contains("lowercase"),
302 "deserialize error must mention the lowercase requirement: {err}"
303 );
304 }
305
306 #[test]
307 fn deserialize_rejects_non_hex_characters() {
308 let mut hex = "a".repeat(63);
309 hex.push('z');
310 let json = serde_json::to_string(&hex).unwrap();
311 let err = serde_json::from_str::<ContentRef>(&json).unwrap_err();
312 assert!(
313 err.to_string().contains("lowercase hex"),
314 "deserialize error must mention the hex requirement: {err}"
315 );
316 }
317
318 #[test]
319 fn content_ref_equality_and_hash_are_string_based() {
320 let a = ContentRef::from_hex("b".repeat(64)).unwrap();
321 let b = ContentRef::from_hex("b".repeat(64)).unwrap();
322 let c = ContentRef::from_hex("c".repeat(64)).unwrap();
323 assert_eq!(a, b);
324 assert_ne!(a, c);
325
326 use std::collections::HashSet;
327 let mut set = HashSet::new();
328 set.insert(a.clone());
329 assert!(set.contains(&b));
330 assert!(!set.contains(&c));
331 }
332}