feldera_storage/
lib.rs

1//! Common Types and Trait Definition for Storage in Feldera.
2
3use std::io::ErrorKind;
4use std::path::{Path, PathBuf};
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 use object_store::path::{Path as StoragePath, PathPart as StoragePathPart};
17
18pub mod block;
19pub mod error;
20pub mod fbuf;
21pub mod file;
22pub mod tokio;
23
24/// Extension for batch files used by the engine.
25const CREATE_FILE_EXTENSION: &str = ".feldera";
26
27/// Helper function that appends to a [`PathBuf`].
28pub fn append_to_path(p: PathBuf, s: &str) -> PathBuf {
29    let mut p = p.into_os_string();
30    p.push(s);
31    p.into()
32}
33
34pub trait StorageBackendFactory: Sync {
35    fn backend(&self) -> &'static str;
36    fn create(
37        &self,
38        storage_config: &StorageConfig,
39        backend_config: &StorageBackendConfig,
40    ) -> Result<Arc<dyn StorageBackend>, StorageError>;
41}
42
43inventory::collect!(&'static dyn StorageBackendFactory);
44
45/// A storage backend.
46pub trait StorageBackend: Send + Sync {
47    /// Create a new file with the given `name`, automatically creating any
48    /// parent directories within `name` that don't already exist.
49    fn create_named(&self, name: &StoragePath) -> Result<Box<dyn FileWriter>, StorageError>;
50
51    /// Creates a new persistent file used for writing data. The backend selects
52    /// a name.
53    fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
54        self.create_with_prefix(&StoragePath::default())
55    }
56
57    /// Creates a new persistent file used for writing data, giving the file's
58    /// name the specified `prefix`. See also [`create`](Self::create).
59    fn create_with_prefix(
60        &self,
61        prefix: &StoragePath,
62    ) -> Result<Box<dyn FileWriter>, StorageError> {
63        let uuid = Uuid::now_v7();
64        let name = format!("{}{}{}", prefix, uuid, CREATE_FILE_EXTENSION);
65        self.create_named(&name.into())
66    }
67
68    /// Opens `name` for reading.
69    fn open(&self, name: &StoragePath) -> Result<Arc<dyn FileReader>, StorageError>;
70
71    /// Calls `cb` with the name of each of the files under `parent`. This is a
72    /// non-recursive list: it does not include files under sub-directories of
73    /// `parent`.
74    fn list(
75        &self,
76        parent: &StoragePath,
77        cb: &mut dyn FnMut(&StoragePath, StorageFileType),
78    ) -> Result<(), StorageError>;
79
80    fn delete(&self, name: &StoragePath) -> Result<(), StorageError>;
81
82    fn delete_recursive(&self, name: &StoragePath) -> Result<(), StorageError>;
83
84    fn delete_if_exists(&self, name: &StoragePath) -> Result<(), StorageError> {
85        match self.delete(name) {
86            Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
87            other => other,
88        }
89    }
90
91    fn exists(&self, name: &StoragePath) -> Result<bool, StorageError> {
92        match self.open(name) {
93            Ok(_) => Ok(true),
94            Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
95            Err(error) => Err(error),
96        }
97    }
98
99    /// Reads `name` and returns its contents.  The file `name` is relative to
100    /// the base of the storage backend.
101    fn read(&self, name: &StoragePath) -> Result<Arc<FBuf>, StorageError> {
102        let reader = self.open(name)?;
103        let size = reader.get_size()?.try_into().unwrap();
104        reader.read_block(BlockLocation { offset: 0, size })
105    }
106
107    /// Writes `content` to `name`, automatically creating any parent
108    /// directories within `name` that don't already exist.
109    fn write(&self, name: &StoragePath, content: FBuf) -> Result<(), StorageError> {
110        let mut writer = self.create_named(name)?;
111        writer.write_block(0, content)?;
112        let (reader, _path) = writer.complete()?;
113        reader.mark_for_checkpoint();
114        Ok(())
115    }
116}
117
118impl dyn StorageBackend {
119    /// Creates and returns a new backend configured according to `config` and `options`.
120    pub fn new(
121        config: &StorageConfig,
122        options: &StorageOptions,
123    ) -> Result<Arc<Self>, StorageError> {
124        Self::warn_about_tmpfs(config.path());
125        for variable_provider in inventory::iter::<&dyn StorageBackendFactory> {
126            if variable_provider.backend() == options.backend.to_string() {
127                return variable_provider.create(config, &options.backend);
128            }
129        }
130        Err(StorageError::BackendNotSupported(options.backend.clone()))
131    }
132
133    fn is_tmpfs(_path: &Path) -> bool {
134        #[cfg(target_os = "linux")]
135        {
136            use nix::sys::statfs;
137            statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
138        }
139
140        #[cfg(not(target_os = "linux"))]
141        false
142    }
143
144    fn warn_about_tmpfs(path: &Path) {
145        if Self::is_tmpfs(path) {
146            static ONCE: std::sync::Once = std::sync::Once::new();
147            ONCE.call_once(|| {
148                warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
149            });
150        }
151    }
152}
153
154/// A file being written.
155///
156/// The file can't be read until it is completed with
157/// [FileWriter::complete]. Until then, the file is temporary and will be
158/// deleted if it is dropped.
159pub trait FileWriter: Send + Sync + HasFileId {
160    /// Writes `data` at the given byte `offset`.  `offset` must be a multiple
161    /// of 512 and `data.len()` must be a multiple of 512.  Returns the data
162    /// that was written encapsulated in an `Arc`.
163    fn write_block(&mut self, offset: u64, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
164
165    /// Completes writing of a file and returns a reader for the file and the
166    /// file's path. The file is treated as temporary and will be deleted if the
167    /// reader is dropped without first calling
168    /// [FileReader::mark_for_checkpoint].
169    fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, StoragePath), StorageError>;
170}
171
172/// A readable file.
173pub trait FileReader: Send + Sync + HasFileId {
174    /// Marks a file to be part of a checkpoint.
175    ///
176    /// This is used to prevent the file from being deleted when it is dropped.
177    /// This is only useful for files obtained via [FileWriter::complete],
178    /// because files that were opened with [StorageBackend::open] are never
179    /// deleted on drop.
180    fn mark_for_checkpoint(&self);
181
182    /// Reads data at `location` from the file.  If successful, the result will
183    /// be exactly the requested length; that is, this API treats read past EOF
184    /// as an error.
185    fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
186
187    /// Returns the file's size in bytes.
188    fn get_size(&self) -> Result<u64, StorageError>;
189}
190
191#[derive(Copy, Clone, Debug, PartialEq, Eq)]
192pub enum StorageFileType {
193    /// A regular file.
194    File,
195
196    /// A directory.
197    ///
198    /// Only some kinds of storage backends support directories. The ones that
199    /// don't still allow files to be named hierarchically, but they don't
200    /// support creating or deleting directories independently from the files in
201    /// them. That is, with such a backend, a directory is effectively created
202    /// by creating a file in it, and is effectively deleted when the last file
203    /// in it is deleted.
204    Directory,
205
206    /// Something else.
207    Other,
208}