mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-29 08:29:22 +00:00
perf(launch): share Keychain/NostrIdentityBridge, offload startup loads, debounce read receipts, and batch sightings (#1895)
This commit is contained in:
16 files changed
+335
-62
No files matched your search
@@ -61,7 +61,7 @@ final class AppRuntime: ObservableObject {
|
||||
|
||||
init(
|
||||
keychain: KeychainManagerProtocol = KeychainManager.makeDefault(),
|
||||
idBridge: NostrIdentityBridge = NostrIdentityBridge(),
|
||||
idBridge: NostrIdentityBridge = .shared,
|
||||
sharedContentStore: SharedContentStore? = nil
|
||||
) {
|
||||
self.idBridge = idBridge
|
||||
|
||||
@@ -150,6 +150,7 @@ final class GeoRelayDirectory {
|
||||
var observers: [NSObjectProtocol] = []
|
||||
var refreshTimer: Timer?
|
||||
var retryTask: Task<Void, Never>?
|
||||
var localLoadTask: Task<Void, Never>?
|
||||
|
||||
init(notificationCenter: NotificationCenter) {
|
||||
self.notificationCenter = notificationCenter
|
||||
@@ -159,6 +160,7 @@ final class GeoRelayDirectory {
|
||||
observers.forEach { notificationCenter.removeObserver($0) }
|
||||
refreshTimer?.invalidate()
|
||||
retryTask?.cancel()
|
||||
localLoadTask?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,13 +203,14 @@ final class GeoRelayDirectory {
|
||||
private let dependencies: GeoRelayDirectoryDependencies
|
||||
private let cleanupState: CleanupState
|
||||
|
||||
private var didCompleteLocalLoad = false
|
||||
private var retryAttempt: Int = 0
|
||||
private var isFetching: Bool = false
|
||||
|
||||
private init() {
|
||||
self.dependencies = .live()
|
||||
self.cleanupState = CleanupState(notificationCenter: dependencies.notificationCenter)
|
||||
entries = loadLocalEntries()
|
||||
startAsyncLocalLoad()
|
||||
if dependencies.autoStart {
|
||||
registerObservers()
|
||||
startRefreshTimer()
|
||||
@@ -219,6 +222,7 @@ final class GeoRelayDirectory {
|
||||
self.dependencies = dependencies
|
||||
self.cleanupState = CleanupState(notificationCenter: dependencies.notificationCenter)
|
||||
entries = loadLocalEntries()
|
||||
didCompleteLocalLoad = true
|
||||
if dependencies.autoStart {
|
||||
registerObservers()
|
||||
startRefreshTimer()
|
||||
@@ -226,8 +230,46 @@ final class GeoRelayDirectory {
|
||||
}
|
||||
}
|
||||
|
||||
private func startAsyncLocalLoad() {
|
||||
let cacheURL = dependencies.cacheURL()
|
||||
let bundleURLs = dependencies.bundledCSVURLs()
|
||||
let cwd = dependencies.currentDirectoryPath()
|
||||
let policy = dependencies.validationPolicy
|
||||
|
||||
cleanupState.localLoadTask = Task { [weak self] in
|
||||
let loaded = await Task.detached(priority: .userInitiated) {
|
||||
Self.loadLocalEntriesOffMain(
|
||||
cacheURL: cacheURL,
|
||||
bundleURLs: bundleURLs,
|
||||
currentDirectoryPath: cwd,
|
||||
policy: policy
|
||||
)
|
||||
}.value
|
||||
guard !Task.isCancelled, let self else { return }
|
||||
self.cleanupState.localLoadTask = nil
|
||||
self.didCompleteLocalLoad = true
|
||||
if self.entries.isEmpty && !loaded.isEmpty {
|
||||
self.entries = loaded
|
||||
self.dependencies.notificationCenter.post(name: .geoRelayDirectoryDidRefresh, object: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func ensureLocalEntriesLoaded() {
|
||||
guard !didCompleteLocalLoad else { return }
|
||||
cleanupState.localLoadTask?.cancel()
|
||||
cleanupState.localLoadTask = nil
|
||||
didCompleteLocalLoad = true
|
||||
if entries.isEmpty {
|
||||
entries = loadLocalEntries()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns up to `count` relay URLs (wss://) closest to the geohash center.
|
||||
func closestRelays(toGeohash geohash: String, count: Int = 5) -> [String] {
|
||||
if entries.isEmpty && !didCompleteLocalLoad {
|
||||
ensureLocalEntriesLoaded()
|
||||
}
|
||||
guard !entries.isEmpty, count > 0 else { return [] }
|
||||
let key = ClosestRelaysCacheKey(geohash: geohash, count: count)
|
||||
if let cached = closestRelaysCache[key] {
|
||||
@@ -246,6 +288,9 @@ final class GeoRelayDirectory {
|
||||
/// Ties break by host so every device with the same directory picks the
|
||||
/// same relay set — publishers and subscribers must agree on relays.
|
||||
func closestRelays(toLat lat: Double, lon: Double, count: Int = 5) -> [String] {
|
||||
if entries.isEmpty && !didCompleteLocalLoad {
|
||||
ensureLocalEntriesLoaded()
|
||||
}
|
||||
guard !entries.isEmpty, count > 0 else { return [] }
|
||||
|
||||
let rad = Double.pi / 180.0
|
||||
@@ -470,6 +515,35 @@ final class GeoRelayDirectory {
|
||||
return []
|
||||
}
|
||||
|
||||
nonisolated private static func loadLocalEntriesOffMain(
|
||||
cacheURL: URL?,
|
||||
bundleURLs: [URL],
|
||||
currentDirectoryPath: String?,
|
||||
policy: GeoRelayDirectoryValidationPolicy
|
||||
) -> [Entry] {
|
||||
if let cacheURL,
|
||||
let data = try? Data(contentsOf: cacheURL),
|
||||
let entries = validatedEntries(from: data, policy: policy, minimumEntries: 1) {
|
||||
return entries
|
||||
}
|
||||
|
||||
for url in bundleURLs {
|
||||
if let data = try? Data(contentsOf: url),
|
||||
let entries = validatedEntries(from: data, policy: policy, minimumEntries: 1) {
|
||||
return entries
|
||||
}
|
||||
}
|
||||
|
||||
if let cwd = currentDirectoryPath,
|
||||
let data = try? Data(contentsOf: URL(fileURLWithPath: cwd).appendingPathComponent("relays/online_relays_gps.csv")),
|
||||
let entries = validatedEntries(from: data, policy: policy, minimumEntries: 1) {
|
||||
return entries
|
||||
}
|
||||
|
||||
SecureLogger.warning("GeoRelayDirectory: no local CSV found; entries empty", category: .session)
|
||||
return []
|
||||
}
|
||||
|
||||
/// Parses the fixed three-column format as an all-or-nothing trust unit.
|
||||
/// One malformed or conflicting row rejects the complete dataset rather
|
||||
/// than silently shrinking or partially replacing the current directory.
|
||||
@@ -678,6 +752,8 @@ final class GeoRelayDirectory {
|
||||
/// from Application Support.
|
||||
func resetForPanic() {
|
||||
cancelRetry()
|
||||
cleanupState.localLoadTask?.cancel()
|
||||
cleanupState.localLoadTask = nil
|
||||
retryAttempt = 0
|
||||
closestRelaysCache.removeAll(keepingCapacity: false)
|
||||
dependencies.userDefaults.removeObject(forKey: lastFetchKey)
|
||||
|
||||
@@ -4,6 +4,8 @@ import CryptoKit
|
||||
|
||||
/// Bridge between Noise and Nostr identities
|
||||
final class NostrIdentityBridge {
|
||||
static let shared = NostrIdentityBridge()
|
||||
|
||||
private let keychainService = "chat.bitchat.nostr"
|
||||
private let currentIdentityKey = "nostr-current-identity"
|
||||
private let deviceSeedKey = "nostr-device-seed"
|
||||
|
||||
@@ -167,7 +167,7 @@ final class BoardManager: ObservableObject {
|
||||
return nil
|
||||
}
|
||||
do {
|
||||
let identity = try NostrIdentityBridge().deriveIdentity(forGeohash: geohash)
|
||||
let identity = try NostrIdentityBridge.shared.deriveIdentity(forGeohash: geohash)
|
||||
let event = try NostrProtocol.createGeohashTextNote(
|
||||
content: content,
|
||||
geohash: geohash,
|
||||
@@ -188,7 +188,7 @@ final class BoardManager: ObservableObject {
|
||||
let relays = GeoRelayDirectory.shared.closestRelays(toGeohash: geohash, count: TransportConfig.nostrGeoRelayCount)
|
||||
guard !relays.isEmpty else { return }
|
||||
do {
|
||||
let identity = try NostrIdentityBridge().deriveIdentity(forGeohash: geohash)
|
||||
let identity = try NostrIdentityBridge.shared.deriveIdentity(forGeohash: geohash)
|
||||
let deletion = try NostrProtocol.createDeleteEvent(ofEventID: eventID, senderIdentity: identity)
|
||||
NostrRelayManager.shared.sendEvent(deletion, to: relays)
|
||||
} catch {
|
||||
|
||||
@@ -99,7 +99,15 @@ final class BoardStore {
|
||||
init(persistsToDisk: Bool = true, fileURL: URL? = nil, now: @escaping () -> Date = Date.init) {
|
||||
self.now = now
|
||||
self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil
|
||||
loadFromDisk()
|
||||
if self.fileURL != nil {
|
||||
// Restore off the calling thread (cold launch on MainActor) on the
|
||||
// serial store queue. Every read/write (`posts`, `syncCandidates`,
|
||||
// `ingest`, `wipe`) serializes on `queue`, so callers are linearly
|
||||
// ordered after restore without blocking init().
|
||||
queue.async { [self] in
|
||||
loadFromDiskLocked()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Ingest
|
||||
@@ -168,18 +176,38 @@ final class BoardStore {
|
||||
packet: BitchatPacket,
|
||||
rawPacket: Data,
|
||||
nowMs: UInt64,
|
||||
retainUntilOverride: UInt64? = nil
|
||||
retainUntilOverride: UInt64? = nil,
|
||||
publishSnapshot: Bool = true
|
||||
) -> BoardIngestResult {
|
||||
pruneExpiredLocked(nowMs: nowMs)
|
||||
pruneExpiredLocked(nowMs: nowMs, publishSnapshot: publishSnapshot)
|
||||
switch wire {
|
||||
case .post(let post):
|
||||
return ingestPostLocked(post, packet: packet, rawPacket: rawPacket, nowMs: nowMs)
|
||||
return ingestPostLocked(
|
||||
post,
|
||||
packet: packet,
|
||||
rawPacket: rawPacket,
|
||||
nowMs: nowMs,
|
||||
publishSnapshot: publishSnapshot
|
||||
)
|
||||
case .tombstone(let tombstone):
|
||||
return ingestTombstoneLocked(tombstone, packet: packet, rawPacket: rawPacket, nowMs: nowMs, retainUntilOverride: retainUntilOverride)
|
||||
return ingestTombstoneLocked(
|
||||
tombstone,
|
||||
packet: packet,
|
||||
rawPacket: rawPacket,
|
||||
nowMs: nowMs,
|
||||
retainUntilOverride: retainUntilOverride,
|
||||
publishSnapshot: publishSnapshot
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func ingestPostLocked(_ post: BoardPostPacket, packet: BitchatPacket, rawPacket: Data, nowMs: UInt64) -> BoardIngestResult {
|
||||
private func ingestPostLocked(
|
||||
_ post: BoardPostPacket,
|
||||
packet: BitchatPacket,
|
||||
rawPacket: Data,
|
||||
nowMs: UInt64,
|
||||
publishSnapshot: Bool = true
|
||||
) -> BoardIngestResult {
|
||||
guard post.expiresAt > nowMs else { return .rejected }
|
||||
// Receive-time sanity (this is the single chokepoint for radio, sync,
|
||||
// and disk restores): the decoder only enforces the createdAt to
|
||||
@@ -204,7 +232,9 @@ final class BoardStore {
|
||||
if posts.count > Limits.maxPosts {
|
||||
evictOldestLocked(from: posts, keep: Limits.maxPosts)
|
||||
}
|
||||
publishSnapshotLocked()
|
||||
if publishSnapshot {
|
||||
publishSnapshotLocked()
|
||||
}
|
||||
// Even when the new post itself was the eviction victim it stays
|
||||
// valid mesh-wide; peers with room should still receive it.
|
||||
return .accepted
|
||||
@@ -215,7 +245,8 @@ final class BoardStore {
|
||||
packet: BitchatPacket,
|
||||
rawPacket: Data,
|
||||
nowMs: UInt64,
|
||||
retainUntilOverride: UInt64? = nil
|
||||
retainUntilOverride: UInt64? = nil,
|
||||
publishSnapshot: Bool = true
|
||||
) -> BoardIngestResult {
|
||||
guard !tombstones.contains(where: { $0.tombstone.postID == tombstone.postID }) else { return .duplicate }
|
||||
|
||||
@@ -238,7 +269,9 @@ final class BoardStore {
|
||||
retainUntil = target.expiresAt
|
||||
isOrphan = false
|
||||
posts.remove(at: index)
|
||||
publishSnapshotLocked()
|
||||
if publishSnapshot {
|
||||
publishSnapshotLocked()
|
||||
}
|
||||
} else if let retainUntilOverride {
|
||||
// Restored from disk: the post is long gone, so trust the
|
||||
// retention deadline recorded when the delete was first applied.
|
||||
@@ -289,11 +322,11 @@ final class BoardStore {
|
||||
posts.removeAll { victimIDs.contains($0.post.postID) }
|
||||
}
|
||||
|
||||
private func pruneExpiredLocked(nowMs: UInt64) {
|
||||
private func pruneExpiredLocked(nowMs: UInt64, publishSnapshot: Bool = true) {
|
||||
let postsBefore = posts.count
|
||||
posts.removeAll { $0.post.expiresAt <= nowMs }
|
||||
tombstones.removeAll { $0.retainUntil <= nowMs }
|
||||
if posts.count != postsBefore {
|
||||
if publishSnapshot && posts.count != postsBefore {
|
||||
publishSnapshotLocked()
|
||||
}
|
||||
}
|
||||
@@ -335,23 +368,28 @@ final class BoardStore {
|
||||
}
|
||||
}
|
||||
|
||||
private func loadFromDisk() {
|
||||
private func loadFromDiskLocked() {
|
||||
guard let fileURL,
|
||||
let data = try? Data(contentsOf: fileURL),
|
||||
let payloads = try? JSONDecoder().decode([PersistedEntry].self, from: data) else {
|
||||
return
|
||||
}
|
||||
let nowMs = currentMs()
|
||||
queue.sync {
|
||||
for entry in payloads {
|
||||
guard let packet = BitchatPacket.from(entry.packet),
|
||||
packet.type == MessageType.boardPost.rawValue,
|
||||
let wire = BoardWire.decode(from: packet.payload),
|
||||
wire.verifySignature() else { continue }
|
||||
_ = ingestLocked(wire, packet: packet, rawPacket: entry.packet, nowMs: nowMs, retainUntilOverride: entry.retainUntil)
|
||||
}
|
||||
publishSnapshotLocked()
|
||||
for entry in payloads {
|
||||
guard let packet = BitchatPacket.from(entry.packet),
|
||||
packet.type == MessageType.boardPost.rawValue,
|
||||
let wire = BoardWire.decode(from: packet.payload),
|
||||
wire.verifySignature() else { continue }
|
||||
_ = ingestLocked(
|
||||
wire,
|
||||
packet: packet,
|
||||
rawPacket: entry.packet,
|
||||
nowMs: nowMs,
|
||||
retainUntilOverride: entry.retainUntil,
|
||||
publishSnapshot: false
|
||||
)
|
||||
}
|
||||
publishSnapshotLocked()
|
||||
}
|
||||
|
||||
private static func defaultFileURL() -> URL? {
|
||||
|
||||
@@ -78,7 +78,7 @@ final class GeohashPresenceService: ObservableObject {
|
||||
]
|
||||
|
||||
private init() {
|
||||
let idBridge = NostrIdentityBridge()
|
||||
let idBridge = NostrIdentityBridge.shared
|
||||
self.availableChannelsProvider = { LocationStateManager.shared.availableChannels }
|
||||
self.locationChanges = LocationStateManager.shared.$availableChannels.eraseToAnyPublisher()
|
||||
self.torReadyPublisher = NotificationCenter.default.publisher(for: .TorDidBecomeReady)
|
||||
|
||||
@@ -22,7 +22,7 @@ struct LocationNotesDependencies {
|
||||
/// fires without data. Defaults to true so tests keep legacy behavior.
|
||||
var anyRelayConnected: @MainActor (_ relayUrls: [String]) -> Bool = { _ in true }
|
||||
|
||||
private static let idBridge = NostrIdentityBridge()
|
||||
private static let idBridge = NostrIdentityBridge.shared
|
||||
|
||||
/// Panic-wipe hook: drop cached per-geohash secp256k1 keys held by the
|
||||
/// live dependencies bridge so post-panic notes/drops cannot sign with
|
||||
|
||||
@@ -33,6 +33,9 @@ final class MeshSightingsTracker: ObservableObject {
|
||||
private let defaults: UserDefaults
|
||||
private let now: () -> Date
|
||||
private var seenHashes: Set<String> = []
|
||||
private var seenPeerIDsToday: Set<String> = []
|
||||
private var currentDayKey: String = ""
|
||||
private var currentSalt: Data = Data()
|
||||
|
||||
init(defaults: UserDefaults = .standard, now: @escaping () -> Date = { Date() }) {
|
||||
self.defaults = defaults
|
||||
@@ -41,14 +44,32 @@ final class MeshSightingsTracker: ObservableObject {
|
||||
}
|
||||
|
||||
func recordSighting(peerID: PeerID) {
|
||||
rollOverIfNeeded()
|
||||
let hash = saltedHash(peerID.id)
|
||||
recordSightings([peerID])
|
||||
}
|
||||
|
||||
func recordSightings(_ peerIDs: [PeerID]) {
|
||||
guard !peerIDs.isEmpty else { return }
|
||||
let seenAt = now()
|
||||
lastSightingAt = seenAt
|
||||
defaults.set(seenAt, forKey: Keys.lastSeenAt)
|
||||
guard seenHashes.insert(hash).inserted else { return }
|
||||
todayCount = seenHashes.count
|
||||
defaults.set(Array(seenHashes), forKey: Keys.hashes)
|
||||
rollOverIfNeeded(at: seenAt)
|
||||
|
||||
var insertedAnyHash = false
|
||||
for peerID in peerIDs {
|
||||
let rawID = peerID.id
|
||||
guard seenPeerIDsToday.insert(rawID).inserted else { continue }
|
||||
let hash = saltedHash(rawID)
|
||||
if seenHashes.insert(hash).inserted {
|
||||
insertedAnyHash = true
|
||||
}
|
||||
}
|
||||
|
||||
if lastSightingAt != seenAt {
|
||||
lastSightingAt = seenAt
|
||||
defaults.set(seenAt, forKey: Keys.lastSeenAt)
|
||||
}
|
||||
if insertedAnyHash {
|
||||
todayCount = seenHashes.count
|
||||
defaults.set(Array(seenHashes), forKey: Keys.hashes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-evaluates the day boundary for the UI. `recordSighting` handles
|
||||
@@ -56,11 +77,14 @@ final class MeshSightingsTracker: ObservableObject {
|
||||
/// would otherwise keep showing yesterday's tally until the next sighting;
|
||||
/// the empty-state view calls this on its periodic refresh tick.
|
||||
func refreshForDisplay() {
|
||||
rollOverIfNeeded()
|
||||
rollOverIfNeeded(at: now())
|
||||
}
|
||||
|
||||
func clear() {
|
||||
seenHashes.removeAll()
|
||||
seenPeerIDsToday.removeAll()
|
||||
currentDayKey = ""
|
||||
currentSalt = Data()
|
||||
todayCount = 0
|
||||
lastSightingAt = nil
|
||||
defaults.removeObject(forKey: Keys.dayKey)
|
||||
@@ -70,7 +94,7 @@ final class MeshSightingsTracker: ObservableObject {
|
||||
}
|
||||
|
||||
private func restore() {
|
||||
rollOverIfNeeded()
|
||||
rollOverIfNeeded(at: now())
|
||||
seenHashes = Set(defaults.stringArray(forKey: Keys.hashes) ?? [])
|
||||
todayCount = seenHashes.count
|
||||
lastSightingAt = defaults.object(forKey: Keys.lastSeenAt) as? Date
|
||||
@@ -78,26 +102,43 @@ final class MeshSightingsTracker: ObservableObject {
|
||||
|
||||
/// Resets the tally when the local calendar day changes; the salt rotates
|
||||
/// with it so hashes from different days can never be correlated.
|
||||
private func rollOverIfNeeded() {
|
||||
let today = Self.dayKey(for: now())
|
||||
guard defaults.string(forKey: Keys.dayKey) != today else { return }
|
||||
private func rollOverIfNeeded(at date: Date) {
|
||||
let today = Self.dayKey(for: date)
|
||||
if currentDayKey == today && !currentSalt.isEmpty {
|
||||
return
|
||||
}
|
||||
if defaults.string(forKey: Keys.dayKey) == today {
|
||||
currentDayKey = today
|
||||
if let persistedSalt = defaults.data(forKey: Keys.salt), !persistedSalt.isEmpty {
|
||||
currentSalt = persistedSalt
|
||||
} else {
|
||||
let fresh = Self.randomSalt()
|
||||
currentSalt = fresh
|
||||
defaults.set(fresh, forKey: Keys.salt)
|
||||
}
|
||||
return
|
||||
}
|
||||
let freshSalt = Self.randomSalt()
|
||||
currentDayKey = today
|
||||
currentSalt = freshSalt
|
||||
defaults.set(today, forKey: Keys.dayKey)
|
||||
defaults.set(Self.randomSalt(), forKey: Keys.salt)
|
||||
defaults.set(freshSalt, forKey: Keys.salt)
|
||||
defaults.removeObject(forKey: Keys.hashes)
|
||||
defaults.removeObject(forKey: Keys.lastSeenAt)
|
||||
seenHashes.removeAll()
|
||||
seenPeerIDsToday.removeAll()
|
||||
todayCount = 0
|
||||
lastSightingAt = nil
|
||||
}
|
||||
|
||||
private func saltedHash(_ value: String) -> String {
|
||||
let salt = defaults.data(forKey: Keys.salt) ?? {
|
||||
if currentSalt.isEmpty {
|
||||
let fresh = Self.randomSalt()
|
||||
currentSalt = fresh
|
||||
defaults.set(fresh, forKey: Keys.salt)
|
||||
return fresh
|
||||
}()
|
||||
}
|
||||
var digest = SHA256()
|
||||
digest.update(data: salt)
|
||||
digest.update(data: currentSalt)
|
||||
digest.update(data: Data(value.utf8))
|
||||
return digest.finalize().map { String(format: "%02x", $0) }.joined()
|
||||
}
|
||||
|
||||
@@ -223,6 +223,7 @@ final class MessageDeduplicationService {
|
||||
private var persistScheduled = false
|
||||
private var persistTask: Task<Void, Never>?
|
||||
private var pendingPersistIDs: [String] = []
|
||||
private var clearAllGeneration: UInt64 = 0
|
||||
|
||||
/// Creates a new deduplication service with specified capacities.
|
||||
/// - Parameters:
|
||||
@@ -241,8 +242,15 @@ final class MessageDeduplicationService {
|
||||
self.nostrEventStore = nostrEventStore
|
||||
self.nostrEventCapacity = nostrEventCapacity
|
||||
if let nostrEventStore {
|
||||
for eventID in nostrEventStore.load() {
|
||||
nostrEventCache.record(eventID, value: true)
|
||||
let generation = clearAllGeneration
|
||||
nostrEventStore.loadAsync { [weak self] eventIDs in
|
||||
guard !eventIDs.isEmpty else { return }
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.clearAllGeneration == generation else { return }
|
||||
for eventID in eventIDs where !self.nostrEventCache.contains(eventID) {
|
||||
self.nostrEventCache.record(eventID, value: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -363,6 +371,7 @@ final class MessageDeduplicationService {
|
||||
/// Clears all caches. This is the wipe/panic path: the persisted
|
||||
/// private-envelope record goes with everything else.
|
||||
func clearAll() {
|
||||
clearAllGeneration &+= 1
|
||||
persistTask?.cancel()
|
||||
persistTask = nil
|
||||
persistScheduled = false
|
||||
|
||||
@@ -57,6 +57,19 @@ final class NostrProcessedEventStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads processed event IDs asynchronously on the utility I/O queue so
|
||||
/// cold launch does not block the main actor on disk I/O + JSON decoding.
|
||||
func loadAsync(completion: @escaping @Sendable ([String]) -> Void) {
|
||||
ioQueue.async { [self] in
|
||||
switch loadLocked() {
|
||||
case .loaded(let ids):
|
||||
completion(ids)
|
||||
case .transientError:
|
||||
completion([])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge new IDs onto the persisted record, oldest-first, trimming from
|
||||
/// the front past `cap`. Append-merge (not snapshot-overwrite) so the
|
||||
/// in-memory cache being cleared transiently (channel switches) can
|
||||
|
||||
@@ -151,17 +151,20 @@ final class PrivateChatManager: ObservableObject {
|
||||
@MainActor
|
||||
func syncReadReceiptsForSentMessages(peerID: PeerID, externalReceipts: inout Set<String>) {
|
||||
guard let myPeerID = meshService?.myPeerID else { return }
|
||||
var syncedIDs: [String] = []
|
||||
for message in messages(for: peerID) {
|
||||
if message.isOwn(myPeerID: myPeerID, myGeoChatPeerID: nil) {
|
||||
switch message.deliveryStatus {
|
||||
case .read, .delivered:
|
||||
externalReceipts.insert(message.id)
|
||||
sentReadReceipts.insert(message.id)
|
||||
syncedIDs.append(message.id)
|
||||
case .notSentYet, .failed, .partiallyDelivered, .sending, .sent, .carried:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
guard !syncedIDs.isEmpty else { return }
|
||||
externalReceipts.formUnion(syncedIDs)
|
||||
sentReadReceipts.formUnion(syncedIDs)
|
||||
}
|
||||
|
||||
/// Start a private chat with a peer. Selection is mutated through the
|
||||
|
||||
@@ -158,7 +158,13 @@ final class ChatLiveVoiceCoordinator {
|
||||
/// `sweepsOnInit` exists for tests whose coordinator shares the real
|
||||
/// application-support directory: they pass `false` so parallel test
|
||||
/// runs never sweep each other's in-flight capture files.
|
||||
init(context: any ChatLiveVoiceContext, fileStore: BLEIncomingFileStore = BLEIncomingFileStore(), sweepsOnInit: Bool = true) {
|
||||
/// `asyncStartupSweep` moves the disk sweep off the main actor for cold launch.
|
||||
init(
|
||||
context: any ChatLiveVoiceContext,
|
||||
fileStore: BLEIncomingFileStore = BLEIncomingFileStore(),
|
||||
sweepsOnInit: Bool = true,
|
||||
asyncStartupSweep: Bool = false
|
||||
) {
|
||||
self.context = context
|
||||
self.fileStore = fileStore
|
||||
// Orphaned partial captures from a previous session (live-only bursts
|
||||
@@ -166,7 +172,14 @@ final class ChatLiveVoiceCoordinator {
|
||||
// never reclaim (eviction skips voice_live_* by design) — sweep them
|
||||
// on startup.
|
||||
if sweepsOnInit {
|
||||
sweepStaleLiveCaptures()
|
||||
if asyncStartupSweep {
|
||||
let store = fileStore
|
||||
Task.detached(priority: .utility) {
|
||||
Self.sweepStaleLiveCaptures(in: store)
|
||||
}
|
||||
} else {
|
||||
Self.sweepStaleLiveCaptures(in: fileStore)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -679,7 +692,7 @@ final class ChatLiveVoiceCoordinator {
|
||||
return Data(hexString: hex)
|
||||
}
|
||||
|
||||
private static let incomingSubdirectory = "\(MimeType.Category.audio.mediaDir)/incoming"
|
||||
nonisolated private static let incomingSubdirectory = "\(MimeType.Category.audio.mediaDir)/incoming"
|
||||
|
||||
/// The peer ID and scope in the name mirror the assembly key: colliding
|
||||
/// burst IDs from different senders — or from the same sender across DM
|
||||
@@ -700,7 +713,8 @@ final class ChatLiveVoiceCoordinator {
|
||||
/// only (ConversationStore never persists; the gossip archive replays
|
||||
/// `MessageType.message` packets only), so no row from a previous
|
||||
/// process can reference the file.
|
||||
private func sweepStaleLiveCaptures() {
|
||||
nonisolated private static func sweepStaleLiveCaptures(in fileStore: BLEIncomingFileStore) {
|
||||
let fileManager = fileStore.fileManager
|
||||
guard let directory = try? fileStore.incomingDirectory(subdirectory: Self.incomingSubdirectory),
|
||||
let contents = try? fileManager.contentsOfDirectory(
|
||||
at: directory,
|
||||
|
||||
@@ -65,9 +65,7 @@ extension ChatViewModel: ChatPeerListContext {
|
||||
}
|
||||
|
||||
func recordMeshSightings(peerIDs: [PeerID]) {
|
||||
for peerID in peerIDs {
|
||||
MeshSightingsTracker.shared.recordSighting(peerID: peerID)
|
||||
}
|
||||
MeshSightingsTracker.shared.recordSightings(peerIDs)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -214,7 +214,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
lazy var mediaTransferCoordinator = ChatMediaTransferCoordinator(context: self)
|
||||
lazy var liveVoiceCoordinator = ChatLiveVoiceCoordinator(
|
||||
context: self,
|
||||
sweepsOnInit: !TestEnvironment.isRunningTests
|
||||
sweepsOnInit: !TestEnvironment.isRunningTests,
|
||||
asyncStartupSweep: true
|
||||
)
|
||||
lazy var verificationCoordinator = ChatVerificationCoordinator(context: self)
|
||||
lazy var groupCoordinator = ChatGroupCoordinator(context: self)
|
||||
@@ -476,19 +477,52 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
return scratch
|
||||
}
|
||||
|
||||
// Track sent read receipts to avoid duplicates (persisted across launches)
|
||||
// Note: Persistence happens automatically in didSet, no lifecycle observers needed
|
||||
// Track sent read receipts to avoid duplicates (persisted across launches).
|
||||
// Mutations coalesce into a debounced off-main encode/write so rapid bursts
|
||||
// (opening a chat, reconnecting) do not re-encode the whole set on MainActor.
|
||||
private var readReceiptPersistTask: Task<Void, Never>?
|
||||
private var readReceiptPersistGeneration: UInt64 = 0
|
||||
|
||||
var sentReadReceipts: Set<String> = [] { // messageID set
|
||||
didSet {
|
||||
// Only persist if there are changes
|
||||
guard oldValue != sentReadReceipts else { return }
|
||||
schedulePersistSentReadReceipts()
|
||||
}
|
||||
}
|
||||
|
||||
// Persist whenever it changes (no manual synchronize/verify re-read)
|
||||
if let data = try? JSONEncoder().encode(Array(sentReadReceipts)) {
|
||||
readReceiptsDefaults.set(data, forKey: "sentReadReceipts")
|
||||
private func schedulePersistSentReadReceipts() {
|
||||
readReceiptPersistTask?.cancel()
|
||||
readReceiptPersistGeneration &+= 1
|
||||
let generation = readReceiptPersistGeneration
|
||||
let snapshot = Array(sentReadReceipts)
|
||||
let defaults = readReceiptsDefaults
|
||||
readReceiptPersistTask = Task.detached(priority: .utility) { [weak self] in
|
||||
try? await Task.sleep(nanoseconds: 250_000_000)
|
||||
guard !Task.isCancelled else { return }
|
||||
if let data = try? JSONEncoder().encode(snapshot) {
|
||||
defaults.set(data, forKey: "sentReadReceipts")
|
||||
} else {
|
||||
SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session)
|
||||
}
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self, self.readReceiptPersistGeneration == generation else { return }
|
||||
self.readReceiptPersistTask = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancels any pending debounced write and persists `sentReadReceipts`
|
||||
/// synchronously (used on termination and panic wipe).
|
||||
func flushPersistedReadReceiptsSynchronously() {
|
||||
readReceiptPersistTask?.cancel()
|
||||
readReceiptPersistTask = nil
|
||||
readReceiptPersistGeneration &+= 1
|
||||
if sentReadReceipts.isEmpty {
|
||||
readReceiptsDefaults.removeObject(forKey: "sentReadReceipts")
|
||||
} else if let data = try? JSONEncoder().encode(Array(sentReadReceipts)) {
|
||||
readReceiptsDefaults.set(data, forKey: "sentReadReceipts")
|
||||
} else {
|
||||
SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1550,10 +1584,12 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
|
||||
/// Save identity state without stopping services (for backgrounding)
|
||||
func saveIdentityState() {
|
||||
flushPersistedReadReceiptsSynchronously()
|
||||
lifecycleCoordinator.saveIdentityState()
|
||||
}
|
||||
|
||||
@objc func applicationWillTerminate() {
|
||||
flushPersistedReadReceiptsSynchronously()
|
||||
lifecycleCoordinator.applicationWillTerminate()
|
||||
}
|
||||
|
||||
@@ -1719,6 +1755,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
|
||||
|
||||
// Clear read receipt tracking
|
||||
sentReadReceipts.removeAll()
|
||||
flushPersistedReadReceiptsSynchronously()
|
||||
privateChatManager.resetForPanic()
|
||||
deduplicationService.clearAll()
|
||||
|
||||
|
||||
@@ -610,6 +610,26 @@ struct ChatLiveVoiceCoordinatorTests {
|
||||
#expect(FileManager.default.fileExists(atPath: promoted.path))
|
||||
}
|
||||
|
||||
@Test func asyncStartupSweepRemovesStaleLiveCapturesOffMain() async throws {
|
||||
let (store, incoming, cleanup) = try makeTempStore()
|
||||
defer { cleanup() }
|
||||
|
||||
let stale = incoming.appendingPathComponent("voice_live_00cc00cc00cc00cc_ddddeeeeffff0002_dm.aac")
|
||||
let finalized = incoming.appendingPathComponent("voice_00112233445566ff.m4a")
|
||||
try Data([0x01]).write(to: stale)
|
||||
try Data([0x02]).write(to: finalized)
|
||||
|
||||
let context = MockChatLiveVoiceContext()
|
||||
_ = ChatLiveVoiceCoordinator(context: context, fileStore: store, sweepsOnInit: true, asyncStartupSweep: true)
|
||||
|
||||
let swept = await TestHelpers.waitUntil(
|
||||
{ !FileManager.default.fileExists(atPath: stale.path) },
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(swept)
|
||||
#expect(FileManager.default.fileExists(atPath: finalized.path))
|
||||
}
|
||||
|
||||
@Test func finalizedFallbackSurvivesNextStartupSweep() throws {
|
||||
let (store, incoming, cleanup) = try makeTempStore()
|
||||
defer { cleanup() }
|
||||
|
||||
@@ -78,4 +78,26 @@ struct MeshSightingsTrackerTests {
|
||||
let reloaded = MeshSightingsTracker(defaults: defaults, now: { self.noon })
|
||||
#expect(reloaded.todayCount == 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
func recordsBatchedSightingsOnceAndDeduplicatesAcrossRepeatCalls() {
|
||||
let defaults = makeDefaults()
|
||||
let tracker = MeshSightingsTracker(defaults: defaults, now: { self.noon })
|
||||
|
||||
let peerA = PeerID(str: "aaaa111122223333")
|
||||
let peerB = PeerID(str: "bbbb444455556666")
|
||||
let peerC = PeerID(str: "cccc777788889999")
|
||||
|
||||
tracker.recordSightings([peerA, peerB, peerA])
|
||||
#expect(tracker.todayCount == 2)
|
||||
#expect(tracker.lastSightingAt == noon)
|
||||
|
||||
tracker.recordSightings([peerA, peerB, peerC])
|
||||
#expect(tracker.todayCount == 3)
|
||||
|
||||
let reloaded = MeshSightingsTracker(defaults: defaults, now: { self.noon.addingTimeInterval(30) })
|
||||
#expect(reloaded.todayCount == 3)
|
||||
reloaded.recordSightings([peerA, peerB, peerC])
|
||||
#expect(reloaded.todayCount == 3)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user