feldera_storage/
lib.rs

1//! Common Types and Trait Definition for Storage in Feldera.
2
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
5use std::sync::Arc;
6
7use feldera_types::config::{StorageBackendConfig, StorageConfig, StorageOptions};
8use tracing::warn;
9use uuid::Uuid;
10
11use crate::block::BlockLocation;
12use crate::error::StorageError;
13use crate::fbuf::FBuf;
14use crate::file::HasFileId;
15
16pub mod block;
17pub mod error;
18pub mod fbuf;
19pub mod file;
20pub mod tokio;
21
22/// Extension for batch files used by the engine.
23const CREATE_FILE_EXTENSION: &str = ".feldera";
24
25/// Helper function that appends to a [`PathBuf`].
26pub fn append_to_path(p: PathBuf, s: &str) -> PathBuf {
27    let mut p = p.into_os_string();
28    p.push(s);
29    p.into()
30}
31
32pub trait StorageBackendFactory: Sync {
33    fn backend(&self) -> &'static str;
34    fn create(
35        &self,
36        storage_config: &StorageConfig,
37        backend_config: &StorageBackendConfig,
38    ) -> Result<Rc<dyn StorageBackend>, StorageError>;
39}
40
41inventory::collect!(&'static dyn StorageBackendFactory);
42
43/// A storage backend.
44pub trait StorageBackend {
45    /// Create a new file with the given `name`, which is relative to the
46    /// backend's base directory.
47    fn create_named(&self, name: &Path) -> Result<Box<dyn FileWriter>, StorageError>;
48
49    /// Creates a new persistent file used for writing data. The backend selects
50    /// a name.
51    fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
52        self.create_with_prefix("")
53    }
54
55    /// Creates a new persistent file used for writing data, giving the file's
56    /// name the specified `prefix`. See also [`create`](Self::create).
57    fn create_with_prefix(&self, prefix: &str) -> Result<Box<dyn FileWriter>, StorageError> {
58        let uuid = Uuid::now_v7();
59        let name = format!("{}{}{}", prefix, uuid, CREATE_FILE_EXTENSION);
60        let name_path = Path::new(&name);
61        self.create_named(name_path)
62    }
63
64    /// Opens a file for reading.  The file `name` is relative to the base of
65    /// the storage backend.
66    fn open(&self, name: &Path) -> Result<Arc<dyn FileReader>, StorageError>;
67}
68
69impl dyn StorageBackend {
70    /// Creates and returns a new backend configured according to `config` and `options`.
71    pub fn new(config: &StorageConfig, options: &StorageOptions) -> Result<Rc<Self>, StorageError> {
72        Self::warn_about_tmpfs(config.path());
73        for variable_provider in inventory::iter::<&dyn StorageBackendFactory> {
74            if variable_provider.backend() == options.backend.to_string() {
75                return variable_provider.create(config, &options.backend);
76            }
77        }
78        Err(StorageError::BackendNotSupported(options.backend.clone()))
79    }
80
81    fn is_tmpfs(_path: &Path) -> bool {
82        #[cfg(target_os = "linux")]
83        {
84            use nix::sys::statfs;
85            statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
86        }
87
88        #[cfg(not(target_os = "linux"))]
89        false
90    }
91
92    fn warn_about_tmpfs(path: &Path) {
93        if Self::is_tmpfs(path) {
94            static ONCE: std::sync::Once = std::sync::Once::new();
95            ONCE.call_once(|| {
96                warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
97            });
98        }
99    }
100}
101
102/// A file being written.
103///
104/// The file can't be read until it is completed with
105/// [FileWriter::complete]. Until then, the file is temporary and will be
106/// deleted if it is dropped.
107pub trait FileWriter: HasFileId {
108    /// Writes `data` at the given byte `offset`.  `offset` must be a multiple
109    /// of 512 and `data.len()` must be a multiple of 512.  Returns the data
110    /// that was written encapsulated in an `Arc`.
111    fn write_block(&mut self, offset: u64, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
112
113    /// Completes writing of a file and returns a reader for the file and the
114    /// file's path. The file is treated as temporary and will be deleted if the
115    /// reader is dropped without first calling
116    /// [FileReader::mark_for_checkpoint].
117    fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, PathBuf), StorageError>;
118}
119
120/// A readable file.
121pub trait FileReader: Send + Sync + HasFileId {
122    /// Marks a file to be part of a checkpoint.
123    ///
124    /// This is used to prevent the file from being deleted when it is dropped.
125    /// This is only useful for files obtained via [FileWriter::complete],
126    /// because files that were opened with [StorageBackend::open] are never
127    /// deleted on drop.
128    fn mark_for_checkpoint(&self);
129
130    /// Reads data at `location` from the file.  If successful, the result will
131    /// be exactly the requested length; that is, this API treats read past EOF
132    /// as an error.
133    fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
134
135    /// Returns the file's size in bytes.
136    fn get_size(&self) -> Result<u64, StorageError>;
137}