Skip to main content

keep_core/
backend.rs

1//! Pluggable storage backends for encrypted key storage.
2use std::collections::BTreeMap;
3use std::path::Path;
4use std::sync::{PoisonError, RwLock};
5
6use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition};
7use tracing::{error, info, warn};
8
9use crate::error::{KeepError, Result, StorageError};
10use crate::migration;
11
12fn lock_error<T>(_: PoisonError<T>) -> KeepError {
13    KeepError::Runtime("lock poisoned".into())
14}
15
16/// Table name for key records.
17pub const KEYS_TABLE: &str = "keys";
18/// Table name for FROST shares.
19pub const SHARES_TABLE: &str = "shares";
20/// Table name for wallet descriptors.
21pub const DESCRIPTORS_TABLE: &str = "wallet_descriptors";
22/// Table name for relay configurations.
23pub const RELAY_CONFIGS_TABLE: &str = "relay_configs";
24/// Table name for application configuration.
25pub const CONFIG_TABLE: &str = "config";
26/// Table name for key health status records.
27pub const HEALTH_STATUS_TABLE: &str = "key_health_status";
28/// Table name for arbitrary-secret records (passwords, API tokens, notes).
29/// Deliberately NOT a replicable table (see `Storage::replicated_table`): a
30/// password vault's metadata surface must not sync to public Nostr relays.
31pub const SECRETS_TABLE: &str = "secrets";
32/// Table name for threshold seals: maps a secret id to its `ThresholdSeal`
33/// (wrapped DEK + OPRF params), present only for secrets whose value is gated
34/// behind a t-of-n OPRF quorum. Like `SECRETS_TABLE`, NOT a replicable table.
35pub const SECRET_SEALS_TABLE: &str = "secret_seals";
36/// Table name for the keep-state replication high-water-mark: maps a `<table>:<record-id>` d-tag to
37/// the highest `created_at` (8-byte big-endian) applied for it, so the consumer rejects any replicated
38/// event that is not strictly newer (replay/rollback protection).
39pub const STATE_VERSIONS_TABLE: &str = "state_versions";
40
41/// A single put-or-delete operation for [`StorageBackend::write_atomic`]. `value` `Some` is a put,
42/// `None` is a delete.
43pub struct AtomicOp<'a> {
44    /// Backend table the op targets.
45    pub table: &'a str,
46    /// Raw key bytes.
47    pub key: &'a [u8],
48    /// `Some(bytes)` to put, `None` to delete.
49    pub value: Option<&'a [u8]>,
50}
51
52/// Trait for pluggable storage backends.
53///
54/// Implementations must be thread-safe (`Send + Sync`).
55pub trait StorageBackend: Send + Sync {
56    /// Get a value by key from the specified table.
57    fn get(&self, table: &str, key: &[u8]) -> Result<Option<Vec<u8>>>;
58    /// Store a key-value pair in the specified table.
59    fn put(&self, table: &str, key: &[u8], value: &[u8]) -> Result<()>;
60    /// Delete a key from the specified table. Returns true if the key existed.
61    fn delete(&self, table: &str, key: &[u8]) -> Result<bool>;
62    /// List all key-value pairs in the specified table.
63    fn list(&self, table: &str) -> Result<Vec<(Vec<u8>, Vec<u8>)>>;
64    /// Create a table if it doesn't exist.
65    fn create_table(&self, table: &str) -> Result<()>;
66
67    /// List only the keys (no values) in the specified table whose bytes
68    /// start with `prefix`. The default implementation falls back to a full
69    /// scan and is suitable for backends without a native prefix iterator.
70    fn list_keys_with_prefix(&self, table: &str, prefix: &[u8]) -> Result<Vec<Vec<u8>>> {
71        Ok(self
72            .list(table)?
73            .into_iter()
74            .filter_map(|(k, _)| if k.starts_with(prefix) { Some(k) } else { None })
75            .collect())
76    }
77
78    /// Delete multiple keys from the specified table in a single atomic
79    /// operation. The default implementation calls `delete` per key and is
80    /// not atomic; backends with transaction support should override this.
81    fn delete_batch(&self, table: &str, keys: &[&[u8]]) -> Result<()> {
82        for key in keys {
83            self.delete(table, key)?;
84        }
85        Ok(())
86    }
87
88    /// Store multiple key-value pairs in a single atomic operation.
89    fn put_batch(&self, table: &str, entries: &[(&[u8], &[u8])]) -> Result<()> {
90        for (key, value) in entries {
91            self.put(table, key, value)?;
92        }
93        Ok(())
94    }
95
96    /// Apply several put/delete operations across tables. The default implementation applies each op
97    /// sequentially via `put`/`delete` and is NOT atomic; backends with transaction support should
98    /// override this so a crash mid-batch cannot leave the ops half-applied. Each op must target a
99    /// DISTINCT table.
100    fn write_atomic(&self, ops: &[AtomicOp<'_>]) -> Result<()> {
101        for op in ops {
102            match op.value {
103                Some(v) => self.put(op.table, op.key, v)?,
104                None => {
105                    self.delete(op.table, op.key)?;
106                }
107            }
108        }
109        Ok(())
110    }
111
112    /// Get the current schema version.
113    ///
114    /// Default implementation returns `CURRENT_SCHEMA_VERSION`, suitable for
115    /// in-memory backends that don't persist schema versions.
116    fn schema_version(&self) -> Result<u32> {
117        Ok(migration::CURRENT_SCHEMA_VERSION)
118    }
119
120    /// Check if migrations are needed.
121    ///
122    /// Default implementation returns `false`, suitable for in-memory backends
123    /// that always start fresh without persisted data to migrate.
124    fn needs_migration(&self) -> Result<bool> {
125        Ok(false)
126    }
127
128    /// Run pending migrations.
129    ///
130    /// Default implementation is a no-op that reports zero migrations run,
131    /// suitable for in-memory backends that don't persist data between sessions.
132    fn run_migrations(&self) -> Result<migration::MigrationResult> {
133        Ok(migration::MigrationResult {
134            from_version: migration::CURRENT_SCHEMA_VERSION,
135            to_version: migration::CURRENT_SCHEMA_VERSION,
136            migrations_run: 0,
137        })
138    }
139}
140
141const KEYS_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("keys");
142const SHARES_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("shares");
143const DESCRIPTORS_TABLE_DEF: TableDefinition<&[u8], &[u8]> =
144    TableDefinition::new("wallet_descriptors");
145const RELAY_CONFIGS_TABLE_DEF: TableDefinition<&[u8], &[u8]> =
146    TableDefinition::new("relay_configs");
147const CONFIG_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("config");
148const HEALTH_STATUS_TABLE_DEF: TableDefinition<&[u8], &[u8]> =
149    TableDefinition::new("key_health_status");
150const SECRETS_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("secrets");
151const SECRET_SEALS_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("secret_seals");
152const STATE_VERSIONS_TABLE_DEF: TableDefinition<&[u8], &[u8]> =
153    TableDefinition::new("state_versions");
154
155/// Redb-based storage backend (default).
156pub struct RedbBackend {
157    db: Database,
158}
159
160impl RedbBackend {
161    /// Create a new database at the given path.
162    pub fn create(path: &Path) -> Result<Self> {
163        let db = Database::create(path)?;
164        migration::initialize_schema(&db)?;
165        Ok(Self { db })
166    }
167
168    /// Open an existing database at the given path.
169    /// Retries on Windows to handle delayed file handle release.
170    /// Auto-upgrades from older redb file formats.
171    pub fn open(path: &Path) -> Result<Self> {
172        match open_database_with_retry(path) {
173            Ok(db) => {
174                migration::check_compatibility(&db)?;
175                let result = migration::run_migrations(&db)?;
176                if result.migrations_run > 0 {
177                    info!(
178                        count = result.migrations_run,
179                        "vault schema migration completed"
180                    );
181                }
182                Ok(Self { db })
183            }
184            Err(OpenWithRetryError::UpgradeRequired(old_version)) => {
185                warn!(
186                    old_version,
187                    "redb file format upgrade required, migrating automatically"
188                );
189                Self::upgrade_file_format(path)
190            }
191            Err(OpenWithRetryError::Other(e)) => Err(map_open_failure(path, e)),
192        }
193    }
194
195    /// Upgrade from an older redb file format by copying all data.
196    fn upgrade_file_format(path: &Path) -> Result<Self> {
197        let old_db = redb2::Database::open(path).map_err(|e| {
198            StorageError::database(format!("failed to open old database for migration: {e}"))
199        })?;
200
201        let table_names: &[&str] = &[
202            KEYS_TABLE,
203            SHARES_TABLE,
204            DESCRIPTORS_TABLE,
205            RELAY_CONFIGS_TABLE,
206            CONFIG_TABLE,
207            HEALTH_STATUS_TABLE,
208            // Arbitrary-secret rows and their threshold seals must survive a file-format upgrade too;
209            // omitting them would silently drop the password/secret store (and leave any sealed value
210            // undecryptable if only one of the pair carried through). Missing tables are skipped below.
211            SECRETS_TABLE,
212            SECRET_SEALS_TABLE,
213            // Carried through a file-format upgrade so the keep-state rollback-guard high-water-marks
214            // survive; otherwise they reset and the guard reverts to first-sync (TOFU) for every d-tag.
215            STATE_VERSIONS_TABLE,
216        ];
217
218        type TableEntries = Vec<(Vec<u8>, Vec<u8>)>;
219        let mut table_data: Vec<(&str, TableEntries)> = Vec::new();
220        let old_schema_version;
221        {
222            use redb2::ReadableTable as _;
223
224            let rtxn = old_db
225                .begin_read()
226                .map_err(|e| StorageError::database(format!("failed to read old database: {e}")))?;
227            for &name in table_names {
228                let table_def: redb2::TableDefinition<&[u8], &[u8]> =
229                    redb2::TableDefinition::new(name);
230                match rtxn.open_table(table_def) {
231                    Ok(table) => {
232                        let entries: Vec<(Vec<u8>, Vec<u8>)> = table
233                            .iter()
234                            .map_err(|e| {
235                                StorageError::database(format!(
236                                    "failed to iterate table {name}: {e}"
237                                ))
238                            })?
239                            .map(|r| {
240                                let (k, v) = r.map_err(|e| {
241                                    StorageError::database(format!(
242                                        "failed to read entry in table {name}: {e}"
243                                    ))
244                                })?;
245                                Ok((k.value().to_vec(), v.value().to_vec()))
246                            })
247                            .collect::<Result<Vec<_>>>()?;
248                        info!(
249                            table = name,
250                            count = entries.len(),
251                            "read table for migration"
252                        );
253                        table_data.push((name, entries));
254                    }
255                    Err(redb2::TableError::TableDoesNotExist(_)) => {}
256                    Err(e) => {
257                        return Err(StorageError::database(format!(
258                            "failed to open table {name}: {e}"
259                        ))
260                        .into());
261                    }
262                }
263            }
264
265            let metadata_def: redb2::TableDefinition<&str, &[u8]> =
266                redb2::TableDefinition::new("metadata");
267            old_schema_version = match rtxn.open_table(metadata_def) {
268                Ok(table) => table
269                    .get("schema_version")
270                    .map_err(|e| {
271                        StorageError::database(format!(
272                            "failed to read schema_version from old database: {e}"
273                        ))
274                    })?
275                    .and_then(|v| <[u8; 4]>::try_from(v.value()).ok())
276                    .map(u32::from_le_bytes),
277                Err(redb2::TableError::TableDoesNotExist(_)) => None,
278                Err(e) => {
279                    return Err(StorageError::database(format!(
280                        "failed to open metadata table: {e}"
281                    ))
282                    .into());
283                }
284            };
285        }
286        drop(old_db);
287
288        let backup_path = path.with_extension("db.old");
289        if backup_path.exists() {
290            let ts = std::time::SystemTime::now()
291                .duration_since(std::time::UNIX_EPOCH)
292                .unwrap_or_default()
293                .as_secs();
294            let alt = path.with_extension(format!("db.old.{ts}"));
295            std::fs::rename(&backup_path, &alt).map_err(|e| {
296                StorageError::database(format!(
297                    "failed to move existing backup before migration: {e}"
298                ))
299            })?;
300            warn!(?alt, "moved existing backup aside");
301        }
302        std::fs::rename(path, &backup_path)?;
303        info!(?backup_path, "backed up old database");
304
305        let new_db = Database::create(path).map_err(|e| {
306            if let Err(re) = std::fs::rename(&backup_path, path) {
307                error!(
308                    "failed to restore backup after migration failure: {re}; \
309                     backup is at {backup_path:?}"
310                );
311            }
312            StorageError::database(format!("failed to create new database: {e}"))
313        })?;
314
315        let write_result: Result<()> = (|| {
316            let wtxn = new_db.begin_write()?;
317            for (name, entries) in &table_data {
318                let table_def: TableDefinition<&[u8], &[u8]> = TableDefinition::new(name);
319                let mut table = wtxn.open_table(table_def)?;
320                for (key, value) in entries {
321                    table.insert(key.as_slice(), value.as_slice())?;
322                }
323            }
324            {
325                let metadata: TableDefinition<&str, &[u8]> = TableDefinition::new("metadata");
326                let mut table = wtxn.open_table(metadata)?;
327                let version = old_schema_version.unwrap_or(1);
328                table.insert("schema_version", version.to_le_bytes().as_slice())?;
329            }
330            wtxn.commit()?;
331            Ok(())
332        })();
333        if let Err(e) = write_result {
334            drop(new_db);
335            let _ = std::fs::remove_file(path);
336            if let Err(re) = std::fs::rename(&backup_path, path) {
337                error!(
338                    "failed to restore backup after write failure: {re}; \
339                     backup is at {backup_path:?}"
340                );
341            }
342            return Err(e);
343        }
344
345        info!("database file format upgrade complete");
346
347        let migrate_result: Result<migration::MigrationResult> = (|| {
348            migration::check_compatibility(&new_db)?;
349            migration::run_migrations(&new_db)
350        })();
351        let result = match migrate_result {
352            Ok(r) => r,
353            Err(e) => {
354                drop(new_db);
355                let _ = std::fs::remove_file(path);
356                if let Err(re) = std::fs::rename(&backup_path, path) {
357                    error!(
358                        "failed to restore backup after migration failure: {re}; \
359                         backup is at {backup_path:?}"
360                    );
361                }
362                return Err(e);
363            }
364        };
365        if result.migrations_run > 0 {
366            info!(
367                count = result.migrations_run,
368                "schema migration completed after file format upgrade"
369            );
370        }
371
372        Ok(Self { db: new_db })
373    }
374
375    fn table_def(
376        &self,
377        name: &str,
378    ) -> Result<TableDefinition<'static, &'static [u8], &'static [u8]>> {
379        match name {
380            KEYS_TABLE => Ok(KEYS_TABLE_DEF),
381            SHARES_TABLE => Ok(SHARES_TABLE_DEF),
382            DESCRIPTORS_TABLE => Ok(DESCRIPTORS_TABLE_DEF),
383            RELAY_CONFIGS_TABLE => Ok(RELAY_CONFIGS_TABLE_DEF),
384            CONFIG_TABLE => Ok(CONFIG_TABLE_DEF),
385            HEALTH_STATUS_TABLE => Ok(HEALTH_STATUS_TABLE_DEF),
386            SECRETS_TABLE => Ok(SECRETS_TABLE_DEF),
387            SECRET_SEALS_TABLE => Ok(SECRET_SEALS_TABLE_DEF),
388            STATE_VERSIONS_TABLE => Ok(STATE_VERSIONS_TABLE_DEF),
389            _ => Err(StorageError::database(format!("unknown table: {name}")).into()),
390        }
391    }
392}
393
394/// Outcome of [`open_database_with_retry`] when retries are exhausted or a
395/// non-retryable failure is observed. `UpgradeRequired` is split out because
396/// callers route it to a format upgrade path, not to error mapping.
397pub(crate) enum OpenWithRetryError {
398    UpgradeRequired(u8),
399    Other(redb::DatabaseError),
400}
401
402/// Open a redb database with the same bounded retry policy used everywhere in
403/// keep-core: handles transient `DatabaseAlreadyOpen` (Windows handle release,
404/// brief contention windows) and `PermissionDenied` failures. After
405/// `MAX_RETRIES` attempts the most recent error is returned so callers can
406/// surface a Keep-layer message via [`map_open_failure`].
407pub(crate) fn open_database_with_retry(
408    path: &Path,
409) -> std::result::Result<Database, OpenWithRetryError> {
410    const MAX_RETRIES: u32 = 10;
411    const RETRY_DELAY_MS: u64 = 50;
412
413    let mut last_err = None;
414    for _ in 0..MAX_RETRIES {
415        match Database::open(path) {
416            Ok(db) => return Ok(db),
417            Err(redb::DatabaseError::UpgradeRequired(old_version)) => {
418                return Err(OpenWithRetryError::UpgradeRequired(old_version));
419            }
420            Err(e) => {
421                let is_retryable = matches!(
422                    &e,
423                    redb::DatabaseError::Storage(redb::StorageError::Io(io_err))
424                        if io_err.kind() == std::io::ErrorKind::PermissionDenied
425                ) || matches!(&e, redb::DatabaseError::DatabaseAlreadyOpen);
426
427                if is_retryable {
428                    last_err = Some(e);
429                    std::thread::sleep(std::time::Duration::from_millis(RETRY_DELAY_MS));
430                    continue;
431                }
432                return Err(OpenWithRetryError::Other(e));
433            }
434        }
435    }
436    Err(OpenWithRetryError::Other(last_err.unwrap_or_else(|| {
437        redb::DatabaseError::Storage(redb::StorageError::Io(std::io::Error::other(
438            "open failed after retries",
439        )))
440    })))
441}
442
443/// Rewrite the redb `DatabaseAlreadyOpen` failure with a Keep-layer hint that
444/// names the most likely cause (another keep process holding the vault) and
445/// points the operator at how to recover (#422). Without this rewrite, the
446/// operator sees the raw redb message "Database already open. Cannot acquire
447/// lock." with no indication that a running `keep serve` or `keep frost
448/// network serve` daemon is the typical holder, or what to do next.
449///
450/// Non-lock-contention errors fall through to the default `KeepError` mapping
451/// so this helper does not swallow real database failures.
452pub(crate) fn map_open_failure(path: &Path, e: redb::DatabaseError) -> KeepError {
453    if matches!(&e, redb::DatabaseError::DatabaseAlreadyOpen) {
454        return KeepError::VaultAlreadyOpen(format!(
455            "vault at {} is already opened by another process. \
456             A `keep serve` or `keep frost network serve` daemon typically holds the lock; \
457             stop it (or wait for it to exit) and retry. \
458             Read-only commands like `list` route through the running daemon automatically \
459             (#533); see #422 for details.",
460            path.display()
461        ));
462    }
463    e.into()
464}
465
466impl StorageBackend for RedbBackend {
467    fn get(&self, table: &str, key: &[u8]) -> Result<Option<Vec<u8>>> {
468        let rtxn = self.db.begin_read()?;
469        let tbl = rtxn.open_table(self.table_def(table)?)?;
470        Ok(tbl.get(key)?.map(|v| v.value().to_vec()))
471    }
472
473    fn put(&self, table: &str, key: &[u8], value: &[u8]) -> Result<()> {
474        let wtxn = self.db.begin_write()?;
475        wtxn.open_table(self.table_def(table)?)?
476            .insert(key, value)?;
477        wtxn.commit()?;
478        Ok(())
479    }
480
481    fn delete(&self, table: &str, key: &[u8]) -> Result<bool> {
482        let wtxn = self.db.begin_write()?;
483        let existed = wtxn
484            .open_table(self.table_def(table)?)?
485            .remove(key)?
486            .is_some();
487        wtxn.commit()?;
488        Ok(existed)
489    }
490
491    fn list(&self, table: &str) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
492        let rtxn = self.db.begin_read()?;
493        let tbl = rtxn.open_table(self.table_def(table)?)?;
494        tbl.iter()?
495            .map(|result| {
496                let (k, v) = result?;
497                Ok((k.value().to_vec(), v.value().to_vec()))
498            })
499            .collect()
500    }
501
502    fn create_table(&self, table: &str) -> Result<()> {
503        let wtxn = self.db.begin_write()?;
504        wtxn.open_table(self.table_def(table)?)?;
505        wtxn.commit()?;
506        Ok(())
507    }
508
509    fn put_batch(&self, table: &str, entries: &[(&[u8], &[u8])]) -> Result<()> {
510        let wtxn = self.db.begin_write()?;
511        {
512            let mut tbl = wtxn.open_table(self.table_def(table)?)?;
513            for (key, value) in entries {
514                tbl.insert(*key, *value)?;
515            }
516        }
517        wtxn.commit()?;
518        Ok(())
519    }
520
521    fn delete_batch(&self, table: &str, keys: &[&[u8]]) -> Result<()> {
522        let wtxn = self.db.begin_write()?;
523        {
524            let mut tbl = wtxn.open_table(self.table_def(table)?)?;
525            for key in keys {
526                tbl.remove(*key)?;
527            }
528        }
529        wtxn.commit()?;
530        Ok(())
531    }
532
533    // Each op must target a distinct table: redb errors on opening the same table twice in one write
534    // txn. The only caller passes exactly [data_table, STATE_VERSIONS_TABLE], always distinct.
535    fn write_atomic(&self, ops: &[AtomicOp<'_>]) -> Result<()> {
536        let wtxn = self.db.begin_write()?;
537        for op in ops {
538            let mut tbl = wtxn.open_table(self.table_def(op.table)?)?;
539            match op.value {
540                Some(v) => {
541                    tbl.insert(op.key, v)?;
542                }
543                None => {
544                    tbl.remove(op.key)?;
545                }
546            }
547        }
548        wtxn.commit()?;
549        Ok(())
550    }
551
552    fn list_keys_with_prefix(&self, table: &str, prefix: &[u8]) -> Result<Vec<Vec<u8>>> {
553        let rtxn = self.db.begin_read()?;
554        let tbl = rtxn.open_table(self.table_def(table)?)?;
555        let mut out = Vec::new();
556        for entry in tbl.iter()? {
557            let (k, _) = entry?;
558            let bytes = k.value();
559            if bytes.starts_with(prefix) {
560                out.push(bytes.to_vec());
561            }
562        }
563        Ok(out)
564    }
565
566    fn schema_version(&self) -> Result<u32> {
567        Ok(migration::read_schema_version(&self.db)?.unwrap_or(1))
568    }
569
570    fn needs_migration(&self) -> Result<bool> {
571        migration::needs_migration(&self.db)
572    }
573
574    fn run_migrations(&self) -> Result<migration::MigrationResult> {
575        migration::run_migrations(&self.db)
576    }
577}
578
579type TableData = BTreeMap<Vec<u8>, Vec<u8>>;
580
581/// In-memory storage backend for testing.
582pub struct MemoryBackend {
583    tables: RwLock<BTreeMap<String, TableData>>,
584}
585
586impl MemoryBackend {
587    /// Create a new in-memory backend.
588    pub fn new() -> Self {
589        Self {
590            tables: RwLock::new(BTreeMap::new()),
591        }
592    }
593}
594
595impl Default for MemoryBackend {
596    fn default() -> Self {
597        Self::new()
598    }
599}
600
601impl StorageBackend for MemoryBackend {
602    fn get(&self, table: &str, key: &[u8]) -> Result<Option<Vec<u8>>> {
603        let tables = self.tables.read().map_err(lock_error)?;
604        Ok(tables.get(table).and_then(|t| t.get(key).cloned()))
605    }
606
607    fn put(&self, table: &str, key: &[u8], value: &[u8]) -> Result<()> {
608        self.tables
609            .write()
610            .map_err(lock_error)?
611            .entry(table.to_string())
612            .or_default()
613            .insert(key.to_vec(), value.to_vec());
614        Ok(())
615    }
616
617    fn delete(&self, table: &str, key: &[u8]) -> Result<bool> {
618        let mut tables = self.tables.write().map_err(lock_error)?;
619        Ok(tables
620            .get_mut(table)
621            .map(|t| t.remove(key).is_some())
622            .unwrap_or(false))
623    }
624
625    fn list(&self, table: &str) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
626        let tables = self.tables.read().map_err(lock_error)?;
627        Ok(tables
628            .get(table)
629            .map(|t| t.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
630            .unwrap_or_default())
631    }
632
633    fn create_table(&self, table: &str) -> Result<()> {
634        self.tables
635            .write()
636            .map_err(lock_error)?
637            .entry(table.to_string())
638            .or_default();
639        Ok(())
640    }
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646    use tempfile::tempdir;
647
648    fn test_backend_operations(backend: &dyn StorageBackend) {
649        backend.create_table(KEYS_TABLE).unwrap();
650
651        assert!(backend.get(KEYS_TABLE, b"key1").unwrap().is_none());
652
653        backend.put(KEYS_TABLE, b"key1", b"value1").unwrap();
654        assert_eq!(
655            backend.get(KEYS_TABLE, b"key1").unwrap(),
656            Some(b"value1".to_vec())
657        );
658
659        backend.put(KEYS_TABLE, b"key2", b"value2").unwrap();
660        let entries = backend.list(KEYS_TABLE).unwrap();
661        assert_eq!(entries.len(), 2);
662
663        assert!(backend.delete(KEYS_TABLE, b"key1").unwrap());
664        assert!(backend.get(KEYS_TABLE, b"key1").unwrap().is_none());
665        assert!(!backend.delete(KEYS_TABLE, b"key1").unwrap());
666    }
667
668    #[test]
669    fn test_memory_backend() {
670        let backend = MemoryBackend::new();
671        test_backend_operations(&backend);
672    }
673
674    #[test]
675    fn test_redb_backend() {
676        let dir = tempdir().unwrap();
677        let backend = RedbBackend::create(&dir.path().join("test.db")).unwrap();
678        test_backend_operations(&backend);
679    }
680
681    #[test]
682    fn test_unknown_table_rejected() {
683        let dir = tempdir().unwrap();
684        let backend = RedbBackend::create(&dir.path().join("test.db")).unwrap();
685        assert!(backend.create_table("unknown").is_err());
686    }
687
688    #[test]
689    fn second_open_surfaces_lock_holder_hint() {
690        // The bare redb message ("Database already open. Cannot acquire lock.")
691        // doesn't tell an operator that a running `keep serve` daemon is the
692        // typical holder, or what to do next. #422 (c) is exactly this rewrite:
693        // when a second open fails on the lock, we surface a Keep-layer hint
694        // that names the daemon and points at the issue for the read-only
695        // follow-up.
696        let dir = tempdir().unwrap();
697        let db_path = dir.path().join("locked.db");
698        let _first = RedbBackend::create(&db_path).expect("first open holds the lock");
699
700        let err = match RedbBackend::open(&db_path) {
701            Err(e) => e,
702            Ok(_) => panic!("second open while the first is held must fail"),
703        };
704        let msg = err.to_string();
705        assert!(
706            matches!(err, KeepError::VaultAlreadyOpen(_)),
707            "expected VaultAlreadyOpen from map_open_failure, got {err:?}"
708        );
709        assert!(
710            msg.contains("already opened by another process"),
711            "got {msg}"
712        );
713        assert!(
714            msg.contains("keep serve") || msg.contains("frost network serve"),
715            "got {msg}"
716        );
717        assert!(msg.contains("#422"), "got {msg}");
718        assert!(msg.contains(&db_path.display().to_string()), "got {msg}");
719    }
720}