1use 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
31const CREATE_FILE_EXTENSION: &str = ".feldera";
33
34pub 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
52pub trait StorageBackend: Send + Sync {
54 fn create_named(&self, name: &StoragePath) -> Result<Box<dyn FileWriter>, StorageError>;
57
58 fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
61 self.create_with_prefix(&StoragePath::default())
62 }
63
64 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 fn open(&self, name: &StoragePath) -> Result<Arc<dyn FileReader>, StorageError>;
77
78 fn file_system_path(&self) -> Option<&Path> {
81 None
82 }
83
84 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 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 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 fn usage(&self) -> Arc<AtomicI64>;
151}
152
153impl dyn StorageBackend {
154 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 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
236impl dyn StorageBackend + '_ {
239 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
250pub trait FileWriter: Send + Sync + HasFileId {
256 fn write_block(&mut self, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
259
260 fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, StoragePath), StorageError>;
265}
266
267pub trait FileReader: Send + Sync + HasFileId {
269 fn mark_for_checkpoint(&self);
276
277 fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
281
282 #[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 fn get_size(&self) -> Result<u64, StorageError>;
297}
298
299#[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 File {
322 size: u64,
324 },
325
326 Directory,
335
336 Other,
338}