1use std::io::ErrorKind;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6
7use feldera_types::config::{StorageBackendConfig, StorageConfig, StorageOptions};
8use tracing::warn;
9use uuid::Uuid;
10
11use crate::block::BlockLocation;
12use crate::error::StorageError;
13use crate::fbuf::FBuf;
14use crate::file::HasFileId;
15
16pub use object_store::path::{Path as StoragePath, PathPart as StoragePathPart};
17
18pub mod block;
19pub mod error;
20pub mod fbuf;
21pub mod file;
22pub mod tokio;
23
24const CREATE_FILE_EXTENSION: &str = ".feldera";
26
27pub fn append_to_path(p: PathBuf, s: &str) -> PathBuf {
29 let mut p = p.into_os_string();
30 p.push(s);
31 p.into()
32}
33
34pub trait StorageBackendFactory: Sync {
35 fn backend(&self) -> &'static str;
36 fn create(
37 &self,
38 storage_config: &StorageConfig,
39 backend_config: &StorageBackendConfig,
40 ) -> Result<Arc<dyn StorageBackend>, StorageError>;
41}
42
43inventory::collect!(&'static dyn StorageBackendFactory);
44
45pub trait StorageBackend: Send + Sync {
47 fn create_named(&self, name: &StoragePath) -> Result<Box<dyn FileWriter>, StorageError>;
50
51 fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
54 self.create_with_prefix(&StoragePath::default())
55 }
56
57 fn create_with_prefix(
60 &self,
61 prefix: &StoragePath,
62 ) -> Result<Box<dyn FileWriter>, StorageError> {
63 let uuid = Uuid::now_v7();
64 let name = format!("{}{}{}", prefix, uuid, CREATE_FILE_EXTENSION);
65 self.create_named(&name.into())
66 }
67
68 fn open(&self, name: &StoragePath) -> Result<Arc<dyn FileReader>, StorageError>;
70
71 fn list(
75 &self,
76 parent: &StoragePath,
77 cb: &mut dyn FnMut(&StoragePath, StorageFileType),
78 ) -> Result<(), StorageError>;
79
80 fn delete(&self, name: &StoragePath) -> Result<(), StorageError>;
81
82 fn delete_recursive(&self, name: &StoragePath) -> Result<(), StorageError>;
83
84 fn delete_if_exists(&self, name: &StoragePath) -> Result<(), StorageError> {
85 match self.delete(name) {
86 Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
87 other => other,
88 }
89 }
90
91 fn exists(&self, name: &StoragePath) -> Result<bool, StorageError> {
92 match self.open(name) {
93 Ok(_) => Ok(true),
94 Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
95 Err(error) => Err(error),
96 }
97 }
98
99 fn read(&self, name: &StoragePath) -> Result<Arc<FBuf>, StorageError> {
102 let reader = self.open(name)?;
103 let size = reader.get_size()?.try_into().unwrap();
104 reader.read_block(BlockLocation { offset: 0, size })
105 }
106
107 fn write(&self, name: &StoragePath, content: FBuf) -> Result<(), StorageError> {
110 let mut writer = self.create_named(name)?;
111 writer.write_block(0, content)?;
112 let (reader, _path) = writer.complete()?;
113 reader.mark_for_checkpoint();
114 Ok(())
115 }
116}
117
118impl dyn StorageBackend {
119 pub fn new(
121 config: &StorageConfig,
122 options: &StorageOptions,
123 ) -> Result<Arc<Self>, StorageError> {
124 Self::warn_about_tmpfs(config.path());
125 for variable_provider in inventory::iter::<&dyn StorageBackendFactory> {
126 if variable_provider.backend() == options.backend.to_string() {
127 return variable_provider.create(config, &options.backend);
128 }
129 }
130 Err(StorageError::BackendNotSupported(options.backend.clone()))
131 }
132
133 fn is_tmpfs(_path: &Path) -> bool {
134 #[cfg(target_os = "linux")]
135 {
136 use nix::sys::statfs;
137 statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
138 }
139
140 #[cfg(not(target_os = "linux"))]
141 false
142 }
143
144 fn warn_about_tmpfs(path: &Path) {
145 if Self::is_tmpfs(path) {
146 static ONCE: std::sync::Once = std::sync::Once::new();
147 ONCE.call_once(|| {
148 warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
149 });
150 }
151 }
152}
153
154pub trait FileWriter: Send + Sync + HasFileId {
160 fn write_block(&mut self, offset: u64, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
164
165 fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, StoragePath), StorageError>;
170}
171
172pub trait FileReader: Send + Sync + HasFileId {
174 fn mark_for_checkpoint(&self);
181
182 fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
186
187 fn get_size(&self) -> Result<u64, StorageError>;
189}
190
191#[derive(Copy, Clone, Debug, PartialEq, Eq)]
192pub enum StorageFileType {
193 File,
195
196 Directory,
205
206 Other,
208}