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