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 tokio;
28
29const CREATE_FILE_EXTENSION: &str = ".feldera";
31
32pub 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
50pub trait StorageBackend: Send + Sync {
52 fn create_named(&self, name: &StoragePath) -> Result<Box<dyn FileWriter>, StorageError>;
55
56 fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
59 self.create_with_prefix(&StoragePath::default())
60 }
61
62 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 fn open(&self, name: &StoragePath) -> Result<Arc<dyn FileReader>, StorageError>;
75
76 fn file_system_path(&self) -> Option<&Path> {
79 None
80 }
81
82 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 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 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 fn usage(&self) -> Arc<AtomicI64>;
149}
150
151impl dyn StorageBackend {
152 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(
189 &self,
190 cpm: &CheckpointMetadata,
191 ) -> Result<HashSet<StoragePath>, StorageError> {
192 assert!(!cpm.uuid.is_nil());
193
194 let mut spines = Vec::new();
195 self.list(&cpm.uuid.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 write_json<V>(&self, name: &StoragePath, value: &V) -> Result<(), StorageError>
218 where
219 V: serde::Serialize,
220 {
221 let mut content = FBuf::new();
222 serde_json::to_writer(&mut content, value).unwrap();
223 self.write(name, content)
224 }
225}
226
227impl dyn StorageBackend + '_ {
230 pub fn read_json<V>(&self, name: &StoragePath) -> Result<V, StorageError>
232 where
233 V: DeserializeOwned,
234 {
235 let content = self.read(name)?;
236 serde_json::from_reader(Cursor::new(content.as_ref()))
237 .map_err(|e| StorageError::JsonError(e.to_string()))
238 }
239}
240
241pub trait FileWriter: Send + Sync + HasFileId {
247 fn write_block(&mut self, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
250
251 fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, StoragePath), StorageError>;
256}
257
258pub trait FileReader: Send + Sync + HasFileId {
260 fn mark_for_checkpoint(&self);
267
268 fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
272
273 #[allow(clippy::type_complexity)]
278 fn read_async(
279 &self,
280 blocks: Vec<BlockLocation>,
281 callback: Box<dyn FnOnce(Vec<Result<Arc<FBuf>, StorageError>>) + Send>,
282 ) {
283 default_read_async(self, blocks, callback);
284 }
285
286 fn get_size(&self) -> Result<u64, StorageError>;
288}
289
290#[allow(clippy::type_complexity)]
294pub fn default_read_async<R>(
295 reader: &R,
296 blocks: Vec<BlockLocation>,
297 callback: Box<dyn FnOnce(Vec<Result<Arc<FBuf>, StorageError>>) + Send>,
298) where
299 R: FileReader + ?Sized,
300{
301 callback(
302 blocks
303 .into_iter()
304 .map(|location| reader.read_block(location))
305 .collect(),
306 )
307}
308
309#[derive(Copy, Clone, Debug, PartialEq, Eq)]
310pub enum StorageFileType {
311 File {
313 size: u64,
315 },
316
317 Directory,
326
327 Other,
329}