1use std::path::{Path, PathBuf};
7use std::sync::Arc;
8#[cfg(test)]
9use std::sync::{Mutex, MutexGuard};
10
11#[cfg(test)]
12use crate::backend::local::LocalConn;
13
14use uuid::Uuid;
15use vcon::read::Inspection;
16
17use crate::audit::{self, Action, Actor, Entry};
18use crate::backend::local::{Durability, LocalCatalog, LocalObjects};
19use crate::backend::{
20 Catalog, CatalogTx, CommitError, NewVersion, ObjectError, Objects, Packed, Packs,
21};
22use crate::catalog;
23use crate::clock::{Clock, nanos};
24use crate::envelope::{self, Context, Key, WrapLimit};
25use crate::fs::Fs;
26use crate::ids::{KeyId, TenantId, VersionId};
27use crate::retention::Retention;
28use crate::reveal::Part;
29use pending::Writers;
30
31mod backup;
32#[cfg(test)]
33mod clock_reading_tests;
34mod compact;
35mod examine;
36mod export;
37mod group;
38#[cfg(test)]
39mod group_tests;
40mod legal;
41mod list;
42pub(crate) mod manifest;
43#[cfg(test)]
44mod manifest_grace_tests;
45#[cfg(test)]
46mod pack_pending_tests;
47pub(crate) mod packed;
48pub(crate) mod packer;
49pub(crate) mod pending;
50mod purge;
51#[cfg(test)]
52mod read_race_tests;
53mod rekey;
54mod rewrite;
55#[cfg(test)]
56mod statement_tests;
57#[cfg(test)]
58mod sync_tests;
59
60pub use backup::{BackupError, Copied, TRIES};
61pub use examine::{Examination, ExamineError};
62pub use export::KeptVersion;
63pub use legal::{Legal, VersionInfo};
64pub use list::{Cursor, ListQuery, Listed, Listing};
65pub use purge::{Kept, PurgeReport, due};
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub struct Caller {
70 pub key: KeyId,
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Created {
76 New(VersionId),
78 Same(VersionId),
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct Stored {
85 pub version: VersionId,
86 pub form: vcon::Form,
87 pub gzip: bool,
89 pub body: Vec<u8>,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct Counts {
96 pub versions: u64,
98 pub held: u64,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum StoreError {
105 Conflict,
106 Gone,
107 NotFound,
108 NotDeleted,
109 PreconditionFailed,
110 Immutable,
111 LimitReached,
113 Damaged,
115 AuditFailed,
117 Io,
118}
119
120#[derive(Debug)]
123pub enum OpenError {
124 WrongKey,
126 Access {
129 path: PathBuf,
130 error: std::io::Error,
131 },
132 Store(StoreError),
134}
135
136impl From<OpenError> for StoreError {
137 fn from(_: OpenError) -> StoreError {
139 StoreError::Io
140 }
141}
142
143impl From<StoreError> for OpenError {
144 fn from(e: StoreError) -> OpenError {
145 OpenError::Store(e)
146 }
147}
148
149impl From<catalog::CatalogError> for OpenError {
150 fn from(e: catalog::CatalogError) -> OpenError {
151 match e {
152 catalog::CatalogError::WrongKey => OpenError::WrongKey,
153 catalog::CatalogError::Access { path, error } => OpenError::Access { path, error },
154 _ => OpenError::Store(StoreError::Io),
155 }
156 }
157}
158
159type Tx<'a> = Box<dyn CatalogTx + 'a>;
161
162pub struct Store {
164 tenant: TenantId,
165 tenant_key: Key,
166 catalog: Box<dyn Catalog>,
167 objects: Arc<dyn Objects>,
168 packs: Option<Arc<dyn Packs>>,
171 footers: packed::Footers,
173 fs: Arc<dyn Fs>,
175 clock: Arc<dyn Clock>,
176 group: group::Group,
178 #[cfg(test)]
180 objects_dir: PathBuf,
181 #[cfg(test)]
182 hooks: tests::Hooks,
183}
184
185impl Store {
186 pub fn open(
189 dir: &Path,
190 tenant: TenantId,
191 tenant_key: Key,
192 fs: Arc<dyn Fs>,
193 clock: Arc<dyn Clock>,
194 ) -> Result<Store, OpenError> {
195 let store = Store::open_as(dir, tenant, tenant_key, fs, clock, Durability::Group)?;
198 store.recover(Writers::None)?;
199 Ok(store)
200 }
201
202 pub fn open_beside(
206 dir: &Path,
207 tenant: TenantId,
208 tenant_key: Key,
209 fs: Arc<dyn Fs>,
210 clock: Arc<dyn Clock>,
211 ) -> Result<Store, OpenError> {
212 Store::open_as(dir, tenant, tenant_key, fs, clock, Durability::Beside)
213 }
214
215 pub(crate) fn open_as(
218 dir: &Path,
219 tenant: TenantId,
220 tenant_key: Key,
221 fs: Arc<dyn Fs>,
222 clock: Arc<dyn Clock>,
223 durability: Durability,
224 ) -> Result<Store, OpenError> {
225 let catalog_key = envelope::catalog_key(&tenant_key).map_err(|_| StoreError::Io)?;
226 let catalog =
227 LocalCatalog::open(&dir.join("catalog.sqlite"), catalog_key, &*fs, durability)?;
228 let objects = dir.join("objects");
229 fs.create_dir_all(&objects).map_err(|_| StoreError::Io)?;
230 catalog::may_use(&objects, libc::W_OK | libc::X_OK)?;
232 fs.sync_dir(dir).map_err(|_| StoreError::Io)?;
236 #[cfg_attr(
237 not(test),
238 allow(unused_mut, reason = "only tests set the objects directory after")
239 )]
240 let mut store = Store::with_backends(
241 tenant,
242 tenant_key,
243 Box::new(catalog),
244 Arc::new(LocalObjects::new(objects.clone(), fs.clone())),
245 None,
246 fs,
247 clock,
248 );
249 #[cfg(test)]
250 {
251 store.objects_dir = objects;
252 }
253 Ok(store)
254 }
255
256 #[cfg(feature = "s3")]
259 #[expect(
260 clippy::too_many_arguments,
261 reason = "each backend is its own argument"
262 )]
263 pub(crate) fn open_on(
264 tenant: TenantId,
265 tenant_key: Key,
266 catalog: Box<dyn Catalog>,
267 objects: Arc<dyn Objects>,
268 packs: Option<Arc<dyn Packs>>,
269 fs: Arc<dyn Fs>,
270 clock: Arc<dyn Clock>,
271 recover: Option<Writers>,
272 ) -> Result<Store, OpenError> {
273 let store = Store::with_backends(tenant, tenant_key, catalog, objects, packs, fs, clock);
274 if let Some(writers) = recover {
275 store.recover(writers)?;
279 }
280 Ok(store)
281 }
282
283 pub(crate) fn with_backends(
286 tenant: TenantId,
287 tenant_key: Key,
288 catalog: Box<dyn Catalog>,
289 objects: Arc<dyn Objects>,
290 packs: Option<Arc<dyn Packs>>,
291 fs: Arc<dyn Fs>,
292 clock: Arc<dyn Clock>,
293 ) -> Store {
294 Store {
295 tenant,
296 tenant_key,
297 catalog,
298 objects,
299 packs,
300 footers: packed::Footers::new(packed::FOOTERS),
301 fs,
302 clock,
303 group: group::Group::default(),
304 #[cfg(test)]
305 objects_dir: PathBuf::new(),
306 #[cfg(test)]
307 hooks: tests::Hooks::default(),
308 }
309 }
310
311 fn catalog_now(&self, tx: &mut dyn CatalogTx, host: i64) -> Result<i64, StoreError> {
314 let now = tx.clock_now(host)?;
315 #[cfg(test)]
316 let now = {
317 let mut steps = self.hooks.clock_steps.lock().expect("hook");
318 if steps.is_empty() {
319 now
320 } else {
321 now + steps.remove(0)
322 }
323 };
324 Ok(now)
325 }
326
327 pub(crate) fn now_in(&self, tx: &mut dyn CatalogTx) -> Result<i64, StoreError> {
332 self.catalog_now(tx, nanos(self.clock.now()))
333 }
334
335 pub(crate) fn recover(&self, writers: Writers) -> Result<(), StoreError> {
348 self.catalog.recover()?;
349 let host = nanos(self.clock.now());
350 let now = {
351 let mut tx = self.catalog.immediate()?;
352 let now = self.catalog_now(tx.as_mut(), host)?;
353 for (version, started_at) in tx.pending()? {
354 if !pending::under_way(writers, started_at, now) {
355 tx.drop_pending(version)?;
356 }
357 }
358 for (file, started_at) in tx.pending_files()? {
359 if !pending::under_way(writers, started_at, now) {
360 tx.drop_pending_file(file)?;
361 }
362 }
363 commit(tx)?;
364 now
365 };
366 let names = self.objects.list().map_err(io)?;
367 let pack_names = match &self.packs {
368 Some(packs) => packs.list().map_err(io)?,
369 None => Vec::new(),
370 };
371 let (places, files, writing, putting) = self.read(|tx| {
373 let places: std::collections::HashMap<VersionId, bool> = tx
374 .places()?
375 .into_iter()
376 .map(|(version, place)| (version, names_its_object(&place)))
377 .collect();
378 let files: std::collections::HashSet<_> = tx.pack_files()?.into_iter().collect();
379 let writing: std::collections::HashSet<VersionId> = tx
380 .pending()?
381 .into_iter()
382 .filter(|(_, started_at)| pending::under_way(writers, *started_at, now))
383 .map(|(version, _)| version)
384 .collect();
385 let putting: std::collections::HashSet<crate::ids::FileId> = tx
386 .pending_files()?
387 .into_iter()
388 .filter(|(_, started_at)| pending::under_way(writers, *started_at, now))
389 .map(|(file, _)| file)
390 .collect();
391 Ok((places, files, writing, putting))
392 })?;
393 #[cfg(test)]
394 {
395 let hook = self.hooks.after_snapshot.lock().expect("hook").take();
396 if let Some(hook) = hook {
397 hook(self);
398 }
399 }
400 let mut removed: u64 = 0;
401 for name in names {
402 let (id, temporary) = match name.strip_suffix(".tmp") {
403 Some(id) => (id, true),
404 None => (name.as_str(), false),
405 };
406 let Some(version) = VersionId::parse(id) else {
407 continue;
408 };
409 let named = places.get(&version).copied().unwrap_or(false);
410 if pending::leftover(named, temporary, writing.contains(&version)) {
411 self.objects.remove_name(&name).map_err(io)?;
412 removed += 1;
413 }
414 }
415 if let Some(packs) = &self.packs {
416 let mut unnamed: u64 = 0;
417 for name in pack_names {
420 let Some((_, file)) = packed::parse_name(&name) else {
421 continue;
422 };
423 if pending::leftover(files.contains(&file), false, putting.contains(&file)) {
424 packs.remove(&name).map_err(io)?;
425 unnamed += 1;
426 }
427 }
428 if unnamed > 0 {
429 tracing::info!(
430 removed = unnamed,
431 "start-up recovery removed pack files that no catalog row names"
432 );
433 }
434 }
435 self.finish_purges()?;
436 self.publish()?;
437 if removed > 0 {
438 self.objects.sync().map_err(io)?;
439 tracing::info!(
442 removed,
443 "start-up recovery removed objects that no catalog row names"
444 );
445 }
446 Ok(())
447 }
448
449 pub fn create(
454 &self,
455 who: &Caller,
456 found: &Inspection,
457 body: &[u8],
458 ) -> Result<Created, StoreError> {
459 let uuid = found.uuid;
460 let entry = |status, version| Entry {
461 actor: Actor::Key(who.key),
462 action: Action::Create,
463 target: Some(uuid.to_string()),
464 version,
465 status,
466 };
467 let key_id = self.tenant_key.id();
468 let version = VersionId::generate();
469 {
470 let mut tx = self.catalog.immediate()?;
471 let refused = match state(&mut tx, uuid)? {
472 State::Gone => Some((410, None, StoreError::Gone)),
473 State::Live(current) => match self.read_version(&mut tx, uuid, current) {
474 Ok(stored) if stored == body => {
475 self.record(&mut tx, &entry(200, Some(current)))?;
476 commit(tx)?;
477 return Ok(Created::Same(current));
478 }
479 Ok(_) => Some((409, None, StoreError::Conflict)),
480 Err(StoreError::Damaged) => Some((500, Some(current), StoreError::Damaged)),
481 Err(e) => return Err(e),
482 },
483 State::Absent if envelope::wrap_limit(tx.wraps(key_id)?) == WrapLimit::Refuse => {
484 Some((503, None, StoreError::LimitReached))
485 }
486 State::Absent => {
491 tx.add_wrap(key_id)?;
492 tx.add_pending(version, nanos(self.clock.now()))?;
493 None
494 }
495 };
496 if let Some((status, version, error)) = refused {
497 self.record(&mut tx, &entry(status, version))?;
498 commit(tx)?;
499 return Err(error);
500 }
501 commit(tx)?;
502 }
503
504 let wrapped = self.write_version(uuid, version, body)?;
505 self.pause();
506
507 let unknown = std::cell::Cell::new(false);
508 let committed = (|| {
509 let mut tx = self.catalog.immediate()?;
510 let mine = tx.drop_pending(version)?;
511 match state(&mut tx, uuid)? {
512 State::Absent => {}
513 lost => {
514 let (status, error) = match lost {
515 State::Gone => (410, StoreError::Gone),
516 _ => (409, StoreError::Conflict),
517 };
518 self.record(&mut tx, &entry(status, None))?;
519 commit(tx)?;
520 return Err(error);
521 }
522 }
523 if !mine {
524 self.record(&mut tx, &entry(500, None))?;
527 commit(tx)?;
528 return Err(StoreError::Io);
529 }
530 let stored_at = self.now_in(tx.as_mut())?;
533 tx.insert_version(&NewVersion {
534 version,
535 uuid,
536 form: form_name(found.form),
537 gzip: found.gzip,
538 size: i64::try_from(body.len()).map_err(io)?,
539 stored_at,
540 key: key_id,
541 wrapped: &wrapped,
542 })?;
543 tx.insert_vcon(uuid, version, stored_at)?;
544 self.record(&mut tx, &entry(201, Some(version)))?;
545 kept(tx.commit(), &unknown)?;
546 Ok(Created::New(version))
547 })();
548 self.drop_unless_kept(committed.is_err(), unknown.get(), version);
549 #[cfg(test)]
550 if committed.is_ok() {
551 self.forced_pack();
552 }
553 committed
554 }
555
556 pub fn get(&self, who: &Caller, uuid: Uuid) -> Result<Stored, StoreError> {
561 self.read_as(who, uuid, Action::Read)
562 }
563
564 pub fn reveal(&self, who: &Caller, uuid: Uuid, part: Part) -> Result<Stored, StoreError> {
568 self.read_as(who, uuid, Action::Reveal(part))
569 }
570
571 pub fn read_masked(&self, who: &Caller, uuid: Uuid) -> Result<Stored, StoreError> {
575 self.read_as(who, uuid, Action::ReadMasked)
576 }
577
578 fn read_as(&self, who: &Caller, uuid: Uuid, action: Action) -> Result<Stored, StoreError> {
581 loop {
582 let found = self.read(|tx| {
586 Ok(match state(tx, uuid)? {
587 State::Live(version) => {
588 #[cfg(test)]
589 {
590 let hook = self.hooks.in_first_step.lock().expect("hook").clone();
591 if let Some(hook) = hook {
592 hook();
593 }
594 }
595 Some((version, version_row(tx, version)))
596 }
597 State::Gone | State::Absent => None,
598 })
599 })?;
600 let (version, opened, place) = match found {
601 Some((version, row)) => {
602 let place = row.as_ref().ok().and_then(|r| r.place.clone());
603 #[cfg(test)]
604 {
605 let hook = self.hooks.before_read.lock().expect("hook").take();
606 if let Some(hook) = hook {
607 hook();
608 }
609 }
610 let opened = row.and_then(|row| {
611 let body = self.open_version(uuid, version, &row)?;
612 Ok(Stored {
613 version,
614 form: row.form,
615 gzip: row.gzip,
616 body,
617 })
618 });
619 (Some(version), Some(opened), place)
620 }
621 None => (None, None, None),
622 };
623 self.pause();
624 #[cfg(test)]
625 {
626 let hook = self.hooks.before_confirm.lock().expect("hook").clone();
627 if let Some(hook) = hook {
628 hook();
629 }
630 }
631 let read = group::Confirm {
632 key: who.key,
633 action,
634 uuid,
635 version,
636 opened: opened.as_ref().is_some_and(Result::is_ok),
637 place,
638 };
639 match self.group.confirm(self, read)? {
640 group::Confirmed::Answer => match opened {
644 Some(opened) => return opened,
645 None => continue,
646 },
647 group::Confirmed::Again => continue,
648 group::Confirmed::Refused(error) => return Err(error),
649 }
650 }
651 }
652
653 pub fn replace(
660 &self,
661 who: &Caller,
662 if_match: VersionId,
663 found: &Inspection,
664 body: &[u8],
665 ) -> Result<VersionId, StoreError> {
666 let uuid = found.uuid;
667 let entry = |status, version| Entry {
668 actor: Actor::Key(who.key),
669 action: Action::Replace,
670 target: Some(uuid.to_string()),
671 version,
672 status,
673 };
674 let key_id = self.tenant_key.id();
675 let version = VersionId::generate();
676 let refusal = |tx: &mut Tx| -> Result<Option<(u16, StoreError)>, StoreError> {
678 Ok(match state(tx, uuid)? {
679 State::Absent => Some((404, StoreError::NotFound)),
680 State::Gone => Some((410, StoreError::Gone)),
681 State::Live(current) if version_row(tx, current)?.form != vcon::Form::Unsigned => {
682 Some((409, StoreError::Immutable))
683 }
684 State::Live(current) if current != if_match => {
685 Some((412, StoreError::PreconditionFailed))
686 }
687 State::Live(_) => None,
688 })
689 };
690 {
691 let mut tx = self.catalog.immediate()?;
692 let refused = match refusal(&mut tx)? {
693 None if envelope::wrap_limit(tx.wraps(key_id)?) == WrapLimit::Refuse => {
694 Some((503, StoreError::LimitReached))
695 }
696 other => other,
697 };
698 if let Some((status, error)) = refused {
699 self.record(&mut tx, &entry(status, None))?;
700 commit(tx)?;
701 return Err(error);
702 }
703 tx.add_wrap(key_id)?;
704 tx.add_pending(version, nanos(self.clock.now()))?;
705 commit(tx)?;
706 }
707
708 let wrapped = self.write_version(uuid, version, body)?;
709 self.pause();
710
711 let unknown = std::cell::Cell::new(false);
712 let committed = (|| {
713 let mut tx = self.catalog.immediate()?;
714 let mine = tx.drop_pending(version)?;
715 if let Some((status, error)) = refusal(&mut tx)? {
716 self.record(&mut tx, &entry(status, None))?;
717 commit(tx)?;
718 return Err(error);
719 }
720 if !mine {
721 self.record(&mut tx, &entry(500, None))?;
723 commit(tx)?;
724 return Err(StoreError::Io);
725 }
726 let now = self.now_in(tx.as_mut())?;
727 tx.insert_version(&NewVersion {
728 version,
729 uuid,
730 form: form_name(found.form),
731 gzip: found.gzip,
732 size: i64::try_from(body.len()).map_err(io)?,
733 stored_at: now,
734 key: key_id,
735 wrapped: &wrapped,
736 })?;
737 tx.hide_version(if_match, now)?;
738 tx.set_current(uuid, version)?;
739 self.record(&mut tx, &entry(200, Some(version)))?;
740 kept(tx.commit(), &unknown)?;
741 Ok(version)
742 })();
743 self.drop_unless_kept(committed.is_err(), unknown.get(), version);
744 #[cfg(test)]
745 if committed.is_ok() {
746 self.forced_pack();
747 }
748 committed
749 }
750
751 pub fn delete(&self, who: &Caller, uuid: Uuid, retention: Retention) -> Result<(), StoreError> {
759 let entry = |status| Entry {
760 actor: Actor::Key(who.key),
761 action: Action::Delete,
762 target: Some(uuid.to_string()),
763 version: None,
764 status,
765 };
766 {
767 let mut tx = self.catalog.immediate()?;
768 let outcome = match state(&mut tx, uuid)? {
769 State::Absent => Err(StoreError::NotFound),
770 State::Gone => Ok(()),
771 State::Live(_) => {
772 tx.mark_deleted(uuid, nanos(self.clock.now()))?;
773 Ok(())
774 }
775 };
776 let status = if outcome.is_ok() { 204 } else { 404 };
777 self.record(&mut tx, &entry(status))?;
778 commit(tx)?;
779 outcome?;
780 }
781 self.purge_hidden(Actor::Key(who.key), retention, Some(uuid))?;
784 Ok(())
785 }
786
787 pub fn check(&self) -> Result<Vec<VersionId>, StoreError> {
791 let versions = self.read(|tx| tx.places())?;
792 let present: std::collections::BTreeSet<String> =
793 self.objects.list().map_err(io)?.into_iter().collect();
794 let mut whole = std::collections::HashMap::new();
795 let mut missing = Vec::new();
796 for (version, place) in versions {
797 let kept = match place {
798 Err(_) => false,
799 Ok(None) => present.contains(&version.to_string()),
800 Ok(Some(packed)) => match whole.get(&packed.file) {
801 Some(&kept) => kept,
802 None => {
803 let kept = match &self.packs {
804 None => false,
805 Some(packs) => {
806 let name = crate::backend::pack::name(&packed.date, packed.file);
807 packs.size(&name).map_err(io)? == Some(packed.bytes)
808 }
809 };
810 whole.insert(packed.file, kept);
811 kept
812 }
813 },
814 };
815 if !kept {
816 missing.push(version);
817 }
818 }
819 Ok(missing)
820 }
821
822 fn write_version(
826 &self,
827 uuid: Uuid,
828 version: VersionId,
829 body: &[u8],
830 ) -> Result<Vec<u8>, StoreError> {
831 let ctx = Context::Version {
832 tenant: self.tenant,
833 uuid,
834 version,
835 };
836 let data_key = Key::generate().map_err(|_| StoreError::Io)?;
837 let blob = envelope::seal(&data_key, &ctx, body);
838 let wrapped = envelope::wrap(&self.tenant_key, &ctx, &data_key);
839 self.objects.put(version, &blob).map_err(io)?;
840 Ok(wrapped)
841 }
842
843 fn drop_unless_kept(&self, failed: bool, unknown: bool, version: VersionId) {
849 if failed && !unknown {
850 let _ = self.objects.remove(version);
852 }
853 }
854
855 fn pause(&self) {
858 #[cfg(test)]
859 {
860 let hook = self.hooks.between.lock().expect("hook").take();
861 if let Some(hook) = hook {
862 hook();
863 }
864 }
865 }
866
867 fn read_version(
870 &self,
871 tx: &mut Tx,
872 uuid: Uuid,
873 version: VersionId,
874 ) -> Result<Vec<u8>, StoreError> {
875 self.read_or_why(tx, uuid, version)
876 .map_err(Unopened::into_store)
877 }
878
879 fn read_or_why(
881 &self,
882 tx: &mut Tx,
883 uuid: Uuid,
884 version: VersionId,
885 ) -> Result<Vec<u8>, Unopened> {
886 let row = version_row(tx, version)?;
887 self.open_or_why(uuid, version, &row)
888 }
889
890 fn open_version(
893 &self,
894 uuid: Uuid,
895 version: VersionId,
896 row: &VersionRow,
897 ) -> Result<Vec<u8>, StoreError> {
898 self.open_or_why(uuid, version, row)
899 .map_err(Unopened::into_store)
900 }
901
902 fn open_or_why(
905 &self,
906 uuid: Uuid,
907 version: VersionId,
908 row: &VersionRow,
909 ) -> Result<Vec<u8>, Unopened> {
910 let ctx = Context::Version {
911 tenant: self.tenant,
912 uuid,
913 version,
914 };
915 let data_key =
916 envelope::unwrap(&self.tenant_key, &ctx, &row.wrapped).map_err(key_failed)?;
917 let blob = match self.sealed_blob(version, row.place.as_ref()) {
918 Ok(blob) => blob,
919 Err(packed::Unread::Object(ObjectError::Io(e))) => return Err(Unopened::Storage(e)),
920 Err(other) => return Err(Unopened::Store(other.into_store())),
921 };
922 Ok(envelope::open(&data_key, &ctx, &blob).map_err(|_| StoreError::Damaged)?)
923 }
924
925 pub fn packed_versions(&self) -> Result<u64, StoreError> {
929 self.read(|tx| tx.count_packed())
930 }
931
932 pub fn close(&self) -> Result<(), StoreError> {
938 self.catalog.close()
939 }
940
941 pub fn counts(&self) -> Result<Counts, StoreError> {
943 self.read(|tx| {
944 Ok(Counts {
945 versions: tx.count_versions()?,
946 held: tx.count_held()?,
947 })
948 })
949 }
950
951 pub(crate) fn read<T>(
956 &self,
957 read: impl FnOnce(&mut Tx<'_>) -> Result<T, StoreError>,
958 ) -> Result<T, StoreError> {
959 let mut tx = self.catalog.snapshot()?;
960 let out = read(&mut tx);
961 tx.end()?;
962 out
963 }
964
965 pub fn export(
968 &self,
969 since: Option<i64>,
970 out: &mut dyn std::io::Write,
971 ) -> Result<(), audit::AuditError> {
972 self.catalog.export(since.unwrap_or(0), out)
973 }
974
975 pub fn audit_page(
980 &self,
981 who: &Caller,
982 query: &audit::AuditQuery,
983 ) -> Result<Vec<u8>, StoreError> {
984 let mut tx = self.catalog.immediate()?;
985 let mut out = Vec::new();
986 let read = tx.audit_lines(query.after, Some(query.limit), &mut out);
987 self.record(
988 &mut tx,
989 &Entry {
990 actor: Actor::Key(who.key),
991 action: Action::AuditRead,
992 target: None,
993 version: None,
994 status: if read.is_ok() { 200 } else { 500 },
995 },
996 )?;
997 commit(tx)?;
998 read.map(|()| out).map_err(io)
999 }
1000
1001 pub fn log(&self, entry: &Entry) -> Result<(), StoreError> {
1004 let mut tx = self.catalog.immediate()?;
1005 self.record(&mut tx, entry)?;
1006 commit(tx)
1007 }
1008
1009 #[cfg(test)]
1010 pub(crate) fn break_audit(&self) {
1011 self.conn()
1012 .execute_batch(
1013 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1014 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
1015 )
1016 .expect("trigger");
1017 }
1018
1019 #[cfg(all(test, feature = "s3"))]
1023 pub(crate) fn pack_after_every_write(&mut self, plan: packer::PackPlan) {
1024 *self.hooks.pack_always.lock().expect("hook") = Some(plan);
1025 }
1026
1027 #[cfg(test)]
1028 fn forced_pack(&self) {
1029 let plan = *self.hooks.pack_always.lock().expect("hook");
1030 if let Some(plan) = plan {
1031 self.pack(&plan).expect("the forced pack run");
1032 }
1033 }
1034
1035 #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
1039 pub(crate) fn on_last_step(&self, hook: Option<Arc<dyn Fn() + Send + Sync>>) {
1040 *self.hooks.before_confirm.lock().expect("hook") = hook;
1041 }
1042
1043 #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
1047 pub(crate) fn in_first_step(&self, hook: Option<Arc<dyn Fn() + Send + Sync>>) {
1048 *self.hooks.in_first_step.lock().expect("hook") = hook;
1049 }
1050
1051 #[cfg(all(test, feature = "postgres", feature = "backend-tests"))]
1054 pub(crate) fn once_before_open(&self, hook: Box<dyn FnOnce() + Send>) {
1055 *self.hooks.before_read.lock().expect("hook") = Some(hook);
1056 }
1057
1058 #[cfg(test)]
1061 pub(crate) fn on_between(&self, hook: Box<dyn FnOnce() + Send>) {
1062 *self.hooks.between.lock().expect("hook") = Some(hook);
1063 }
1064
1065 #[cfg(test)]
1067 pub(crate) fn pending_writes(&self) -> Result<Vec<(VersionId, i64)>, StoreError> {
1068 self.read(|tx| tx.pending())
1069 }
1070
1071 #[cfg(test)]
1072 pub(crate) fn on_backup_copied(&self, hook: tests::BackupHook) {
1073 *self.hooks.copied.lock().expect("hook") = Some(hook);
1074 }
1075
1076 #[cfg(test)]
1077 pub(crate) fn conn_for_test(&self) -> MutexGuard<'_, LocalConn> {
1078 self.conn()
1079 }
1080
1081 #[cfg(test)]
1085 pub(crate) fn await_sync_waiters(&self, n: usize) {
1086 self.catalog.await_sync_waiters(n);
1087 }
1088
1089 #[cfg(test)]
1090 pub(crate) fn records(&self) -> Vec<serde_json::Value> {
1091 crate::audit::testing::exported(&self.conn(), None)
1092 }
1093
1094 pub fn count(&self, entry: &Entry) -> Result<(), StoreError> {
1098 let mut tx = self.catalog.immediate()?;
1099 tx.count(entry, self.clock.now())
1100 .map_err(|_| StoreError::AuditFailed)?;
1101 commit(tx)
1102 }
1103
1104 fn record(&self, tx: &mut Tx, entry: &Entry) -> Result<(), StoreError> {
1112 tx.record(entry, self.clock.now())
1113 .map_err(|_| StoreError::AuditFailed)
1114 }
1115
1116 #[cfg(test)]
1118 fn conn(&self) -> MutexGuard<'_, LocalConn> {
1119 self.catalog.local_conn()
1120 }
1121}
1122
1123enum State {
1124 Absent,
1125 Live(VersionId),
1126 Gone,
1127}
1128
1129fn state(tx: &mut Tx, uuid: Uuid) -> Result<State, StoreError> {
1132 if tx.tombstoned(uuid)? {
1133 return Ok(State::Gone);
1134 }
1135 match tx.vcon_row(uuid)? {
1136 None => Ok(State::Absent),
1137 Some(row) if row.deleted_at.is_some() => Ok(State::Gone),
1138 Some(row) => row.current.map(State::Live).ok_or(StoreError::Damaged),
1139 }
1140}
1141
1142fn names_its_object(place: &Result<Option<Packed>, StoreError>) -> bool {
1147 !matches!(place, Ok(Some(_)))
1148}
1149
1150struct VersionRow {
1151 form: vcon::Form,
1152 gzip: bool,
1153 wrapped: Vec<u8>,
1154 place: Option<Packed>,
1155}
1156
1157fn version_row(tx: &mut Tx, version: VersionId) -> Result<VersionRow, StoreError> {
1160 let row = tx.version_row(version)?.ok_or(StoreError::Damaged)?;
1161 let form = match row.form.as_str() {
1162 "unsigned" => vcon::Form::Unsigned,
1163 "signed" => vcon::Form::Signed,
1164 "encrypted" => vcon::Form::Encrypted,
1165 _ => return Err(StoreError::Damaged),
1166 };
1167 Ok(VersionRow {
1168 form,
1169 gzip: row.gzip,
1170 wrapped: row.wrapped,
1171 place: row.place,
1172 })
1173}
1174
1175fn commit(tx: Tx) -> Result<(), StoreError> {
1176 tx.commit().map_err(io)
1177}
1178
1179fn kept(
1182 outcome: Result<(), CommitError>,
1183 unknown: &std::cell::Cell<bool>,
1184) -> Result<(), StoreError> {
1185 outcome.map_err(|e| {
1186 unknown.set(e == CommitError::Unknown);
1187 StoreError::Io
1188 })
1189}
1190
1191fn key_failed(e: envelope::KeyError) -> StoreError {
1194 match e {
1195 envelope::KeyError::Damaged => StoreError::Damaged,
1196 _ => StoreError::Io,
1197 }
1198}
1199
1200fn read_failed(e: ObjectError) -> StoreError {
1206 match e {
1207 ObjectError::Missing => StoreError::Damaged,
1208 ObjectError::Io(e) => {
1209 storage_failed(&e);
1210 StoreError::Io
1211 }
1212 }
1213}
1214
1215fn storage_failed(e: &std::io::Error) {
1219 tracing::warn!(
1220 kind = %e.kind(),
1221 os_error = e.raw_os_error(),
1222 "a stored version's object could not be read"
1223 );
1224}
1225
1226#[derive(Debug)]
1229enum Unopened {
1230 Store(StoreError),
1231 Storage(std::io::Error),
1232}
1233
1234impl Unopened {
1235 fn into_store(self) -> StoreError {
1238 match self {
1239 Unopened::Store(e) => e,
1240 Unopened::Storage(e) => read_failed(ObjectError::Io(e)),
1241 }
1242 }
1243}
1244
1245impl From<StoreError> for Unopened {
1246 fn from(e: StoreError) -> Unopened {
1247 Unopened::Store(e)
1248 }
1249}
1250
1251fn io<E>(_: E) -> StoreError {
1252 StoreError::Io
1253}
1254
1255fn form_name(form: vcon::Form) -> &'static str {
1257 form.as_str()
1258}
1259
1260impl From<ObjectError> for StoreError {
1261 fn from(_: ObjectError) -> StoreError {
1262 StoreError::Io
1263 }
1264}
1265
1266#[cfg(test)]
1267pub(crate) mod testing {
1268 use std::collections::BTreeSet;
1269
1270 use vcon::Form;
1271 use vcon::read::{Inspection, Limits, inspect};
1272
1273 pub(crate) fn vcon(uuid: &str, subject: &str) -> (Inspection, Vec<u8>) {
1275 let body = format!(
1276 r#"{{"uuid": "{uuid}", "created_at": "2026-10-23T12:00:00Z", "subject": "{subject}", "parties": []}}"#
1277 )
1278 .into_bytes();
1279 let found =
1280 inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a valid vCon");
1281 assert_eq!(found.form, Form::Unsigned);
1282 (found, body)
1283 }
1284}
1285
1286#[cfg(test)]
1287pub(crate) mod tests {
1288 use std::collections::BTreeSet;
1289
1290 use serde_json::Value;
1291 use time::macros::datetime;
1292 use vcon::read::{Limits, inspect};
1293
1294 use super::testing::vcon;
1295 use super::*;
1296 use crate::audit::testing::exported;
1297
1298 #[test]
1302 fn an_objects_directory_the_process_may_not_write_is_named() {
1303 use std::os::unix::fs::PermissionsExt;
1304 let f = fixture();
1305 let objects = f.dir.path().join("objects");
1306 let mode = |m| {
1307 std::fs::set_permissions(&objects, std::fs::Permissions::from_mode(m)).expect("chmod")
1308 };
1309 mode(0o500);
1310 let refused = f.open_or_why();
1311 mode(0o700);
1312 match refused {
1313 Err(OpenError::Access { path, error }) => {
1314 assert_eq!(path, objects);
1315 assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
1316 }
1317 other => panic!("{:?}", other.map(|_| "opened")),
1318 }
1319 assert!(f.open_or_why().is_ok(), "opens once allowed");
1320 }
1321 use crate::catalog::testing::columns_taking_null;
1322 use crate::clock::ManualClock;
1323 use rusqlite::{Connection, params};
1324
1325 use crate::catalog;
1326 use crate::fs::{CrashFs, Op};
1327
1328 const UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
1329
1330 pub(crate) type BackupHook = Box<dyn FnMut(&Store) + Send>;
1332
1333 pub(crate) type StoreHook = Box<dyn FnOnce(&Store) + Send>;
1335
1336 #[derive(Default)]
1338 pub(super) struct Hooks {
1339 pub(super) between: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1343 pub(super) copied: Mutex<Option<BackupHook>>,
1346 pub(super) before_read: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1349 pub(super) pack_always: Mutex<Option<super::packer::PackPlan>>,
1351 pub(super) before_confirm: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
1354 pub(super) in_first_step: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
1357 pub(super) after_snapshot: Mutex<Option<StoreHook>>,
1360 pub(super) clock_steps: Mutex<Vec<i64>>,
1365 }
1366
1367 impl Store {
1368 pub(crate) fn step_clock(&self, steps: Vec<i64>) {
1371 *self.hooks.clock_steps.lock().expect("hook") = steps;
1372 }
1373 }
1374
1375 pub(crate) struct Fixture {
1376 pub(crate) dir: tempfile::TempDir,
1377 pub(crate) fs: Arc<CrashFs>,
1378 pub(crate) clock: Arc<ManualClock>,
1379 master: Key,
1382 wrapped: Vec<u8>,
1383 pub(crate) store: Store,
1384 pub(crate) caller: Caller,
1385 pub(crate) packs: Option<Arc<dyn Packs>>,
1388 }
1389
1390 pub(super) const TENANT: TenantId = TenantId([0x11; 16]);
1391
1392 impl Fixture {
1393 pub(super) fn open(&self) -> Result<Store, StoreError> {
1394 self.open_or_why().map_err(StoreError::from)
1395 }
1396
1397 pub(super) fn open_or_why(&self) -> Result<Store, OpenError> {
1399 let ctx = Context::Tenant { tenant: TENANT };
1400 let tenant_key = envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps");
1401 let mut store = Store::open_beside(
1404 self.dir.path(),
1405 TENANT,
1406 tenant_key,
1407 self.fs.clone(),
1408 self.clock.clone(),
1409 )?;
1410 store.packs = self.packs.clone();
1411 store.recover(super::pending::Writers::None)?;
1412 Ok(store)
1413 }
1414
1415 pub(crate) fn tenant_key(&self) -> Key {
1417 let ctx = Context::Tenant { tenant: TENANT };
1418 envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps")
1419 }
1420
1421 pub(crate) fn tenant(&self) -> TenantId {
1422 TENANT
1423 }
1424
1425 pub(crate) fn store_objects_dir(&self) -> PathBuf {
1427 self.store.objects_dir.clone()
1428 }
1429
1430 pub(crate) fn open_beside_store(&self) -> Store {
1434 self.open_beside().expect("opens beside")
1435 }
1436
1437 fn open_beside(&self) -> Result<Store, StoreError> {
1439 let ctx = Context::Tenant { tenant: TENANT };
1440 let tenant_key = envelope::unwrap(&self.master, &ctx, &self.wrapped).expect("unwraps");
1441 Store::open_beside(
1442 self.dir.path(),
1443 TENANT,
1444 tenant_key,
1445 self.fs.clone(),
1446 self.clock.clone(),
1447 )
1448 .map_err(StoreError::from)
1449 }
1450
1451 pub(super) fn reopen(&mut self) {
1453 let placeholder = self.open().expect("opens");
1454 drop(std::mem::replace(&mut self.store, placeholder));
1455 self.store = self.open().expect("reopens");
1456 }
1457 }
1458
1459 pub(crate) fn fixture() -> Fixture {
1460 let dir = tempfile::tempdir().expect("temp dir");
1461 let fs = Arc::new(CrashFs::new(dir.path()));
1462 let clock = Arc::new(ManualClock::at(datetime!(2026-10-23 12:00 UTC)));
1463 let master = Key::generate().expect("master key");
1464 let tenant_key = Key::generate().expect("tenant key");
1465 let wrapped = envelope::wrap(&master, &Context::Tenant { tenant: TENANT }, &tenant_key);
1466 let store =
1467 Store::open(dir.path(), TENANT, tenant_key, fs.clone(), clock.clone()).expect("opens");
1468 let caller = Caller {
1469 key: Key::generate().expect("caller key").id(),
1470 };
1471 Fixture {
1472 dir,
1473 fs,
1474 clock,
1475 master,
1476 wrapped,
1477 store,
1478 caller,
1479 packs: None,
1480 }
1481 }
1482
1483 fn audit_log(store: &Store) -> Vec<Value> {
1484 exported(&store.conn(), None)
1485 }
1486
1487 fn count(store: &Store, sql: &str) -> i64 {
1488 store.conn().query_row(sql, [], |r| r.get(0)).expect(sql)
1489 }
1490
1491 fn wraps(store: &Store) -> i64 {
1492 store
1493 .conn()
1494 .query_row("SELECT coalesce(sum(wraps), 0) FROM key_use", [], |r| {
1495 r.get(0)
1496 })
1497 .expect("wraps")
1498 }
1499
1500 fn stored_body(f: &Fixture, uuid: Uuid, version: VersionId) -> Vec<u8> {
1502 let wrapped: Vec<u8> = f
1503 .store
1504 .conn()
1505 .query_row(
1506 "SELECT wrapped_key FROM version WHERE version = ?1",
1507 [version.0],
1508 |r| r.get(0),
1509 )
1510 .expect("row");
1511 let ctx = Context::Version {
1512 tenant: f.store.tenant,
1513 uuid,
1514 version,
1515 };
1516 let data_key = envelope::unwrap(&f.store.tenant_key, &ctx, &wrapped).expect("unwraps");
1517 let blob =
1518 f.fs.read(&f.store.objects_dir.join(version.to_string()))
1519 .expect("file");
1520 envelope::open(&data_key, &ctx, &blob).expect("opens")
1521 }
1522
1523 fn audit_page(f: &Fixture, after: i64, limit: u32) -> Result<Vec<u8>, StoreError> {
1524 f.store
1525 .audit_page(&f.caller, &audit::AuditQuery { after, limit })
1526 }
1527
1528 fn export_text(store: &Store, since: Option<i64>) -> Vec<u8> {
1529 let mut out = Vec::new();
1530 store.export(since, &mut out).expect("export");
1531 out
1532 }
1533
1534 #[test]
1535 fn an_audit_page_is_export_s_lines_and_records_its_read_after_them() {
1536 let f = fixture();
1537 for n in 0..3 {
1538 let (found, body) = vcon(&format!("01a07da8-c2bb-83e5-b9a2-27900000000{n}"), "x");
1539 f.store.create(&f.caller, &found, &body).expect("stored");
1540 }
1541 let before = export_text(&f.store, None);
1542 assert_eq!(audit_page(&f, 0, 1000), Ok(before.clone()));
1543 let read = audit_log(&f.store);
1544 assert_eq!(read.len(), 4, "three creates and the read");
1545 assert_eq!(read[3]["action"], "audit_read");
1546 assert_eq!(read[3]["actor"], f.caller.key.to_string());
1547 assert_eq!(read[3]["status"], 200);
1548 assert_eq!(read[3]["seq"], 4);
1549 assert_eq!(read[3]["target"], Value::Null);
1550 let lines: Vec<&[u8]> = before.split_inclusive(|b| *b == b'\n').collect();
1552 assert_eq!(audit_page(&f, 1, 2), Ok(lines[1..3].concat()));
1553 let tail = audit_page(&f, 4, 1000).expect("a page");
1555 assert_eq!(tail, export_text(&f.store, Some(4))[..tail.len()]);
1556 assert_eq!(String::from_utf8(tail).expect("UTF-8").lines().count(), 1);
1557 }
1558
1559 #[test]
1562 fn an_audit_page_that_cannot_be_read_is_a_failure_and_recorded() {
1563 let f = fixture();
1564 f.store
1565 .conn_for_test()
1566 .execute(
1567 "INSERT INTO audit (at, actor, action, status, count)
1568 VALUES ('2026-10-23T12:00:00Z', 'cli', 'read', 70000, 1)",
1569 [],
1570 )
1571 .expect("damaged");
1572 assert_eq!(audit_page(&f, 0, 10), Err(StoreError::Io));
1573 let mut recorded = Vec::new();
1574 f.store.export(Some(1), &mut recorded).expect("export");
1575 let recorded: Value = serde_json::from_slice(&recorded).expect("one record");
1576 assert_eq!(recorded["action"], "audit_read");
1577 assert_eq!(recorded["status"], 500);
1578 }
1579
1580 #[test]
1581 fn an_audit_page_whose_record_fails_is_refused() {
1582 let f = fixture();
1583 f.store.break_audit();
1584 assert_eq!(audit_page(&f, 0, 10), Err(StoreError::AuditFailed));
1585 }
1586
1587 pub(super) fn wal(f: &Fixture) -> std::path::PathBuf {
1589 f.dir.path().join("catalog.sqlite-wal")
1590 }
1591
1592 fn only_its_record_synced(f: &Fixture, ops: usize) {
1596 assert_eq!(
1597 f.fs.log()[ops..],
1598 [Op::SyncData(wal(f))],
1599 "no file written; the record's commit synced before the answer"
1600 );
1601 }
1602
1603 #[test]
1604 fn a_new_vcon_is_written_in_order_and_recorded() {
1605 let f = fixture();
1606 let (found, body) = vcon(UUID, "first");
1607 let ops = f.fs.log().len();
1608 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1609 panic!("a new vCon")
1610 };
1611 let (tmp, done) = (
1612 f.store.objects_dir.join(format!("{version}.tmp")),
1613 f.store.objects_dir.join(version.to_string()),
1614 );
1615 assert_eq!(
1616 f.fs.log()[ops..],
1617 [
1618 Op::SyncData(wal(&f)),
1621 Op::Write(tmp.clone()),
1622 Op::SyncFile(tmp.clone()),
1623 Op::Rename(tmp, done),
1624 Op::SyncDir(f.store.objects_dir.clone()),
1625 Op::SyncData(wal(&f)),
1627 ],
1628 "every change and sync of a create, in order"
1629 );
1630 assert_eq!(
1631 f.fs.log().len() - ops,
1632 WRITE_STEPS,
1633 "the steps a cut can hit"
1634 );
1635 assert_eq!(stored_body(&f, found.uuid, version), body);
1636 assert_eq!(
1637 count(
1638 &f.store,
1639 "SELECT count(*) FROM version WHERE hidden_at IS NULL"
1640 ),
1641 1
1642 );
1643 let current: Vec<u8> = f
1644 .store
1645 .conn()
1646 .query_row(
1647 "SELECT current FROM vcon WHERE uuid = ?1",
1648 [found.uuid.as_bytes()],
1649 |r| r.get(0),
1650 )
1651 .expect("vcon row");
1652 assert_eq!(current, version.0);
1653 assert_eq!(wraps(&f.store), 1, "one data key wrapped");
1654 let log = audit_log(&f.store);
1655 assert_eq!(log.len(), 1);
1656 assert_eq!(log[0]["action"], "create");
1657 assert_eq!(log[0]["actor"], f.caller.key.to_string());
1658 assert_eq!(log[0]["target"], UUID);
1659 assert_eq!(log[0]["version"], version.to_string());
1660 assert_eq!(log[0]["status"], 201);
1661 }
1662
1663 #[test]
1664 fn a_replace_is_written_in_order_and_synced() {
1665 let f = fixture();
1666 let (found, old) = stored(&f, "first");
1667 let (_, newer) = vcon(UUID, "second");
1668 let ops = f.fs.log().len();
1669 let version = f
1670 .store
1671 .replace(&f.caller, old, &found, &newer)
1672 .expect("replaced");
1673 let (tmp, done) = (
1674 f.store.objects_dir.join(format!("{version}.tmp")),
1675 f.store.objects_dir.join(version.to_string()),
1676 );
1677 assert_eq!(
1678 f.fs.log()[ops..],
1679 [
1680 Op::SyncData(wal(&f)),
1681 Op::Write(tmp.clone()),
1682 Op::SyncFile(tmp.clone()),
1683 Op::Rename(tmp, done),
1684 Op::SyncDir(f.store.objects_dir.clone()),
1685 Op::SyncData(wal(&f)),
1686 ],
1687 "every change and sync of a replace, in order"
1688 );
1689 assert_eq!(
1690 f.fs.log().len() - ops,
1691 REPLACE_STEPS,
1692 "the steps a cut can hit"
1693 );
1694 }
1695
1696 #[test]
1697 fn the_same_body_again_is_same_and_writes_nothing() {
1698 let f = fixture();
1699 let (found, body) = vcon(UUID, "first");
1700 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1701 panic!("a new vCon")
1702 };
1703 let ops = f.fs.log().len();
1704 assert_eq!(
1705 f.store.create(&f.caller, &found, &body),
1706 Ok(Created::Same(version))
1707 );
1708 only_its_record_synced(&f, ops);
1709 assert_eq!(count(&f.store, "SELECT count(*) FROM version"), 1);
1710 assert_eq!(wraps(&f.store), 1, "nothing wrapped");
1711 let log = audit_log(&f.store);
1712 assert_eq!(
1713 (log[1]["status"].clone(), log[1]["version"].clone()),
1714 (200.into(), version.to_string().into())
1715 );
1716 }
1717
1718 #[test]
1719 fn another_body_for_a_stored_uuid_is_a_conflict_and_writes_nothing() {
1720 let f = fixture();
1721 let (found, body) = vcon(UUID, "first");
1722 f.store.create(&f.caller, &found, &body).expect("stored");
1723 let ops = f.fs.log().len();
1724 let (found, other) = vcon(UUID, "other");
1726 assert_eq!(
1727 f.store.create(&f.caller, &found, &other),
1728 Err(StoreError::Conflict)
1729 );
1730 only_its_record_synced(&f, ops);
1731 assert_eq!(wraps(&f.store), 1, "nothing wrapped");
1732 assert_eq!(audit_log(&f.store)[1]["status"], 409);
1733 }
1734
1735 #[test]
1736 fn a_deleted_or_purged_uuid_is_gone_and_writes_nothing() {
1737 for sql in [
1738 "INSERT INTO vcon (uuid, current, deleted_at) VALUES (?1, NULL, 1)",
1739 "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
1740 ] {
1741 let f = fixture();
1742 let (found, body) = vcon(UUID, "first");
1743 f.store
1744 .conn()
1745 .execute(sql, [found.uuid.as_bytes()])
1746 .expect(sql);
1747 let ops = f.fs.log().len();
1748 assert_eq!(
1749 f.store.create(&f.caller, &found, &body),
1750 Err(StoreError::Gone),
1751 "{sql}"
1752 );
1753 only_its_record_synced(&f, ops);
1754 assert_eq!(wraps(&f.store), 0, "nothing wrapped");
1755 assert_eq!(audit_log(&f.store)[0]["status"], 410);
1756 }
1757 }
1758
1759 #[test]
1760 fn counts_include_hidden_versions_and_held_uuids() {
1761 let f = fixture();
1762 let none = Counts {
1763 versions: 0,
1764 held: 0,
1765 };
1766 assert_eq!(f.store.counts(), Ok(none));
1767 let (found, old) = stored(&f, "first");
1768 let (_, newer) = vcon(UUID, "second");
1769 f.store
1770 .replace(&f.caller, old, &found, &newer)
1771 .expect("replaced");
1772 f.store
1773 .delete(&f.caller, found.uuid, Retention::Years(7))
1774 .expect("deleted");
1775 let (other, body) = vcon("01a07da8-c2bb-83e5-b9a2-279e0d16bc47", "other");
1776 f.store.create(&f.caller, &other, &body).expect("stored");
1777 assert_eq!(
1778 f.store.counts(),
1779 Ok(Counts {
1780 versions: 3,
1781 held: 0
1782 }),
1783 "two hidden versions and a live one"
1784 );
1785 f.store
1786 .conn()
1787 .execute(
1788 "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
1789 [found.uuid.as_bytes()],
1790 )
1791 .expect("a hold");
1792 assert_eq!(f.store.counts().map(|c| c.held), Ok(1));
1793 }
1794
1795 #[test]
1796 fn a_negative_wrap_count_is_damage_and_stores_nothing() {
1797 let f = fixture();
1798 f.store
1799 .conn()
1800 .execute(
1801 "INSERT INTO key_use (tenant_key_id, wraps) VALUES (?1, -1)",
1802 [f.store.tenant_key.id().bytes()],
1803 )
1804 .expect("a damaged count");
1805 let (found, body) = vcon(UUID, "first");
1806 let ops = f.fs.log().len();
1807 assert_eq!(
1808 f.store.create(&f.caller, &found, &body),
1809 Err(StoreError::Io)
1810 );
1811 assert_eq!(f.fs.log().len(), ops, "no file written");
1812 }
1813
1814 #[test]
1815 fn a_tenant_key_at_its_wrap_limit_refuses_new_vcons() {
1816 let f = fixture();
1817 f.store
1818 .conn()
1819 .execute(
1820 "INSERT INTO key_use (tenant_key_id, wraps) VALUES (?1, ?2)",
1821 params![f.store.tenant_key.id().bytes(), 1_i64 << 32],
1822 )
1823 .expect("at the limit");
1824 let (found, body) = vcon(UUID, "first");
1825 let ops = f.fs.log().len();
1826 assert_eq!(
1827 f.store.create(&f.caller, &found, &body),
1828 Err(StoreError::LimitReached)
1829 );
1830 only_its_record_synced(&f, ops);
1831 assert_eq!(audit_log(&f.store)[0]["status"], 503);
1832 }
1833
1834 #[test]
1835 fn a_missing_current_file_is_damage_not_a_conflict() {
1836 let f = fixture();
1837 let (found, body) = vcon(UUID, "first");
1838 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1839 panic!("a new vCon")
1840 };
1841 f.fs.remove(&f.store.objects_dir.join(version.to_string()))
1842 .expect("remove");
1843 assert_eq!(
1844 f.store.create(&f.caller, &found, &body),
1845 Err(StoreError::Damaged)
1846 );
1847 assert_eq!(audit_log(&f.store)[1]["status"], 500);
1848 }
1849
1850 #[test]
1851 fn a_racing_create_that_loses_gets_a_conflict_and_leaves_no_file() {
1852 let f = Arc::new(fixture());
1853 let (found, body) = vcon(UUID, "first");
1854 let winner = f.clone();
1855 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
1856 let (found, other) = vcon(UUID, "second");
1857 assert!(matches!(
1858 winner.store.create(&winner.caller, &found, &other),
1859 Ok(Created::New(_))
1860 ));
1861 }));
1862 assert_eq!(
1863 f.store.create(&f.caller, &found, &body),
1864 Err(StoreError::Conflict)
1865 );
1866 assert_eq!(
1867 count(&f.store, "SELECT count(*) FROM version"),
1868 1,
1869 "only the winner"
1870 );
1871 assert_eq!(
1872 f.fs.list(&f.store.objects_dir).expect("list").len(),
1873 1,
1874 "the loser's file is gone"
1875 );
1876 assert_eq!(wraps(&f.store), 2, "both wraps are counted");
1877 let statuses: Vec<_> = audit_log(&f.store)
1878 .iter()
1879 .map(|r| r["status"].clone())
1880 .collect();
1881 assert_eq!(statuses, [201, 409]);
1882 }
1883
1884 #[test]
1885 fn a_create_whose_audit_record_fails_leaves_no_row_and_no_file() {
1886 let f = fixture();
1887 f.store
1889 .conn()
1890 .execute_batch(
1891 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
1892 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
1893 )
1894 .expect("trigger");
1895 let (found, body) = vcon(UUID, "first");
1896 assert_eq!(
1897 f.store.create(&f.caller, &found, &body),
1898 Err(StoreError::AuditFailed)
1899 );
1900 assert_eq!(count(&f.store, "SELECT count(*) FROM version"), 0);
1901 assert_eq!(count(&f.store, "SELECT count(*) FROM vcon"), 0);
1902 assert_eq!(
1903 f.fs.list(&f.store.objects_dir).expect("list"),
1904 Vec::<std::ffi::OsString>::new()
1905 );
1906 }
1907
1908 #[test]
1909 fn a_create_whose_commit_outcome_is_unknown_keeps_its_object() {
1910 let f = fixture();
1911 let (found, body) = vcon(UUID, "first");
1912 f.store.catalog.fail_commit(2, CommitError::Unknown);
1916 assert_eq!(
1917 f.store.create(&f.caller, &found, &body),
1918 Err(StoreError::Io),
1919 "a_create_whose_commit_outcome_is_unknown_keeps_its_object: f.store.create(&f.caller, &found, &body)"
1920 );
1921 let stored = f
1922 .store
1923 .get(&f.caller, found.uuid)
1924 .expect("the kept row reads");
1925 assert_eq!(
1926 stored.body, body,
1927 "a_create_whose_commit_outcome_is_unknown_keeps_its_object: stored.body"
1928 );
1929 assert_eq!(f.store.check(), Ok(Vec::new()), "no row without its object");
1930 drop(f.open().expect("reopens"));
1931 assert_eq!(
1932 f.store.get(&f.caller, found.uuid).map(|s| s.body),
1933 Ok(body),
1934 "recovery keeps an object a row names"
1935 );
1936 }
1937
1938 #[test]
1939 fn a_replace_whose_commit_outcome_is_unknown_keeps_its_object() {
1940 let f = fixture();
1941 let (found, body) = vcon(UUID, "first");
1942 let Ok(Created::New(first)) = f.store.create(&f.caller, &found, &body) else {
1943 panic!("a new vCon")
1944 };
1945 let (found, second) = vcon(UUID, "second");
1946 f.store.catalog.fail_commit(2, CommitError::Unknown);
1947 assert_eq!(
1948 f.store.replace(&f.caller, first, &found, &second),
1949 Err(StoreError::Io),
1950 "a_replace_whose_commit_outcome_is_unknown_keeps_its_object: f.store.replace(&f.caller, first, &found, &second)"
1951 );
1952 let stored = f
1953 .store
1954 .get(&f.caller, found.uuid)
1955 .expect("the kept row reads");
1956 assert_eq!(
1957 stored.body, second,
1958 "a_replace_whose_commit_outcome_is_unknown_keeps_its_object: stored.body"
1959 );
1960 assert_eq!(f.store.check(), Ok(Vec::new()), "no row without its object");
1961 }
1962
1963 #[test]
1964 fn a_create_whose_commit_rolls_back_leaves_no_object() {
1965 let f = fixture();
1966 let (found, body) = vcon(UUID, "first");
1967 f.store.catalog.fail_commit(2, CommitError::RolledBack);
1968 assert_eq!(
1969 f.store.create(&f.caller, &found, &body),
1970 Err(StoreError::Io),
1971 "a_create_whose_commit_rolls_back_leaves_no_object: f.store.create(&f.caller, &found, &body)"
1972 );
1973 assert_eq!(
1974 count(&f.store, "SELECT count(*) FROM version"),
1975 0,
1976 "a_create_whose_commit_rolls_back_leaves_no_object: count(&f.store, \"SELECT count(*) FROM version\")"
1977 );
1978 assert_eq!(
1979 f.fs.list(&f.store.objects_dir).expect("list"),
1980 Vec::<std::ffi::OsString>::new(),
1981 "a_create_whose_commit_rolls_back_leaves_no_object: f.fs.list(&f.store.objects_dir).expect(\"list\")"
1982 );
1983 }
1984
1985 fn get_entry_status(f: &Fixture) -> Value {
1986 audit_log(&f.store).last().expect("a record")["status"].clone()
1987 }
1988
1989 #[test]
1990 fn a_stored_vcon_reads_back_byte_for_byte_and_is_recorded() {
1991 let f = fixture();
1992 let (found, body) = vcon(UUID, "first");
1993 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
1994 panic!("a new vCon")
1995 };
1996 let stored = f.store.get(&f.caller, found.uuid).expect("reads");
1997 assert_eq!(
1998 stored,
1999 Stored {
2000 version,
2001 form: vcon::Form::Unsigned,
2002 gzip: false,
2003 body
2004 }
2005 );
2006 let log = audit_log(&f.store);
2007 let read = log.last().expect("a record");
2008 assert_eq!(read["action"], "read");
2009 assert_eq!(read["status"], 200);
2010 assert_eq!(read["version"], version.to_string());
2011 assert_eq!(read["target"], UUID);
2012 }
2013
2014 #[test]
2015 fn a_uuid_never_stored_is_not_found() {
2016 let f = fixture();
2017 let (found, _) = vcon(UUID, "first");
2018 assert_eq!(
2019 f.store.get(&f.caller, found.uuid),
2020 Err(StoreError::NotFound)
2021 );
2022 assert_eq!(get_entry_status(&f), 404);
2023 }
2024
2025 #[test]
2026 fn a_deleted_or_purged_uuid_is_gone() {
2027 for sql in [
2028 "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2029 "DELETE FROM vcon WHERE uuid = ?1; INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
2030 ] {
2031 let f = fixture();
2032 let (found, body) = vcon(UUID, "first");
2033 f.store.create(&f.caller, &found, &body).expect("stored");
2034 for statement in sql.split("; ") {
2035 f.store
2036 .conn()
2037 .execute(statement, [found.uuid.as_bytes()])
2038 .expect(statement);
2039 }
2040 assert_eq!(
2041 f.store.get(&f.caller, found.uuid),
2042 Err(StoreError::Gone),
2043 "{sql}"
2044 );
2045 assert_eq!(get_entry_status(&f), 410);
2046 }
2047 }
2048
2049 #[test]
2050 fn a_missing_or_damaged_file_is_a_500_never_an_empty_body() {
2051 let f = fixture();
2052 let (found, body) = vcon(UUID, "first");
2053 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2054 panic!("a new vCon")
2055 };
2056 let file = f.store.objects_dir.join(version.to_string());
2057 let blob = f.fs.read(&file).expect("file");
2058 f.fs.remove(&file).expect("remove");
2059 assert_eq!(
2060 f.store.get(&f.caller, found.uuid),
2061 Err(StoreError::Damaged),
2062 "missing"
2063 );
2064 assert_eq!(get_entry_status(&f), 500);
2065 let mut bad = blob.clone();
2066 let last = bad.len() - 1;
2067 bad[last] ^= 1;
2068 f.fs.write_new(&file, &bad).expect("write");
2069 assert_eq!(
2070 f.store.get(&f.caller, found.uuid),
2071 Err(StoreError::Damaged),
2072 "tampered"
2073 );
2074 }
2075
2076 pub(super) type Fail = fn() -> ObjectError;
2078
2079 pub(super) struct ReadsFail {
2082 pub(super) inner: Arc<dyn Objects>,
2083 pub(super) fail: Fail,
2084 }
2085
2086 impl Objects for ReadsFail {
2087 fn put(&self, version: VersionId, blob: &[u8]) -> Result<(), ObjectError> {
2088 self.inner.put(version, blob)
2089 }
2090
2091 fn get(&self, _: VersionId) -> Result<Vec<u8>, ObjectError> {
2092 Err((self.fail)())
2093 }
2094
2095 fn remove(&self, version: VersionId) -> Result<(), ObjectError> {
2096 self.inner.remove(version)
2097 }
2098
2099 fn list(&self) -> Result<Vec<String>, ObjectError> {
2100 self.inner.list()
2101 }
2102
2103 fn remove_name(&self, name: &str) -> Result<(), ObjectError> {
2104 self.inner.remove_name(name)
2105 }
2106
2107 fn sync(&self) -> Result<(), ObjectError> {
2108 self.inner.sync()
2109 }
2110 }
2111
2112 struct ListFails {
2114 inner: Arc<dyn Objects>,
2115 fail: Fail,
2116 }
2117
2118 impl Objects for ListFails {
2119 fn put(&self, version: VersionId, blob: &[u8]) -> Result<(), ObjectError> {
2120 self.inner.put(version, blob)
2121 }
2122
2123 fn get(&self, version: VersionId) -> Result<Vec<u8>, ObjectError> {
2124 self.inner.get(version)
2125 }
2126
2127 fn remove(&self, version: VersionId) -> Result<(), ObjectError> {
2128 self.inner.remove(version)
2129 }
2130
2131 fn list(&self) -> Result<Vec<String>, ObjectError> {
2132 Err((self.fail)())
2133 }
2134
2135 fn remove_name(&self, name: &str) -> Result<(), ObjectError> {
2136 self.inner.remove_name(name)
2137 }
2138
2139 fn sync(&self) -> Result<(), ObjectError> {
2140 self.inner.sync()
2141 }
2142 }
2143
2144 #[test]
2149 fn a_listing_the_storage_fails_is_reported_with_its_kind() {
2150 let cases: [(Fail, ExamineError); 2] = [
2151 (
2152 || storage_failed(std::io::ErrorKind::PermissionDenied),
2153 ExamineError::Objects {
2154 kind: std::io::ErrorKind::PermissionDenied,
2155 os_error: None,
2156 },
2157 ),
2158 (
2159 || ObjectError::Missing,
2160 ExamineError::Failed(StoreError::Io),
2161 ),
2162 ];
2163 for (fail, expected) in cases {
2164 let mut f = fixture();
2165 let (found, body) = vcon(UUID, "first");
2166 f.store.create(&f.caller, &found, &body).expect("stored");
2167 f.store.objects = Arc::new(ListFails {
2168 inner: f.store.objects.clone(),
2169 fail,
2170 });
2171 assert_eq!(
2172 f.store
2173 .examine(
2174 Retention::Years(7),
2175 datetime!(2026-10-23 12:00 UTC),
2176 datetime!(2026-10-23 12:00 UTC),
2177 )
2178 .err(),
2179 Some(expected),
2180 "examine fails with the listing's failure"
2181 );
2182 }
2183 }
2184
2185 fn storage_failed(kind: std::io::ErrorKind) -> ObjectError {
2187 ObjectError::Io(std::io::Error::from(kind))
2188 }
2189
2190 #[test]
2194 fn a_read_the_storage_fails_is_io_and_only_a_missing_object_is_damage() {
2195 let cases: [(Fail, StoreError, &str); 5] = [
2196 (|| ObjectError::Missing, StoreError::Damaged, "missing"),
2197 (
2198 || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
2199 StoreError::Io,
2200 "EIO",
2201 ),
2202 (
2203 || storage_failed(std::io::ErrorKind::PermissionDenied),
2204 StoreError::Io,
2205 "permission denied",
2206 ),
2207 (
2208 || storage_failed(std::io::ErrorKind::ConnectionRefused),
2209 StoreError::Io,
2210 "connection refused",
2211 ),
2212 (
2213 || storage_failed(std::io::ErrorKind::TimedOut),
2214 StoreError::Io,
2215 "timed out",
2216 ),
2217 ];
2218 for (fail, expected, why) in cases {
2219 let mut f = fixture();
2220 let (found, body) = vcon(UUID, "first");
2221 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2222 panic!("a new vCon")
2223 };
2224 f.store.objects = Arc::new(ReadsFail {
2225 inner: f.store.objects.clone(),
2226 fail,
2227 });
2228 assert_eq!(
2229 f.store.get(&f.caller, found.uuid),
2230 Err(expected),
2231 "{why}: get"
2232 );
2233 assert_eq!(get_entry_status(&f), 500, "{why}: get is recorded");
2234 assert_eq!(
2235 f.store.create(&f.caller, &found, &body),
2236 Err(expected),
2237 "{why}: create of the same body"
2238 );
2239 for asked in [None, Some(version)] {
2240 assert_eq!(
2241 f.store.legal_get(&f.caller, found.uuid, asked).err(),
2242 Some(expected),
2243 "{why}: legal_get {asked:?}"
2244 );
2245 }
2246 let examined = f.store.examine(
2247 Retention::Years(7),
2248 datetime!(2026-10-23 12:00 UTC),
2249 datetime!(2026-10-23 12:00 UTC),
2250 );
2251 match expected {
2252 StoreError::Damaged => assert_eq!(
2253 examined.map(|e| e.damaged),
2254 Ok(vec![version]),
2255 "{why}: examine lists the version"
2256 ),
2257 _ => {
2258 let ObjectError::Io(failed) = fail() else {
2259 panic!("{why}: a storage failure")
2260 };
2261 assert_eq!(
2262 examined.err(),
2263 Some(ExamineError::Objects {
2264 kind: failed.kind(),
2265 os_error: failed.raw_os_error(),
2266 }),
2267 "{why}: examine fails with the storage's error kind, listing nothing as damaged"
2268 );
2269 }
2270 }
2271 }
2272 }
2273
2274 #[derive(Clone, Default)]
2276 pub(super) struct Capture(pub(super) Arc<Mutex<Vec<u8>>>);
2277
2278 impl std::io::Write for Capture {
2279 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2280 self.0.lock().expect("lock").extend_from_slice(bytes);
2281 Ok(bytes.len())
2282 }
2283
2284 fn flush(&mut self) -> std::io::Result<()> {
2285 Ok(())
2286 }
2287 }
2288
2289 impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Capture {
2290 type Writer = Capture;
2291
2292 fn make_writer(&'a self) -> Capture {
2293 self.clone()
2294 }
2295 }
2296
2297 const LEAKY: &str = "tenants/1111/objects/0e0e AKIAIOSFODNN7EXAMPLE wJalrXUtnFEMI";
2300
2301 #[test]
2305 fn a_failed_read_is_logged_by_its_kind_only() {
2306 let mut f = fixture();
2307 let (found, body) = vcon(UUID, "first");
2308 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2309 panic!("a new vCon")
2310 };
2311 f.store.objects = Arc::new(ReadsFail {
2312 inner: f.store.objects.clone(),
2313 fail: || {
2314 ObjectError::Io(std::io::Error::new(
2315 std::io::ErrorKind::PermissionDenied,
2316 LEAKY,
2317 ))
2318 },
2319 });
2320 let capture = Capture::default();
2321 let subscriber = tracing_subscriber::fmt()
2322 .with_writer(capture.clone())
2323 .with_ansi(false)
2324 .log_internal_errors(false)
2325 .finish();
2326 let read =
2327 tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid));
2328 assert_eq!(read, Err(StoreError::Io), "the read fails as Io");
2329 let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2330 assert!(log.contains("WARN"), "a warning: {log}");
2331 assert!(
2332 log.contains("kind=permission denied"),
2333 "the kind is logged: {log}"
2334 );
2335 let version = version.to_string();
2337 let tenant = TENANT.to_string();
2338 for (what, value) in [
2339 ("the error's text", LEAKY),
2340 ("the object's key", "tenants/1111"),
2341 ("the access key id", "AKIAIOSFODNN7EXAMPLE"),
2342 ("the secret key", "wJalrXUtnFEMI"),
2343 ("the uuid", UUID),
2344 ("the version id", version.as_str()),
2345 ("the tenant id", tenant.as_str()),
2346 ] {
2347 assert!(!log.contains(value), "{what} is logged");
2348 }
2349
2350 f.store.objects = Arc::new(ReadsFail {
2352 inner: f.store.objects.clone(),
2353 fail: || ObjectError::Io(std::io::Error::from_raw_os_error(libc::EIO)),
2354 });
2355 let capture = Capture::default();
2356 let subscriber = tracing_subscriber::fmt()
2357 .with_writer(capture.clone())
2358 .with_ansi(false)
2359 .log_internal_errors(false)
2360 .finish();
2361 tracing::subscriber::with_default(subscriber, || f.store.get(&f.caller, found.uuid))
2362 .expect_err("fails");
2363 let log = String::from_utf8(capture.0.lock().expect("lock").clone()).expect("UTF-8");
2364 assert!(
2365 log.contains(&format!("os_error={}", libc::EIO)),
2366 "the error number is logged: {log}"
2367 );
2368 }
2369
2370 #[test]
2373 fn only_a_wrapped_key_that_does_not_open_is_damage() {
2374 assert_eq!(
2375 key_failed(envelope::KeyError::Damaged),
2376 StoreError::Damaged,
2377 "a key that does not open"
2378 );
2379 assert_eq!(
2380 key_failed(envelope::KeyError::Memory(
2381 std::io::Error::from_raw_os_error(libc::ENOMEM)
2382 )),
2383 StoreError::Io,
2384 "a key page that cannot be locked"
2385 );
2386 }
2387
2388 #[test]
2389 fn a_read_racing_a_delete_never_returns_the_body() {
2390 let f = Arc::new(fixture());
2391 let (found, body) = vcon(UUID, "first");
2392 f.store.create(&f.caller, &found, &body).expect("stored");
2393 let deleter = f.clone();
2394 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2395 deleter
2396 .store
2397 .conn()
2398 .execute(
2399 "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2400 [found.uuid.as_bytes()],
2401 )
2402 .expect("delete");
2403 }));
2404 assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2405 assert_eq!(get_entry_status(&f), 410);
2406 }
2407
2408 #[test]
2409 fn a_read_racing_a_new_version_starts_again_and_returns_the_new_one() {
2410 let f = Arc::new(fixture());
2411 let (found, body) = vcon(UUID, "first");
2412 f.store.create(&f.caller, &found, &body).expect("stored");
2413 let (_, newer) = vcon(UUID, "newer");
2414 let version = VersionId::generate();
2415 let wrapped = f
2416 .store
2417 .write_version(found.uuid, version, &newer)
2418 .expect("written");
2419 let writer = f.clone();
2420 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2421 let conn = writer.store.conn();
2422 conn.execute(
2423 "INSERT INTO version
2424 (version, uuid, form, gzip, size, stored_at, tenant_key_id, wrapped_key)
2425 VALUES (?1, ?2, 'unsigned', 0, 0, 0, ?3, ?4)",
2426 params![
2427 version.0,
2428 found.uuid.as_bytes(),
2429 writer.store.tenant_key.id().bytes(),
2430 wrapped
2431 ],
2432 )
2433 .expect("new version");
2434 conn.execute(
2435 "UPDATE vcon SET current = ?1 WHERE uuid = ?2",
2436 params![version.0, found.uuid.as_bytes()],
2437 )
2438 .expect("made current");
2439 }));
2440 let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2441 assert_eq!((stored.version, stored.body), (version, newer));
2442 let reads = audit_log(&f.store)
2443 .iter()
2444 .filter(|r| r["action"] == "read")
2445 .count();
2446 assert_eq!(reads, 1, "one record for the one request");
2447 }
2448
2449 #[test]
2450 fn every_form_and_the_gzip_flag_read_back_as_stored() {
2451 use base64::Engine;
2452 use std::io::Write;
2453 let f = fixture();
2454 let uuids = [
2455 "01a07da8-c2bb-83e5-b9a2-279e0d16bc01",
2456 "01a07da8-c2bb-83e5-b9a2-279e0d16bc02",
2457 "01a07da8-c2bb-83e5-b9a2-279e0d16bc03",
2458 ];
2459 let (_, unsigned) = vcon(uuids[0], "plain");
2460 let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
2461 gz.write_all(&unsigned).expect("gzip");
2462 let gzipped = gz.finish().expect("gzip");
2463 let (_, inner) = vcon(uuids[1], "signed");
2464 let signed = format!(
2465 r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2466 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2467 )
2468 .into_bytes();
2469 let encrypted = format!(
2470 r#"{{"unprotected": {{"uuid": "{}"}}, "ciphertext": "x", "recipients": []}}"#,
2471 uuids[2]
2472 )
2473 .into_bytes();
2474 let cases = [
2475 (gzipped, vcon::Form::Unsigned, true),
2476 (signed, vcon::Form::Signed, false),
2477 (encrypted, vcon::Form::Encrypted, false),
2478 ];
2479 for (body, form, gzip) in cases {
2480 let found = inspect(&body, None, &Limits::new(1 << 20), &BTreeSet::new())
2481 .expect("a valid vCon");
2482 assert_eq!((found.form, found.gzip), (form, gzip));
2483 f.store.create(&f.caller, &found, &body).expect("stored");
2484 let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2485 assert_eq!((stored.form, stored.gzip, stored.body), (form, gzip, body));
2486 }
2487 }
2488
2489 fn stored(f: &Fixture, subject: &str) -> (Inspection, VersionId) {
2491 let (found, body) = vcon(UUID, subject);
2492 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
2493 panic!("a new vCon")
2494 };
2495 (found, version)
2496 }
2497
2498 #[test]
2499 fn a_replace_makes_a_new_current_version_and_hides_the_old_one() {
2500 let f = fixture();
2501 let (found, old) = stored(&f, "first");
2502 let (_, newer) = vcon(UUID, "second");
2503 let version = f
2504 .store
2505 .replace(&f.caller, old, &found, &newer)
2506 .expect("replaced");
2507 assert_ne!(version, old);
2508 let stored = f.store.get(&f.caller, found.uuid).expect("reads");
2509 assert_eq!((stored.version, stored.body), (version, newer));
2510 let hidden: Option<i64> = f
2511 .store
2512 .conn()
2513 .query_row(
2514 "SELECT hidden_at FROM version WHERE version = ?1",
2515 [old.0],
2516 |r| r.get(0),
2517 )
2518 .expect("the old row is kept");
2519 assert_eq!(
2520 hidden,
2521 Some(crate::clock::nanos(datetime!(2026-10-23 12:00 UTC))),
2522 "the old version is hidden at the replace's time"
2523 );
2524 assert!(
2525 f.fs.read(&f.store.objects_dir.join(old.to_string()))
2526 .is_ok(),
2527 "its file is kept"
2528 );
2529 let record = audit_log(&f.store)
2530 .into_iter()
2531 .find(|r| r["action"] == "replace")
2532 .expect("a replace record");
2533 assert_eq!(
2534 (record["status"].clone(), record["version"].clone()),
2535 (200.into(), version.to_string().into())
2536 );
2537 }
2538
2539 #[test]
2540 fn a_replace_of_a_missing_or_gone_uuid_is_refused() {
2541 let f = fixture();
2542 let (found, body) = vcon(UUID, "first");
2543 let any = VersionId([7; 16]);
2544 assert_eq!(
2545 f.store.replace(&f.caller, any, &found, &body),
2546 Err(StoreError::NotFound)
2547 );
2548 assert_eq!(get_entry_status(&f), 404);
2549 let (found, old) = stored(&f, "first");
2550 f.store
2551 .conn()
2552 .execute(
2553 "UPDATE vcon SET current = NULL, deleted_at = 1 WHERE uuid = ?1",
2554 [found.uuid.as_bytes()],
2555 )
2556 .expect("delete");
2557 assert_eq!(
2558 f.store.replace(&f.caller, old, &found, &body),
2559 Err(StoreError::Gone)
2560 );
2561 assert_eq!(get_entry_status(&f), 410);
2562 }
2563
2564 #[test]
2565 fn a_stale_if_match_is_refused_and_writes_nothing() {
2566 let f = fixture();
2567 let (found, _) = stored(&f, "first");
2568 let ops = f.fs.log().len();
2569 let (_, newer) = vcon(UUID, "second");
2570 assert_eq!(
2571 f.store
2572 .replace(&f.caller, VersionId([7; 16]), &found, &newer),
2573 Err(StoreError::PreconditionFailed)
2574 );
2575 only_its_record_synced(&f, ops);
2576 assert_eq!(wraps(&f.store), 1, "nothing wrapped");
2577 assert_eq!(get_entry_status(&f), 412);
2578 }
2579
2580 #[test]
2581 fn a_signed_or_encrypted_current_version_is_immutable() {
2582 use base64::Engine;
2583 let f = fixture();
2584 let (found, old) = stored(&f, "first");
2585 let (_, inner) = vcon(UUID, "signed");
2586 let signed = format!(
2587 r#"{{"payload": "{}", "signatures": [{{"header": {{}}}}]}}"#,
2588 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(inner)
2589 )
2590 .into_bytes();
2591 let signed_found =
2592 inspect(&signed, None, &Limits::new(1 << 20), &BTreeSet::new()).expect("a signed vCon");
2593 let version = f
2594 .store
2595 .replace(&f.caller, old, &signed_found, &signed)
2596 .expect("an unsigned vCon may be replaced by a signed one");
2597 let (_, newer) = vcon(UUID, "second");
2598 let ops = f.fs.log().len();
2599 assert_eq!(
2600 f.store.replace(&f.caller, version, &found, &newer),
2601 Err(StoreError::Immutable)
2602 );
2603 only_its_record_synced(&f, ops);
2604 assert_eq!(get_entry_status(&f), 409);
2605
2606 let g = fixture();
2607 let encrypted = format!(
2608 r#"{{"unprotected": {{"uuid": "{UUID}"}}, "ciphertext": "x", "recipients": []}}"#
2609 )
2610 .into_bytes();
2611 let enc_found = inspect(&encrypted, None, &Limits::new(1 << 20), &BTreeSet::new())
2612 .expect("an encrypted vCon");
2613 let Ok(Created::New(enc_version)) = g.store.create(&g.caller, &enc_found, &encrypted)
2614 else {
2615 panic!("stored")
2616 };
2617 assert_eq!(
2618 g.store.replace(&g.caller, enc_version, &found, &newer),
2619 Err(StoreError::Immutable)
2620 );
2621 }
2622
2623 #[test]
2624 fn a_replace_at_the_wrap_limit_is_refused() {
2625 let f = fixture();
2626 let (found, old) = stored(&f, "first");
2627 f.store
2628 .conn()
2629 .execute("UPDATE key_use SET wraps = ?1", [1_i64 << 32])
2630 .expect("at the limit");
2631 let (_, newer) = vcon(UUID, "second");
2632 assert_eq!(
2633 f.store.replace(&f.caller, old, &found, &newer),
2634 Err(StoreError::LimitReached)
2635 );
2636 assert_eq!(get_entry_status(&f), 503);
2637 }
2638
2639 #[test]
2640 fn of_two_replaces_racing_on_one_version_the_second_to_commit_loses() {
2641 let f = Arc::new(fixture());
2642 let (found, old) = stored(&f, "first");
2643 let winner = f.clone();
2644 let racer = found;
2645 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
2646 let (_, body) = vcon(UUID, "winner");
2647 winner
2648 .store
2649 .replace(&winner.caller, old, &racer, &body)
2650 .expect("wins");
2651 }));
2652 let (_, body) = vcon(UUID, "loser");
2653 assert_eq!(
2654 f.store.replace(&f.caller, old, &found, &body),
2655 Err(StoreError::PreconditionFailed)
2656 );
2657 assert_eq!(
2658 f.fs.list(&f.store.objects_dir).expect("list").len(),
2659 2,
2660 "first and winner only"
2661 );
2662 assert_eq!(wraps(&f.store), 3, "every wrap counted");
2663 assert_eq!(get_entry_status(&f), 412);
2664 }
2665
2666 #[test]
2667 fn two_threads_replacing_with_the_same_if_match_one_wins() {
2668 let f = Arc::new(fixture());
2669 let (_, old) = stored(&f, "first");
2670 let threads: Vec<_> = ["one", "two"]
2671 .into_iter()
2672 .map(|subject| {
2673 let f = f.clone();
2674 std::thread::spawn(move || {
2675 let (found, body) = vcon(UUID, subject);
2676 f.store.replace(&f.caller, old, &found, &body)
2677 })
2678 })
2679 .collect();
2680 let results: Vec<_> = threads
2681 .into_iter()
2682 .map(|t| t.join().expect("thread"))
2683 .collect();
2684 assert_eq!(
2685 results.iter().filter(|r| r.is_ok()).count(),
2686 1,
2687 "{results:?}"
2688 );
2689 assert!(
2690 results.contains(&Err(StoreError::PreconditionFailed)),
2691 "{results:?}"
2692 );
2693 }
2694
2695 #[test]
2696 fn a_replace_whose_audit_record_fails_changes_nothing() {
2697 let f = fixture();
2698 let (found, old) = stored(&f, "first");
2699 f.store
2700 .conn()
2701 .execute_batch(
2702 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2703 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2704 )
2705 .expect("trigger");
2706 let (_, newer) = vcon(UUID, "second");
2707 assert_eq!(
2708 f.store.replace(&f.caller, old, &found, &newer),
2709 Err(StoreError::AuditFailed)
2710 );
2711 f.store
2712 .conn()
2713 .execute_batch("DROP TRIGGER no_audit")
2714 .expect("drop trigger");
2715 assert_eq!(
2716 f.store.get(&f.caller, found.uuid).expect("reads").version,
2717 old
2718 );
2719 assert_eq!(
2720 f.fs.list(&f.store.objects_dir).expect("list").len(),
2721 1,
2722 "only the first file"
2723 );
2724 }
2725
2726 fn hidden_versions(f: &Fixture) -> i64 {
2727 count(
2728 &f.store,
2729 "SELECT count(*) FROM version WHERE hidden_at IS NOT NULL",
2730 )
2731 }
2732
2733 #[test]
2734 fn a_deleted_uuid_answers_gone_and_keeps_its_versions_hidden() {
2735 let f = fixture();
2736 let (found, old) = stored(&f, "first");
2737 let (_, newer) = vcon(UUID, "second");
2738 f.clock.set(datetime!(2026-10-23 13:00 UTC));
2739 let current = f
2740 .store
2741 .replace(&f.caller, old, &found, &newer)
2742 .expect("replaced");
2743 f.clock.set(datetime!(2026-10-23 14:00 UTC));
2744 assert_eq!(
2745 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2746 Ok(())
2747 );
2748 let record = audit_log(&f.store).pop().expect("a record");
2749 assert_eq!(
2750 (record["action"].clone(), record["status"].clone()),
2751 ("delete".into(), 204.into())
2752 );
2753 let hidden_at = |version: VersionId| -> i64 {
2754 f.store
2755 .conn()
2756 .query_row(
2757 "SELECT hidden_at FROM version WHERE version = ?1",
2758 [version.0],
2759 |r| r.get(0),
2760 )
2761 .expect("hidden")
2762 };
2763 assert_eq!(
2764 hidden_at(old),
2765 nanos(datetime!(2026-10-23 13:00 UTC)),
2766 "hidden by the replace"
2767 );
2768 assert_eq!(
2769 hidden_at(current),
2770 nanos(datetime!(2026-10-23 14:00 UTC)),
2771 "hidden by the delete"
2772 );
2773 assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2774 let (_, body) = vcon(UUID, "third");
2775 assert_eq!(
2776 f.store.create(&f.caller, &found, &body),
2777 Err(StoreError::Gone)
2778 );
2779 assert_eq!(hidden_versions(&f), 2, "both versions hidden");
2780 assert_eq!(
2781 f.fs.list(&f.store.objects_dir).expect("list").len(),
2782 2,
2783 "files kept for legal reads"
2784 );
2785 let (current, deleted_at): (Option<Vec<u8>>, Option<i64>) = f
2786 .store
2787 .conn()
2788 .query_row(
2789 "SELECT current, deleted_at FROM vcon WHERE uuid = ?1",
2790 [found.uuid.as_bytes()],
2791 |r| Ok((r.get(0)?, r.get(1)?)),
2792 )
2793 .expect("row");
2794 assert_eq!(current, None);
2795 assert_eq!(deleted_at, Some(nanos(datetime!(2026-10-23 14:00 UTC))));
2796 }
2797
2798 #[test]
2799 fn deleting_a_deleted_or_purged_uuid_succeeds_again() {
2800 let f = fixture();
2801 let (found, _) = stored(&f, "first");
2802 f.store
2803 .delete(&f.caller, found.uuid, Retention::Years(7))
2804 .expect("deleted");
2805 assert_eq!(
2806 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2807 Ok(())
2808 );
2809 assert_eq!(get_entry_status(&f), 204);
2810 let g = fixture();
2811 g.store
2812 .conn()
2813 .execute(
2814 "INSERT INTO tombstone (uuid, purged_at) VALUES (?1, 1)",
2815 [found.uuid.as_bytes()],
2816 )
2817 .expect("purged");
2818 assert_eq!(
2819 g.store.delete(&g.caller, found.uuid, Retention::Years(7)),
2820 Ok(())
2821 );
2822 assert_eq!(get_entry_status(&g), 204);
2823 }
2824
2825 #[test]
2826 fn deleting_a_uuid_never_stored_is_not_found() {
2827 let f = fixture();
2828 let (found, _) = vcon(UUID, "first");
2829 assert_eq!(
2830 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2831 Err(StoreError::NotFound)
2832 );
2833 assert_eq!(get_entry_status(&f), 404);
2834 }
2835
2836 #[test]
2837 fn a_hold_does_not_stop_a_delete() {
2838 let f = fixture();
2839 let (found, _) = stored(&f, "first");
2840 f.store
2841 .conn()
2842 .execute(
2843 "UPDATE vcon SET hold = 1 WHERE uuid = ?1",
2844 [found.uuid.as_bytes()],
2845 )
2846 .expect("hold");
2847 assert_eq!(
2848 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2849 Ok(())
2850 );
2851 assert_eq!(f.store.get(&f.caller, found.uuid), Err(StoreError::Gone));
2852 }
2853
2854 #[test]
2855 fn a_delete_whose_audit_record_fails_changes_nothing() {
2856 let f = fixture();
2857 let (found, version) = stored(&f, "first");
2858 f.store
2859 .conn()
2860 .execute_batch(
2861 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
2862 BEGIN SELECT RAISE(ABORT, 'audit fails'); END;",
2863 )
2864 .expect("trigger");
2865 assert_eq!(
2866 f.store.delete(&f.caller, found.uuid, Retention::Years(7)),
2867 Err(StoreError::AuditFailed)
2868 );
2869 f.store
2870 .conn()
2871 .execute_batch("DROP TRIGGER no_audit")
2872 .expect("drop trigger");
2873 assert_eq!(
2874 f.store
2875 .get(&f.caller, found.uuid)
2876 .expect("still live")
2877 .version,
2878 version
2879 );
2880 assert_eq!(hidden_versions(&f), 0);
2881 }
2882
2883 #[test]
2884 fn only_the_optional_catalog_columns_may_be_empty() {
2885 let f = fixture();
2886 let conn = f.store.conn();
2887 let tables: [(&str, &[(&str, &str)]); 8] = [
2888 (
2889 "vcon",
2890 &[
2891 ("uuid", "x'01'"),
2892 ("current", "x'02'"),
2893 ("deleted_at", "1"),
2894 ("hold", "0"),
2895 ],
2896 ),
2897 (
2898 "version",
2899 &[
2900 ("version", "x'02'"),
2901 ("uuid", "x'01'"),
2902 ("form", "'unsigned'"),
2903 ("gzip", "0"),
2904 ("size", "1"),
2905 ("stored_at", "1"),
2906 ("hidden_at", "1"),
2907 ("tenant_key_id", "x'03'"),
2908 ("wrapped_key", "x'04'"),
2909 ("place_file", "x'05'"),
2910 ("place_group", "0"),
2911 ("place_row", "0"),
2912 ],
2913 ),
2914 (
2915 "parquet_file",
2916 &[
2917 ("file_id", "x'05'"),
2918 ("date", "'2026-10-23'"),
2919 ("rows", "1"),
2920 ("live_rows", "1"),
2921 ("bytes", "1"),
2922 ("created_at", "1"),
2923 ("unnamed_at", "1"),
2924 ],
2925 ),
2926 ("purge_pending", &[("file_id", "x'05'")]),
2927 ("manifest", &[("seq", "1"), ("published_at", "1")]),
2928 ("tombstone", &[("uuid", "x'01'"), ("purged_at", "1")]),
2929 ("key_use", &[("tenant_key_id", "x'03'"), ("wraps", "1")]),
2930 (
2931 "audit",
2932 &[
2933 ("at", "'2026-10-23T12:00Z'"),
2934 ("actor", "'cli'"),
2935 ("action", "'create'"),
2936 ("target", "'x'"),
2937 ("version", "'y'"),
2938 ("status", "201"),
2939 ("count", "1"),
2940 ],
2941 ),
2942 ];
2943 let may_be_empty: Vec<String> = tables
2944 .iter()
2945 .flat_map(|(table, row)| columns_taking_null(&conn, table, row))
2946 .collect();
2947 assert_eq!(
2948 may_be_empty,
2949 [
2950 "vcon.current",
2951 "vcon.deleted_at",
2952 "version.hidden_at",
2953 "version.place_file",
2954 "version.place_group",
2955 "version.place_row",
2956 "parquet_file.unnamed_at",
2957 "manifest.seq",
2959 "manifest.published_at",
2960 "audit.target",
2961 "audit.version",
2962 "audit.status"
2964 ]
2965 );
2966 }
2967
2968 #[test]
2969 fn a_new_stores_objects_directory_survives_a_crash() {
2970 let f = fixture();
2971 f.fs.crash();
2972 assert_eq!(
2973 f.fs.list(f.dir.path()).expect("list"),
2974 [std::ffi::OsString::from("objects")]
2975 );
2976 }
2977
2978 #[test]
2979 fn opening_removes_temporary_and_orphaned_files_and_nothing_else() {
2980 let mut f = fixture();
2981 let (found, version) = stored(&f, "first");
2982 let orphan = VersionId([0x0e; 16]);
2983 let objects = f.store.objects_dir.clone();
2984 for name in [
2985 format!("{orphan}"),
2986 format!("{orphan}.tmp"),
2987 format!("{version}.tmp"),
2988 "notes.txt".to_owned(),
2989 ] {
2990 f.fs.write_new(&objects.join(name), b"x").expect("write");
2991 }
2992 f.reopen();
2993 let names: Vec<String> =
2994 f.fs.list(&objects)
2995 .expect("list")
2996 .into_iter()
2997 .map(|n| n.to_string_lossy().into_owned())
2998 .collect();
2999 assert_eq!(names, [version.to_string(), "notes.txt".to_owned()]);
3000 assert_eq!(
3001 f.store
3002 .get(&f.caller, found.uuid)
3003 .expect("still reads")
3004 .version,
3005 version
3006 );
3007 let log = f.fs.log();
3008 let last_removal = log
3009 .iter()
3010 .rposition(|op| matches!(op, Op::Remove(_)))
3011 .expect("files were removed");
3012 assert!(
3013 log[last_removal..].contains(&Op::SyncDir(objects)),
3014 "the removals are synced"
3015 );
3016 }
3017
3018 #[test]
3021 fn opening_beside_a_server_removes_nothing() {
3022 let f = fixture();
3023 let (found, version) = stored(&f, "first");
3024 let orphan = VersionId([0x0e; 16]);
3025 let objects = f.store.objects_dir.clone();
3026 let mut written = vec![version.to_string()];
3027 for name in [
3028 format!("{orphan}"),
3029 format!("{orphan}.tmp"),
3030 format!("{version}.tmp"),
3031 ] {
3032 f.fs.write_new(&objects.join(&name), b"x").expect("write");
3033 written.push(name);
3034 }
3035 written.sort();
3036 let ops = f.fs.log().len();
3037 let beside = f.open_beside().expect("opens beside");
3038 let mut names: Vec<String> =
3039 f.fs.list(&objects)
3040 .expect("list")
3041 .into_iter()
3042 .map(|n| n.to_string_lossy().into_owned())
3043 .collect();
3044 names.sort();
3045 assert_eq!(names, written);
3046 assert!(
3047 !f.fs.log()[ops..]
3048 .iter()
3049 .any(|op| matches!(op, Op::Remove(_))),
3050 "nothing removed"
3051 );
3052 assert_eq!(
3053 beside.get(&f.caller, found.uuid).expect("reads").version,
3054 version
3055 );
3056 }
3057
3058 #[test]
3059 fn opening_checkpoints_the_wal_with_truncation() {
3060 let mut f = fixture();
3061 stored(&f, "first");
3062 let wal = f.dir.path().join("catalog.sqlite-wal");
3063 assert!(
3064 std::fs::metadata(&wal).expect("a WAL").len() > 0,
3065 "the WAL holds the write"
3066 );
3067 f.reopen();
3068 assert_eq!(std::fs::metadata(&wal).expect("a WAL").len(), 0);
3069 }
3070
3071 #[test]
3072 fn check_reports_a_version_whose_file_is_missing() {
3073 let f = fixture();
3074 let (_, version) = stored(&f, "first");
3075 assert_eq!(f.store.check(), Ok(vec![]));
3076 f.fs.remove(&f.store.objects_dir.join(version.to_string()))
3077 .expect("remove");
3078 assert_eq!(f.store.check(), Ok(vec![version]));
3079 }
3080
3081 #[test]
3082 fn opening_refuses_while_a_reader_stops_the_wal_from_being_truncated() {
3083 let f = fixture();
3084 stored(&f, "first");
3085 let ctx = Context::Tenant { tenant: TENANT };
3086 let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
3087 let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
3088 let mut reader = catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
3089 .expect("a second connection");
3090 let read = reader.transaction().expect("read transaction");
3091 let _: i64 = read
3092 .query_row("SELECT count(*) FROM vcon", [], |r| r.get(0))
3093 .expect("a read holds a snapshot");
3094 assert!(matches!(f.open(), Err(StoreError::Io)));
3095 drop(read);
3096 assert!(f.open().is_ok(), "opens once the reader is done");
3097 }
3098
3099 const WRITE_STEPS: usize = 6;
3104
3105 const REPLACE_STEPS: usize = 6;
3108
3109 fn assert_whole(f: &Fixture, step: usize) {
3111 assert_eq!(
3112 f.store.check(),
3113 Ok(vec![]),
3114 "a row without its file at step {step}"
3115 );
3116 for name in f.fs.list(&f.store.objects_dir).expect("list") {
3117 let name = name.to_string_lossy().into_owned();
3118 let version = VersionId::parse(&name)
3119 .unwrap_or_else(|| panic!("{name} left over at step {step}"));
3120 let rows = count(
3121 &f.store,
3122 &format!("SELECT count(*) FROM version WHERE hex(version) = upper('{version}')"),
3123 );
3124 assert_eq!(rows, 1, "{name} has no row at step {step}");
3125 }
3126 }
3127
3128 pub(super) fn second_connection(f: &Fixture) -> Connection {
3132 let ctx = Context::Tenant { tenant: TENANT };
3133 let tenant_key = envelope::unwrap(&f.master, &ctx, &f.wrapped).expect("unwraps");
3134 let catalog_key = envelope::catalog_key(&tenant_key).expect("catalog key");
3135 catalog::open(&f.dir.path().join("catalog.sqlite"), &catalog_key, "")
3136 .expect("second connection")
3137 }
3138
3139 fn die_before_commit(f: &Fixture) {
3140 let other = second_connection(f);
3141 let fs = f.fs.clone();
3142 *f.store.hooks.between.lock().expect("hook") = Some(Box::new(move || {
3143 fs.fail_from(0);
3144 other
3145 .execute_batch(
3146 "CREATE TRIGGER dead BEFORE INSERT ON audit
3147 BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
3148 )
3149 .expect("trigger");
3150 }));
3151 }
3152
3153 pub(super) fn restart(f: &mut Fixture) {
3154 f.fs.crash();
3155 f.store
3156 .conn()
3157 .execute_batch("DROP TRIGGER IF EXISTS dead")
3158 .expect("drop trigger");
3159 f.reopen();
3160 }
3161
3162 fn uncut_log(write: impl Fn(&Fixture)) -> Vec<Op> {
3164 let f = fixture();
3165 let ops = f.fs.log().len();
3166 write(&f);
3167 f.fs.log()[ops..].to_vec()
3168 }
3169
3170 fn assert_poisoned_at_a_sync(
3175 f: &Fixture,
3176 uncut: &[Op],
3177 step: usize,
3178 result: Result<(), StoreError>,
3179 ) {
3180 if !matches!(uncut.get(step), Some(Op::SyncData(_))) {
3181 return;
3182 }
3183 assert_eq!(result, Err(StoreError::Io), "step {step}: a failed sync");
3184 f.fs.revive();
3185 assert_eq!(
3186 f.store
3187 .get(&f.caller, Uuid::parse_str(UUID).expect("uuid"))
3188 .map(|_| ()),
3189 Err(StoreError::Io),
3190 "step {step}: poisoned until the catalog is reopened"
3191 );
3192 }
3193
3194 #[test]
3195 fn a_create_cut_off_at_any_step_leaves_no_vcon_or_the_whole_vcon() {
3196 let (found, body) = vcon(UUID, "first");
3197 let uncut = uncut_log(|f| {
3198 f.store.create(&f.caller, &found, &body).expect("created");
3199 });
3200 assert_eq!(
3201 uncut.len(),
3202 WRITE_STEPS,
3203 "every step of a create: {uncut:?}"
3204 );
3205 for step in 0..=WRITE_STEPS {
3206 let mut f = fixture();
3207 f.fs.fail_from(f.fs.log().len() + step);
3208 let result = f.store.create(&f.caller, &found, &body);
3209 assert_eq!(
3210 result.is_ok(),
3211 step == WRITE_STEPS,
3212 "step {step}: {result:?}"
3213 );
3214 assert_poisoned_at_a_sync(&f, &uncut, step, result.map(|_| ()));
3215 restart(&mut f);
3216 match f.store.get(&f.caller, found.uuid) {
3217 Ok(stored) => assert_eq!(stored.body, body, "step {step}"),
3218 Err(StoreError::NotFound) => {
3219 assert!(result.is_err(), "acknowledged, then lost, at step {step}")
3220 }
3221 other => panic!("half a vCon at step {step}: {other:?}"),
3222 }
3223 assert_whole(&f, step);
3224 }
3225 }
3226
3227 #[test]
3228 fn a_create_cut_off_between_its_file_and_its_commit_leaves_nothing() {
3229 let mut f = fixture();
3230 let (found, body) = vcon(UUID, "first");
3231 die_before_commit(&f);
3232 assert!(f.store.create(&f.caller, &found, &body).is_err());
3233 restart(&mut f);
3234 assert_eq!(
3235 f.store.get(&f.caller, found.uuid),
3236 Err(StoreError::NotFound)
3237 );
3238 assert_whole(&f, WRITE_STEPS);
3239 }
3240
3241 #[test]
3242 fn a_replace_cut_off_at_any_step_leaves_the_old_version_or_the_new() {
3243 let (found, old_body) = vcon(UUID, "first");
3244 let (_, new_body) = vcon(UUID, "second");
3245 let uncut = {
3246 let f = fixture();
3247 let Ok(Created::New(old)) = f.store.create(&f.caller, &found, &old_body) else {
3248 panic!("stored")
3249 };
3250 let ops = f.fs.log().len();
3251 f.store
3252 .replace(&f.caller, old, &found, &new_body)
3253 .expect("replaced");
3254 f.fs.log()[ops..].to_vec()
3255 };
3256 assert_eq!(
3257 uncut.len(),
3258 REPLACE_STEPS,
3259 "every step of a replace: {uncut:?}"
3260 );
3261 let last_sync = uncut
3262 .iter()
3263 .rposition(|op| matches!(op, Op::SyncData(_)))
3264 .expect("the final commit syncs");
3265 for step in 0..=REPLACE_STEPS {
3266 let mut f = fixture();
3267 let Ok(Created::New(old)) = f.store.create(&f.caller, &found, &old_body) else {
3268 panic!("stored")
3269 };
3270 f.fs.fail_from(f.fs.log().len() + step);
3271 let result = f.store.replace(&f.caller, old, &found, &new_body);
3272 assert_eq!(
3273 result.is_ok(),
3274 step == REPLACE_STEPS,
3275 "step {step}: {result:?}"
3276 );
3277 assert_poisoned_at_a_sync(&f, &uncut, step, result.map(|_| ()));
3278 restart(&mut f);
3279 let stored = f
3280 .store
3281 .get(&f.caller, found.uuid)
3282 .unwrap_or_else(|e| panic!("step {step}: {e:?}"));
3283 match result {
3284 Ok(new) => assert_eq!(
3285 (stored.version, stored.body),
3286 (new, new_body.clone()),
3287 "step {step}"
3288 ),
3289 Err(_) if step == last_sync && stored.version != old => {
3293 assert_eq!(stored.body, new_body, "step {step}: the new version whole")
3294 }
3295 Err(_) => assert_eq!(
3296 (stored.version, stored.body),
3297 (old, old_body.clone()),
3298 "step {step}"
3299 ),
3300 }
3301 assert_whole(&f, step);
3302 }
3303 }
3304
3305 #[test]
3306 fn a_replace_cut_off_between_its_file_and_its_commit_keeps_the_old_version() {
3307 let mut f = fixture();
3308 let (found, old) = stored(&f, "first");
3309 let (_, newer) = vcon(UUID, "second");
3310 die_before_commit(&f);
3311 assert!(f.store.replace(&f.caller, old, &found, &newer).is_err());
3312 restart(&mut f);
3313 assert_eq!(
3314 f.store.get(&f.caller, found.uuid).expect("reads").version,
3315 old
3316 );
3317 assert_eq!(hidden_versions(&f), 0);
3318 assert_whole(&f, WRITE_STEPS);
3319 }
3320
3321 #[test]
3322 fn a_delete_cut_off_before_its_commit_leaves_the_vcon_live() {
3323 let mut f = fixture();
3324 let (found, version) = stored(&f, "first");
3325 let other = second_connection(&f);
3326 other
3327 .execute_batch(
3328 "CREATE TRIGGER dead BEFORE INSERT ON audit
3329 BEGIN SELECT RAISE(ABORT, 'the process has died'); END;",
3330 )
3331 .expect("trigger");
3332 assert!(
3333 f.store
3334 .delete(&f.caller, found.uuid, Retention::Years(7))
3335 .is_err()
3336 );
3337 drop(other);
3338 restart(&mut f);
3339 assert_eq!(
3340 f.store
3341 .get(&f.caller, found.uuid)
3342 .expect("still live")
3343 .version,
3344 version
3345 );
3346 assert_eq!(hidden_versions(&f), 0);
3347 }
3348
3349 fn last_record(f: &Fixture) -> (String, Value, Value, Value) {
3351 let log = audit_log(&f.store);
3352 let last = log.last().expect("a record");
3353 (
3354 last["action"].as_str().expect("an action").to_owned(),
3355 last["status"].clone(),
3356 last["version"].clone(),
3357 last["target"].clone(),
3358 )
3359 }
3360
3361 #[test]
3362 fn a_reveal_reads_what_a_read_does_and_is_recorded_under_its_part() {
3363 let f = fixture();
3364 let (found, body) = vcon(UUID, "first");
3365 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
3366 panic!("a new vCon")
3367 };
3368 let read = f.store.get(&f.caller, found.uuid).expect("reads");
3369 for part in Part::ALL {
3370 let revealed = f.store.reveal(&f.caller, found.uuid, part).expect("reads");
3371 assert_eq!(revealed, read, "{part:?}");
3372 assert_eq!(
3373 last_record(&f),
3374 (
3375 format!("reveal_{}", part.name()),
3376 200.into(),
3377 version.to_string().into(),
3378 UUID.into()
3379 ),
3380 "{part:?}"
3381 );
3382 }
3383 }
3384
3385 #[test]
3386 fn a_reveal_of_a_uuid_never_stored_is_not_found_and_recorded_as_the_reveal() {
3387 let f = fixture();
3388 let (found, _) = vcon(UUID, "first");
3389 assert_eq!(
3390 f.store.reveal(&f.caller, found.uuid, Part::Dialog),
3391 Err(StoreError::NotFound),
3392 "the answer"
3393 );
3394 assert_eq!(
3395 last_record(&f),
3396 (
3397 "reveal_dialog".to_owned(),
3398 404.into(),
3399 Value::Null,
3400 UUID.into()
3401 ),
3402 "the record"
3403 );
3404 }
3405
3406 #[test]
3407 fn a_reveal_of_a_deleted_vcon_is_gone_and_recorded_as_the_reveal() {
3408 let f = fixture();
3409 let (found, body) = vcon(UUID, "first");
3410 f.store.create(&f.caller, &found, &body).expect("stored");
3411 f.store
3412 .delete(&f.caller, found.uuid, Retention::Years(7))
3413 .expect("deleted");
3414 assert_eq!(
3415 f.store.reveal(&f.caller, found.uuid, Part::Parties),
3416 Err(StoreError::Gone),
3417 "the answer"
3418 );
3419 assert_eq!(
3420 last_record(&f),
3421 (
3422 "reveal_parties".to_owned(),
3423 410.into(),
3424 Value::Null,
3425 UUID.into()
3426 ),
3427 "the record"
3428 );
3429 }
3430
3431 #[test]
3432 fn a_reveal_of_a_version_whose_file_is_missing_is_damage_recorded_as_the_reveal() {
3433 let f = fixture();
3434 let (found, body) = vcon(UUID, "first");
3435 let Ok(Created::New(version)) = f.store.create(&f.caller, &found, &body) else {
3436 panic!("a new vCon")
3437 };
3438 f.fs.remove(&f.store.objects_dir.join(version.to_string()))
3439 .expect("remove");
3440 assert_eq!(
3441 f.store.reveal(&f.caller, found.uuid, Part::All),
3442 Err(StoreError::Damaged),
3443 "the answer"
3444 );
3445 assert_eq!(
3446 last_record(&f),
3447 (
3448 "reveal_all".to_owned(),
3449 500.into(),
3450 version.to_string().into(),
3451 UUID.into()
3452 ),
3453 "the record"
3454 );
3455 }
3456
3457 #[test]
3460 fn a_read_before_and_after_a_reveal_is_still_recorded_as_a_read() {
3461 let f = fixture();
3462 let (found, body) = vcon(UUID, "first");
3463 f.store.create(&f.caller, &found, &body).expect("stored");
3464 f.store.get(&f.caller, found.uuid).expect("reads");
3465 f.store
3466 .reveal(&f.caller, found.uuid, Part::Subject)
3467 .expect("reads");
3468 f.store.get(&f.caller, found.uuid).expect("reads");
3469 let actions: Vec<String> = audit_log(&f.store)
3470 .iter()
3471 .map(|r| r["action"].as_str().expect("an action").to_owned())
3472 .collect();
3473 assert_eq!(
3474 actions,
3475 ["create", "read", "reveal_subject", "read"],
3476 "the record"
3477 );
3478 }
3479}