ndb: add safemode so we don't instantly crash on bad dbs

Fixes: https://github.com/damus-io/damus/issues/1741
This commit is contained in:
William Casarin
2023-12-04 12:42:45 -08:00
parent 4e447ddbed
commit a07b78e47f
6 changed files with 42 additions and 14 deletions

View File

@@ -17,8 +17,25 @@ enum NdbSearchOrder {
class Ndb {
let ndb: ndb_t
let owns_db_file: Bool // Determines whether this class should be allowed to create or move the db file.
static func safemode() -> Ndb? {
guard let path = db_path ?? old_db_path else { return nil }
// delete the database and start fresh
if Self.db_files_exist(path: path) {
let file_manager = FileManager.default
for db_file in db_files {
try? file_manager.removeItem(atPath: "\(path)/\(db_file)")
}
}
guard let ndb = Ndb(path: path) else {
return nil
}
return ndb
}
// NostrDB used to be stored on the app container's document directory
static private var old_db_path: String? {
guard let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.absoluteString else {
@@ -42,7 +59,7 @@ class Ndb {
Ndb(ndb: ndb_t(ndb: nil))
}
init?(path: String? = nil, owns_db_file: Bool = true) throws {
init?(path: String? = nil, owns_db_file: Bool = true) {
var ndb_p: OpaquePointer? = nil
let ingest_threads: Int32 = 4
@@ -66,7 +83,7 @@ class Ndb {
}
guard let path = path.map(remove_file_prefix) ?? Ndb.db_path else {
throw Errors.cannot_find_db_path
return nil
}
let ok = path.withCString { testdir in
@@ -85,7 +102,6 @@ class Ndb {
return nil
}
self.owns_db_file = owns_db_file
self.ndb = ndb_t(ndb: ndb_p)
}
@@ -127,7 +143,6 @@ class Ndb {
}
init(ndb: ndb_t) {
self.owns_db_file = true
self.ndb = ndb
}

View File

@@ -55,13 +55,13 @@ final class NdbTests: XCTestCase {
func test_ndb_init() {
do {
let ndb = try! Ndb(path: db_dir)!
let ndb = Ndb(path: db_dir)!
let ok = ndb.process_events(test_wire_events)
XCTAssertTrue(ok)
}
do {
let ndb = try! Ndb(path: db_dir)!
let ndb = Ndb(path: db_dir)!
let id = NoteId(hex: "d12c17bde3094ad32f4ab862a6cc6f5c289cfe7d5802270bdf34904df585f349")!
let txn = NdbTxn(ndb: ndb)
let note = ndb.lookup_note_with_txn(id: id, txn: txn)
@@ -83,13 +83,13 @@ final class NdbTests: XCTestCase {
func test_ndb_seach() throws {
do {
let ndb = try! Ndb(path: db_dir)!
let ndb = Ndb(path: db_dir)!
let ok = ndb.process_events(test_wire_events)
XCTAssertTrue(ok)
}
do {
let ndb = try! Ndb(path: db_dir)!
let ndb = Ndb(path: db_dir)!
let note_ids = ndb.text_search(query: "barked")
XCTAssertEqual(note_ids.count, 1)
let expected_note_id = NoteId(hex: "b17a540710fe8495b16bfbaf31c6962c4ba8387f3284a7973ad523988095417e")!