recern_vector/
database.rs1use crate::collection::{Collection, CollectionConfig};
2use crate::error::{Error, Result};
3use crate::{storage, wal};
4use std::collections::BTreeMap;
5use std::fs::{self, File, OpenOptions};
6use std::io::Write;
7use std::path::{Path, PathBuf};
8use std::sync::Mutex;
9
10pub struct Database {
14 path: PathBuf,
15 collections: BTreeMap<String, Collection>,
16 persistence: Mutex<Vec<u8>>,
17 read_only: bool,
18}
19struct Lock(File);
20impl Lock {
21 fn write(path: &Path) -> Result<Self> {
22 let file = OpenOptions::new()
23 .create(true)
24 .truncate(false)
25 .read(true)
26 .write(true)
27 .open(wal::sidecar(path, ".lock"))?;
28 file.lock()?;
29 Ok(Self(file))
30 }
31 fn read(path: &Path) -> Result<Option<Self>> {
32 match File::open(wal::sidecar(path, ".lock")) {
33 Ok(file) => {
34 file.lock_shared()?;
35 Ok(Some(Self(file)))
36 }
37 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
38 Err(e) => Err(e.into()),
39 }
40 }
41}
42impl Drop for Lock {
43 fn drop(&mut self) {
44 let _ = self.0.unlock();
45 }
46}
47
48impl Database {
49 pub fn create(path: impl AsRef<Path>) -> Result<Self> {
50 let path = absolute(path.as_ref())?;
51 let _lock = Lock::write(&path)?;
52 if path.exists() {
53 return Err(Error::FileExists(path));
54 }
55 if wal::sidecar(&path, ".wal").exists() {
56 return Err(Error::InvalidArgument(
57 "orphan WAL exists; recover or remove it before creating a database".into(),
58 ));
59 }
60 let collections = BTreeMap::new();
61 let bytes = storage::encode(&collections, identity(), 0);
62 atomic_snapshot(&path, &bytes)?;
63 Ok(Self {
64 path,
65 collections,
66 persistence: Mutex::new(bytes),
67 read_only: false,
68 })
69 }
70 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
71 Self::load(path.as_ref(), false)
72 }
73 pub fn open_read_only(path: impl AsRef<Path>) -> Result<Self> {
76 Self::load(path.as_ref(), true)
77 }
78 fn load(path: &Path, read_only: bool) -> Result<Self> {
79 let path = fs::canonicalize(path)?;
80 let _lock = if read_only {
81 Lock::read(&path)?
82 } else {
83 Some(Lock::write(&path)?)
84 };
85 let loaded = wal::load(&path)?;
86 let collections = storage::decode(&loaded.bytes)?;
87 Ok(Self {
88 path,
89 collections,
90 persistence: Mutex::new(loaded.bytes),
91 read_only,
92 })
93 }
94 pub fn open_or_create(path: impl AsRef<Path>) -> Result<Self> {
95 match Self::open(&path) {
96 Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {
97 match Self::create(&path) {
98 Err(Error::FileExists(_)) => Self::open(path),
99 result => result,
100 }
101 }
102 result => result,
103 }
104 }
105 pub fn format_version(&self) -> u32 {
107 let bytes = self
108 .persistence
109 .lock()
110 .unwrap_or_else(std::sync::PoisonError::into_inner);
111 u32::from_le_bytes(bytes[4..8].try_into().expect("validated header"))
112 }
113 pub fn is_read_only(&self) -> bool {
114 self.read_only
115 }
116 fn writable(&self) -> Result<()> {
117 if self.read_only {
118 Err(Error::InvalidArgument("database is read-only".into()))
119 } else {
120 Ok(())
121 }
122 }
123 pub fn path(&self) -> &Path {
124 &self.path
125 }
126
127 pub fn create_collection(
128 &mut self,
129 name: &str,
130 config: CollectionConfig,
131 ) -> Result<&mut Collection> {
132 self.writable()?;
133 if name.is_empty() || name.len() > 255 {
134 return Err(Error::InvalidArgument(
135 "collection name must be 1-255 bytes".into(),
136 ));
137 }
138 if self.collections.contains_key(name) {
139 return Err(Error::CollectionExists(name.to_owned()));
140 }
141 let collection = Collection::new(name, config)?;
142 Ok(self
143 .collections
144 .entry(name.to_owned())
145 .or_insert(collection))
146 }
147
148 pub fn collection(&self, name: &str) -> Result<&Collection> {
149 self.collections
150 .get(name)
151 .ok_or_else(|| Error::CollectionNotFound(name.to_owned()))
152 }
153
154 pub fn collection_mut(&mut self, name: &str) -> Result<&mut Collection> {
155 self.writable()?;
156 self.collections
157 .get_mut(name)
158 .ok_or_else(|| Error::CollectionNotFound(name.to_owned()))
159 }
160
161 pub fn drop_collection(&mut self, name: &str) -> Result<()> {
162 self.writable()?;
163 self.collections
164 .remove(name)
165 .map(|_| ())
166 .ok_or_else(|| Error::CollectionNotFound(name.to_owned()))
167 }
168
169 pub fn collections(&self) -> impl Iterator<Item = &Collection> {
170 self.collections.values()
171 }
172
173 pub fn save(&self) -> Result<()> {
176 self.persist(false)
177 }
178 pub fn checkpoint(&self) -> Result<()> {
181 self.persist(true)
182 }
183 fn persist(&self, checkpoint: bool) -> Result<()> {
184 self.writable()?;
185 let mut previous = self
186 .persistence
187 .lock()
188 .map_err(|_| Error::InvalidArgument("persistence lock poisoned".into()))?;
189 let _lock = Lock::write(&self.path)?;
190 let disk = wal::load(&self.path)?;
191 if disk.bytes != *previous {
192 return Err(Error::InvalidArgument(
193 "database changed in another handle; reopen before writing".into(),
194 ));
195 }
196 let (mut id, seq) = storage::header(&previous);
197 let migrate = id == 0;
198 if migrate {
199 id = identity();
200 }
201 let unchanged = storage::encode(&self.collections, id, seq) == *previous;
202 if unchanged && !checkpoint {
203 return Ok(());
204 }
205 let next = if unchanged {
206 seq
207 } else {
208 seq.checked_add(1)
209 .ok_or_else(|| Error::InvalidArgument("commit sequence exhausted".into()))?
210 };
211 let bytes = storage::encode(&self.collections, id, next);
212 if checkpoint || migrate {
213 atomic_snapshot(&self.path, &bytes)?;
214 *previous = bytes;
217 atomic_snapshot(&wal::sidecar(&self.path, ".wal"), &wal::header(id))?;
218 sync_parent_dir(&self.path);
219 } else {
220 let frame = wal::frame(&previous, &bytes, next);
221 wal::append(&self.path, disk.wal_len, id, &frame)?;
222 *previous = bytes;
223 }
224 Ok(())
225 }
226}
227fn absolute(path: &Path) -> Result<PathBuf> {
228 if path.exists() {
229 return Ok(fs::canonicalize(path)?);
230 }
231 let parent = path
232 .parent()
233 .filter(|p| !p.as_os_str().is_empty())
234 .unwrap_or(Path::new("."));
235 Ok(fs::canonicalize(parent)?.join(
236 path.file_name()
237 .ok_or_else(|| Error::InvalidArgument("file name required".into()))?,
238 ))
239}
240fn identity() -> u128 {
241 use std::sync::atomic::{AtomicU64, Ordering};
242 static NEXT: AtomicU64 = AtomicU64::new(1);
243 let time = std::time::SystemTime::now()
244 .duration_since(std::time::UNIX_EPOCH)
245 .unwrap_or_default()
246 .as_nanos();
247 time ^ ((std::process::id() as u128) << 64) ^ NEXT.fetch_add(1, Ordering::Relaxed) as u128
248}
249fn atomic_snapshot(path: &Path, bytes: &[u8]) -> Result<()> {
250 let tmp = wal::sidecar(path, &format!(".{}.tmp", identity()));
251 let result = (|| {
252 let mut file = OpenOptions::new().create_new(true).write(true).open(&tmp)?;
253 file.write_all(bytes)?;
254 file.sync_all()?;
255 fs::rename(&tmp, path)?;
256 sync_parent_dir(path);
257 Ok(())
258 })();
259 if result.is_err() {
260 let _ = fs::remove_file(tmp);
261 }
262 result
263}
264pub(crate) fn sync_parent_dir(path: &Path) {
265 let dir = path
266 .parent()
267 .filter(|p| !p.as_os_str().is_empty())
268 .unwrap_or(Path::new("."));
269 if let Ok(dir) = File::open(dir) {
270 let _ = dir.sync_all();
271 }
272}