1use std::io::ErrorKind;
4use std::path::{Path, PathBuf};
5use std::sync::atomic::AtomicI64;
6use std::sync::Arc;
7
8use feldera_types::config::{StorageBackendConfig, StorageConfig, StorageOptions};
9use tracing::warn;
10use uuid::Uuid;
11
12use crate::block::BlockLocation;
13use crate::error::StorageError;
14use crate::fbuf::FBuf;
15use crate::file::HasFileId;
16
17pub use object_store::path::{Path as StoragePath, PathPart as StoragePathPart};
18
19pub mod block;
20pub mod error;
21pub mod fbuf;
22pub mod file;
23pub mod tokio;
24
25const CREATE_FILE_EXTENSION: &str = ".feldera";
27
28pub fn append_to_path(p: PathBuf, s: &str) -> PathBuf {
30 let mut p = p.into_os_string();
31 p.push(s);
32 p.into()
33}
34
35pub trait StorageBackendFactory: Sync {
36 fn backend(&self) -> &'static str;
37 fn create(
38 &self,
39 storage_config: &StorageConfig,
40 backend_config: &StorageBackendConfig,
41 ) -> Result<Arc<dyn StorageBackend>, StorageError>;
42}
43
44inventory::collect!(&'static dyn StorageBackendFactory);
45
46pub trait StorageBackend: Send + Sync {
48 fn create_named(&self, name: &StoragePath) -> Result<Box<dyn FileWriter>, StorageError>;
51
52 fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
55 self.create_with_prefix(&StoragePath::default())
56 }
57
58 fn create_with_prefix(
61 &self,
62 prefix: &StoragePath,
63 ) -> Result<Box<dyn FileWriter>, StorageError> {
64 let uuid = Uuid::now_v7();
65 let name = format!("{}{}{}", prefix, uuid, CREATE_FILE_EXTENSION);
66 self.create_named(&name.into())
67 }
68
69 fn open(&self, name: &StoragePath) -> Result<Arc<dyn FileReader>, StorageError>;
71
72 fn list(
76 &self,
77 parent: &StoragePath,
78 cb: &mut dyn FnMut(&StoragePath, StorageFileType),
79 ) -> Result<(), StorageError>;
80
81 fn delete(&self, name: &StoragePath) -> Result<(), StorageError>;
82
83 fn delete_recursive(&self, name: &StoragePath) -> Result<(), StorageError>;
84
85 fn delete_if_exists(&self, name: &StoragePath) -> Result<(), StorageError> {
86 match self.delete(name) {
87 Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
88 other => other,
89 }
90 }
91
92 fn exists(&self, name: &StoragePath) -> Result<bool, StorageError> {
93 match self.open(name) {
94 Ok(_) => Ok(true),
95 Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
96 Err(error) => Err(error),
97 }
98 }
99
100 fn read(&self, name: &StoragePath) -> Result<Arc<FBuf>, StorageError> {
103 let reader = self.open(name)?;
104 let size = reader.get_size()?.try_into().unwrap();
105 reader.read_block(BlockLocation { offset: 0, size })
106 }
107
108 fn write(&self, name: &StoragePath, content: FBuf) -> Result<(), StorageError> {
111 let mut writer = self.create_named(name)?;
112 writer.write_block(content)?;
113 let (reader, _path) = writer.complete()?;
114 reader.mark_for_checkpoint();
115 Ok(())
116 }
117
118 fn usage(&self) -> Arc<AtomicI64>;
139}
140
141impl dyn StorageBackend {
142 pub fn new(
144 config: &StorageConfig,
145 options: &StorageOptions,
146 ) -> Result<Arc<Self>, StorageError> {
147 Self::warn_about_tmpfs(config.path());
148 for variable_provider in inventory::iter::<&dyn StorageBackendFactory> {
149 if variable_provider.backend() == options.backend.to_string() {
150 return variable_provider.create(config, &options.backend);
151 }
152 }
153 Err(StorageError::BackendNotSupported(Box::new(
154 options.backend.clone(),
155 )))
156 }
157
158 fn is_tmpfs(_path: &Path) -> bool {
159 #[cfg(target_os = "linux")]
160 {
161 use nix::sys::statfs;
162 statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
163 }
164
165 #[cfg(not(target_os = "linux"))]
166 false
167 }
168
169 fn warn_about_tmpfs(path: &Path) {
170 if Self::is_tmpfs(path) {
171 static ONCE: std::sync::Once = std::sync::Once::new();
172 ONCE.call_once(|| {
173 warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
174 });
175 }
176 }
177}
178
179pub trait FileWriter: Send + Sync + HasFileId {
185 fn write_block(&mut self, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
188
189 fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, StoragePath), StorageError>;
194}
195
196pub trait FileReader: Send + Sync + HasFileId {
198 fn mark_for_checkpoint(&self);
205
206 fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
210
211 fn read_async(
216 &self,
217 blocks: Vec<BlockLocation>,
218 callback: Box<dyn FnOnce(Vec<Result<Arc<FBuf>, StorageError>>) + Send>,
219 ) {
220 default_read_async(self, blocks, callback);
221 }
222
223 fn get_size(&self) -> Result<u64, StorageError>;
225}
226
227pub fn default_read_async<R>(
231 reader: &R,
232 blocks: Vec<BlockLocation>,
233 callback: Box<dyn FnOnce(Vec<Result<Arc<FBuf>, StorageError>>) + Send>,
234) where
235 R: FileReader + ?Sized,
236{
237 callback(
238 blocks
239 .into_iter()
240 .map(|location| reader.read_block(location))
241 .collect(),
242 )
243}
244
245#[derive(Copy, Clone, Debug, PartialEq, Eq)]
246pub enum StorageFileType {
247 File {
249 size: u64,
251 },
252
253 Directory,
262
263 Other,
265}