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