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(options.backend.clone()))
154 }
155
156 fn is_tmpfs(_path: &Path) -> bool {
157 #[cfg(target_os = "linux")]
158 {
159 use nix::sys::statfs;
160 statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
161 }
162
163 #[cfg(not(target_os = "linux"))]
164 false
165 }
166
167 fn warn_about_tmpfs(path: &Path) {
168 if Self::is_tmpfs(path) {
169 static ONCE: std::sync::Once = std::sync::Once::new();
170 ONCE.call_once(|| {
171 warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
172 });
173 }
174 }
175}
176
177pub trait FileWriter: Send + Sync + HasFileId {
183 fn write_block(&mut self, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
186
187 fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, StoragePath), StorageError>;
192}
193
194pub trait FileReader: Send + Sync + HasFileId {
196 fn mark_for_checkpoint(&self);
203
204 fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
208
209 fn get_size(&self) -> Result<u64, StorageError>;
211}
212
213#[derive(Copy, Clone, Debug, PartialEq, Eq)]
214pub enum StorageFileType {
215 File {
217 size: u64,
219 },
220
221 Directory,
230
231 Other,
233}