khive_runtime/events_split/
registry.rs1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3
4use khive_db::{StorageBackend, WalCeilingPolicy};
5
6use super::file_hardening::refuse_events_db_symlinks;
7#[cfg(unix)]
8use super::file_hardening::{ensure_events_db_parent_trusted, harden_events_db_sidecars};
9#[cfg(unix)]
10use super::forwarder::{EventsForwardingMetrics, EventsSplitClient};
11use super::paths::absolutize;
12
13#[derive(Debug, Clone)]
15pub struct EventsSplitConfig {
16 pub db_path: PathBuf,
19 pub socket_path: Option<PathBuf>,
23}
24
25#[cfg(unix)]
35pub(super) type ClientMap = std::collections::HashMap<PathBuf, Arc<EventsSplitClient>>;
36pub(super) type BackendMap = std::collections::HashMap<PathBuf, (bool, Arc<StorageBackend>)>;
40
41#[cfg(unix)]
42pub(super) fn client_registry() -> &'static std::sync::Mutex<ClientMap> {
43 static REGISTRY: std::sync::OnceLock<std::sync::Mutex<ClientMap>> = std::sync::OnceLock::new();
44 REGISTRY.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
45}
46
47pub(super) fn direct_backend_registry() -> &'static std::sync::Mutex<BackendMap> {
48 static REGISTRY: std::sync::OnceLock<std::sync::Mutex<BackendMap>> = std::sync::OnceLock::new();
49 REGISTRY.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
50}
51
52#[cfg(any(test, feature = "test-internals"))]
59#[doc(hidden)]
60pub struct TestRegistryGuard<'a> {
61 pub(super) root: &'a Path,
62 pub(super) canonical_root: PathBuf,
63}
64
65#[cfg(any(test, feature = "test-internals"))]
66impl<'a> TestRegistryGuard<'a> {
67 pub fn new(root: &'a Path) -> Self {
69 Self {
70 root,
71 canonical_root: std::fs::canonicalize(root).expect("existing unique fixture root"),
72 }
73 }
74
75 pub(super) fn remove_entries<T>(
76 &self,
77 registry: &std::sync::Mutex<std::collections::HashMap<PathBuf, T>>,
78 ) -> Vec<T> {
79 let mut entries = registry
80 .lock()
81 .unwrap_or_else(std::sync::PoisonError::into_inner);
82 let keys: Vec<_> = entries
83 .keys()
84 .filter(|path| path.starts_with(self.root) || path.starts_with(&self.canonical_root))
85 .cloned()
86 .collect();
87 keys.into_iter()
88 .filter_map(|key| entries.remove(&key))
89 .collect()
90 }
91}
92
93#[cfg(any(test, feature = "test-internals"))]
94impl Drop for TestRegistryGuard<'_> {
95 fn drop(&mut self) {
96 let backends = self.remove_entries(direct_backend_registry());
99 #[cfg(unix)]
100 let clients = self.remove_entries(client_registry());
101 drop(backends);
102 #[cfg(unix)]
103 drop(clients);
104 }
105}
106
107#[cfg(unix)]
110pub fn client_for(socket_path: &Path) -> crate::error::RuntimeResult<Arc<EventsSplitClient>> {
111 let mut registry = client_registry()
112 .lock()
113 .unwrap_or_else(std::sync::PoisonError::into_inner);
114 if let Some(existing) = registry.get(socket_path) {
115 return Ok(Arc::clone(existing));
116 }
117 let client = EventsSplitClient::new(socket_path.to_path_buf())?;
118 registry.insert(socket_path.to_path_buf(), Arc::clone(&client));
119 Ok(client)
120}
121
122pub fn direct_backend_for(db_path: &Path) -> crate::error::RuntimeResult<Arc<StorageBackend>> {
125 direct_backend_with_max_readers(db_path, false, None)
126}
127
128pub fn direct_backend_read_only_for(
133 db_path: &Path,
134) -> crate::error::RuntimeResult<Arc<StorageBackend>> {
135 direct_backend_with_max_readers(db_path, true, None)
136}
137
138pub(crate) fn direct_backend_with_max_readers(
140 db_path: &Path,
141 read_only: bool,
142 max_readers: Option<usize>,
143) -> crate::error::RuntimeResult<Arc<StorageBackend>> {
144 let mut config = crate::RuntimeConfig {
145 db_path: Some(db_path.to_path_buf()),
146 ..crate::RuntimeConfig::no_embeddings()
147 };
148 let wal_ceiling = config.resolve_wal_ceiling_policy(read_only)?;
149 let disk_guard = config.resolve_disk_guard_policy(read_only)?;
150 direct_backend_with_policies(
151 db_path,
152 read_only,
153 max_readers,
154 wal_ceiling,
155 disk_guard,
156 config.volume_lock_dir,
157 )
158}
159
160pub(crate) fn direct_backend_with_policies(
164 db_path: &Path,
165 read_only: bool,
166 max_readers: Option<usize>,
167 wal_ceiling: WalCeilingPolicy,
168 disk_guard: Option<khive_db::EffectiveDiskGuardConfig>,
169 volume_lock_dir: Option<PathBuf>,
170) -> crate::error::RuntimeResult<Arc<StorageBackend>> {
171 wal_ceiling.validate_static(true, true, read_only)?;
172 if !read_only {
173 disk_guard
174 .ok_or_else(|| {
175 crate::error::RuntimeError::Internal("missing events disk policy".into())
176 })?
177 .validate()?;
178 khive_db::require_volume_lock_dir(volume_lock_dir.clone())?;
179 }
180 let mut registry = direct_backend_registry()
181 .lock()
182 .unwrap_or_else(std::sync::PoisonError::into_inner);
183 let absolute_path = absolutize(db_path);
184 let db_path = absolute_path.as_path();
185 refuse_events_db_symlinks(db_path)
186 .map_err(|e| crate::error::RuntimeError::Internal(e.to_string()))?;
187 #[cfg(unix)]
188 if !read_only {
189 if let Some(parent) = db_path.parent().filter(|p| !p.as_os_str().is_empty()) {
190 let _ = std::fs::create_dir_all(parent);
191 }
192 }
193 #[cfg(unix)]
199 ensure_events_db_parent_trusted(db_path)
200 .map_err(|e| crate::error::RuntimeError::Internal(e.to_string()))?;
201 let key = std::fs::canonicalize(db_path)
202 .or_else(|error| {
203 if error.kind() != std::io::ErrorKind::NotFound {
204 return Err(error);
205 }
206 let parent = db_path.parent().ok_or(error)?;
207 let name = db_path.file_name().ok_or_else(|| {
208 std::io::Error::new(
209 std::io::ErrorKind::InvalidInput,
210 "events path has no file name",
211 )
212 })?;
213 std::fs::canonicalize(parent).map(|parent| parent.join(name))
214 })
215 .map_err(|e| crate::error::RuntimeError::Internal(e.to_string()))?;
216 if let Some((existing_read_only, existing)) = registry.get(&key) {
217 if *existing_read_only != read_only {
218 let existing_mode = if *existing_read_only {
219 "read-only"
220 } else {
221 "writable"
222 };
223 let requested_mode = if read_only { "read-only" } else { "writable" };
224 return Err(crate::error::RuntimeError::InvalidInput(format!(
225 "events database {} is already open {existing_mode} in this process; cannot \
226 open it {requested_mode}; read-only events access requires a separate frozen snapshot",
227 key.display()
228 )));
229 }
230 let numbers = |p: Option<khive_db::EffectiveDiskGuardConfig>| {
231 p.map(|p| (p.reserve_bytes, p.guard_deadline_ms))
232 };
233 if numbers(existing.pool().effective_disk_guard_config()) != numbers(disk_guard) {
234 return Err(crate::error::RuntimeError::Internal(
235 "events database is already open with a different disk reserve/deadline policy"
236 .into(),
237 ));
238 }
239 if !read_only && existing.pool().config().volume_lock_dir != volume_lock_dir {
240 return Err(crate::error::RuntimeError::Internal(
241 "events database is already open with a different volume-lock directory".into(),
242 ));
243 }
244 let existing_bytes = existing.pool().config().wal_ceiling.bytes;
245 if existing_bytes != wal_ceiling.bytes {
246 return Err(khive_db::SqliteError::InvalidConfig(format!(
247 "events database {} is already open with wal_ceiling_bytes={existing_bytes}; \
248 requested {}; drain and restart before changing the WAL ceiling",
249 key.display(),
250 wal_ceiling.bytes
251 ))
252 .into());
253 }
254 return Ok(Arc::clone(existing));
255 }
256 let db_path = key.as_path();
257 #[cfg(unix)]
263 if !read_only {
264 use std::os::unix::fs::OpenOptionsExt;
265 let _ = std::fs::OpenOptions::new()
266 .write(true)
267 .create_new(true)
268 .mode(0o600)
269 .open(db_path);
270 let _before_open = harden_events_db_sidecars(db_path)
273 .map_err(|e| crate::error::RuntimeError::Internal(e.to_string()))?;
274 }
275 let backend = Arc::new(if read_only {
276 StorageBackend::sqlite_read_only_with_max_readers_and_wal_ceiling(
277 db_path,
278 max_readers,
279 wal_ceiling,
280 )?
281 } else {
282 StorageBackend::sqlite_with_max_readers_and_policies(
283 db_path,
284 max_readers,
285 wal_ceiling,
286 disk_guard.ok_or_else(|| {
287 crate::error::RuntimeError::Internal("missing events disk policy".into())
288 })?,
289 khive_db::require_volume_lock_dir(volume_lock_dir)?,
290 )?
291 });
292 registry.insert(key, (read_only, Arc::clone(&backend)));
293 Ok(backend)
294}
295
296#[cfg(unix)]
299pub fn forwarding_metrics(socket_path: &Path) -> Option<EventsForwardingMetrics> {
300 let registry = client_registry()
301 .lock()
302 .unwrap_or_else(std::sync::PoisonError::into_inner);
303 registry.get(socket_path).map(|client| client.metrics())
304}