1use std::io::{Cursor, ErrorKind};
4use std::path::{Path, PathBuf};
5use std::sync::atomic::AtomicI64;
6use std::sync::Arc;
7
8use feldera_types::config::{StorageBackendConfig, StorageConfig, StorageOptions};
9use serde::de::DeserializeOwned;
10use tracing::warn;
11use uuid::Uuid;
12
13use crate::block::BlockLocation;
14use crate::error::StorageError;
15use crate::fbuf::FBuf;
16use crate::file::HasFileId;
17
18pub use object_store::path::{Path as StoragePath, PathPart as StoragePathPart};
19
20pub mod block;
21pub mod error;
22pub mod fbuf;
23pub mod file;
24pub mod tokio;
25
26const CREATE_FILE_EXTENSION: &str = ".feldera";
28
29pub fn append_to_path(p: PathBuf, s: &str) -> PathBuf {
31 let mut p = p.into_os_string();
32 p.push(s);
33 p.into()
34}
35
36pub trait StorageBackendFactory: Sync {
37 fn backend(&self) -> &'static str;
38 fn create(
39 &self,
40 storage_config: &StorageConfig,
41 backend_config: &StorageBackendConfig,
42 ) -> Result<Arc<dyn StorageBackend>, StorageError>;
43}
44
45inventory::collect!(&'static dyn StorageBackendFactory);
46
47pub trait StorageBackend: Send + Sync {
49 fn create_named(&self, name: &StoragePath) -> Result<Box<dyn FileWriter>, StorageError>;
52
53 fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
56 self.create_with_prefix(&StoragePath::default())
57 }
58
59 fn create_with_prefix(
62 &self,
63 prefix: &StoragePath,
64 ) -> Result<Box<dyn FileWriter>, StorageError> {
65 let uuid = Uuid::now_v7();
66 let name = format!("{}{}{}", prefix, uuid, CREATE_FILE_EXTENSION);
67 self.create_named(&name.into())
68 }
69
70 fn open(&self, name: &StoragePath) -> Result<Arc<dyn FileReader>, StorageError>;
72
73 fn list(
77 &self,
78 parent: &StoragePath,
79 cb: &mut dyn FnMut(&StoragePath, StorageFileType),
80 ) -> Result<(), StorageError>;
81
82 fn delete(&self, name: &StoragePath) -> Result<(), StorageError>;
83
84 fn delete_recursive(&self, name: &StoragePath) -> Result<(), StorageError>;
85
86 fn delete_if_exists(&self, name: &StoragePath) -> Result<(), StorageError> {
87 match self.delete(name) {
88 Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
89 other => other,
90 }
91 }
92
93 fn exists(&self, name: &StoragePath) -> Result<bool, StorageError> {
94 match self.open(name) {
95 Ok(_) => Ok(true),
96 Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
97 Err(error) => Err(error),
98 }
99 }
100
101 fn read(&self, name: &StoragePath) -> Result<Arc<FBuf>, StorageError> {
104 let reader = self.open(name)?;
105 let size = reader.get_size()?.try_into().unwrap();
106 reader.read_block(BlockLocation { offset: 0, size })
107 }
108
109 fn write(&self, name: &StoragePath, content: FBuf) -> Result<(), StorageError> {
112 let mut writer = self.create_named(name)?;
113 writer.write_block(content)?;
114 let (reader, _path) = writer.complete()?;
115 reader.mark_for_checkpoint();
116 Ok(())
117 }
118
119 fn usage(&self) -> Arc<AtomicI64>;
140}
141
142impl dyn StorageBackend {
143 pub fn new(
145 config: &StorageConfig,
146 options: &StorageOptions,
147 ) -> Result<Arc<Self>, StorageError> {
148 Self::warn_about_tmpfs(config.path());
149 for variable_provider in inventory::iter::<&dyn StorageBackendFactory> {
150 if variable_provider.backend() == options.backend.to_string() {
151 return variable_provider.create(config, &options.backend);
152 }
153 }
154 Err(StorageError::BackendNotSupported(Box::new(
155 options.backend.clone(),
156 )))
157 }
158
159 fn is_tmpfs(_path: &Path) -> bool {
160 #[cfg(target_os = "linux")]
161 {
162 use nix::sys::statfs;
163 statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
164 }
165
166 #[cfg(not(target_os = "linux"))]
167 false
168 }
169
170 fn warn_about_tmpfs(path: &Path) {
171 if Self::is_tmpfs(path) {
172 static ONCE: std::sync::Once = std::sync::Once::new();
173 ONCE.call_once(|| {
174 warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
175 });
176 }
177 }
178
179 pub fn write_json<V>(&self, name: &StoragePath, value: &V) -> Result<(), StorageError>
182 where
183 V: serde::Serialize,
184 {
185 let mut content = FBuf::new();
186 serde_json::to_writer(&mut content, value).unwrap();
187 self.write(name, content)
188 }
189}
190
191impl dyn StorageBackend + '_ {
194 pub fn read_json<V>(&self, name: &StoragePath) -> Result<V, StorageError>
196 where
197 V: DeserializeOwned,
198 {
199 let content = self.read(name)?;
200 serde_json::from_reader(Cursor::new(content.as_ref()))
201 .map_err(|e| StorageError::JsonError(e.to_string()))
202 }
203}
204
205pub trait FileWriter: Send + Sync + HasFileId {
211 fn write_block(&mut self, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
214
215 fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, StoragePath), StorageError>;
220}
221
222pub trait FileReader: Send + Sync + HasFileId {
224 fn mark_for_checkpoint(&self);
231
232 fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
236
237 fn read_async(
242 &self,
243 blocks: Vec<BlockLocation>,
244 callback: Box<dyn FnOnce(Vec<Result<Arc<FBuf>, StorageError>>) + Send>,
245 ) {
246 default_read_async(self, blocks, callback);
247 }
248
249 fn get_size(&self) -> Result<u64, StorageError>;
251}
252
253pub fn default_read_async<R>(
257 reader: &R,
258 blocks: Vec<BlockLocation>,
259 callback: Box<dyn FnOnce(Vec<Result<Arc<FBuf>, StorageError>>) + Send>,
260) where
261 R: FileReader + ?Sized,
262{
263 callback(
264 blocks
265 .into_iter()
266 .map(|location| reader.read_block(location))
267 .collect(),
268 )
269}
270
271#[derive(Copy, Clone, Debug, PartialEq, Eq)]
272pub enum StorageFileType {
273 File {
275 size: u64,
277 },
278
279 Directory,
288
289 Other,
291}