Redesign Ndb.swift interface with build safety

This commit redesigns the Ndb.swift interface with a focus on build-time
safety against crashes.

It removes the external usage of NdbTxn and SafeNdbTxn, restricting it
to be used only in NostrDB internal code.

This prevents dangerous and crash prone usages throughout the app, such
as holding transactions in a variable in an async function (which can
cause thread-based reference counting to incorrectly deinit inherited
transactions in use by separate callers), as well as holding unsafe
unowned values longer than the lifetime of their corresponding
transactions.

Closes: https://github.com/damus-io/damus/issues/3364
Changelog-Fixed: Fixed several crashes throughout the app
Signed-off-by: Daniel D’Aquino <daniel@daquino.me>
This commit is contained in:
Daniel D’Aquino
2025-11-28 19:17:35 -08:00
parent b562b930cc
commit f844ed9931
60 changed files with 611 additions and 497 deletions

View File

@@ -73,6 +73,10 @@ class NdbNote: Codable, Equatable, Hashable {
}
#endif
}
func clone() -> NdbNote {
return self.to_owned()
}
func to_owned() -> NdbNote {
if self.owned {
@@ -474,17 +478,12 @@ extension NdbNote {
return ThreadReply(tags: self.tags)?.reply.note_id
}
func block_offsets(ndb: Ndb) -> SafeNdbTxn<NdbBlockGroup.BlocksMetadata>? {
let blocks_txn: SafeNdbTxn<NdbBlockGroup.BlocksMetadata>? = .new(on: ndb) { txn -> NdbBlockGroup.BlocksMetadata? in
guard let key = ndb.lookup_note_key_with_txn(self.id, txn: txn) else {
return nil
}
return ndb.lookup_blocks_by_key_with_txn(key, txn: txn)
}
guard let blocks_txn else { return nil }
return blocks_txn
func block_offsets<T>(ndb: Ndb, borrow lendingFunction: (_: borrowing NdbBlockGroup.BlocksMetadata?) throws -> T) rethrows -> T {
guard let key = ndb.lookup_note_key(self.id) else { return try lendingFunction(nil) }
return try ndb.lookup_blocks_by_key(key, borrow: { blocks in
return try lendingFunction(blocks)
})
}
func is_content_encrypted() -> Bool {