feat: implement LMDB compact solution for storage optimization

- Add `compact(to:)` method on `Ndb` using `mdb_env_copy2` / `ndb_snapshot`
  with `MDB_CP_COMPACT` flag to produce a smaller compacted database copy
- Add `compact_if_needed(db_path:)` static startup method that reads a
  UserDefaults flag, opens a temp Ndb, compacts to a sibling temp dir,
  atomically replaces `data.mdb`, cleans up, and clears the flag
- Add `set_compact_on_next_launch()` to schedule compaction from the UI
- Call `Ndb.compact_if_needed()` in `ContentView.connect()` before the
  main Ndb instance is opened
- Add `CompactDatabaseButton` to `StorageSettingsView` with a confirmation
  dialog that informs the user a restart is needed
- Add `NdbCompactionTests` unit tests covering flag API, no-op path,
  missing-DB path, and full round-trip compaction

Closes: https://github.com/damus-io/damus/issues/3680
Changelog-Added: Added "Compact Database" button in Settings → Storage that reclaims unused space by compacting the NostrDB on the next app launch
Signed-off-by: Daniel D’Aquino <daniel@daquino.me>
This commit is contained in:
Daniel D’Aquino
2026-03-16 16:29:27 -07:00
parent 55817d066e
commit 2c6e574b11
6 changed files with 339 additions and 3 deletions
+2 -2
View File
@@ -241,7 +241,7 @@ class Ndb {
}
}
private static func db_file_exists(path: String) -> Bool {
static func db_file_exists(path: String) -> Bool {
return FileManager.default.fileExists(atPath: "\(path)/\(Self.main_db_file_name)")
}
@@ -324,7 +324,7 @@ class Ndb {
})
})
}
// MARK: Thread safety mechanisms
// Use these for all externally accessible methods that interact with the nostrdb database to prevent race conditions with app lifecycle events (i.e. NostrDB opening and closing)