1pub mod packfile;
18
19use crate::addressing::{Hash, PartitionId};
20use crate::error::{Result, StorageError};
21use crate::partition::{self, EncryptionMode, PartitionRecord, PartitionSpec, RetentionClass};
22use packfile::PackWriter;
23use std::collections::HashMap;
24use std::fs;
25use std::path::{Path, PathBuf};
26
27pub const SEAL_CAP_BYTES: u64 = 128 * 1024 * 1024;
29
30pub fn list_partitions(store_root: &Path) -> Result<Vec<PartitionId>> {
39 if !store_root.exists() {
40 return Ok(Vec::new());
41 }
42 let mut out = Vec::new();
43 for entry in fs::read_dir(store_root)? {
44 let entry = entry?;
45 if !entry.file_type()?.is_dir() {
46 continue;
47 }
48 let name = entry.file_name();
49 let Some(name) = name.to_str() else { continue };
50 if name.len() == 32 && name.chars().all(|c| c.is_ascii_hexdigit()) {
51 let partition_id = PartitionId::from_hex(name)?;
52 if partition::is_provisioned(store_root, partition_id) {
53 out.push(partition_id);
54 }
55 }
56 }
57 out.sort_by_key(|p| p.to_hex());
58 Ok(out)
59}
60
61pub trait ImmutableStore {
72 fn get(&self, hash: &Hash) -> Result<Vec<u8>>;
74 fn has(&self, hash: &Hash) -> bool;
75 fn put(&mut self, data: &[u8]) -> Result<Hash>;
79 fn partition_id(&self) -> PartitionId;
80}
81
82pub trait MutableStore {
90 fn load(&self, key: &str) -> Result<Vec<u8>>;
91 fn store(&mut self, key: &str, data: &[u8]) -> Result<()>;
92 fn cas(&mut self, key: &str, expected: Option<&[u8]>, new: &[u8]) -> Result<bool>;
96 fn list(&self, prefix: &str) -> Result<Vec<String>>;
97}
98
99struct SealedPack {
100 pack_id: Hash,
101 path: PathBuf,
102 offsets: HashMap<Hash, (u64, packfile::EntryMeta)>,
107}
108
109pub struct PartitionStore {
112 root: PathBuf,
113 partition_id: PartitionId,
114 record: PartitionRecord,
115 active: PackWriter,
116 sealed: Vec<SealedPack>,
117 sealed_lookup: HashMap<Hash, usize>,
119}
120
121impl PartitionStore {
122 pub fn create(
138 store_root: &Path,
139 partition_id: PartitionId,
140 spec: PartitionSpec,
141 ) -> Result<Self> {
142 partition::verify_derivation(partition_id, &spec.subject)?;
143
144 if partition::is_provisioned(store_root, partition_id) {
145 return Err(StorageError::PartitionAlreadyProvisioned(
146 partition_id.to_hex(),
147 ));
148 }
149
150 let root = store_root.join(partition_id.to_hex());
151 fs::create_dir_all(&root)?;
152
153 let record =
154 partition::new_record(partition_id, spec.retention_class, spec.encryption_mode);
155 partition::write_new_record(store_root, partition_id, &record)?;
156 partition::bind_local(store_root, partition_id, &spec.subject, &spec.label)?;
157
158 Self::open_provisioned(store_root, partition_id, record)
159 }
160
161 pub fn open(store_root: &Path, partition_id: PartitionId) -> Result<Self> {
174 if !partition::is_provisioned(store_root, partition_id) {
175 return Err(StorageError::PartitionNotProvisioned(partition_id.to_hex()));
176 }
177 let record = partition::load_record(store_root, partition_id)?;
178 Self::open_provisioned(store_root, partition_id, record)
179 }
180
181 fn open_provisioned(
186 store_root: &Path,
187 partition_id: PartitionId,
188 record: PartitionRecord,
189 ) -> Result<Self> {
190 let root = store_root.join(partition_id.to_hex());
191 let packs_dir = root.join("packs");
192 let active_path = root.join("active").join("active.pack");
193 fs::create_dir_all(&packs_dir)?;
194
195 let active = PackWriter::open_active(&active_path, partition_id)?;
196
197 let mut sealed = Vec::new();
198 let mut sealed_lookup = HashMap::new();
199 if packs_dir.exists() {
200 for shard_entry in fs::read_dir(&packs_dir)? {
201 let shard_entry = shard_entry?;
202 if !shard_entry.file_type()?.is_dir() {
203 continue;
204 }
205 for pack_entry in fs::read_dir(shard_entry.path())? {
206 let pack_entry = pack_entry?;
207 let path = pack_entry.path();
208 if path.extension().and_then(|e| e.to_str()) != Some("pack") {
209 continue;
210 }
211 let pack_id_hex = path
212 .file_stem()
213 .and_then(|s| s.to_str())
214 .ok_or_else(|| StorageError::CorruptPack("bad pack filename".into()))?
215 .to_string();
216 let pack_id = Hash::from_hex(&pack_id_hex)?;
217
218 let idx_path = path.with_extension("idx");
219 let offsets = match packfile::read_index(&idx_path) {
220 Ok(idx) => idx,
221 Err(_) => {
222 let entries = packfile::rebuild_index_entries(&path)?;
224 packfile::write_index(&idx_path, &partition_id, &entries)?;
225 entries
226 .into_iter()
227 .map(|(off, m)| (m.hash, (off, m)))
228 .collect()
229 }
230 };
231
232 let idx = sealed.len();
233 for hash in offsets.keys() {
234 sealed_lookup.insert(*hash, idx);
235 }
236 sealed.push(SealedPack {
237 pack_id,
238 path,
239 offsets,
240 });
241 }
242 }
243 }
244
245 Ok(PartitionStore {
246 root,
247 partition_id,
248 record,
249 active,
250 sealed,
251 sealed_lookup,
252 })
253 }
254
255 pub fn partition_root(&self) -> &Path {
256 &self.root
257 }
258
259 pub fn record(&self) -> &PartitionRecord {
264 &self.record
265 }
266
267 pub fn retention_class(&self) -> RetentionClass {
272 self.record.retention_class
273 }
274
275 pub fn encryption_mode(&self) -> EncryptionMode {
281 self.record.encryption_mode
282 }
283
284 pub fn packs_dir(&self) -> PathBuf {
285 self.root.join("packs")
286 }
287
288 pub fn manifests_dir(&self) -> PathBuf {
289 self.root.join("manifests")
290 }
291
292 pub fn write_manifest(&self, name: &str, manifest_json: &str) -> Result<PathBuf> {
295 let dir = self.manifests_dir();
296 fs::create_dir_all(&dir)?;
297 let path = dir.join(format!("{name}.json"));
298 fs::write(&path, manifest_json)?;
299 Ok(path)
300 }
301
302 pub fn list_manifests(&self) -> Result<Vec<PathBuf>> {
303 let dir = self.manifests_dir();
304 if !dir.exists() {
305 return Ok(Vec::new());
306 }
307 let mut out = Vec::new();
308 for entry in fs::read_dir(dir)? {
309 let entry = entry?;
310 if entry.path().extension().and_then(|e| e.to_str()) == Some("json") {
311 out.push(entry.path());
312 }
313 }
314 out.sort();
315 Ok(out)
316 }
317
318 pub fn all_hashes(&self) -> Vec<Hash> {
321 let mut out: Vec<Hash> = self.active.offsets.keys().copied().collect();
322 for pack in &self.sealed {
323 out.extend(pack.offsets.keys().copied());
324 }
325 out
326 }
327
328 pub fn sealed_pack_ids(&self) -> Vec<Hash> {
329 self.sealed.iter().map(|p| p.pack_id).collect()
330 }
331
332 pub fn active_entry_count(&self) -> u64 {
335 self.active.entry_count
336 }
337
338 pub fn verify_all(&self) -> Result<u64> {
342 let mut checked = 0u64;
343 for pack in &self.sealed {
344 packfile::verify_trailer(&pack.path)?;
345 for (offset, _meta) in pack.offsets.values() {
346 packfile::get_at(&pack.path, *offset)?;
347 checked += 1;
348 }
349 }
350 for hash in self.active.offsets.keys() {
352 self.get(hash)?;
353 checked += 1;
354 }
355 Ok(checked)
356 }
357
358 fn seal_active_if_over_cap(&mut self) -> Result<()> {
359 if self.active.len < SEAL_CAP_BYTES {
360 return Ok(());
361 }
362 let fresh_active_path = self.root.join("active").join("active.pack");
363 let old = std::mem::replace(
364 &mut self.active,
365 PackWriter::open_active(
368 &fresh_active_path.with_extension("pack.next"),
369 self.partition_id,
370 )?,
371 );
372 let (pack_id, path) = old.seal(&self.packs_dir())?;
373 let offsets = packfile::read_index(&path.with_extension("idx"))?;
374 let idx = self.sealed.len();
375 for hash in offsets.keys() {
376 self.sealed_lookup.insert(*hash, idx);
377 }
378 self.sealed.push(SealedPack {
379 pack_id,
380 path,
381 offsets,
382 });
383 let _ = fs::remove_file(fresh_active_path.with_extension("pack.next"));
385 self.active = PackWriter::open_active(&fresh_active_path, self.partition_id)?;
386 Ok(())
387 }
388
389 pub fn seal_active(&mut self) -> Result<Option<Hash>> {
394 if self.active.entry_count == 0 {
395 return Ok(None);
396 }
397 let fresh_active_path = self.root.join("active").join("active.pack");
398 let old = std::mem::replace(
399 &mut self.active,
400 PackWriter::open_active(
401 &fresh_active_path.with_extension("pack.sealing"),
402 self.partition_id,
403 )?,
404 );
405 let (pack_id, path) = old.seal(&self.packs_dir())?;
406 let offsets = packfile::read_index(&path.with_extension("idx"))?;
407 let idx = self.sealed.len();
408 for hash in offsets.keys() {
409 self.sealed_lookup.insert(*hash, idx);
410 }
411 self.sealed.push(SealedPack {
412 pack_id,
413 path,
414 offsets,
415 });
416 let _ = fs::remove_file(fresh_active_path.with_extension("pack.sealing"));
417 self.active = PackWriter::open_active(&fresh_active_path, self.partition_id)?;
418 Ok(Some(pack_id))
419 }
420}
421
422impl PartitionStore {
423 pub fn get_raw(&self, hash: &Hash) -> Result<(packfile::EntryMeta, Vec<u8>)> {
431 if let Some(offset) = self.active.offsets.get(hash) {
432 return self.active.read_payload_at(*offset);
433 }
434 if let Some(&idx) = self.sealed_lookup.get(hash) {
435 let pack = &self.sealed[idx];
436 let (offset, _meta) = *pack.offsets.get(hash).ok_or_else(|| {
437 StorageError::NotFound(format!("{hash} indexed but missing in pack"))
438 })?;
439 return packfile::get_raw_at(&pack.path, offset);
440 }
441 Err(StorageError::NotFound(hash.to_hex()))
442 }
443
444 pub fn put_raw(&mut self, meta: packfile::EntryMeta, payload: &[u8]) -> Result<Hash> {
453 if self.has(&meta.hash) {
454 return Ok(meta.hash); }
456 self.active.append_raw(&meta, payload)?;
457 self.seal_active_if_over_cap()?;
458 Ok(meta.hash)
459 }
460}
461
462impl ImmutableStore for PartitionStore {
463 fn get(&self, hash: &Hash) -> Result<Vec<u8>> {
464 if let Some(offset) = self.active.offsets.get(hash) {
465 let (meta, payload) = self.active.read_payload_at(*offset)?;
466 meta.validate_reserved()?;
467 let decoded = packfile::decode(meta.codec, &payload)?;
468 let actual = Hash::of(&decoded);
469 if actual != *hash {
470 return Err(StorageError::HashMismatch {
471 expected: hash.to_hex(),
472 actual: actual.to_hex(),
473 });
474 }
475 return Ok(decoded);
476 }
477 if let Some(&idx) = self.sealed_lookup.get(hash) {
478 let pack = &self.sealed[idx];
479 let (offset, _meta) = *pack.offsets.get(hash).ok_or_else(|| {
480 StorageError::NotFound(format!("{hash} indexed but missing in pack"))
481 })?;
482 return packfile::get_at(&pack.path, offset);
483 }
484 Err(StorageError::NotFound(hash.to_hex()))
485 }
486
487 fn has(&self, hash: &Hash) -> bool {
488 self.active.offsets.contains_key(hash) || self.sealed_lookup.contains_key(hash)
489 }
490
491 fn put(&mut self, data: &[u8]) -> Result<Hash> {
492 let hash = Hash::of(data);
493 if self.has(&hash) {
494 return Ok(hash); }
496 let (codec, payload) = packfile::encode(data)?;
497 self.active
498 .append(hash, codec, data.len() as u64, &payload)?;
499 self.seal_active_if_over_cap()?;
500 Ok(hash)
501 }
502
503 fn partition_id(&self) -> PartitionId {
504 self.partition_id
505 }
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511 use crate::partition::{Subject, SubjectKind};
512 use tempfile::tempdir;
513
514 fn create_person(dir: &Path, name: &str, retention_class: RetentionClass) -> PartitionStore {
518 let partition_id = PartitionId::for_person(name);
519 let spec = PartitionSpec {
520 subject: Subject {
521 kind: SubjectKind::Person,
522 id: name.to_string(),
523 },
524 retention_class,
525 encryption_mode: EncryptionMode::Plaintext,
526 label: None,
527 };
528 PartitionStore::create(dir, partition_id, spec).unwrap()
529 }
530
531 #[test]
532 fn put_dedups_within_partition() {
533 let dir = tempdir().unwrap();
534 let mut store = create_person(dir.path(), "dedup-test", RetentionClass::Standard);
535
536 let h1 = store.put(b"same bytes").unwrap();
537 let h2 = store.put(b"same bytes").unwrap();
538 assert_eq!(h1, h2);
539 assert_eq!(
540 store.active.entry_count, 1,
541 "second put must be a dedup no-op"
542 );
543 }
544
545 #[test]
546 fn put_then_get_roundtrips() {
547 let dir = tempdir().unwrap();
548 let mut store = create_person(dir.path(), "roundtrip-test", RetentionClass::Standard);
549 let hash = store.put(b"round trip me").unwrap();
550 let back = store.get(&hash).unwrap();
551 assert_eq!(back, b"round trip me");
552 }
553
554 #[test]
555 fn seal_then_reopen_still_reads() {
556 let dir = tempdir().unwrap();
557 let partition_id = PartitionId::for_person("seal-reopen-test");
558 let hash;
559 {
560 let mut store = create_person(dir.path(), "seal-reopen-test", RetentionClass::Standard);
561 hash = store.put(b"persist across reopen").unwrap();
562 store.seal_active().unwrap();
563 }
564 let store2 = PartitionStore::open(dir.path(), partition_id).unwrap();
565 let back = store2.get(&hash).unwrap();
566 assert_eq!(back, b"persist across reopen");
567 }
568
569 #[test]
570 fn partitions_are_isolated_directories() {
571 let dir = tempdir().unwrap();
572 let mut store_a = create_person(dir.path(), "partition-a", RetentionClass::Standard);
573 let mut store_b = create_person(dir.path(), "partition-b", RetentionClass::Standard);
574
575 let hash_a = store_a.put(b"only in a").unwrap();
576 let _hash_b = store_b.put(b"only in b").unwrap();
577
578 assert!(store_a.has(&hash_a));
579 assert!(!store_b.has(&hash_a));
580 assert_ne!(store_a.partition_root(), store_b.partition_root());
581 }
582
583 #[test]
584 fn open_on_an_unprovisioned_partition_fails() {
585 let dir = tempdir().unwrap();
586 let partition_id = PartitionId::for_person("never-created");
587 let err = match PartitionStore::open(dir.path(), partition_id) {
588 Err(e) => e,
589 Ok(_) => panic!("open() must not create a partition on first use"),
590 };
591 assert!(matches!(err, StorageError::PartitionNotProvisioned(_)));
592 }
593
594 #[test]
595 fn open_creates_no_directory() {
596 let dir = tempdir().unwrap();
597 let partition_id = PartitionId::for_person("open-creates-nothing");
598 let _ = PartitionStore::open(dir.path(), partition_id);
599 assert!(
600 !dir.path().join(partition_id.to_hex()).exists(),
601 "open() on an unprovisioned partition must create no directory"
602 );
603 }
604
605 #[test]
606 fn create_twice_fails_already_provisioned() {
607 let dir = tempdir().unwrap();
608 let partition_id = PartitionId::for_person("double-create");
609 let spec = || PartitionSpec {
610 subject: Subject {
611 kind: SubjectKind::Person,
612 id: "double-create".to_string(),
613 },
614 retention_class: RetentionClass::Standard,
615 encryption_mode: EncryptionMode::Plaintext,
616 label: None,
617 };
618 PartitionStore::create(dir.path(), partition_id, spec()).unwrap();
619 let err = match PartitionStore::create(dir.path(), partition_id, spec()) {
620 Err(e) => e,
621 Ok(_) => panic!("re-provisioning the same partition must fail"),
622 };
623 assert!(matches!(err, StorageError::PartitionAlreadyProvisioned(_)));
624 }
625
626 #[test]
627 fn create_rejects_a_subject_that_does_not_derive_the_partition_id() {
628 let dir = tempdir().unwrap();
629 let partition_id = PartitionId::for_person("someone-else");
631 let spec = PartitionSpec {
632 subject: Subject {
633 kind: SubjectKind::Person,
634 id: "not-someone-else".to_string(),
635 },
636 retention_class: RetentionClass::Standard,
637 encryption_mode: EncryptionMode::Plaintext,
638 label: None,
639 };
640 let err = match PartitionStore::create(dir.path(), partition_id, spec) {
641 Err(e) => e,
642 Ok(_) => panic!(
643 "a partition must not be provisionable under a subject it wasn't derived from"
644 ),
645 };
646 assert!(matches!(err, StorageError::PartitionBoundary(_)));
647 }
648
649 #[test]
650 fn list_partitions_only_reports_provisioned_partitions() {
651 let dir = tempdir().unwrap();
652 let provisioned = create_person(dir.path(), "listed", RetentionClass::Standard);
653 let provisioned_id = provisioned.partition_id();
654
655 let orphan_id = PartitionId::for_person("orphan");
657 fs::create_dir_all(dir.path().join(orphan_id.to_hex())).unwrap();
658
659 let listed = list_partitions(dir.path()).unwrap();
660 assert!(listed.contains(&provisioned_id));
661 assert!(
662 !listed.contains(&orphan_id),
663 "a directory with no partition.json must not be reported as a partition"
664 );
665 }
666
667 #[test]
668 fn retention_class_is_visible_and_matches_what_was_provisioned() {
669 let dir = tempdir().unwrap();
670 let store = create_person(dir.path(), "durable-check", RetentionClass::Durable);
671 assert_eq!(store.retention_class(), RetentionClass::Durable);
672 }
673
674 #[test]
675 fn encryption_mode_is_visible_and_matches_what_was_provisioned() {
676 let dir = tempdir().unwrap();
677 let partition_id = PartitionId::for_person("sealed-required-check");
678 let spec = PartitionSpec {
679 subject: Subject {
680 kind: SubjectKind::Person,
681 id: "sealed-required-check".to_string(),
682 },
683 retention_class: RetentionClass::Standard,
684 encryption_mode: EncryptionMode::SealedRequired,
685 label: None,
686 };
687 let store = PartitionStore::create(dir.path(), partition_id, spec).unwrap();
688 assert_eq!(store.encryption_mode(), EncryptionMode::SealedRequired);
689
690 let reopened = PartitionStore::open(dir.path(), partition_id).unwrap();
692 assert_eq!(reopened.encryption_mode(), EncryptionMode::SealedRequired);
693 }
694
695 #[test]
696 fn encryption_mode_defaults_to_plaintext_for_current_callers() {
697 let dir = tempdir().unwrap();
701 let store = create_person(dir.path(), "plaintext-check", RetentionClass::Standard);
702 assert_eq!(store.encryption_mode(), EncryptionMode::Plaintext);
703 }
704}