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