Elffuss BraidHub

utopia-ia/elffuss-braid public

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