feldera_storage/
lib.rs

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