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    /// Reads `name` and returns its contents.  The file `name` is relative to
69    /// the base of the storage backend.
70    fn read(&self, name: &Path) -> Result<Arc<FBuf>, StorageError> {
71        let reader = self.open(name)?;
72        let size = reader.get_size()?.try_into().unwrap();
73        reader.read_block(BlockLocation { offset: 0, size })
74    }
75
76    fn write(&self, name: &Path, content: FBuf) -> Result<(), StorageError> {
77        let mut writer = self.create_named(name)?;
78        writer.write_block(0, content)?;
79        let (reader, _path) = writer.complete()?;
80        reader.mark_for_checkpoint();
81        Ok(())
82    }
83}
84
85impl dyn StorageBackend {
86    /// Creates and returns a new backend configured according to `config` and `options`.
87    pub fn new(config: &StorageConfig, options: &StorageOptions) -> Result<Rc<Self>, StorageError> {
88        Self::warn_about_tmpfs(config.path());
89        for variable_provider in inventory::iter::<&dyn StorageBackendFactory> {
90            if variable_provider.backend() == options.backend.to_string() {
91                return variable_provider.create(config, &options.backend);
92            }
93        }
94        Err(StorageError::BackendNotSupported(options.backend.clone()))
95    }
96
97    fn is_tmpfs(_path: &Path) -> bool {
98        #[cfg(target_os = "linux")]
99        {
100            use nix::sys::statfs;
101            statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
102        }
103
104        #[cfg(not(target_os = "linux"))]
105        false
106    }
107
108    fn warn_about_tmpfs(path: &Path) {
109        if Self::is_tmpfs(path) {
110            static ONCE: std::sync::Once = std::sync::Once::new();
111            ONCE.call_once(|| {
112                warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
113            });
114        }
115    }
116}
117
118/// A file being written.
119///
120/// The file can't be read until it is completed with
121/// [FileWriter::complete]. Until then, the file is temporary and will be
122/// deleted if it is dropped.
123pub trait FileWriter: HasFileId {
124    /// Writes `data` at the given byte `offset`.  `offset` must be a multiple
125    /// of 512 and `data.len()` must be a multiple of 512.  Returns the data
126    /// that was written encapsulated in an `Arc`.
127    fn write_block(&mut self, offset: u64, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
128
129    /// Completes writing of a file and returns a reader for the file and the
130    /// file's path. The file is treated as temporary and will be deleted if the
131    /// reader is dropped without first calling
132    /// [FileReader::mark_for_checkpoint].
133    fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, PathBuf), StorageError>;
134}
135
136/// A readable file.
137pub trait FileReader: Send + Sync + HasFileId {
138    /// Marks a file to be part of a checkpoint.
139    ///
140    /// This is used to prevent the file from being deleted when it is dropped.
141    /// This is only useful for files obtained via [FileWriter::complete],
142    /// because files that were opened with [StorageBackend::open] are never
143    /// deleted on drop.
144    fn mark_for_checkpoint(&self);
145
146    /// Reads data at `location` from the file.  If successful, the result will
147    /// be exactly the requested length; that is, this API treats read past EOF
148    /// as an error.
149    fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
150
151    /// Returns the file's size in bytes.
152    fn get_size(&self) -> Result<u64, StorageError>;
153}