1mod disk;
44mod lease;
45mod manifest;
46pub(crate) mod record;
47mod snapshot;
48pub mod workspace;
49mod writer;
50
51#[cfg(test)]
52mod model;
53#[cfg(test)]
54mod tests;
55
56use std::fs::OpenOptions;
57use std::io;
58use std::path::{Path, PathBuf};
59use std::sync::{Arc, Mutex};
60
61pub use disk::{DiskUsage, DiskUsageStop, measure_disk_usage};
62pub use manifest::{Manifest, SegmentEntry, StateRef};
63pub use snapshot::Snapshot;
64pub use writer::{
65 BuildScratch, PendingSegment, Publication, ReclaimOutcome, ReclaimReport, Reclaimed,
66 ScratchClaim, ScratchDir, WriteSession, reclaim_dead_workspaces,
67};
68
69use crate::ids::{CheckoutId, FamilyId, Generation, SegmentId};
70use crate::segment::SegmentError;
71use lease::Owner;
72use record::{Kind, RecordError};
73
74#[derive(Debug, thiserror::Error)]
76pub enum FamilyError {
77 #[error("{}: {source}", path.display())]
78 Io {
79 path: PathBuf,
80 #[source]
81 source: io::Error,
82 },
83 #[error("{}: {reason}", path.display())]
85 Foreign { path: PathBuf, reason: String },
86 #[error("{}: {reason}", path.display())]
88 Damaged { path: PathBuf, reason: String },
89 #[error(transparent)]
95 NewerFormat(NewerFormat),
96 #[error(transparent)]
99 Segment(SegmentError),
100 #[error(
101 "no snapshot after {0} tries: each generation read was reclaimed before its lease took hold"
102 )]
103 SnapshotRetries(u32),
104 #[error(
105 "this write session failed while publishing and cannot publish again; start a new session"
106 )]
107 Poisoned,
108 #[error("{0}")]
109 Misuse(&'static str),
110 #[error("{0}")]
113 CheckoutBusy(&'static str),
114}
115
116impl FamilyError {
117 #[must_use]
131 pub fn is_unusable_file(&self) -> bool {
132 match self {
133 Self::Foreign { .. } | Self::Damaged { .. } => true,
134 Self::Segment(error) => {
135 error.is_corruption()
136 || match error.kind() {
137 crate::segment::ErrorKind::UnsupportedVersion { found, supported } => {
138 found < supported
139 }
140 crate::segment::ErrorKind::UnknownRequiredSection { .. }
141 | crate::segment::ErrorKind::NotASegment => true,
142 _ => false,
143 }
144 }
145 _ => false,
146 }
147 }
148
149 #[must_use]
152 pub fn newer_format(&self) -> Option<&NewerFormat> {
153 match self {
154 Self::NewerFormat(refusal) => Some(refusal),
155 _ => None,
156 }
157 }
158
159 fn io(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ {
160 move |source| Self::Io {
161 path: path.to_path_buf(),
162 source,
163 }
164 }
165
166 fn record(path: &Path, error: RecordError) -> Self {
167 match error {
168 RecordError::Io(source) => Self::Io {
169 path: path.to_path_buf(),
170 source,
171 },
172 RecordError::Invalid(reason) => Self::Damaged {
173 path: path.to_path_buf(),
174 reason: format!("the record's bytes do not check ({reason})"),
175 },
176 RecordError::UnsupportedVersion { found, supported }
177 | RecordError::NewerPayload { found, supported }
178 if found > supported =>
179 {
180 Self::NewerFormat(NewerFormat {
181 path: path.to_path_buf(),
182 file: FileKind::Record,
183 found,
184 supported,
185 })
186 }
187 foreign => Self::Foreign {
188 path: path.to_path_buf(),
189 reason: foreign.to_string(),
190 },
191 }
192 }
193}
194
195impl From<SegmentError> for FamilyError {
196 fn from(error: SegmentError) -> Self {
197 match NewerFormat::of_segment(&error) {
198 Some(refusal) => Self::NewerFormat(refusal),
199 None => Self::Segment(error),
200 }
201 }
202}
203
204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub enum FileKind {
207 Record,
209 Segment,
211}
212
213#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct NewerFormat {
219 pub path: PathBuf,
220 pub file: FileKind,
221 pub found: u16,
223 pub supported: u16,
225}
226
227impl NewerFormat {
228 #[must_use]
231 pub fn of_segment(error: &SegmentError) -> Option<Self> {
232 match *error.kind() {
233 crate::segment::ErrorKind::UnsupportedVersion { found, supported }
234 if found > supported =>
235 {
236 Some(Self {
237 path: error.path().to_path_buf(),
238 file: FileKind::Segment,
239 found,
240 supported,
241 })
242 }
243 _ => None,
244 }
245 }
246}
247
248impl std::fmt::Display for NewerFormat {
249 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250 let kind = match self.file {
253 FileKind::Record => "",
254 FileKind::Segment => "segment ",
255 };
256 write!(
257 f,
258 "{}: {kind}format version {} is not supported; this build reads version {}",
259 self.path.display(),
260 self.found,
261 self.supported
262 )
263 }
264}
265
266impl std::error::Error for NewerFormat {}
267
268#[derive(Debug)]
270pub struct Family {
271 layout: Layout,
272 id: FamilyId,
273 owner: Mutex<Option<Arc<Owner>>>,
274}
275
276impl Family {
277 pub fn open(dir: &Path, id: FamilyId) -> Result<Self, FamilyError> {
283 let layout = Layout::new(dir);
284 for sub in [
285 layout.dir.clone(),
286 layout.segments_dir(),
287 layout.tmp_dir(),
288 layout.checkouts_dir(),
289 layout.leases_dir(),
290 layout.incoming_dir(),
291 ] {
292 std::fs::create_dir_all(&sub).map_err(FamilyError::io(&sub))?;
293 }
294 Ok(Self {
295 layout,
296 id,
297 owner: Mutex::new(None),
298 })
299 }
300
301 #[must_use]
302 pub const fn id(&self) -> FamilyId {
303 self.id
304 }
305
306 #[must_use]
307 pub fn dir(&self) -> &Path {
308 &self.layout.dir
309 }
310
311 pub fn snapshot(&self) -> Result<Snapshot, FamilyError> {
321 snapshot::take(self)
322 }
323
324 pub fn newest_generation(&self) -> Result<Generation, FamilyError> {
334 self.newest_manifest()
335 .map(|(manifest, _)| manifest.generation())
336 }
337
338 pub fn has_manifest_above(&self, generation: Generation) -> Result<bool, FamilyError> {
350 let dir = &self.layout.dir;
351 for entry in std::fs::read_dir(dir).map_err(FamilyError::io(dir))? {
352 let name = entry.map_err(FamilyError::io(dir))?.file_name();
353 if name
354 .to_str()
355 .and_then(|name| name.strip_prefix(MANIFEST_PREFIX))
356 .and_then(canonical_number)
357 .is_some_and(|number| number > generation.get())
358 {
359 return Ok(true);
360 }
361 }
362 Ok(false)
363 }
364
365 pub fn try_write(&self) -> Result<Option<WriteSession<'_>>, FamilyError> {
375 let path = self.layout.writer_lock();
376 let mut options = OpenOptions::new();
377 options.read(true).write(true).create(true).truncate(false);
378 #[cfg(unix)]
379 {
380 use std::os::unix::fs::OpenOptionsExt;
381 options.mode(0o600);
382 }
383 let lock = options.open(&path).map_err(FamilyError::io(&path))?;
384 match lock.try_lock() {
385 Ok(()) => WriteSession::start(self, lock).map(Some),
386 Err(std::fs::TryLockError::WouldBlock) => Ok(None),
387 Err(std::fs::TryLockError::Error(error)) => Err(FamilyError::io(&path)(error)),
388 }
389 }
390
391 pub fn check_formats(&self) -> Result<(), FamilyError> {
405 let (manifest, _) = self.newest_manifest()?;
406 self.check_named_formats(&manifest)
407 }
408
409 fn check_named_formats(&self, manifest: &Manifest) -> Result<(), FamilyError> {
412 for entry in manifest.segments() {
413 if let Some(error) = crate::segment::newer_version(&self.layout.segment(entry.id)) {
414 return Err(error.into());
415 }
416 }
417 for state in manifest.checkouts() {
418 let path = self.layout.state(state.checkout, state.number);
419 if let Some(error) = record::newer_version(&path, Kind::State, self.id, state.number)
420 .or_else(|| crate::checkout::newer_state_format(&path, self.id, state.number))
421 {
422 return Err(FamilyError::record(&path, error));
423 }
424 }
425 Ok(())
426 }
427
428 fn owner(&self) -> Result<Arc<Owner>, FamilyError> {
430 let mut owner = self
431 .owner
432 .lock()
433 .unwrap_or_else(std::sync::PoisonError::into_inner);
434 if let Some(owner) = owner.as_ref() {
435 return Ok(owner.clone());
436 }
437 let created = Arc::new(Owner::create(&self.layout)?);
438 *owner = Some(created.clone());
439 Ok(created)
440 }
441
442 fn newest_manifest(&self) -> Result<(Manifest, usize), FamilyError> {
447 for _ in 0..snapshot::MAX_TRIES {
448 if let Some(found) = self.list_newest_manifest()? {
449 return Ok(found);
450 }
451 }
452 Err(FamilyError::SnapshotRetries(snapshot::MAX_TRIES))
453 }
454
455 fn list_newest_manifest(&self) -> Result<Option<(Manifest, usize)>, FamilyError> {
459 let mut skipped = 0;
460 let mut vanished = false;
461 let listed = numbered_desc(&self.layout.dir, MANIFEST_PREFIX)?;
462 #[cfg(test)]
463 tests::AFTER_MANIFEST_LIST.with(|slot| {
464 let callback = slot.borrow_mut().take();
465 if let Some(callback) = callback {
466 callback();
467 }
468 });
469 for (number, path) in listed {
470 match record::read(&path, Kind::Manifest, self.id, number) {
471 Ok(payload) => match Manifest::decode(Generation::new(number), &payload) {
472 Ok(manifest) => return Ok(Some((manifest, skipped))),
473 Err(RecordError::Invalid(_)) => skipped += 1,
474 Err(error) => return Err(FamilyError::record(&path, error)),
475 },
476 Err(RecordError::Invalid(_)) => skipped += 1,
477 Err(RecordError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
478 vanished = true;
479 }
480 Err(error) => return Err(FamilyError::record(&path, error)),
481 }
482 }
483 Ok((!vanished).then(|| (Manifest::empty(), skipped)))
484 }
485
486 fn newest_horizon(&self) -> Result<Option<(u64, Generation)>, FamilyError> {
488 for (number, path) in numbered_desc(&self.layout.dir, HORIZON_PREFIX)? {
489 match read_horizon(&path, self.id, number) {
490 Ok(horizon) => return Ok(Some((number, horizon))),
491 Err(RecordError::Invalid(_)) => {}
492 Err(RecordError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {}
493 Err(error) => return Err(FamilyError::record(&path, error)),
494 }
495 }
496 Ok(None)
497 }
498}
499
500const MANIFEST_PREFIX: &str = "MANIFEST-";
501const HORIZON_PREFIX: &str = "HORIZON-";
502const STATE_PREFIX: &str = "STATE-";
503
504fn read_horizon(path: &Path, family: FamilyId, number: u64) -> Result<Generation, RecordError> {
505 let payload = record::read(path, Kind::Horizon, family, number)?;
506 let mut input = record::Payload::new(&payload);
507 let generation = Generation::new(input.u64()?);
508 input.finish()?;
509 Ok(generation)
510}
511
512#[derive(Clone, Debug)]
514struct Layout {
515 dir: PathBuf,
516}
517
518impl Layout {
519 fn new(dir: &Path) -> Self {
520 Self {
521 dir: dir.to_path_buf(),
522 }
523 }
524
525 fn writer_lock(&self) -> PathBuf {
526 self.dir.join("writer.lock")
527 }
528
529 fn manifest(&self, generation: Generation) -> PathBuf {
530 self.dir.join(format!("{MANIFEST_PREFIX}{generation}"))
531 }
532
533 fn horizon(&self, number: u64) -> PathBuf {
534 self.dir.join(format!("{HORIZON_PREFIX}{number}"))
535 }
536
537 fn segments_dir(&self) -> PathBuf {
538 self.dir.join("segments")
539 }
540
541 fn segment(&self, id: SegmentId) -> PathBuf {
542 self.segments_dir().join(format!("{id}.seg"))
543 }
544
545 fn tmp_dir(&self) -> PathBuf {
546 self.dir.join("tmp")
547 }
548
549 fn tmp_segment(&self, id: SegmentId) -> PathBuf {
550 self.tmp_dir().join(format!("{id}.seg"))
551 }
552
553 fn checkouts_dir(&self) -> PathBuf {
554 self.dir.join("checkouts")
555 }
556
557 fn checkout_dir(&self, checkout: CheckoutId) -> PathBuf {
558 self.checkouts_dir().join(checkout.to_string())
559 }
560
561 fn state(&self, checkout: CheckoutId, number: u64) -> PathBuf {
562 self.checkout_dir(checkout)
563 .join(format!("{STATE_PREFIX}{number}"))
564 }
565
566 fn leases_dir(&self) -> PathBuf {
567 self.dir.join("leases")
568 }
569
570 fn incoming_dir(&self) -> PathBuf {
571 self.dir.join("incoming")
572 }
573}
574
575fn numbered_desc(dir: &Path, prefix: &str) -> Result<Vec<(u64, PathBuf)>, FamilyError> {
579 let mut found = Vec::new();
580 for entry in std::fs::read_dir(dir).map_err(FamilyError::io(dir))? {
581 let entry = entry.map_err(FamilyError::io(dir))?;
582 let name = entry.file_name();
583 let Some(number) = name
584 .to_str()
585 .and_then(|name| name.strip_prefix(prefix))
586 .and_then(canonical_number)
587 else {
588 continue;
589 };
590 found.push((number, entry.path()));
591 }
592 found.sort_by_key(|(number, _)| std::cmp::Reverse(*number));
593 Ok(found)
594}
595
596fn canonical_number(text: &str) -> Option<u64> {
598 let number = text.parse::<u64>().ok()?;
599 (number.to_string() == text).then_some(number)
600}
601
602fn names_with_suffix(dir: &Path, suffix: &str) -> Result<Vec<(String, PathBuf)>, FamilyError> {
604 let mut found = Vec::new();
605 for entry in std::fs::read_dir(dir).map_err(FamilyError::io(dir))? {
606 let entry = entry.map_err(FamilyError::io(dir))?;
607 if let Some(stem) = entry
608 .file_name()
609 .to_str()
610 .and_then(|name| name.strip_suffix(suffix))
611 {
612 found.push((stem.to_string(), entry.path()));
613 }
614 }
615 Ok(found)
616}
617
618crate::heap_bytes_of_fields!(Layout { dir });
619crate::heap_bytes_none!(FileKind);
620crate::heap_bytes_of_fields!(NewerFormat {
621 path,
622 file,
623 found,
624 supported,
625});