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
117 pub fn identity(&self) -> u128 {
120 let bytes = self
121 .persistence
122 .lock()
123 .unwrap_or_else(std::sync::PoisonError::into_inner);
124 storage::header(&bytes).0
125 }
126 fn writable(&self) -> Result<()> {
127 if self.read_only {
128 Err(Error::InvalidArgument("database is read-only".into()))
129 } else {
130 Ok(())
131 }
132 }
133 pub fn path(&self) -> &Path {
134 &self.path
135 }
136
137 pub fn create_collection(
138 &mut self,
139 name: &str,
140 config: CollectionConfig,
141 ) -> Result<&mut Collection> {
142 self.writable()?;
143 if name.is_empty() || name.len() > 255 {
144 return Err(Error::InvalidArgument(
145 "collection name must be 1-255 bytes".into(),
146 ));
147 }
148 if self.collections.contains_key(name) {
149 return Err(Error::CollectionExists(name.to_owned()));
150 }
151 let collection = Collection::new(name, config)?;
152 Ok(self
153 .collections
154 .entry(name.to_owned())
155 .or_insert(collection))
156 }
157
158 pub fn collection(&self, name: &str) -> Result<&Collection> {
159 self.collections
160 .get(name)
161 .ok_or_else(|| Error::CollectionNotFound(name.to_owned()))
162 }
163
164 pub fn collection_mut(&mut self, name: &str) -> Result<&mut Collection> {
165 self.writable()?;
166 self.collections
167 .get_mut(name)
168 .ok_or_else(|| Error::CollectionNotFound(name.to_owned()))
169 }
170
171 pub fn drop_collection(&mut self, name: &str) -> Result<()> {
172 self.writable()?;
173 self.collections
174 .remove(name)
175 .map(|_| ())
176 .ok_or_else(|| Error::CollectionNotFound(name.to_owned()))
177 }
178
179 pub fn collections(&self) -> impl Iterator<Item = &Collection> {
180 self.collections.values()
181 }
182
183 pub fn save(&self) -> Result<()> {
186 self.persist(false)
187 }
188 pub fn checkpoint(&self) -> Result<()> {
191 self.persist(true)
192 }
193 fn persist(&self, checkpoint: bool) -> Result<()> {
194 self.writable()?;
195 let mut previous = self
196 .persistence
197 .lock()
198 .map_err(|_| Error::InvalidArgument("persistence lock poisoned".into()))?;
199 let _lock = Lock::write(&self.path)?;
200 let disk = wal::load(&self.path)?;
201 if disk.bytes != *previous {
202 return Err(Error::InvalidArgument(
203 "database changed in another handle; reopen before writing".into(),
204 ));
205 }
206 let (mut id, seq) = storage::header(&previous);
207 let migrate = id == 0;
208 if migrate {
209 id = identity();
210 }
211 let unchanged = storage::encode(&self.collections, id, seq) == *previous;
212 if unchanged && !checkpoint {
213 return Ok(());
214 }
215 let next = if unchanged {
216 seq
217 } else {
218 seq.checked_add(1)
219 .ok_or_else(|| Error::InvalidArgument("commit sequence exhausted".into()))?
220 };
221 let bytes = storage::encode(&self.collections, id, next);
222 if checkpoint || migrate {
223 atomic_snapshot(&self.path, &bytes)?;
224 *previous = bytes;
227 atomic_snapshot(&wal::sidecar(&self.path, ".wal"), &wal::header(id))?;
228 sync_parent_dir(&self.path);
229 } else {
230 let frame = wal::frame(&previous, &bytes, next);
231 wal::append(&self.path, disk.wal_len, id, &frame)?;
232 *previous = bytes;
233 }
234 Ok(())
235 }
236}
237fn absolute(path: &Path) -> Result<PathBuf> {
238 if path.exists() {
239 return Ok(fs::canonicalize(path)?);
240 }
241 let parent = path
242 .parent()
243 .filter(|p| !p.as_os_str().is_empty())
244 .unwrap_or(Path::new("."));
245 Ok(fs::canonicalize(parent)?.join(
246 path.file_name()
247 .ok_or_else(|| Error::InvalidArgument("file name required".into()))?,
248 ))
249}
250fn identity() -> u128 {
251 use std::sync::atomic::{AtomicU64, Ordering};
252 static NEXT: AtomicU64 = AtomicU64::new(1);
253 let time = std::time::SystemTime::now()
254 .duration_since(std::time::UNIX_EPOCH)
255 .unwrap_or_default()
256 .as_nanos();
257 time ^ ((std::process::id() as u128) << 64) ^ NEXT.fetch_add(1, Ordering::Relaxed) as u128
258}
259fn atomic_snapshot(path: &Path, bytes: &[u8]) -> Result<()> {
260 let tmp = wal::sidecar(path, &format!(".{}.tmp", identity()));
261 let result = (|| {
262 let mut file = OpenOptions::new().create_new(true).write(true).open(&tmp)?;
263 file.write_all(bytes)?;
264 file.sync_all()?;
265 fs::rename(&tmp, path)?;
266 sync_parent_dir(path);
267 Ok(())
268 })();
269 if result.is_err() {
270 let _ = fs::remove_file(tmp);
271 }
272 result
273}
274pub(crate) fn sync_parent_dir(path: &Path) {
275 let dir = path
276 .parent()
277 .filter(|p| !p.as_os_str().is_empty())
278 .unwrap_or(Path::new("."));
279 if let Ok(dir) = File::open(dir) {
280 let _ = dir.sync_all();
281 }
282}