1use std::{
13 fs::{File, OpenOptions},
14 io,
15 path::{Path, PathBuf},
16 sync::{
17 Mutex,
18 atomic::{AtomicBool, Ordering},
19 },
20};
21
22use crate::error::{Result, WalError};
23
24pub trait WalStore: Send + Sync {
63 fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()>;
66
67 fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize>;
73
74 fn truncate(&self, len: u64) -> Result<()>;
77
78 fn sync(&self) -> Result<()>;
83
84 fn len(&self) -> Result<u64>;
86
87 fn is_empty(&self) -> Result<bool> {
92 Ok(self.len()? == 0)
93 }
94
95 fn head(&self) -> Result<u64> {
102 Ok(0)
103 }
104
105 fn truncate_before(&self, _offset: u64) -> Result<u64> {
116 self.head()
117 }
118}
119
120#[derive(Debug)]
130pub struct FileStore {
131 file: File,
132 path: PathBuf,
133 parent: PathBuf,
136 parent_dirty: AtomicBool,
137}
138
139impl FileStore {
140 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
151 let path = path.as_ref().to_path_buf();
152 let file = OpenOptions::new()
153 .read(true)
154 .write(true)
155 .create(true)
156 .truncate(false)
157 .open(&path)
158 .map_err(|e| WalError::io("opening the log file", e))?;
159 let parent = parent_dir(&path);
160 Ok(FileStore {
161 file,
162 path,
163 parent,
164 parent_dirty: AtomicBool::new(true),
165 })
166 }
167
168 #[must_use]
170 pub fn path(&self) -> &Path {
171 &self.path
172 }
173}
174
175impl WalStore for FileStore {
176 fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
177 pwrite_all(&self.file, offset, bytes).map_err(|e| WalError::io("writing a record", e))
178 }
179
180 fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize> {
181 pread_fill(&self.file, offset, buf).map_err(|e| WalError::io("reading from the log", e))
182 }
183
184 fn truncate(&self, len: u64) -> Result<()> {
185 self.file
186 .set_len(len)
187 .map_err(|e| WalError::io("truncating the log", e))
188 }
189
190 fn sync(&self) -> Result<()> {
191 flush_dir_if_dirty(&self.parent_dirty, &self.parent)?;
192 durable_sync(&self.file).map_err(|e| WalError::io("flushing to stable storage", e))
193 }
194
195 fn len(&self) -> Result<u64> {
196 Ok(self
197 .file
198 .metadata()
199 .map_err(|e| WalError::io("reading log file metadata", e))?
200 .len())
201 }
202}
203
204#[derive(Debug, Default)]
225pub struct MemStore {
226 data: Mutex<Vec<u8>>,
227}
228
229impl MemStore {
230 #[must_use]
232 pub fn new() -> Self {
233 MemStore {
234 data: Mutex::new(Vec::new()),
235 }
236 }
237
238 #[must_use]
241 pub fn with_capacity(capacity: usize) -> Self {
242 MemStore {
243 data: Mutex::new(Vec::with_capacity(capacity)),
244 }
245 }
246
247 #[must_use]
250 pub fn from_bytes(bytes: Vec<u8>) -> Self {
251 MemStore {
252 data: Mutex::new(bytes),
253 }
254 }
255
256 fn lock(&self) -> std::sync::MutexGuard<'_, Vec<u8>> {
257 self.data
258 .lock()
259 .unwrap_or_else(std::sync::PoisonError::into_inner)
260 }
261
262 #[cfg(test)]
265 pub(crate) fn snapshot(&self) -> Vec<u8> {
266 self.lock().clone()
267 }
268}
269
270impl Clone for MemStore {
271 fn clone(&self) -> Self {
272 MemStore {
273 data: Mutex::new(self.lock().clone()),
274 }
275 }
276}
277
278impl WalStore for MemStore {
279 fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
280 let start = usize::try_from(offset).map_err(|_| {
281 WalError::io(
282 "writing to memory",
283 io::Error::other("offset exceeds usize"),
284 )
285 })?;
286 let end = start.checked_add(bytes.len()).ok_or_else(|| {
287 WalError::io(
288 "writing to memory",
289 io::Error::other("write overflows usize"),
290 )
291 })?;
292
293 let mut data = self.lock();
294 if data.len() < end {
295 data.resize(end, 0); }
297 data[start..end].copy_from_slice(bytes);
298 Ok(())
299 }
300
301 fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize> {
302 let data = self.lock();
303 let start = match usize::try_from(offset) {
304 Ok(start) if start < data.len() => start,
305 _ => return Ok(0),
306 };
307 let available = &data[start..];
308 let n = available.len().min(buf.len());
309 buf[..n].copy_from_slice(&available[..n]);
310 Ok(n)
311 }
312
313 fn truncate(&self, len: u64) -> Result<()> {
314 let len = usize::try_from(len).unwrap_or(usize::MAX);
315 self.lock().truncate(len);
316 Ok(())
317 }
318
319 fn sync(&self) -> Result<()> {
320 Ok(())
321 }
322
323 fn len(&self) -> Result<u64> {
324 Ok(self.lock().len() as u64)
325 }
326}
327
328#[cfg(target_os = "macos")]
339pub(crate) fn durable_sync(file: &File) -> io::Result<()> {
340 use std::os::unix::io::AsRawFd;
341
342 let fd = file.as_raw_fd();
343 let ret = unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) };
349 if ret == -1 {
350 return Err(io::Error::last_os_error());
351 }
352 Ok(())
353}
354
355#[cfg(not(target_os = "macos"))]
359pub(crate) fn durable_sync(file: &File) -> io::Result<()> {
360 file.sync_data()
361}
362
363#[cfg(unix)]
373pub(crate) fn sync_dir(dir: &Path) -> io::Result<()> {
374 let file = match File::open(dir) {
375 Ok(file) => file,
376 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => return Ok(()),
377 Err(error) => return Err(error),
378 };
379 match file.sync_all() {
380 Err(error)
381 if matches!(
382 error.kind(),
383 io::ErrorKind::InvalidInput | io::ErrorKind::Unsupported
384 ) =>
385 {
386 Ok(())
387 }
388 other => other,
389 }
390}
391
392#[cfg(not(unix))]
395pub(crate) fn sync_dir(_dir: &Path) -> io::Result<()> {
396 Ok(())
397}
398
399pub(crate) fn flush_dir_if_dirty(dirty: &AtomicBool, dir: &Path) -> Result<()> {
405 if dirty.load(Ordering::Acquire) && dirty.swap(false, Ordering::AcqRel) {
406 if let Err(error) = sync_dir(dir) {
407 dirty.store(true, Ordering::Release);
408 return Err(WalError::io("flushing the log directory", error));
409 }
410 }
411 Ok(())
412}
413
414pub(crate) fn parent_dir(path: &Path) -> PathBuf {
416 match path.parent() {
417 Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
418 _ => PathBuf::from("."),
419 }
420}
421
422#[cfg(unix)]
429pub(crate) fn pwrite_all(file: &File, mut offset: u64, mut buf: &[u8]) -> io::Result<()> {
430 use std::os::unix::fs::FileExt;
431
432 while !buf.is_empty() {
433 match file.write_at(buf, offset) {
434 Ok(0) => {
435 return Err(io::Error::new(
436 io::ErrorKind::WriteZero,
437 "the store accepted zero bytes mid-record",
438 ));
439 }
440 Ok(n) => {
441 buf = &buf[n..];
442 offset += n as u64;
443 }
444 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
445 Err(e) => return Err(e),
446 }
447 }
448 Ok(())
449}
450
451#[cfg(windows)]
452pub(crate) fn pwrite_all(file: &File, mut offset: u64, mut buf: &[u8]) -> io::Result<()> {
453 use std::os::windows::fs::FileExt;
454
455 while !buf.is_empty() {
456 match file.seek_write(buf, offset) {
457 Ok(0) => {
458 return Err(io::Error::new(
459 io::ErrorKind::WriteZero,
460 "the store accepted zero bytes mid-record",
461 ));
462 }
463 Ok(n) => {
464 buf = &buf[n..];
465 offset += n as u64;
466 }
467 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
468 Err(e) => return Err(e),
469 }
470 }
471 Ok(())
472}
473
474#[cfg(unix)]
475pub(crate) fn pread_fill(file: &File, mut offset: u64, buf: &mut [u8]) -> io::Result<usize> {
476 use std::os::unix::fs::FileExt;
477
478 let mut total = 0;
479 while total < buf.len() {
480 match file.read_at(&mut buf[total..], offset) {
481 Ok(0) => break,
482 Ok(n) => {
483 total += n;
484 offset += n as u64;
485 }
486 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
487 Err(e) => return Err(e),
488 }
489 }
490 Ok(total)
491}
492
493#[cfg(windows)]
494pub(crate) fn pread_fill(file: &File, mut offset: u64, buf: &mut [u8]) -> io::Result<usize> {
495 use std::os::windows::fs::FileExt;
496
497 let mut total = 0;
498 while total < buf.len() {
499 match file.seek_read(&mut buf[total..], offset) {
500 Ok(0) => break,
501 Ok(n) => {
502 total += n;
503 offset += n as u64;
504 }
505 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
506 Err(e) => return Err(e),
507 }
508 }
509 Ok(total)
510}
511
512#[cfg(test)]
513#[allow(clippy::unwrap_used, clippy::expect_used)]
514mod dir_tests {
515 use super::*;
516
517 #[test]
518 fn test_parent_dir_of_a_bare_name_is_the_current_directory() {
519 assert_eq!(parent_dir(Path::new("app.wal")), PathBuf::from("."));
520 assert_eq!(parent_dir(Path::new("a/app.wal")), PathBuf::from("a"));
521 }
522
523 #[test]
524 fn test_sync_dir_flushes_a_real_directory() {
525 let dir = tempfile::tempdir().unwrap();
526 sync_dir(dir.path()).unwrap();
527 }
528
529 #[cfg(unix)]
530 #[test]
531 fn test_flush_failure_keeps_the_directory_dirty() {
532 let dir = tempfile::tempdir().unwrap();
533 let missing = dir.path().join("missing");
534 let dirty = AtomicBool::new(true);
535 assert!(flush_dir_if_dirty(&dirty, &missing).is_err());
536 assert!(dirty.load(Ordering::Acquire));
537 }
538
539 #[test]
540 fn test_clean_directory_is_not_flushed() {
541 let dir = tempfile::tempdir().unwrap();
542 let missing = dir.path().join("missing");
543 let dirty = AtomicBool::new(false);
544 flush_dir_if_dirty(&dirty, &missing).unwrap();
546 }
547
548 #[test]
549 fn test_file_store_flushes_its_directory_once() {
550 let dir = tempfile::tempdir().unwrap();
551 let store = FileStore::open(dir.path().join("log.wal")).unwrap();
552 assert!(store.parent_dirty.load(Ordering::Acquire));
553 store.sync().unwrap();
554 assert!(!store.parent_dirty.load(Ordering::Acquire));
555 }
556}
557
558#[cfg(test)]
559#[allow(clippy::unwrap_used, clippy::expect_used)]
560mod tests {
561 use super::*;
562
563 #[test]
564 fn test_memstore_write_at_advances_len() {
565 let store = MemStore::new();
566 assert_eq!(store.len().unwrap(), 0);
567 store.write_at(0, b"abc").unwrap();
568 assert_eq!(store.len().unwrap(), 3);
569 store.write_at(3, b"de").unwrap();
570 assert_eq!(store.len().unwrap(), 5);
571 }
572
573 #[test]
574 fn test_memstore_write_past_end_zero_fills_gap() {
575 let store = MemStore::new();
576 store.write_at(4, b"XY").unwrap();
578 assert_eq!(store.len().unwrap(), 6);
579 let mut buf = [0xFFu8; 6];
580 assert_eq!(store.read_at(0, &mut buf).unwrap(), 6);
581 assert_eq!(&buf, &[0, 0, 0, 0, b'X', b'Y']);
582 }
583
584 #[test]
585 fn test_memstore_read_past_end_is_short() {
586 let store = MemStore::new();
587 store.write_at(0, b"abc").unwrap();
588 let mut buf = [0u8; 8];
589 assert_eq!(store.read_at(1, &mut buf).unwrap(), 2);
590 assert_eq!(&buf[..2], b"bc");
591 }
592
593 #[test]
594 fn test_memstore_truncate_shrinks() {
595 let store = MemStore::new();
596 store.write_at(0, b"0123456789").unwrap();
597 store.truncate(4).unwrap();
598 assert_eq!(store.len().unwrap(), 4);
599 }
600
601 #[test]
602 fn test_filestore_roundtrip_through_disk() {
603 let dir = tempfile::tempdir().unwrap();
604 let path = dir.path().join("store.bin");
605
606 {
607 let store = FileStore::open(&path).unwrap();
608 store.write_at(0, b"hello world").unwrap();
609 store.sync().unwrap();
610 assert_eq!(store.len().unwrap(), 11);
611 }
612
613 let store = FileStore::open(&path).unwrap();
614 assert_eq!(store.len().unwrap(), 11);
615 let mut buf = [0u8; 5];
616 assert_eq!(store.read_at(6, &mut buf).unwrap(), 5);
617 assert_eq!(&buf, b"world");
618 }
619
620 #[test]
621 fn test_filestore_concurrent_disjoint_writes() {
622 use std::sync::Arc;
623 use std::thread;
624
625 let dir = tempfile::tempdir().unwrap();
626 let path = dir.path().join("concurrent.bin");
627 let store = Arc::new(FileStore::open(&path).unwrap());
628
629 let mut handles = Vec::new();
630 for i in 0..8u64 {
631 let store = Arc::clone(&store);
632 handles.push(thread::spawn(move || {
633 let byte = b'A' + i as u8;
634 store.write_at(i * 4, &[byte; 4]).unwrap();
635 }));
636 }
637 for h in handles {
638 h.join().unwrap();
639 }
640 store.sync().unwrap();
641
642 let mut buf = [0u8; 32];
643 assert_eq!(store.read_at(0, &mut buf).unwrap(), 32);
644 for i in 0..8 {
645 let expected = b'A' + i as u8;
646 assert_eq!(&buf[i * 4..i * 4 + 4], &[expected; 4]);
647 }
648 }
649
650 #[test]
651 fn test_filestore_sync_durable_across_reopen() {
652 let dir = tempfile::tempdir().unwrap();
653 let path = dir.path().join("durable.bin");
654 {
655 let store = FileStore::open(&path).unwrap();
656 store.write_at(0, b"persisted").unwrap();
657 store.sync().unwrap();
658 }
659 let store = FileStore::open(&path).unwrap();
660 let mut buf = [0u8; 9];
661 assert_eq!(store.read_at(0, &mut buf).unwrap(), 9);
662 assert_eq!(&buf, b"persisted");
663 }
664}