ab_client_database/storage_backend.rs
1use ab_aligned_buffer::alignment::Align4096;
2use ab_aligned_buffer::{AllocationError, OwnedAlignedBuffer, SharedAlignedBuffer};
3use futures::channel::oneshot;
4use std::{fmt, io};
5
6/// Owned buffer of pages, which are the unit of reads and writes of a storage backend.
7///
8/// The size of a page is the alignment of the buffer, [`OwnedPages::ALIGN`] bytes. 4096 bytes is a
9/// relatively safe size due to sector size on SSDs commonly being 512 or 4096 bytes.
10pub type OwnedPages = OwnedAlignedBuffer<Align4096>;
11/// Shared buffer of pages, see [`OwnedPages`]
12pub type SharedPages = SharedAlignedBuffer<Align4096>;
13
14/// Error of a storage backend operation
15#[derive(Debug, thiserror::Error)]
16pub enum StorageBackendError {
17 /// Failed to allocate a buffer for the requested pages
18 #[error("Failed to allocate a buffer: {0}")]
19 AllocationFailed(#[from] AllocationError),
20 /// I/O error
21 #[error("I/O error: {0}")]
22 Io(#[from] io::Error),
23}
24
25impl From<StorageBackendError> for io::Error {
26 #[inline]
27 fn from(error: StorageBackendError) -> Self {
28 match error {
29 StorageBackendError::AllocationFailed(_) => {
30 io::Error::new(io::ErrorKind::OutOfMemory, error)
31 }
32 StorageBackendError::Io(error) => error,
33 }
34 }
35}
36
37/// Storage backend to be used by [`ClientDatabase`].
38///
39/// Read and write errors are fatal: the database doesn't try to recover from them, and the node is
40/// expected to stop when it encounters one.
41///
42/// [`ClientDatabase`]: crate::ClientDatabase
43pub trait ClientDatabaseStorageBackend: fmt::Debug + Send + Sync + 'static {
44 /// Total number of pages available for reads/writes
45 fn num_pages(&self) -> u32;
46
47 /// Read `num_pages` pages at `offset` (in pages) into `buffer`, replacing its contents.
48 ///
49 /// The buffer grows if its capacity is smaller than `num_pages` pages. Existing contents are
50 /// discarded, so they are never copied, and [`StorageBackendError::AllocationFailed`] is
51 /// returned if growing fails. On success the buffer contains exactly `num_pages` pages. The
52 /// buffer is returned back regardless of the result.
53 ///
54 /// The read is started before this method returns.
55 fn read(
56 &self,
57 buffer: OwnedPages,
58 num_pages: u32,
59 offset: u32,
60 ) -> oneshot::Receiver<(Result<(), StorageBackendError>, OwnedPages)>;
61
62 /// Write the contents of `buffer`, which are whole pages, at `offset` (in pages).
63 ///
64 /// The buffer is shared, so the caller can keep reading it while the write is in progress. The
65 /// buffer is returned back regardless of the result.
66 ///
67 /// The write is started before this method returns.
68 fn write(
69 &self,
70 buffer: SharedPages,
71 offset: u32,
72 ) -> oneshot::Receiver<(Result<(), StorageBackendError>, SharedPages)>;
73}