feldera_storage/
lib.rs

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