1use std::path::{Path, PathBuf};
4use std::rc::Rc;
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 mod block;
17pub mod error;
18pub mod fbuf;
19pub mod file;
20pub mod tokio;
21
22const CREATE_FILE_EXTENSION: &str = ".feldera";
24
25pub fn append_to_path(p: PathBuf, s: &str) -> PathBuf {
27 let mut p = p.into_os_string();
28 p.push(s);
29 p.into()
30}
31
32pub trait StorageBackendFactory: Sync {
33 fn backend(&self) -> &'static str;
34 fn create(
35 &self,
36 storage_config: &StorageConfig,
37 backend_config: &StorageBackendConfig,
38 ) -> Result<Rc<dyn StorageBackend>, StorageError>;
39}
40
41inventory::collect!(&'static dyn StorageBackendFactory);
42
43pub trait StorageBackend {
45 fn create_named(&self, name: &Path) -> Result<Box<dyn FileWriter>, StorageError>;
48
49 fn create(&self) -> Result<Box<dyn FileWriter>, StorageError> {
52 self.create_with_prefix("")
53 }
54
55 fn create_with_prefix(&self, prefix: &str) -> Result<Box<dyn FileWriter>, StorageError> {
58 let uuid = Uuid::now_v7();
59 let name = format!("{}{}{}", prefix, uuid, CREATE_FILE_EXTENSION);
60 let name_path = Path::new(&name);
61 self.create_named(name_path)
62 }
63
64 fn open(&self, name: &Path) -> Result<Arc<dyn FileReader>, StorageError>;
67}
68
69impl dyn StorageBackend {
70 pub fn new(config: &StorageConfig, options: &StorageOptions) -> Result<Rc<Self>, StorageError> {
72 Self::warn_about_tmpfs(config.path());
73 for variable_provider in inventory::iter::<&dyn StorageBackendFactory> {
74 if variable_provider.backend() == options.backend.to_string() {
75 return variable_provider.create(config, &options.backend);
76 }
77 }
78 Err(StorageError::BackendNotSupported(options.backend.clone()))
79 }
80
81 fn is_tmpfs(_path: &Path) -> bool {
82 #[cfg(target_os = "linux")]
83 {
84 use nix::sys::statfs;
85 statfs::statfs(_path).is_ok_and(|s| s.filesystem_type() == statfs::TMPFS_MAGIC)
86 }
87
88 #[cfg(not(target_os = "linux"))]
89 false
90 }
91
92 fn warn_about_tmpfs(path: &Path) {
93 if Self::is_tmpfs(path) {
94 static ONCE: std::sync::Once = std::sync::Once::new();
95 ONCE.call_once(|| {
96 warn!("initializing storage on in-memory tmpfs filesystem at {}; consider configuring physical storage", path.display())
97 });
98 }
99 }
100}
101
102pub trait FileWriter: HasFileId {
108 fn write_block(&mut self, offset: u64, data: FBuf) -> Result<Arc<FBuf>, StorageError>;
112
113 fn complete(self: Box<Self>) -> Result<(Arc<dyn FileReader>, PathBuf), StorageError>;
118}
119
120pub trait FileReader: Send + Sync + HasFileId {
122 fn mark_for_checkpoint(&self);
129
130 fn read_block(&self, location: BlockLocation) -> Result<Arc<FBuf>, StorageError>;
134
135 fn get_size(&self) -> Result<u64, StorageError>;
137}