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(options.backend.clone()))
154    }
155
156    fn is_tmpfs(_path: &Path) -> bool {
157        #[cfg(target_os = "linux")]
158        {
159            use nix::sys::statfs;
160            statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
161        }
162
163        #[cfg(not(target_os = "linux"))]
164        false
165    }
166
167    fn warn_about_tmpfs(path: &Path) {
168        if Self::is_tmpfs(path) {
169            static ONCE: std::sync::Once = std::sync::Once::new();
170            ONCE.call_once(|| {
171                warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
172            });
173        }
174    }
175}
176
177/// A file being written.
178///
179/// The file can't be read until it is completed with
180/// [FileWriter::complete]. Until then, the file is temporary and will be
181/// deleted if it is dropped.
182pub trait FileWriter: Send + Sync + HasFileId {
183    /// Writes `data` at the end of the file. len()` must be a multiple of 512.
184    /// Returns the data that was written encapsulated in an `Arc`.
185    fn write_block(&mut self, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
186
187    /// Completes writing of a file and returns a reader for the file and the
188    /// file's path. The file is treated as temporary and will be deleted if the
189    /// reader is dropped without first calling
190    /// [FileReader::mark_for_checkpoint].
191    fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, StoragePath), StorageError>;
192}
193
194/// A readable file.
195pub trait FileReader: Send + Sync + HasFileId {
196    /// Marks a file to be part of a checkpoint.
197    ///
198    /// This is used to prevent the file from being deleted when it is dropped.
199    /// This is only useful for files obtained via [FileWriter::complete],
200    /// because files that were opened with [StorageBackend::open] are never
201    /// deleted on drop.
202    fn mark_for_checkpoint(&self);
203
204    /// Reads data at `location` from the file.  If successful, the result will
205    /// be exactly the requested length; that is, this API treats read past EOF
206    /// as an error.
207    fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
208
209    /// Returns the file's size in bytes.
210    fn get_size(&self) -> Result<u64, StorageError>;
211}
212
213#[derive(Copy, Clone, Debug, PartialEq, Eq)]
214pub enum StorageFileType {
215    /// A regular file.
216    File {
217        /// File size in bytes.
218        size: u64,
219    },
220
221    /// A directory.
222    ///
223    /// Only some kinds of storage backends support directories. The ones that
224    /// don't still allow files to be named hierarchically, but they don't
225    /// support creating or deleting directories independently from the files in
226    /// them. That is, with such a backend, a directory is effectively created
227    /// by creating a file in it, and is effectively deleted when the last file
228    /// in it is deleted.
229    Directory,
230
231    /// Something else.
232    Other,
233}