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