| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The `format` file: which ids a store's objects have, and which storage |
| 5 | //! version its files follow (format spec, section 7). |
| 6 | //! |
| 7 | //! ```text |
| 8 | //! object-format=blake3-dk-v1 |
| 9 | //! storage=2 |
| 10 | //! ``` |
| 11 | //! |
| 12 | //! The first line names the object ids. The second is the storage version: |
| 13 | //! what a reader must understand to use the store. A store without it has |
| 14 | //! storage version 1: records stored whole (codecs 0 and 1), which every |
| 15 | //! version of braid reads. Version 2 adds deltas (codec 3) and chunked |
| 16 | //! blobs (codec 4). Version 3 adds indexes of version 2, whose entries carry |
| 17 | //! their own checksums, and merged indexes, which take the place of the |
| 18 | //! indexes they merge, so that a sealed segment may have no index of its |
| 19 | //! own. Versions of braid from before storage versions compare the whole |
| 20 | //! file with the first line, so they refuse a store of version 2 or later, |
| 21 | //! and this version refuses any version after 3, and any line it does not |
| 22 | //! know. |
| 23 | //! |
| 24 | //! New stores start at the current version. An older store is raised only |
| 25 | //! when a writer is about to append its first record of codec 3 or 4 (to |
| 26 | //! 2), or to write its first index of version 2 (to 3), or when a handle |
| 27 | //! finds records that need a later version already there. The file is |
| 28 | //! rewritten through a temporary file and a rename, under an exclusive lock |
| 29 | //! on `format.lock`, after reading it again: a store is never lowered, and |
| 30 | //! its new version reaches the disk before anything that needs it. |
| 31 | |
| 32 | use std::fs::{self, OpenOptions}; |
| 33 | use std::io; |
| 34 | use std::path::Path; |
| 35 | |
| 36 | use crate::error::{Error, io_error}; |
| 37 | use crate::fsutil::publish_file; |
| 38 | use crate::{Durability, OBJECT_FORMAT, STORAGE_VERSION}; |
| 39 | |
| 40 | /// The bytes of the `format` file of a store of storage `version`. |
| 41 | pub(crate) fn contents(version: u32) -> String { |
| 42 | if version <= 1 { |
| 43 | format!("{OBJECT_FORMAT}\n") |
| 44 | } else { |
| 45 | format!("{OBJECT_FORMAT}\nstorage={version}\n") |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// The storage version of the store at `root`. Refuses a directory that is |
| 50 | /// not a store, a store whose objects have other ids, and a store that |
| 51 | /// needs a newer version of braid. |
| 52 | pub(crate) fn read(root: &Path) -> Result<u32, Error> { |
| 53 | let path = root.join("format"); |
| 54 | let bytes = match fs::read(&path) { |
| 55 | Ok(bytes) => bytes, |
| 56 | Err(err) if err.kind() == io::ErrorKind::NotFound => { |
| 57 | return Err(Error::NotAStore { |
| 58 | path: root.to_path_buf(), |
| 59 | }); |
| 60 | } |
| 61 | Err(err) => return Err(io_error("read", &path)(err)), |
| 62 | }; |
| 63 | let unsupported = || Error::UnsupportedFormat { |
| 64 | found: String::from_utf8_lossy(&bytes).trim_end().to_owned(), |
| 65 | }; |
| 66 | let text = std::str::from_utf8(&bytes).map_err(|_| unsupported())?; |
| 67 | let mut lines = text.strip_suffix('\n').unwrap_or(text).split('\n'); |
| 68 | if lines.next() != Some(OBJECT_FORMAT) { |
| 69 | return Err(unsupported()); |
| 70 | } |
| 71 | let version = match lines.next() { |
| 72 | None => 1, |
| 73 | Some(line) => line |
| 74 | .strip_prefix("storage=") |
| 75 | .filter(|digits| { |
| 76 | !digits.is_empty() |
| 77 | && !digits.starts_with('0') |
| 78 | && digits.bytes().all(|b| b.is_ascii_digit()) |
| 79 | }) |
| 80 | .and_then(|digits| digits.parse::<u32>().ok()) |
| 81 | .ok_or_else(unsupported)?, |
| 82 | }; |
| 83 | if lines.next().is_some() { |
| 84 | return Err(unsupported()); |
| 85 | } |
| 86 | if version > STORAGE_VERSION { |
| 87 | return Err(Error::NewerStore { |
| 88 | path, |
| 89 | detail: format!( |
| 90 | "it has storage version {version}, and this version reads versions up to \ |
| 91 | {STORAGE_VERSION}" |
| 92 | ), |
| 93 | }); |
| 94 | } |
| 95 | Ok(version) |
| 96 | } |
| 97 | |
| 98 | /// Raises the storage version of the store at `root` to at least `version`, |
| 99 | /// under the lock that every writer takes to change it. Fails, changing |
| 100 | /// nothing, if the store needs a newer version of braid by now. |
| 101 | pub(crate) fn raise(root: &Path, version: u32, durability: Durability) -> Result<(), Error> { |
| 102 | let lock_path = root.join("format.lock"); |
| 103 | let lock = OpenOptions::new() |
| 104 | .write(true) |
| 105 | .create(true) |
| 106 | .truncate(false) |
| 107 | .open(&lock_path) |
| 108 | .map_err(io_error("create", &lock_path))?; |
| 109 | lock.lock().map_err(io_error("lock", &lock_path))?; |
| 110 | if read(root)? < version { |
| 111 | publish_file( |
| 112 | root, |
| 113 | "format", |
| 114 | contents(version).as_bytes(), |
| 115 | durability, |
| 116 | &[], |
| 117 | )?; |
| 118 | } |
| 119 | Ok(()) |
| 120 | } |
| 121 | |
| 122 | #[cfg(test)] |
| 123 | mod tests { |
| 124 | use super::*; |
| 125 | |
| 126 | fn read_text(text: &str) -> Result<u32, Error> { |
| 127 | let dir = tempfile::tempdir().unwrap(); |
| 128 | fs::write(dir.path().join("format"), text).unwrap(); |
| 129 | read(dir.path()) |
| 130 | } |
| 131 | |
| 132 | #[test] |
| 133 | fn versions_are_read_and_written() { |
| 134 | assert_eq!(read_text(&contents(1)).unwrap(), 1); |
| 135 | assert_eq!(read_text(&contents(2)).unwrap(), 2); |
| 136 | assert_eq!(read_text(&contents(3)).unwrap(), 3); |
| 137 | assert_eq!(contents(1), "object-format=blake3-dk-v1\n"); |
| 138 | assert_eq!(contents(2), "object-format=blake3-dk-v1\nstorage=2\n"); |
| 139 | assert_eq!(contents(3), "object-format=blake3-dk-v1\nstorage=3\n"); |
| 140 | // Without the final newline too. |
| 141 | assert_eq!( |
| 142 | read_text("object-format=blake3-dk-v1\nstorage=2").unwrap(), |
| 143 | 2 |
| 144 | ); |
| 145 | } |
| 146 | |
| 147 | #[test] |
| 148 | fn newer_versions_and_unknown_lines_are_refused() { |
| 149 | let err = read_text("object-format=blake3-dk-v1\nstorage=4\n").unwrap_err(); |
| 150 | assert!(matches!(err, Error::NewerStore { .. }), "{err}"); |
| 151 | assert!(err.to_string().contains("storage version 4"), "{err}"); |
| 152 | for bad in [ |
| 153 | "object-format=sha1\n", |
| 154 | "object-format=blake3-dk-v1\nstorage=\n", |
| 155 | "object-format=blake3-dk-v1\nstorage=02\n", |
| 156 | "object-format=blake3-dk-v1\nstorage=two\n", |
| 157 | "object-format=blake3-dk-v1\nstorage=2\nmore=1\n", |
| 158 | "object-format=blake3-dk-v1\nchunks=yes\n", |
| 159 | "", |
| 160 | ] { |
| 161 | assert!( |
| 162 | matches!(read_text(bad), Err(Error::UnsupportedFormat { .. })), |
| 163 | "{bad:?}" |
| 164 | ); |
| 165 | } |
| 166 | let dir = tempfile::tempdir().unwrap(); |
| 167 | assert!(matches!(read(dir.path()), Err(Error::NotAStore { .. }))); |
| 168 | } |
| 169 | |
| 170 | #[test] |
| 171 | fn raising_never_lowers() { |
| 172 | let dir = tempfile::tempdir().unwrap(); |
| 173 | let path = dir.path().join("format"); |
| 174 | fs::write(&path, contents(1)).unwrap(); |
| 175 | raise(dir.path(), 2, Durability::Ordered).unwrap(); |
| 176 | assert_eq!(fs::read_to_string(&path).unwrap(), contents(2)); |
| 177 | raise(dir.path(), 1, Durability::Ordered).unwrap(); |
| 178 | assert_eq!(fs::read_to_string(&path).unwrap(), contents(2)); |
| 179 | raise(dir.path(), 3, Durability::Full).unwrap(); |
| 180 | assert_eq!(fs::read_to_string(&path).unwrap(), contents(3)); |
| 181 | // A store that went past this version is left alone. |
| 182 | fs::write(&path, "object-format=blake3-dk-v1\nstorage=9\n").unwrap(); |
| 183 | assert!(matches!( |
| 184 | raise(dir.path(), 2, Durability::Ordered), |
| 185 | Err(Error::NewerStore { .. }) |
| 186 | )); |
| 187 | assert_eq!( |
| 188 | fs::read_to_string(&path).unwrap(), |
| 189 | "object-format=blake3-dk-v1\nstorage=9\n" |
| 190 | ); |
| 191 | } |
| 192 | } |