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
328pub(crate) fn durable_sync(file: &File) -> io::Result<()> {
342 file.sync_data()
343}
344
345#[cfg(unix)]
355pub(crate) fn sync_dir(dir: &Path) -> io::Result<()> {
356 let file = match File::open(dir) {
357 Ok(file) => file,
358 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => return Ok(()),
359 Err(error) => return Err(error),
360 };
361 match file.sync_all() {
362 Err(error)
363 if matches!(
364 error.kind(),
365 io::ErrorKind::InvalidInput | io::ErrorKind::Unsupported
366 ) =>
367 {
368 Ok(())
369 }
370 other => other,
371 }
372}
373
374#[cfg(not(unix))]
377pub(crate) fn sync_dir(_dir: &Path) -> io::Result<()> {
378 Ok(())
379}
380
381pub(crate) fn flush_dir_if_dirty(dirty: &AtomicBool, dir: &Path) -> Result<()> {
387 if dirty.load(Ordering::Acquire) && dirty.swap(false, Ordering::AcqRel) {
388 if let Err(error) = sync_dir(dir) {
389 dirty.store(true, Ordering::Release);
390 return Err(WalError::io("flushing the log directory", error));
391 }
392 }
393 Ok(())
394}
395
396pub(crate) fn parent_dir(path: &Path) -> PathBuf {
398 match path.parent() {
399 Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
400 _ => PathBuf::from("."),
401 }
402}
403
404#[cfg(unix)]
411pub(crate) fn pwrite_all(file: &File, mut offset: u64, mut buf: &[u8]) -> io::Result<()> {
412 use std::os::unix::fs::FileExt;
413
414 while !buf.is_empty() {
415 match file.write_at(buf, offset) {
416 Ok(0) => {
417 return Err(io::Error::new(
418 io::ErrorKind::WriteZero,
419 "the store accepted zero bytes mid-record",
420 ));
421 }
422 Ok(n) => {
423 buf = &buf[n..];
424 offset += n as u64;
425 }
426 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
427 Err(e) => return Err(e),
428 }
429 }
430 Ok(())
431}
432
433#[cfg(windows)]
434pub(crate) fn pwrite_all(file: &File, mut offset: u64, mut buf: &[u8]) -> io::Result<()> {
435 use std::os::windows::fs::FileExt;
436
437 while !buf.is_empty() {
438 match file.seek_write(buf, offset) {
439 Ok(0) => {
440 return Err(io::Error::new(
441 io::ErrorKind::WriteZero,
442 "the store accepted zero bytes mid-record",
443 ));
444 }
445 Ok(n) => {
446 buf = &buf[n..];
447 offset += n as u64;
448 }
449 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
450 Err(e) => return Err(e),
451 }
452 }
453 Ok(())
454}
455
456#[cfg(unix)]
457pub(crate) fn pread_fill(file: &File, mut offset: u64, buf: &mut [u8]) -> io::Result<usize> {
458 use std::os::unix::fs::FileExt;
459
460 let mut total = 0;
461 while total < buf.len() {
462 match file.read_at(&mut buf[total..], offset) {
463 Ok(0) => break,
464 Ok(n) => {
465 total += n;
466 offset += n as u64;
467 }
468 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
469 Err(e) => return Err(e),
470 }
471 }
472 Ok(total)
473}
474
475#[cfg(windows)]
476pub(crate) fn pread_fill(file: &File, mut offset: u64, buf: &mut [u8]) -> io::Result<usize> {
477 use std::os::windows::fs::FileExt;
478
479 let mut total = 0;
480 while total < buf.len() {
481 match file.seek_read(&mut buf[total..], offset) {
482 Ok(0) => break,
483 Ok(n) => {
484 total += n;
485 offset += n as u64;
486 }
487 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
488 Err(e) => return Err(e),
489 }
490 }
491 Ok(total)
492}
493
494#[cfg(test)]
495#[allow(clippy::unwrap_used, clippy::expect_used)]
496mod dir_tests {
497 use super::*;
498
499 #[test]
500 fn test_parent_dir_of_a_bare_name_is_the_current_directory() {
501 assert_eq!(parent_dir(Path::new("app.wal")), PathBuf::from("."));
502 assert_eq!(parent_dir(Path::new("a/app.wal")), PathBuf::from("a"));
503 }
504
505 #[test]
506 fn test_sync_dir_flushes_a_real_directory() {
507 let dir = tempfile::tempdir().unwrap();
508 sync_dir(dir.path()).unwrap();
509 }
510
511 #[cfg(unix)]
512 #[test]
513 fn test_flush_failure_keeps_the_directory_dirty() {
514 let dir = tempfile::tempdir().unwrap();
515 let missing = dir.path().join("missing");
516 let dirty = AtomicBool::new(true);
517 assert!(flush_dir_if_dirty(&dirty, &missing).is_err());
518 assert!(dirty.load(Ordering::Acquire));
519 }
520
521 #[test]
522 fn test_clean_directory_is_not_flushed() {
523 let dir = tempfile::tempdir().unwrap();
524 let missing = dir.path().join("missing");
525 let dirty = AtomicBool::new(false);
526 flush_dir_if_dirty(&dirty, &missing).unwrap();
528 }
529
530 #[test]
531 fn test_file_store_flushes_its_directory_once() {
532 let dir = tempfile::tempdir().unwrap();
533 let store = FileStore::open(dir.path().join("log.wal")).unwrap();
534 assert!(store.parent_dirty.load(Ordering::Acquire));
535 store.sync().unwrap();
536 assert!(!store.parent_dirty.load(Ordering::Acquire));
537 }
538}
539
540#[cfg(test)]
541#[allow(clippy::unwrap_used, clippy::expect_used)]
542mod tests {
543 use super::*;
544
545 #[test]
546 fn test_memstore_write_at_advances_len() {
547 let store = MemStore::new();
548 assert_eq!(store.len().unwrap(), 0);
549 store.write_at(0, b"abc").unwrap();
550 assert_eq!(store.len().unwrap(), 3);
551 store.write_at(3, b"de").unwrap();
552 assert_eq!(store.len().unwrap(), 5);
553 }
554
555 #[test]
556 fn test_memstore_write_past_end_zero_fills_gap() {
557 let store = MemStore::new();
558 store.write_at(4, b"XY").unwrap();
560 assert_eq!(store.len().unwrap(), 6);
561 let mut buf = [0xFFu8; 6];
562 assert_eq!(store.read_at(0, &mut buf).unwrap(), 6);
563 assert_eq!(&buf, &[0, 0, 0, 0, b'X', b'Y']);
564 }
565
566 #[test]
567 fn test_memstore_read_past_end_is_short() {
568 let store = MemStore::new();
569 store.write_at(0, b"abc").unwrap();
570 let mut buf = [0u8; 8];
571 assert_eq!(store.read_at(1, &mut buf).unwrap(), 2);
572 assert_eq!(&buf[..2], b"bc");
573 }
574
575 #[test]
576 fn test_memstore_truncate_shrinks() {
577 let store = MemStore::new();
578 store.write_at(0, b"0123456789").unwrap();
579 store.truncate(4).unwrap();
580 assert_eq!(store.len().unwrap(), 4);
581 }
582
583 #[test]
584 fn test_filestore_roundtrip_through_disk() {
585 let dir = tempfile::tempdir().unwrap();
586 let path = dir.path().join("store.bin");
587
588 {
589 let store = FileStore::open(&path).unwrap();
590 store.write_at(0, b"hello world").unwrap();
591 store.sync().unwrap();
592 assert_eq!(store.len().unwrap(), 11);
593 }
594
595 let store = FileStore::open(&path).unwrap();
596 assert_eq!(store.len().unwrap(), 11);
597 let mut buf = [0u8; 5];
598 assert_eq!(store.read_at(6, &mut buf).unwrap(), 5);
599 assert_eq!(&buf, b"world");
600 }
601
602 #[test]
603 fn test_filestore_concurrent_disjoint_writes() {
604 use std::sync::Arc;
605 use std::thread;
606
607 let dir = tempfile::tempdir().unwrap();
608 let path = dir.path().join("concurrent.bin");
609 let store = Arc::new(FileStore::open(&path).unwrap());
610
611 let mut handles = Vec::new();
612 for i in 0..8u64 {
613 let store = Arc::clone(&store);
614 handles.push(thread::spawn(move || {
615 let byte = b'A' + i as u8;
616 store.write_at(i * 4, &[byte; 4]).unwrap();
617 }));
618 }
619 for h in handles {
620 h.join().unwrap();
621 }
622 store.sync().unwrap();
623
624 let mut buf = [0u8; 32];
625 assert_eq!(store.read_at(0, &mut buf).unwrap(), 32);
626 for i in 0..8 {
627 let expected = b'A' + i as u8;
628 assert_eq!(&buf[i * 4..i * 4 + 4], &[expected; 4]);
629 }
630 }
631
632 #[test]
633 fn test_filestore_sync_durable_across_reopen() {
634 let dir = tempfile::tempdir().unwrap();
635 let path = dir.path().join("durable.bin");
636 {
637 let store = FileStore::open(&path).unwrap();
638 store.write_at(0, b"persisted").unwrap();
639 store.sync().unwrap();
640 }
641 let store = FileStore::open(&path).unwrap();
642 let mut buf = [0u8; 9];
643 assert_eq!(store.read_at(0, &mut buf).unwrap(), 9);
644 assert_eq!(&buf, b"persisted");
645 }
646}