Skip to main content

feldera_storage/
lib.rs

1//! Common Types and Trait Definition for Storage in Feldera.
2
3use std::collections::HashSet;
4use std::fmt::Debug;
5use std::io::{Cursor, ErrorKind};
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use std::sync::atomic::AtomicI64;
9
10use feldera_types::checkpoint::{CheckpointDependencies, CheckpointMetadata, PSpineBatches};
11use feldera_types::config::{StorageBackendConfig, StorageConfig, StorageOptions};
12use feldera_types::constants::{CHECKPOINT_DEPENDENCIES, CREATE_FILE_EXTENSION};
13use serde::de::DeserializeOwned;
14use tracing::warn;
15use uuid::Uuid;
16
17use crate::block::BlockLocation;
18use crate::error::StorageError;
19use crate::fbuf::FBuf;
20use crate::file::FileId;
21use crate::metrics::COMMIT_ALL_LATENCY_MICROSECONDS;
22
23pub use object_store::path::{Path as StoragePath, PathPart as StoragePathPart};
24
25pub mod block;
26pub mod checkpoint_synchronizer;
27pub mod disk;
28pub mod error;
29pub mod fbuf;
30pub mod file;
31pub mod histogram;
32pub mod metrics;
33pub mod tokio;
34
35/// Helper function that appends to a [`PathBuf`].
36pub fn append_to_path(p: PathBuf, s: &str) -> PathBuf {
37    let mut p = p.into_os_string();
38    p.push(s);
39    p.into()
40}
41
42pub trait StorageBackendFactory: Sync {
43    fn backend(&self) -> &'static str;
44    fn create(
45        &self,
46        storage_config: &StorageConfig,
47        backend_config: &StorageBackendConfig,
48    ) -> Result<Arc<dyn StorageBackend>, StorageError>;
49}
50
51inventory::collect!(&'static dyn StorageBackendFactory);
52
53/// A storage backend.
54pub trait StorageBackend: Send + Sync {
55    /// Create a new file with the given `name`, automatically creating any
56    /// parent directories within `name` that don't already exist.
57    fn create_named(&self, name: &StoragePath) -> Result<Box<dyn FileWriter>, StorageError>;
58
59    /// Creates a new persistent file used for writing data. The backend selects
60    /// a name.
61    fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
62        self.create_with_prefix(&StoragePath::default())
63    }
64
65    /// Creates a new persistent file used for writing data, giving the file's
66    /// name the specified `prefix`. See also [`create`](Self::create).
67    fn create_with_prefix(
68        &self,
69        prefix: &StoragePath,
70    ) -> Result<Box<dyn FileWriter>, StorageError> {
71        let uuid = Uuid::now_v7();
72        let name = format!("{}{}{}", prefix, uuid, CREATE_FILE_EXTENSION);
73        self.create_named(&name.into())
74    }
75
76    /// Opens `name` for reading.
77    fn open(&self, name: &StoragePath) -> Result<Arc<dyn FileReader>, StorageError>;
78
79    /// Returns the base directory path on the local file system if the storage backend
80    /// uses local disk.
81    fn file_system_path(&self) -> Option<&Path> {
82        None
83    }
84
85    /// Calls `cb` with the name and type of each file under `parent`. This is a
86    /// non-recursive list: it does not include files under sub-directories of
87    /// `parent`.
88    ///
89    /// This method can report two classes of errors:
90    ///
91    /// - The return value indicates errors that could prevent `cb` from being
92    ///   called for some or all of the files in the directory.  These errors
93    ///   indicate that `parent` does not exist or cannot be (fully) read
94    ///   successfully.  If more than one such error occurs, the method returns
95    ///   the last one.
96    ///
97    /// - [DirEntry::file_type] in the argument to the callback reports errors
98    ///   obtaining the file type.  Errors reported this way only mean that
99    ///   there was a problem obtaining metadata for the file itself.
100    fn list(&self, parent: &StoragePath, cb: &mut dyn FnMut(DirEntry)) -> Result<(), StorageError>;
101
102    fn delete(&self, name: &StoragePath) -> Result<(), StorageError>;
103
104    fn delete_recursive(&self, name: &StoragePath) -> Result<(), StorageError>;
105
106    fn delete_if_exists(&self, name: &StoragePath) -> Result<(), StorageError> {
107        match self.delete(name) {
108            Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
109            other => other,
110        }
111    }
112
113    fn exists(&self, name: &StoragePath) -> Result<bool, StorageError> {
114        match self.open(name) {
115            Ok(_) => Ok(true),
116            Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
117            Err(error) => Err(error),
118        }
119    }
120
121    /// Reads `name` and returns its contents.  The file `name` is relative to
122    /// the base of the storage backend.
123    fn read(&self, name: &StoragePath) -> Result<Arc<FBuf>, StorageError> {
124        let reader = self.open(name)?;
125        let size = reader.get_size()?.try_into().unwrap();
126        reader.read_block(BlockLocation { offset: 0, size })
127    }
128
129    /// Writes `content` to `name`, automatically creating any parent
130    /// directories within `name` that don't already exist.
131    ///
132    /// The returned file is readable but not durable. To make it durable, the
133    /// caller must either call `commit` on it or hand it to the checkpoint
134    /// commit phase.
135    #[must_use = "the file is not durable until this committer is committed"]
136    fn write(
137        &self,
138        name: &StoragePath,
139        content: FBuf,
140    ) -> Result<Arc<dyn FileCommitter>, StorageError> {
141        let mut writer = self.create_named(name)?;
142        writer.write_block(content)?;
143        let reader = writer.complete()?;
144        reader.mark_for_checkpoint();
145        Ok(reader)
146    }
147
148    /// Makes every file in `files` durable, and times how long that took.
149    ///
150    /// This is how the checkpoint commit phase makes a checkpoint's files
151    /// durable. Backends vary what they do here, so this times the call rather
152    /// than the syncs inside it: that is the figure the strategies have to be
153    /// compared on, and for a backend that overlaps its syncs it cannot be
154    /// recovered by adding up the individual ones.
155    ///
156    /// Override [Self::sync_files], not this.
157    fn commit_all(&self, files: &[Arc<dyn FileCommitter>]) -> Result<(), StorageError> {
158        if files.is_empty() {
159            return Ok(());
160        }
161        COMMIT_ALL_LATENCY_MICROSECONDS.record_callback(|| self.sync_files(files))
162    }
163
164    /// Makes every file in `files` durable, however this backend does it best.
165    ///
166    /// Committing each file in turn is the obvious implementation and the
167    /// default here, which is right for a backend whose `commit` is a no-op. On
168    /// a real filesystem it is the slowest option available: it keeps exactly
169    /// one sync in flight, so nothing the kernel does to batch them applies.
170    ///
171    /// Committing a file that is already durable is harmless, so a backend may
172    /// make more files durable than were asked for. `files` is never empty.
173    fn sync_files(&self, files: &[Arc<dyn FileCommitter>]) -> Result<(), StorageError> {
174        for file in files {
175            file.commit()?;
176        }
177        Ok(())
178    }
179
180    /// Flushes the directory entry metadata for `dir` to stable storage.
181    ///
182    /// POSIX `fsync(file)` guarantees the file's data is durable but says
183    /// nothing about whether the file's name in its parent directory is
184    /// durable. After renaming files into a directory or creating new
185    /// subdirectories, the caller can use this barrier to make those
186    /// directory entries durable in one syscall.
187    ///
188    /// Backends that do not have a meaningful notion of directory
189    /// durability (e.g. object stores) may treat this as a no-op.
190    fn fsync_dir(&self, _dir: &StoragePath) -> Result<(), StorageError> {
191        Ok(())
192    }
193
194    /// Returns a value that represents the number of bytes of storage in use.
195    /// The storage backend updates this value when its own functions cause more
196    /// or less storage to be used:
197    ///
198    /// - Writing to a file.
199    ///
200    /// - Deleting a file (by dropping a [FileWriter] without completing, or by
201    ///   dropping a [FileReader] without marking it for a checkpoint, or by
202    ///   calling functions to delete files.
203    ///
204    /// The backend is *not* required to:
205    ///
206    /// - Initially report how much storage is in use. Instead, it just starts
207    ///   out at zero. The client can traverse the storage itself and store the
208    ///   correct initial value.
209    ///
210    /// - Detect changes made by a different backend or outside any backend.
211    ///
212    /// The value is signed because the problems above can cause it to become
213    /// negative.
214    fn usage(&self) -> Arc<AtomicI64>;
215}
216
217impl dyn StorageBackend {
218    /// Creates and returns a new backend configured according to `config` and `options`.
219    pub fn new(
220        config: &StorageConfig,
221        options: &StorageOptions,
222    ) -> Result<Arc<Self>, StorageError> {
223        Self::warn_about_tmpfs(config.path());
224        for variable_provider in inventory::iter::<&dyn StorageBackendFactory> {
225            if variable_provider.backend() == options.backend.to_string() {
226                return variable_provider.create(config, &options.backend);
227            }
228        }
229        Err(StorageError::BackendNotSupported(Box::new(
230            options.backend.clone(),
231        )))
232    }
233
234    fn is_tmpfs(_path: &Path) -> bool {
235        #[cfg(target_os = "linux")]
236        {
237            use nix::sys::statfs;
238            statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
239        }
240
241        #[cfg(not(target_os = "linux"))]
242        false
243    }
244
245    fn warn_about_tmpfs(path: &Path) {
246        if Self::is_tmpfs(path) {
247            static ONCE: std::sync::Once = std::sync::Once::new();
248            ONCE.call_once(|| {
249                warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
250            });
251        }
252    }
253
254    pub fn gather_batches_for_checkpoint_uuid(
255        &self,
256        cpm: uuid::Uuid,
257    ) -> Result<HashSet<StoragePath>, StorageError> {
258        assert!(!cpm.is_nil());
259
260        let checkpoint_dir: StoragePath = cpm.to_string().into();
261
262        // `dependencies.json` holds the authoritative snapshot of every
263        // batch referenced by the checkpoint at commit time. Prefer it
264        // over the per-spine `pspine-batches-*.dat` scan below: a valid
265        // commit always writes it, and it captures the full list in one
266        // place so a single read suffices. See `CheckpointDependencies`
267        // for the accepted JSON forms.
268        let deps_path = checkpoint_dir.clone().join(CHECKPOINT_DEPENDENCIES);
269        match self.read_json::<CheckpointDependencies>(&deps_path) {
270            Ok(deps) => {
271                return Ok(deps
272                    .batches()
273                    .iter()
274                    .map(|b| StoragePath::from(b.as_str()))
275                    .collect());
276            }
277            Err(error) if error.kind() == ErrorKind::NotFound => {
278                // Fall back to scanning per-spine sidecars. Predates the
279                // `dependencies.json` snapshot entirely.
280            }
281            Err(error) => return Err(error),
282        }
283
284        // Legacy fallback. New checkpoints always carry a
285        // `dependencies.json` (the early-return above), so this scan only
286        // runs for checkpoints written before that file existed.
287        // TODO: remove once no such old checkpoints remain in use.
288        let mut spines = Vec::new();
289        self.list(&checkpoint_dir, &mut |entry| {
290            if let Some(filename) = entry.name.filename()
291                && filename.starts_with("pspine-batches")
292            {
293                spines.push(entry.name);
294            }
295        })?;
296
297        let mut batch_files_in_commit: HashSet<StoragePath> = HashSet::new();
298        for spine in spines {
299            let pspine_batches = self.read_json::<PSpineBatches>(&spine)?;
300            for file in pspine_batches.files {
301                batch_files_in_commit.insert(file.into());
302            }
303        }
304
305        Ok(batch_files_in_commit)
306    }
307
308    pub fn gather_batches_for_checkpoint(
309        &self,
310        cpm: &CheckpointMetadata,
311    ) -> Result<HashSet<StoragePath>, StorageError> {
312        self.gather_batches_for_checkpoint_uuid(cpm.uuid)
313    }
314}
315
316// For an explanation of the `+ '_` here, see:
317// https://stackoverflow.com/questions/73495603/trait-problem-borrowed-data-escapes-outside-of-associated-function
318impl dyn StorageBackend + '_ {
319    /// Writes `content` to `name` as JSON, automatically creating any parent
320    /// directories within `name` that don't already exist.
321    ///
322    /// The returned file is readable but not durable. To make it durable, the
323    /// caller must either call `commit` on it or hand it to the checkpoint
324    /// commit phase.
325    #[must_use = "the file is not durable until this committer is committed"]
326    pub fn write_json<V>(
327        &self,
328        name: &StoragePath,
329        value: &V,
330    ) -> Result<Arc<dyn FileCommitter>, StorageError>
331    where
332        V: serde::Serialize,
333    {
334        let mut content = FBuf::new();
335        serde_json::to_writer(&mut content, value).unwrap();
336        self.write(name, content)
337    }
338
339    /// Reads `name` as JSON.
340    pub fn read_json<V>(&self, name: &StoragePath) -> Result<V, StorageError>
341    where
342        V: DeserializeOwned,
343    {
344        let content = self.read(name)?;
345        serde_json::from_reader(Cursor::new(content.as_ref()))
346            .map_err(|e| StorageError::JsonError(e.to_string()))
347    }
348}
349
350/// A directory entry read by [StorageBackend::list].
351pub struct DirEntry {
352    /// File name.
353    pub name: StoragePath,
354
355    /// File type, if it could be obtained.
356    pub file_type: Result<StorageFileType, StorageError>,
357}
358
359/// A file being read or written.
360pub trait FileRw {
361    /// Returns the file's unique ID.
362    fn file_id(&self) -> FileId;
363
364    /// Returns the file's path.
365    fn path(&self) -> &StoragePath;
366}
367
368/// A file being written.
369///
370/// The file can't be read until it is completed with
371/// [FileWriter::complete]. Until then, the file is temporary and will be
372/// deleted if it is dropped.
373pub trait FileWriter: Send + Sync + FileRw {
374    /// Writes `data` at the end of the file. len()` must be a multiple of 512.
375    /// Returns the data that was written encapsulated in an `Arc`.
376    fn write_block(&mut self, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
377
378    /// Completes writing of a file and returns a reader for the file.
379    ///
380    /// The file will be deleted if the reader is dropped without calling
381    /// [FileReader::mark_for_checkpoint].
382    ///
383    /// This makes the file readable, not durable. The contents survive a crash
384    /// only once [FileCommitter::commit] returns for the reader, so a caller
385    /// that needs durability must commit, either directly or by handing the
386    /// reader to the checkpoint commit phase.
387    fn complete(self: Box<Self>) -> Result<Arc<dyn FileReader>, StorageError>;
388}
389
390/// Allows a file to be committed to stable storage.
391///
392/// This is a supertrait of [FileReader] that only allows the commit operation.
393/// It's somewhat surprising that a file that can't be written can be committed,
394/// but it makes sense in the context of [FileWriter::complete] returning a
395/// [FileReader] that isn't necessarily committed yet.  Making this a separate
396/// trait allows code to split off a `FileCommitter` to hand to a piece of code
397/// that only needs to be able to commit it.
398pub trait FileCommitter: Send + Sync + Debug + FileRw {
399    /// Commits the file to stable storage.
400    fn commit(&self) -> Result<(), StorageError>;
401}
402
403/// A readable file.
404pub trait FileReader: Send + Sync + Debug + FileRw + FileCommitter {
405    /// Marks a file to be part of a checkpoint.
406    ///
407    /// This is used to prevent the file from being deleted when it is dropped.
408    /// This is only useful for files obtained via [FileWriter::complete],
409    /// because files that were opened with [StorageBackend::open] are never
410    /// deleted on drop.
411    fn mark_for_checkpoint(&self);
412
413    /// Reads data at `location` from the file.  If successful, the result will
414    /// be exactly the requested length; that is, this API treats read past EOF
415    /// as an error.
416    fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
417
418    /// Initiates an asynchronous read.  When the read completes, `callback`
419    /// will be called.
420    ///
421    /// The default implementation is not actually asynchronous.
422    #[allow(clippy::type_complexity)]
423    fn read_async(
424        &self,
425        blocks: Vec<BlockLocation>,
426        callback: Box<dyn FnOnce(Vec<Result<Arc<FBuf>, StorageError>>) + Send>,
427    ) {
428        default_read_async(self, blocks, callback);
429    }
430
431    /// Returns the file's size in bytes.
432    fn get_size(&self) -> Result<u64, StorageError>;
433}
434
435/// Default implementation for [FileReader::read_async].
436///
437/// This implementation is not actually asynchronous.
438#[allow(clippy::type_complexity)]
439pub fn default_read_async<R>(
440    reader: &R,
441    blocks: Vec<BlockLocation>,
442    callback: Box<dyn FnOnce(Vec<Result<Arc<FBuf>, StorageError>>) + Send>,
443) where
444    R: FileReader + ?Sized,
445{
446    callback(
447        blocks
448            .into_iter()
449            .map(|location| reader.read_block(location))
450            .collect(),
451    )
452}
453
454#[derive(Copy, Clone, Debug, PartialEq, Eq)]
455pub enum StorageFileType {
456    /// A regular file.
457    File {
458        /// File size in bytes.
459        size: u64,
460    },
461
462    /// A directory.
463    ///
464    /// Only some kinds of storage backends support directories. The ones that
465    /// don't still allow files to be named hierarchically, but they don't
466    /// support creating or deleting directories independently from the files in
467    /// them. That is, with such a backend, a directory is effectively created
468    /// by creating a file in it, and is effectively deleted when the last file
469    /// in it is deleted.
470    Directory,
471
472    /// Something else.
473    Other,
474}