mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-11-29 08:29:22 +00:00
Harden offline-to-online and mesh-to-Nostr transport handoffs (#1946)
* Harden offline-to-online and mesh-to-Nostr transport handoffs * Use inclusive identifiers in NostrRelayManagerTests for SwiftLint * Fix Periphery dead-code findings on NetworkInterfaceSignature and unused helpers --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
1 parent
15ea762abc
commit
a00cc51be2
27 files changed
+1090
-98
No files matched your search
@@ -248,22 +248,34 @@ final class AppRuntime: ObservableObject {
|
||||
guard chatViewModel.networkActivationAllowed else { return }
|
||||
chatViewModel.meshService.startServices()
|
||||
TorManager.shared.setAppForeground(true)
|
||||
let shouldRefreshNostrConnections = didHandleInitialActive && didEnterBackground
|
||||
|
||||
if didHandleInitialActive && didEnterBackground {
|
||||
if TorManager.shared.isAutoStartAllowed() && !TorManager.shared.isReady {
|
||||
TorManager.shared.ensureRunningOnForeground()
|
||||
}
|
||||
} else {
|
||||
didHandleInitialActive = true
|
||||
}
|
||||
|
||||
let reconnectAction = Self.resolveForegroundNostrReconnectAction(
|
||||
didEnterBackground: didEnterBackground,
|
||||
activationAllowed: NetworkActivationService.shared.activationAllowed,
|
||||
userTorEnabled: NetworkActivationService.shared.userTorEnabled,
|
||||
torAutoStartAllowed: TorManager.shared.isAutoStartAllowed()
|
||||
)
|
||||
didHandleInitialActive = true
|
||||
didEnterBackground = false
|
||||
|
||||
if shouldRefreshNostrConnections && TorManager.shared.isAutoStartAllowed() {
|
||||
Task.detached {
|
||||
let _ = await TorManager.shared.awaitReady(timeout: 60)
|
||||
switch reconnectAction {
|
||||
case .none:
|
||||
break
|
||||
case .reconnectDirect:
|
||||
TorURLSession.shared.rebuild()
|
||||
NostrRelayManager.shared.resetAllConnections()
|
||||
case .awaitTorAndReconnect:
|
||||
if !TorManager.shared.isReady {
|
||||
TorManager.shared.ensureRunningOnForeground()
|
||||
}
|
||||
Task.detached { [weak self] in
|
||||
let ready = await TorManager.shared.awaitReady(timeout: 60)
|
||||
guard ready else { return }
|
||||
await MainActor.run {
|
||||
guard let self,
|
||||
self.chatViewModel.networkActivationAllowed,
|
||||
NetworkActivationService.shared.activationAllowed,
|
||||
NetworkActivationService.shared.userTorEnabled else { return }
|
||||
TorURLSession.shared.rebuild()
|
||||
NostrRelayManager.shared.resetAllConnections()
|
||||
}
|
||||
@@ -337,8 +349,11 @@ private extension AppRuntime {
|
||||
.removeDuplicates()
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] allowed in
|
||||
guard allowed, self?.chatViewModel.networkActivationAllowed == true else { return }
|
||||
guard allowed, let self, self.chatViewModel.networkActivationAllowed else { return }
|
||||
GeoRelayDirectory.shared.prefetchIfNeeded()
|
||||
// Recover any active location channel whose subscribe() was
|
||||
// dropped while offline or during the teleport activation race.
|
||||
self.chatViewModel.ensureCurrentGeohashSubscribed()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
@@ -439,7 +454,15 @@ private extension AppRuntime {
|
||||
chatViewModel.nostrHandlersSetup = true
|
||||
}
|
||||
|
||||
guard !isInitialConnection else { return }
|
||||
if isInitialConnection {
|
||||
// If the app launched offline (or teleported before activation
|
||||
// opened), the active geohash subscription and sampling were
|
||||
// dropped before relays came up. Ensure they are registered now
|
||||
// without disturbing an already-subscribed online launch.
|
||||
chatViewModel.ensureCurrentGeohashSubscribed()
|
||||
chatViewModel.geoChannelCoordinator?.refreshSampling()
|
||||
return
|
||||
}
|
||||
|
||||
chatViewModel.resubscribeCurrentGeohash()
|
||||
chatViewModel.geoChannelCoordinator?.refreshSampling()
|
||||
@@ -527,3 +550,29 @@ extension AppRuntime {
|
||||
return .forwardToChat
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Foreground Nostr reconnection
|
||||
|
||||
extension AppRuntime {
|
||||
enum ForegroundNostrReconnectAction: Equatable {
|
||||
case none
|
||||
case reconnectDirect
|
||||
case awaitTorAndReconnect
|
||||
}
|
||||
|
||||
/// Pure decision table for foreground Nostr recovery after `.background`
|
||||
/// disconnected relay sockets. Everyday Mode (Tor off) must reconnect
|
||||
/// directly instead of gating on `TorManager.isAutoStartAllowed()`.
|
||||
nonisolated static func resolveForegroundNostrReconnectAction(
|
||||
didEnterBackground: Bool,
|
||||
activationAllowed: Bool,
|
||||
userTorEnabled: Bool,
|
||||
torAutoStartAllowed: Bool
|
||||
) -> ForegroundNostrReconnectAction {
|
||||
guard didEnterBackground, activationAllowed else { return .none }
|
||||
if userTorEnabled {
|
||||
return torAutoStartAllowed ? .awaitTorAndReconnect : .none
|
||||
}
|
||||
return .reconnectDirect
|
||||
}
|
||||
}
|
||||
@@ -321,6 +321,64 @@ final class NostrRelayManager: ObservableObject {
|
||||
guard dependencies.activationAllowed() else { return }
|
||||
connectToRelays(relays.map(\.url), shouldLog: true)
|
||||
}
|
||||
|
||||
/// Reconnects after an offline → online transition or gate reopening.
|
||||
/// Clears transient DNS and backoff failure state accumulated while the
|
||||
/// network was dropping, ensures relays referenced by durable
|
||||
/// subscriptions are present, and connects immediately.
|
||||
func resetForNetworkRecovery() {
|
||||
guard dependencies.activationAllowed() else { return }
|
||||
for index in relays.indices {
|
||||
relays[index].reconnectAttempts = 0
|
||||
relays[index].nextReconnectTime = nil
|
||||
relays[index].lastError = nil
|
||||
}
|
||||
var existing = Set(relays.map(\.url))
|
||||
let requiredSubRelays = subscriptionRequestState.values.flatMap(\.relayURLs)
|
||||
for url in allowedRelayList(from: requiredSubRelays) where !existing.contains(url) {
|
||||
relays.append(Relay(url: url))
|
||||
existing.insert(url)
|
||||
}
|
||||
connect()
|
||||
}
|
||||
|
||||
/// Retries only disconnected relays that accumulated backoff or DNS
|
||||
/// failures (e.g. during a brief Wi-Fi ↔ Cellular handoff) without
|
||||
/// touching already-connected sockets.
|
||||
func recoverFailedRelays() {
|
||||
guard dependencies.activationAllowed() else { return }
|
||||
var recoveredURLs: [String] = []
|
||||
for index in relays.indices {
|
||||
let url = relays[index].url
|
||||
guard !relays[index].isConnected,
|
||||
connections[url] == nil,
|
||||
relays[index].reconnectAttempts > 0 || relays[index].lastError != nil else {
|
||||
continue
|
||||
}
|
||||
relays[index].reconnectAttempts = 0
|
||||
relays[index].nextReconnectTime = nil
|
||||
relays[index].lastError = nil
|
||||
recoveredURLs.append(url)
|
||||
}
|
||||
guard !recoveredURLs.isEmpty else { return }
|
||||
SecureLogger.info(
|
||||
"🌐 Recovering \(recoveredURLs.count) failed Nostr relay(s) after network path change",
|
||||
category: .session
|
||||
)
|
||||
connectToRelays(recoveredURLs, shouldLog: true)
|
||||
}
|
||||
|
||||
/// Whether a durable subscription with `id` is currently registered with
|
||||
/// at least one target relay (active or pending). Used after offline →
|
||||
/// online transitions to detect subscriptions that were dropped while the
|
||||
/// network gate was closed.
|
||||
func hasRegisteredSubscription(id: String) -> Bool {
|
||||
guard messageHandlers[id] != nil,
|
||||
let state = subscriptionRequestState[id] else {
|
||||
return false
|
||||
}
|
||||
return !state.relayURLs.isEmpty
|
||||
}
|
||||
|
||||
/// Disconnect from all relays
|
||||
func disconnect() {
|
||||
@@ -641,8 +699,13 @@ final class NostrRelayManager: ObservableObject {
|
||||
handler: @escaping (NostrEvent) -> Void,
|
||||
onEOSE: (() -> Void)? = nil
|
||||
) {
|
||||
// Global network policy gate
|
||||
guard dependencies.activationAllowed() else { return }
|
||||
// Global network policy gate. Always settle an EOSE waiter when
|
||||
// disallowed so callers (e.g. LocationNotesManager) transition to
|
||||
// their connecting/retry state instead of hanging in `.loading`.
|
||||
guard dependencies.activationAllowed() else {
|
||||
onEOSE?()
|
||||
return
|
||||
}
|
||||
// Coalesce rapid duplicate subscribe requests even while Tor readiness is pending.
|
||||
let now = dependencies.now()
|
||||
if let last = subscribeCoalesce[id], now.timeIntervalSince(last) < subscribeCoalesceInterval {
|
||||
|
||||
@@ -153,6 +153,10 @@ final class BridgeService: ObservableObject {
|
||||
var openSubscription: (@MainActor ([String]) -> Void)?
|
||||
/// Closes the rendezvous subscription.
|
||||
var closeSubscription: (@MainActor () -> Void)?
|
||||
/// Whether the rendezvous subscription is currently registered on the
|
||||
/// relay manager. When `false` after an offline → online transition,
|
||||
/// `ensureSubscriptionOpen()` re-opens it.
|
||||
var isSubscriptionRegistered: (@MainActor () -> Bool)?
|
||||
/// Whether any Nostr relay connection is currently working.
|
||||
var relaysConnected: (@MainActor () -> Bool)?
|
||||
/// The local neighborhood cell from CoreLocation, if permitted.
|
||||
@@ -349,6 +353,18 @@ final class BridgeService: ObservableObject {
|
||||
armPresenceTimerIfNeeded()
|
||||
}
|
||||
|
||||
/// Re-opens the rendezvous subscription when relays come back online after
|
||||
/// an outage during which the original `openSubscription` call was dropped
|
||||
/// by the network activation gate. Idempotent when already registered.
|
||||
func ensureSubscriptionOpen() {
|
||||
guard isEnabled, let cell = activeCell else { return }
|
||||
if isSubscriptionRegistered?() == true { return }
|
||||
let cells = [cell] + Geohash.neighbors(of: cell)
|
||||
subscribedCells = Set(cells)
|
||||
openSubscription?(cells)
|
||||
SecureLogger.info("🌉 Bridge: restored rendezvous subscription for cell \(cell)", category: .session)
|
||||
}
|
||||
|
||||
/// The rendezvous cell: our own location when we have it, else the cell
|
||||
/// a reachable bridge gateway advertises in its announce.
|
||||
private func currentCell() -> String? {
|
||||
|
||||
@@ -86,10 +86,20 @@ final class GeohashPresenceService: ObservableObject {
|
||||
self.availableChannelsProvider = { LocationStateManager.shared.availableChannels }
|
||||
self.isLocationAuthorized = { LocationStateManager.shared.permissionState == .authorized }
|
||||
self.locationChanges = LocationStateManager.shared.$availableChannels.eraseToAnyPublisher()
|
||||
self.torReadyPublisher = NotificationCenter.default.publisher(for: .TorDidBecomeReady)
|
||||
.map { _ in () }
|
||||
.eraseToAnyPublisher()
|
||||
self.torIsReady = { TorManager.shared.isReady }
|
||||
self.torReadyPublisher = Publishers.Merge(
|
||||
NotificationCenter.default.publisher(for: .TorDidBecomeReady).map { _ in () },
|
||||
NetworkActivationService.shared.$activationAllowed
|
||||
.removeDuplicates()
|
||||
.filter { $0 }
|
||||
.map { _ in () }
|
||||
).eraseToAnyPublisher()
|
||||
self.torIsReady = {
|
||||
guard NetworkActivationService.shared.activationAllowed else { return false }
|
||||
if NetworkActivationService.shared.userTorEnabled {
|
||||
return TorManager.shared.isReady
|
||||
}
|
||||
return true
|
||||
}
|
||||
self.torIsForeground = { TorManager.shared.isForeground() }
|
||||
self.deriveIdentity = { try idBridge.deriveIdentity(forGeohash: $0) }
|
||||
self.clearIdentityCache = { idBridge.clearInMemoryCaches() }
|
||||
|
||||
@@ -17,6 +17,12 @@ struct LocationNotesDependencies {
|
||||
var now: () -> Date
|
||||
// Fires when the geo relay directory refreshes; used to retry after "no relays".
|
||||
var relayDirectoryUpdates: AnyPublisher<Void, Never> = Empty(completeImmediately: false).eraseToAnyPublisher()
|
||||
/// Fires when Nostr relay connectivity comes back online so notes opened
|
||||
/// while offline (`.connecting`) refresh immediately without waiting for
|
||||
/// geo relays that were never added while activation was disallowed.
|
||||
var networkBecameAvailable: @MainActor () -> AnyPublisher<Void, Never> = {
|
||||
Empty(completeImmediately: false).eraseToAnyPublisher()
|
||||
}
|
||||
/// Whether any of the target relays has a live connection — distinguishes
|
||||
/// "loaded, empty" from "still connecting (Tor warming up)" when EOSE
|
||||
/// fires without data. Defaults to true so tests keep legacy behavior.
|
||||
@@ -58,6 +64,18 @@ struct LocationNotesDependencies {
|
||||
.publisher(for: .geoRelayDirectoryDidRefresh)
|
||||
.map { _ in () }
|
||||
.eraseToAnyPublisher(),
|
||||
networkBecameAvailable: {
|
||||
Publishers.Merge(
|
||||
NostrRelayManager.shared.$isConnected
|
||||
.removeDuplicates()
|
||||
.filter { $0 }
|
||||
.map { _ in () },
|
||||
NetworkActivationService.shared.$activationAllowed
|
||||
.removeDuplicates()
|
||||
.filter { $0 }
|
||||
.map { _ in () }
|
||||
).eraseToAnyPublisher()
|
||||
},
|
||||
anyRelayConnected: { relayUrls in
|
||||
NostrRelayManager.shared.isAnyRelayConnected(among: relayUrls)
|
||||
}
|
||||
@@ -132,6 +150,7 @@ final class LocationNotesManager: ObservableObject {
|
||||
private var subscriptionID: String?
|
||||
private var noteIDs = Set<String>() // O(1) duplicate detection
|
||||
private var directoryUpdateCancellable: AnyCancellable?
|
||||
private var networkAvailableCancellable: AnyCancellable?
|
||||
private var expiryPruneTimer: Timer?
|
||||
private var connectivityRetryTimer: Timer?
|
||||
private let dependencies: LocationNotesDependencies
|
||||
@@ -167,6 +186,13 @@ final class LocationNotesManager: ObservableObject {
|
||||
self.subscribe()
|
||||
}
|
||||
}
|
||||
networkAvailableCancellable = dependencies.networkBecameAvailable()
|
||||
.sink { [weak self] in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.state == .connecting else { return }
|
||||
self.refresh()
|
||||
}
|
||||
}
|
||||
// NIP-40 notes can expire while displayed (a 24h dead drop crossing
|
||||
// its boundary); ingest-time filtering alone would keep it visible
|
||||
// until the subscription is recreated.
|
||||
@@ -528,6 +554,7 @@ final class LocationNotesManager: ObservableObject {
|
||||
expiryPruneTimer?.invalidate()
|
||||
expiryPruneTimer = nil
|
||||
directoryUpdateCancellable = nil
|
||||
networkAvailableCancellable = nil
|
||||
notes.removeAll(keepingCapacity: false)
|
||||
noteIDs.removeAll(keepingCapacity: false)
|
||||
ownPubkey = nil
|
||||
|
||||
@@ -63,6 +63,12 @@ final class MessageRouter {
|
||||
/// message until an ack arrives.
|
||||
var onMessageCarried: ((_ messageID: String, _ peerID: PeerID) -> Void)?
|
||||
|
||||
/// Invoked when a previously queued or failed-over private message is
|
||||
/// handed to a live transport during a flush or disconnect failover, so
|
||||
/// the UI can advance `.sending` → `.sent` without ever downgrading
|
||||
/// stronger states (`.carried`/`.delivered`/`.read`).
|
||||
var onMessageSent: ((_ messageID: String, _ peerID: PeerID) -> Void)?
|
||||
|
||||
/// Parallel deposit into the internet bridge: park a sealed copy on
|
||||
/// relays as a courier drop, so delivery stops requiring a physical
|
||||
/// courier encounter. No-op unless the bridge is enabled. Runs alongside
|
||||
@@ -236,22 +242,37 @@ final class MessageRouter {
|
||||
return
|
||||
}
|
||||
|
||||
if let transport = reachableTransport(for: peerID) {
|
||||
// Reachability without a connection is a freshness heuristic (e.g.
|
||||
// the mesh retention window), so the send can silently go nowhere.
|
||||
// Send now, but retain a copy until a delivery/read ack clears it;
|
||||
// receivers dedup resends by message ID.
|
||||
SecureLogger.debug("Routing PM via \(type(of: transport)) (reachable) to \(peerID.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session)
|
||||
let promptTransports = transports.filter {
|
||||
$0.isPeerReachable(peerID) && $0.canDeliverPromptly(to: peerID)
|
||||
}
|
||||
if !promptTransports.isEmpty {
|
||||
// Reachability without a direct connection can be a freshness
|
||||
// heuristic (e.g. the BLE retention window after a peer walked
|
||||
// away) or a live Nostr relay. Sending across every promptly
|
||||
// deliverable transport (e.g. BLE multi-hop + live Nostr) avoids
|
||||
// stranding a DM in a stale 60s BLE retention window while still
|
||||
// reaching offline multi-hop mesh peers; receivers dedup by ID.
|
||||
enqueue(message, for: peerID)
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
// "Reachable" without prompt delivery means the send only joined
|
||||
// a queue (Nostr with relays down): also hand a sealed copy to
|
||||
// any connected couriers rather than waiting for internet that
|
||||
// may never come. Double delivery is harmless — receivers dedup
|
||||
// by message ID, and delivered/read acks never downgrade.
|
||||
if !transport.canDeliverPromptly(to: peerID) {
|
||||
attemptCourierDeposit(messageID: messageID, for: peerID)
|
||||
for transport in promptTransports {
|
||||
SecureLogger.debug("Routing PM via \(type(of: transport)) (reachable/prompt) to \(peerID.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session)
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if let transport = reachableTransport(for: peerID) {
|
||||
// Reachable without prompt delivery means the send only joins a
|
||||
// transport queue (or drops while offline, e.g. Nostr with relays
|
||||
// down). Keep `sendAttempts = 0` so offline sends never burn the
|
||||
// retry budget before relays reconnect, hand off to the transport
|
||||
// (so Tor-warmup queues still work), and deposit a sealed copy
|
||||
// with couriers in parallel.
|
||||
var unsent = message
|
||||
unsent.sendAttempts = 0
|
||||
enqueue(unsent, for: peerID)
|
||||
SecureLogger.debug("Routing PM via \(type(of: transport)) (reachable, not prompt) to \(peerID.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session)
|
||||
transport.sendPrivateMessage(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
attemptCourierDeposit(messageID: messageID, for: peerID)
|
||||
} else {
|
||||
var unsent = message
|
||||
unsent.sendAttempts = 0
|
||||
@@ -502,6 +523,22 @@ final class MessageRouter {
|
||||
return true
|
||||
}
|
||||
|
||||
/// Marks an offline-queued (`sendAttempts == 0`) message as handed off to
|
||||
/// a connected pre-handshake link without burning past 1 on subsequent
|
||||
/// insecure flushes. Prevents `retrySecurePrivateMessagesAfterAuthentication`
|
||||
/// from duplicating the message BLE's handshake queue already drains.
|
||||
@discardableResult
|
||||
private func markPreHandshakeHandoffIfUnsent(_ messageID: String, for peerID: PeerID) -> Bool {
|
||||
guard var queue = outbox[peerID],
|
||||
let index = queue.firstIndex(where: { $0.messageID == messageID }),
|
||||
queue[index].sendAttempts == 0 else {
|
||||
return false
|
||||
}
|
||||
queue[index].sendAttempts = 1
|
||||
outbox[peerID] = queue
|
||||
return true
|
||||
}
|
||||
|
||||
private func dropMessage(_ messageID: String, for peerID: PeerID) {
|
||||
secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: messageID))
|
||||
onMessageDropped?(messageID, peerID)
|
||||
@@ -540,11 +577,14 @@ final class MessageRouter {
|
||||
outboxStore?.wipe()
|
||||
}
|
||||
|
||||
/// Returns true only when the receipt was handed to a reachable transport.
|
||||
/// Returns true only when the receipt was handed to a transport that can
|
||||
/// deliver it (connected, or reachable with prompt delivery — never an
|
||||
/// offline Nostr transport whose send would be dropped).
|
||||
/// Prefers a transport that can deliver securely right now (established
|
||||
/// Noise session on BLE, or connected DM relay on Nostr), then a connected
|
||||
/// transport, then any reachable transport — avoiding throwing receipts
|
||||
/// into a stale BLE reachability retention window when Nostr is live.
|
||||
/// transport, then any promptly-deliverable reachable transport — avoiding
|
||||
/// throwing receipts into a stale BLE reachability retention window when
|
||||
/// Nostr is live, and avoiding burning receipts while offline.
|
||||
/// A false result means it was dropped (no route) and must NOT be recorded
|
||||
/// as sent, or the sender's message would stay unread forever — the receipt
|
||||
/// is retried on the next read scan (chat open / foreground / reconnect).
|
||||
@@ -552,7 +592,7 @@ final class MessageRouter {
|
||||
func sendReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool {
|
||||
let transport = transports.first { $0.isPeerReachable(peerID) && $0.canDeliverSecurely(to: peerID) }
|
||||
?? connectedTransport(for: peerID)
|
||||
?? reachableTransport(for: peerID)
|
||||
?? transports.first { $0.isPeerReachable(peerID) && $0.canDeliverPromptly(to: peerID) }
|
||||
if let transport {
|
||||
SecureLogger.debug("Routing READ ack via \(type(of: transport)) to \(peerID.id.prefix(8))… id=\(receipt.originalMessageID.prefix(8))…", category: .session)
|
||||
transport.sendReadReceipt(receipt, to: peerID)
|
||||
@@ -566,6 +606,8 @@ final class MessageRouter {
|
||||
func sendFavoriteNotification(to peerID: PeerID, isFavorite: Bool) {
|
||||
if let transport = connectedTransport(for: peerID) {
|
||||
transport.sendFavoriteNotification(to: peerID, isFavorite: isFavorite)
|
||||
} else if let transport = transports.first(where: { $0.isPeerReachable(peerID) && $0.canDeliverPromptly(to: peerID) }) {
|
||||
transport.sendFavoriteNotification(to: peerID, isFavorite: isFavorite)
|
||||
} else if let transport = reachableTransport(for: peerID) {
|
||||
transport.sendFavoriteNotification(to: peerID, isFavorite: isFavorite)
|
||||
} else if let nostr = nostrTransport, nostr.canSendFavoriteNotification(to: peerID) {
|
||||
@@ -802,35 +844,7 @@ final class MessageRouter {
|
||||
}
|
||||
|
||||
let key = PeerMessageKey(peerID: peerID, messageID: message.messageID)
|
||||
let routeTarget: (transport: Transport, sendPeerID: PeerID, kind: Int)? = {
|
||||
if let transport = connectedTransport(for: peerID), transport.canDeliverSecurely(to: peerID) {
|
||||
return (transport, peerID, 0)
|
||||
}
|
||||
if let fallbackPeerID, fallbackPeerID != peerID,
|
||||
let transport = connectedTransport(for: fallbackPeerID), transport.canDeliverSecurely(to: fallbackPeerID) {
|
||||
return (transport, fallbackPeerID, 0)
|
||||
}
|
||||
if let transport = connectedTransport(for: peerID) {
|
||||
return (transport, peerID, 1)
|
||||
}
|
||||
if let fallbackPeerID, fallbackPeerID != peerID,
|
||||
let transport = connectedTransport(for: fallbackPeerID) {
|
||||
return (transport, fallbackPeerID, 1)
|
||||
}
|
||||
if let transport = reachableTransport(for: peerID) {
|
||||
return (transport, peerID, 2)
|
||||
}
|
||||
if let fallbackPeerID, fallbackPeerID != peerID,
|
||||
let transport = reachableTransport(for: fallbackPeerID) {
|
||||
return (transport, fallbackPeerID, 2)
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
|
||||
guard let (transport, sendPeerID, kind) = routeTarget else { return false }
|
||||
|
||||
switch kind {
|
||||
case 0:
|
||||
if let (transport, sendPeerID) = connectedSecureTarget(for: peerID, fallbackPeerID: fallbackPeerID) {
|
||||
// Bound actual secure transmissions for peers that never ack.
|
||||
if dropIfExpiredOrAtAttemptCap(message, for: peerID, now: now, enforceAttemptCap: true) {
|
||||
return true
|
||||
@@ -838,24 +852,181 @@ final class MessageRouter {
|
||||
SecureLogger.debug("Outbox -> \(type(of: transport)) (connected) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", category: .session)
|
||||
secureTransmissions.insert(key)
|
||||
transport.sendPrivateMessage(message.content, to: sendPeerID, recipientNickname: message.nickname, messageID: message.messageID)
|
||||
onMessageSent?(message.messageID, peerID)
|
||||
return incrementSendAttemptsIfQueued(message.messageID, for: peerID)
|
||||
case 1:
|
||||
}
|
||||
|
||||
if let (transport, sendPeerID) = connectedTarget(for: peerID, fallbackPeerID: fallbackPeerID) {
|
||||
// Connected without a secure session: send over the live link
|
||||
// without burning the attempt cap (bounded by 24h TTL + FIFO cap).
|
||||
// Mark an unsent (0-attempt) entry as handed off to BLE so the
|
||||
// subsequent authentication callback does not duplicate it.
|
||||
SecureLogger.debug("Outbox -> \(type(of: transport)) (connected, no secure session) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", category: .session)
|
||||
secureTransmissions.remove(key)
|
||||
transport.sendPrivateMessage(message.content, to: sendPeerID, recipientNickname: message.nickname, messageID: message.messageID)
|
||||
return false
|
||||
default:
|
||||
// Reachability without a connection is a freshness heuristic:
|
||||
// send and retain, bounded by attempt count for silent peers.
|
||||
if dropIfExpiredOrAtAttemptCap(message, for: peerID, now: now, enforceAttemptCap: true) {
|
||||
return true
|
||||
}
|
||||
SecureLogger.debug("Outbox -> \(type(of: transport)) (reachable) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", category: .session)
|
||||
transport.sendPrivateMessage(message.content, to: sendPeerID, recipientNickname: message.nickname, messageID: message.messageID)
|
||||
return incrementSendAttemptsIfQueued(message.messageID, for: peerID)
|
||||
onMessageSent?(message.messageID, peerID)
|
||||
return markPreHandshakeHandoffIfUnsent(message.messageID, for: peerID)
|
||||
}
|
||||
|
||||
let promptTargets = promptReachableTargets(for: peerID, fallbackPeerID: fallbackPeerID)
|
||||
guard !promptTargets.isEmpty else { return false }
|
||||
|
||||
// Reachability without a connection: send only on promptly deliverable
|
||||
// transports (never burn attempts against an offline Nostr queue),
|
||||
// bounded by attempt count for silent peers.
|
||||
if dropIfExpiredOrAtAttemptCap(message, for: peerID, now: now, enforceAttemptCap: true) {
|
||||
return true
|
||||
}
|
||||
for (transport, sendPeerID) in promptTargets {
|
||||
SecureLogger.debug("Outbox -> \(type(of: transport)) (reachable/prompt) for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…", category: .session)
|
||||
transport.sendPrivateMessage(message.content, to: sendPeerID, recipientNickname: message.nickname, messageID: message.messageID)
|
||||
}
|
||||
onMessageSent?(message.messageID, peerID)
|
||||
return incrementSendAttemptsIfQueued(message.messageID, for: peerID)
|
||||
}
|
||||
|
||||
/// Immediately fails over unacked retained messages for a peer whose
|
||||
/// transport just disconnected (e.g. BLE peer walked out of range) to any
|
||||
/// alternate transport that can deliver promptly (e.g. live Nostr relays).
|
||||
func failOverOutbox(for peerIDAliases: [PeerID], excluding disconnectedTransport: Transport) {
|
||||
typealias Entry = (peerID: PeerID, message: QueuedMessage, aliasOrder: Int, queueOrder: Int)
|
||||
var expandedAliases: [PeerID] = []
|
||||
var seenAlias = Set<PeerID>()
|
||||
for alias in peerIDAliases {
|
||||
for candidateAlias in outboxAliases(for: alias) where seenAlias.insert(candidateAlias).inserted {
|
||||
expandedAliases.append(candidateAlias)
|
||||
}
|
||||
}
|
||||
guard !expandedAliases.isEmpty else { return }
|
||||
|
||||
var entries: [Entry] = []
|
||||
for (aliasOrder, alias) in expandedAliases.enumerated() {
|
||||
guard let queued = outbox[alias] else { continue }
|
||||
for (queueOrder, message) in queued.enumerated() {
|
||||
entries.append((alias, message, aliasOrder, queueOrder))
|
||||
}
|
||||
}
|
||||
guard !entries.isEmpty else { return }
|
||||
|
||||
entries.sort { lhs, rhs in
|
||||
if lhs.message.timestamp != rhs.message.timestamp {
|
||||
return lhs.message.timestamp < rhs.message.timestamp
|
||||
}
|
||||
if lhs.aliasOrder != rhs.aliasOrder {
|
||||
return lhs.aliasOrder < rhs.aliasOrder
|
||||
}
|
||||
if lhs.queueOrder != rhs.queueOrder {
|
||||
return lhs.queueOrder < rhs.queueOrder
|
||||
}
|
||||
return lhs.message.messageID < rhs.message.messageID
|
||||
}
|
||||
|
||||
let currentDate = now()
|
||||
var sentMessageIDs = Set<String>()
|
||||
var outboxChanged = false
|
||||
for entry in entries {
|
||||
let peerID = entry.peerID
|
||||
let message = entry.message
|
||||
guard sentMessageIDs.insert(message.messageID).inserted,
|
||||
queuedMessage(message.messageID, for: peerID) != nil else {
|
||||
continue
|
||||
}
|
||||
let targets = alternatePromptTargets(
|
||||
for: peerID,
|
||||
fallbackAliases: peerIDAliases,
|
||||
excluding: disconnectedTransport
|
||||
)
|
||||
guard !targets.isEmpty else { continue }
|
||||
|
||||
if dropIfExpiredOrAtAttemptCap(message, for: peerID, now: currentDate, enforceAttemptCap: true) {
|
||||
outboxChanged = true
|
||||
continue
|
||||
}
|
||||
secureTransmissions.remove(PeerMessageKey(peerID: peerID, messageID: message.messageID))
|
||||
for (transport, sendPeerID) in targets {
|
||||
SecureLogger.debug(
|
||||
"Failover -> \(type(of: transport)) after disconnect for \(peerID.id.prefix(8))… id=\(message.messageID.prefix(8))…",
|
||||
category: .session
|
||||
)
|
||||
transport.sendPrivateMessage(
|
||||
message.content,
|
||||
to: sendPeerID,
|
||||
recipientNickname: message.nickname,
|
||||
messageID: message.messageID
|
||||
)
|
||||
}
|
||||
onMessageSent?(message.messageID, peerID)
|
||||
outboxChanged = incrementSendAttemptsIfQueued(message.messageID, for: peerID) || outboxChanged
|
||||
}
|
||||
|
||||
if outboxChanged {
|
||||
persistOutbox()
|
||||
}
|
||||
}
|
||||
|
||||
private func connectedSecureTarget(
|
||||
for peerID: PeerID,
|
||||
fallbackPeerID: PeerID?
|
||||
) -> (Transport, PeerID)? {
|
||||
if let transport = connectedTransport(for: peerID), transport.canDeliverSecurely(to: peerID) {
|
||||
return (transport, peerID)
|
||||
}
|
||||
if let fallbackPeerID, fallbackPeerID != peerID,
|
||||
let transport = connectedTransport(for: fallbackPeerID), transport.canDeliverSecurely(to: fallbackPeerID) {
|
||||
return (transport, fallbackPeerID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func connectedTarget(
|
||||
for peerID: PeerID,
|
||||
fallbackPeerID: PeerID?
|
||||
) -> (Transport, PeerID)? {
|
||||
if let transport = connectedTransport(for: peerID) {
|
||||
return (transport, peerID)
|
||||
}
|
||||
if let fallbackPeerID, fallbackPeerID != peerID,
|
||||
let transport = connectedTransport(for: fallbackPeerID) {
|
||||
return (transport, fallbackPeerID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private func promptReachableTargets(
|
||||
for peerID: PeerID,
|
||||
fallbackPeerID: PeerID?
|
||||
) -> [(Transport, PeerID)] {
|
||||
var targets: [(Transport, PeerID)] = []
|
||||
for transport in transports {
|
||||
if transport.isPeerReachable(peerID) && transport.canDeliverPromptly(to: peerID) {
|
||||
targets.append((transport, peerID))
|
||||
} else if let fallbackPeerID, fallbackPeerID != peerID,
|
||||
transport.isPeerReachable(fallbackPeerID) && transport.canDeliverPromptly(to: fallbackPeerID) {
|
||||
targets.append((transport, fallbackPeerID))
|
||||
}
|
||||
}
|
||||
return targets
|
||||
}
|
||||
|
||||
private func alternatePromptTargets(
|
||||
for peerID: PeerID,
|
||||
fallbackAliases: [PeerID],
|
||||
excluding disconnectedTransport: Transport
|
||||
) -> [(Transport, PeerID)] {
|
||||
var targets: [(Transport, PeerID)] = []
|
||||
for transport in transports where transport !== disconnectedTransport {
|
||||
if transport.isPeerConnected(peerID) || (transport.isPeerReachable(peerID) && transport.canDeliverPromptly(to: peerID)) {
|
||||
targets.append((transport, peerID))
|
||||
continue
|
||||
}
|
||||
for alias in fallbackAliases where alias != peerID && alias.toShort() == peerID.toShort() {
|
||||
if transport.isPeerConnected(alias) || (transport.isPeerReachable(alias) && transport.canDeliverPromptly(to: alias)) {
|
||||
targets.append((transport, alias))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return targets
|
||||
}
|
||||
|
||||
/// Removes and drops `message` when its TTL has expired or (when
|
||||
|
||||
@@ -14,6 +14,20 @@ protocol NetworkActivationTorControlling: AnyObject {
|
||||
protocol NetworkActivationRelayControlling: AnyObject {
|
||||
func connect()
|
||||
func disconnect()
|
||||
/// Reconnects after the network gate reopens (e.g. offline → online),
|
||||
/// clearing transient DNS/backoff failures accumulated during the outage.
|
||||
func resetForNetworkRecovery()
|
||||
/// Retries only disconnected/failed relays after an in-place interface
|
||||
/// switch or brief blip without tearing down already-healthy sockets.
|
||||
func recoverFailedRelays()
|
||||
}
|
||||
|
||||
extension NetworkActivationRelayControlling {
|
||||
func resetForNetworkRecovery() {
|
||||
connect()
|
||||
}
|
||||
|
||||
func recoverFailedRelays() {}
|
||||
}
|
||||
|
||||
protocol NetworkActivationProxyControlling: AnyObject {
|
||||
@@ -192,6 +206,17 @@ final class NetworkActivationService: ObservableObject {
|
||||
self.reevaluate()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
// React to interface transitions or brief (<debounce) offline blips
|
||||
// while staying reachable: clear transient DNS/backoff failures so
|
||||
// relays recover immediately without disturbing healthy sockets.
|
||||
reachabilityMonitor.pathDidChangePublisher
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] in
|
||||
guard let self, self.started, self.activationAllowed else { return }
|
||||
self.relayController.recoverFailedRelays()
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
/// Stops all internet-facing work at the synchronous panic boundary and
|
||||
@@ -259,7 +284,11 @@ final class NetworkActivationService: ObservableObject {
|
||||
}
|
||||
|
||||
if allowed {
|
||||
relayController.connect()
|
||||
if statusChanged {
|
||||
relayController.resetForNetworkRecovery()
|
||||
} else {
|
||||
relayController.connect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,12 +25,56 @@ protocol NetworkReachabilityMonitoring: AnyObject {
|
||||
var isReachable: Bool { get }
|
||||
/// Emits the debounced reachability whenever it changes (main-actor).
|
||||
var reachabilityPublisher: AnyPublisher<Bool, Never> { get }
|
||||
/// Emits when the underlying network path recovers from a brief blip or
|
||||
/// switches interfaces (e.g. Wi-Fi ↔ Cellular) while `isReachable` stays
|
||||
/// `true`. Lets relay managers clear transient DNS/backoff failures
|
||||
/// without disrupting already-healthy sockets.
|
||||
var pathDidChangePublisher: AnyPublisher<Void, Never> { get }
|
||||
/// Begin monitoring. Idempotent.
|
||||
func start()
|
||||
/// Stop monitoring and discard pending debounce work. Idempotent.
|
||||
func stop()
|
||||
}
|
||||
|
||||
extension NetworkReachabilityMonitoring {
|
||||
var pathDidChangePublisher: AnyPublisher<Void, Never> {
|
||||
Empty().eraseToAnyPublisher()
|
||||
}
|
||||
}
|
||||
|
||||
/// Coarse fingerprint of active satisfied network interfaces so Wi-Fi ↔
|
||||
/// Cellular transitions can be detected without flapping on unrelated path
|
||||
/// metadata changes.
|
||||
struct NetworkInterfaceSignature: Equatable {
|
||||
let usesWiFi: Bool
|
||||
let usesCellular: Bool
|
||||
let usesWired: Bool
|
||||
let usesOther: Bool
|
||||
|
||||
#if canImport(Network)
|
||||
init(path: NWPath) {
|
||||
self.usesWiFi = path.usesInterfaceType(.wifi)
|
||||
self.usesCellular = path.usesInterfaceType(.cellular)
|
||||
self.usesWired = path.usesInterfaceType(.wiredEthernet)
|
||||
self.usesOther = path.usesInterfaceType(.other)
|
||||
}
|
||||
#endif
|
||||
|
||||
init(usesWiFi: Bool = false, usesCellular: Bool = false, usesWired: Bool = false, usesOther: Bool = false) {
|
||||
self.usesWiFi = usesWiFi
|
||||
self.usesCellular = usesCellular
|
||||
self.usesWired = usesWired
|
||||
self.usesOther = usesOther
|
||||
}
|
||||
|
||||
static func == (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs.usesWiFi == rhs.usesWiFi
|
||||
&& lhs.usesCellular == rhs.usesCellular
|
||||
&& lhs.usesWired == rhs.usesWired
|
||||
&& lhs.usesOther == rhs.usesOther
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure debounce/decision logic for reachability, split out so it can be
|
||||
/// unit-tested without the Network framework or real timers.
|
||||
///
|
||||
@@ -95,8 +139,10 @@ struct ReachabilityDebounce {
|
||||
@MainActor
|
||||
final class NWPathReachabilityMonitor: NetworkReachabilityMonitoring {
|
||||
private let subject: CurrentValueSubject<Bool, Never>
|
||||
private let pathChangeSubject = PassthroughSubject<Void, Never>()
|
||||
private var debounce: ReachabilityDebounce
|
||||
private var flushWorkItem: DispatchWorkItem?
|
||||
private var lastSatisfiedInterfaceSignature: NetworkInterfaceSignature?
|
||||
private var started = false
|
||||
private let now: () -> Date
|
||||
|
||||
@@ -117,6 +163,10 @@ final class NWPathReachabilityMonitor: NetworkReachabilityMonitoring {
|
||||
subject.removeDuplicates().dropFirst().eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
var pathDidChangePublisher: AnyPublisher<Void, Never> {
|
||||
pathChangeSubject.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard !started else { return }
|
||||
started = true
|
||||
@@ -126,8 +176,9 @@ final class NWPathReachabilityMonitor: NetworkReachabilityMonitoring {
|
||||
monitor.pathUpdateHandler = { [weak self] path in
|
||||
// Conservative: only "no interface at all" counts as unreachable.
|
||||
let reachable = path.status != .unsatisfied
|
||||
let signature = reachable ? NetworkInterfaceSignature(path: path) : nil
|
||||
Task { @MainActor in
|
||||
self?.ingest(reachable: reachable)
|
||||
self?.ingest(reachable: reachable, interfaceSignature: signature)
|
||||
}
|
||||
}
|
||||
monitor.start(queue: monitorQueue)
|
||||
@@ -141,6 +192,7 @@ final class NWPathReachabilityMonitor: NetworkReachabilityMonitoring {
|
||||
started = false
|
||||
flushWorkItem?.cancel()
|
||||
flushWorkItem = nil
|
||||
lastSatisfiedInterfaceSignature = nil
|
||||
#if canImport(Network)
|
||||
monitor?.pathUpdateHandler = nil
|
||||
monitor?.cancel()
|
||||
@@ -150,13 +202,38 @@ final class NWPathReachabilityMonitor: NetworkReachabilityMonitoring {
|
||||
|
||||
/// Feed an observation into the debounce and publish committed changes.
|
||||
/// Exposed internally so higher layers/tests could drive it if needed.
|
||||
func ingest(reachable: Bool) {
|
||||
func ingest(reachable: Bool, interfaceSignature: NetworkInterfaceSignature? = nil) {
|
||||
let hadPendingDrop = debounce.hasPendingChange && debounce.committed
|
||||
flushWorkItem?.cancel()
|
||||
flushWorkItem = nil
|
||||
if let committed = debounce.observe(reachable: reachable, at: now()) {
|
||||
if committed {
|
||||
lastSatisfiedInterfaceSignature = interfaceSignature
|
||||
} else {
|
||||
lastSatisfiedInterfaceSignature = nil
|
||||
}
|
||||
publish(committed)
|
||||
} else if debounce.hasPendingChange {
|
||||
scheduleFlush()
|
||||
} else if reachable && debounce.committed {
|
||||
// Still committed-reachable, but either a brief (<debounce) offline
|
||||
// blip just cleared or the active interface changed (e.g. Wi-Fi ↔
|
||||
// Cellular). Notify listeners so failed/DNS-blocked relays can
|
||||
// retry immediately instead of waiting out the 10-minute cooldown.
|
||||
var interfaceChanged = false
|
||||
if let interfaceSignature {
|
||||
if let previous = lastSatisfiedInterfaceSignature, previous != interfaceSignature {
|
||||
interfaceChanged = true
|
||||
}
|
||||
lastSatisfiedInterfaceSignature = interfaceSignature
|
||||
}
|
||||
if hadPendingDrop || interfaceChanged {
|
||||
SecureLogger.debug(
|
||||
"NWPathReachabilityMonitor: path recovered/switched (pendingDrop=\(hadPendingDrop), interfaceChanged=\(interfaceChanged))",
|
||||
category: .session
|
||||
)
|
||||
pathChangeSubject.send(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +241,9 @@ final class NWPathReachabilityMonitor: NetworkReachabilityMonitoring {
|
||||
let work = DispatchWorkItem { [weak self] in
|
||||
guard let self else { return }
|
||||
if let committed = self.debounce.flush(at: self.now()) {
|
||||
if !committed {
|
||||
self.lastSatisfiedInterfaceSignature = nil
|
||||
}
|
||||
self.publish(committed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,6 +176,10 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
// canDeliverPromptly is called synchronously off the main actor.
|
||||
private var relaysConnected = false
|
||||
private var relayConnectivityCancellable: AnyCancellable?
|
||||
/// Invoked on the main actor after `relaysConnected` transitions, so
|
||||
/// higher layers (e.g. MessageRouter outbox flush) always observe the
|
||||
/// updated `canDeliverPromptly` state with no barrier race.
|
||||
var onRelayConnectivityChanged: (@MainActor (Bool) -> Void)?
|
||||
private let queue = DispatchQueue(label: "nostr.transport.state", attributes: .concurrent)
|
||||
|
||||
@MainActor
|
||||
@@ -192,9 +196,19 @@ final class NostrTransport: Transport, @unchecked Sendable {
|
||||
refreshReachablePeersSynchronously()
|
||||
|
||||
relayConnectivityCancellable = self.dependencies.relayConnectivity()
|
||||
.removeDuplicates()
|
||||
.sink { [weak self] connected in
|
||||
guard let self else { return }
|
||||
self.queue.async(flags: .barrier) { self.relaysConnected = connected }
|
||||
let didChange: Bool = self.queue.sync(flags: .barrier) {
|
||||
let changed = self.relaysConnected != connected
|
||||
self.relaysConnected = connected
|
||||
return changed
|
||||
}
|
||||
if didChange {
|
||||
Task { @MainActor [weak self] in
|
||||
self?.onRelayConnectivityChanged?(connected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -347,11 +347,14 @@ final class ChatPeerIdentityCoordinator {
|
||||
if let oldPeerID = context.selectedPrivateChatPeer, oldPeerID != currentPeerID {
|
||||
migrateChatState(from: oldPeerID, to: currentPeerID)
|
||||
context.selectedPrivateChatPeer = currentPeerID
|
||||
context.markPrivateChatRead(currentPeerID)
|
||||
context.markPrivateMessagesAsRead(from: currentPeerID)
|
||||
} else if context.selectedPrivateChatPeer == nil {
|
||||
context.selectedPrivateChatPeer = currentPeerID
|
||||
context.markPrivateChatRead(currentPeerID)
|
||||
} else {
|
||||
context.markPrivateChatRead(currentPeerID)
|
||||
}
|
||||
|
||||
context.markPrivateChatRead(currentPeerID)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -404,6 +407,11 @@ final class ChatPeerIdentityCoordinator {
|
||||
if let fingerprint = getFingerprint(for: peerID) {
|
||||
context.setStoredFingerprint(fingerprint, for: peerID)
|
||||
context.selectedPrivateChatFingerprint = fingerprint
|
||||
} else if let noiseKey = peerID.noiseKey {
|
||||
// Offline 64-hex Noise-key chats (e.g. non-favorite persisted or
|
||||
// courier threads) still carry their static key, so retain the
|
||||
// fingerprint for automatic migration when the peer reconnects on BLE.
|
||||
context.selectedPrivateChatFingerprint = noiseKey.sha256Fingerprint()
|
||||
} else {
|
||||
context.selectedPrivateChatFingerprint = nil
|
||||
}
|
||||
|
||||
@@ -44,8 +44,6 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS
|
||||
func registerVerifiedFriendInviteIdentity(_ invite: FriendInvite)
|
||||
/// `true` when any private chat contains a message with `messageID`.
|
||||
func privateChatsContainMessage(withID messageID: String) -> Bool
|
||||
/// `true` when `peerID`'s chat contains a message with `messageID`.
|
||||
func privateChat(_ peerID: PeerID, containsMessageWithID messageID: String) -> Bool
|
||||
/// `true` only when `messageID` is one of our outgoing messages in at least
|
||||
/// one of the authenticated peer's conversation aliases.
|
||||
func isOutgoingPrivateMessage(_ messageID: String, toAny peerIDs: Set<PeerID>) -> Bool
|
||||
@@ -79,6 +77,10 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS
|
||||
func isNostrBlocked(pubkeyHexLowercased: String) -> Bool
|
||||
func displayNameForNostrPubkey(_ pubkeyHex: String) -> String
|
||||
func deriveNostrIdentity(forGeohash geohash: String) throws -> NostrIdentity
|
||||
/// Whether at least one default (DM-capable) Nostr relay is connected right
|
||||
/// now. Prevents offline mutual-favorite DMs from falsely showing `.sent`
|
||||
/// while they are actually queued in the outbox waiting for internet.
|
||||
var isNostrRelayConnected: Bool { get }
|
||||
|
||||
// MARK: Routing & acknowledgements
|
||||
func routePrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String)
|
||||
@@ -119,6 +121,7 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS
|
||||
|
||||
extension ChatPrivateConversationContext {
|
||||
var sendReadReceiptsEnabled: Bool { true }
|
||||
var isNostrRelayConnected: Bool { true }
|
||||
func reconcileDisappearingTimer(from sourcePeerID: PeerID, to destinationPeerID: PeerID) {}
|
||||
func registerVerifiedFriendInviteIdentity(_ invite: FriendInvite) {}
|
||||
func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data? { nil }
|
||||
@@ -197,6 +200,10 @@ extension ChatViewModel: ChatPrivateConversationContext {
|
||||
try? idBridge.getCurrentNostrIdentity()
|
||||
}
|
||||
|
||||
var isNostrRelayConnected: Bool {
|
||||
NostrRelayManager.shared.isDMRelayConnected
|
||||
}
|
||||
|
||||
func routePrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) {
|
||||
messageRouter.sendPrivate(content, to: peerID, recipientNickname: recipientNickname, messageID: messageID)
|
||||
}
|
||||
@@ -433,7 +440,7 @@ final class ChatPrivateConversationCoordinator {
|
||||
recipientNickname: recipientNickname,
|
||||
messageID: messageID
|
||||
)
|
||||
if isConnected || isReachable || (isMutualFavorite && hasNostrKey) {
|
||||
if isConnected || isReachable || (isMutualFavorite && hasNostrKey && context.isNostrRelayConnected) {
|
||||
context.setPrivateDeliveryStatus(.sent, forMessageID: messageID, peerID: peerID)
|
||||
}
|
||||
// Otherwise the message stays "sending"; router callbacks move it to
|
||||
|
||||
@@ -52,6 +52,13 @@ protocol ChatTransportEventContext: AnyObject {
|
||||
|
||||
// MARK: Routing & acknowledgements
|
||||
func flushRouterOutbox(for peerID: PeerID)
|
||||
/// Immediately fails over any unacked outbox entries for `peerIDAliases`
|
||||
/// onto an alternate prompt transport (e.g. Nostr) when a mesh link drops.
|
||||
func failOverRouterOutboxAfterMeshDisconnect(for peerIDAliases: [PeerID])
|
||||
/// Re-runs the read-receipt pass if the user is actively viewing a direct
|
||||
/// chat for one of `peerIDAliases`, so receipts deferred while offline
|
||||
/// leave as soon as the peer reconnects.
|
||||
func retryPendingReadReceiptsIfViewing(peerIDAliases: [PeerID])
|
||||
/// Offer queued mail for *other* peers to this newly connected courier.
|
||||
func retryCourierDeposits(via peerID: PeerID)
|
||||
func sendMeshDeliveryAck(for messageID: String, to peerID: PeerID)
|
||||
@@ -81,6 +88,11 @@ protocol ChatTransportEventContext: AnyObject {
|
||||
func handleVouchPayload(from peerID: PeerID, payload: Data)
|
||||
}
|
||||
|
||||
extension ChatTransportEventContext {
|
||||
func failOverRouterOutboxAfterMeshDisconnect(for peerIDAliases: [PeerID]) {}
|
||||
func retryPendingReadReceiptsIfViewing(peerIDAliases: [PeerID]) {}
|
||||
}
|
||||
|
||||
extension ChatViewModel: ChatTransportEventContext {
|
||||
// `isConnected`, `nickname`, `myPeerID`, `privateMessages(for:)`,
|
||||
// `unreadPrivateMessages`, `selectedPrivateChatPeer`, `notifyUIChanged()`,
|
||||
@@ -105,6 +117,19 @@ extension ChatViewModel: ChatTransportEventContext {
|
||||
messageRouter.flushOutbox(for: peerID)
|
||||
}
|
||||
|
||||
func failOverRouterOutboxAfterMeshDisconnect(for peerIDAliases: [PeerID]) {
|
||||
messageRouter.failOverOutbox(for: peerIDAliases, excluding: meshService)
|
||||
}
|
||||
|
||||
func retryPendingReadReceiptsIfViewing(peerIDAliases: [PeerID]) {
|
||||
guard isAppActive, let selected = selectedPrivateChatPeer else { return }
|
||||
let aliasSet = Set(peerIDAliases)
|
||||
let shortAliases = Set(peerIDAliases.map { $0.toShort() })
|
||||
if aliasSet.contains(selected) || shortAliases.contains(selected.toShort()) {
|
||||
markPrivateMessagesAsRead(from: selected)
|
||||
}
|
||||
}
|
||||
|
||||
func retryCourierDeposits(via peerID: PeerID) {
|
||||
messageRouter.courierBecameAvailable(peerID)
|
||||
}
|
||||
@@ -209,13 +234,18 @@ final class ChatTransportEventCoordinator {
|
||||
func didConnectToPeerSynchronously(_ peerID: PeerID) {
|
||||
SecureLogger.debug("🤝 Peer connected: \(peerID)", category: .session)
|
||||
|
||||
var aliases = [peerID]
|
||||
if let peer = context.unifiedPeer(for: peerID) {
|
||||
let stablePeerID = PeerID(hexData: peer.noisePublicKey)
|
||||
context.cacheStablePeerID(stablePeerID, for: peerID)
|
||||
if stablePeerID != peerID {
|
||||
aliases.append(stablePeerID)
|
||||
}
|
||||
}
|
||||
|
||||
context.flushRouterOutbox(for: peerID)
|
||||
context.retryCourierDeposits(via: peerID)
|
||||
context.retryPendingReadReceiptsIfViewing(peerIDAliases: aliases)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -254,6 +284,12 @@ final class ChatTransportEventCoordinator {
|
||||
if !recentReceiptIDs.isEmpty {
|
||||
context.unmarkReadReceiptsSent(recentReceiptIDs)
|
||||
}
|
||||
|
||||
var aliases = [peerID]
|
||||
if let stablePeerID, stablePeerID != peerID {
|
||||
aliases.append(stablePeerID)
|
||||
}
|
||||
context.failOverRouterOutboxAfterMeshDisconnect(for: aliases)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1017,12 +1017,6 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
|
||||
conversations.directConversationsContainMessage(withID: messageID)
|
||||
}
|
||||
|
||||
/// `true` when `peerID`'s chat contains a message with `messageID`.
|
||||
@MainActor
|
||||
func privateChat(_ peerID: PeerID, containsMessageWithID messageID: String) -> Bool {
|
||||
conversations.conversationsByID[.directPeer(peerID)]?.containsMessage(withID: messageID) ?? false
|
||||
}
|
||||
|
||||
/// Removes a message by ID from every private chat that contains it,
|
||||
/// dropping chats that become empty. Returns the removed message, if any.
|
||||
@MainActor
|
||||
|
||||
@@ -144,6 +144,24 @@ private extension ChatViewModelBootstrapper {
|
||||
viewModel.conversations.setDeliveryStatus(.carried, forMessageID: messageID)
|
||||
}
|
||||
}
|
||||
// When a queued/offline DM flushes onto a newly available transport
|
||||
// (BLE reconnect or Nostr relay recovery), advance `.sending` → `.sent`
|
||||
// (ConversationStore's no-downgrade rule protects `.carried`/`.delivered`/`.read`).
|
||||
viewModel.messageRouter.onMessageSent = { [weak viewModel] messageID, _ in
|
||||
guard let viewModel else { return }
|
||||
_ = viewModel.conversations.setDeliveryStatus(.sent, forMessageID: messageID)
|
||||
}
|
||||
// Offline → online DM handoff: flush retained outbox messages, retry
|
||||
// bridge courier drops, and emit any deferred read receipts for the
|
||||
// currently viewed chat the moment a DM-capable Nostr relay connects.
|
||||
viewModel.messageRouter.nostrTransport?.onRelayConnectivityChanged = { [weak viewModel] connected in
|
||||
guard let viewModel, connected else { return }
|
||||
viewModel.messageRouter.flushAllOutbox()
|
||||
viewModel.messageRouter.retryBridgeCourierDeposits()
|
||||
if let selectedPeer = viewModel.selectedPrivateChatPeer {
|
||||
viewModel.markPrivateMessagesAsRead(from: selectedPeer)
|
||||
}
|
||||
}
|
||||
viewModel.commandProcessor.contextProvider = viewModel
|
||||
viewModel.commandProcessor.meshService = viewModel.meshService
|
||||
viewModel.participantTracker.configure(context: viewModel)
|
||||
@@ -393,6 +411,7 @@ private extension ChatViewModelBootstrapper {
|
||||
.sink { connected in
|
||||
if connected {
|
||||
GatewayService.shared.flushQueuedUplinks()
|
||||
BridgeService.shared.ensureSubscriptionOpen()
|
||||
BridgeService.shared.flushQueuedUplinks()
|
||||
BridgeService.shared.publishPresence()
|
||||
}
|
||||
@@ -434,6 +453,9 @@ private extension ChatViewModelBootstrapper {
|
||||
bridge.closeSubscription = {
|
||||
NostrRelayManager.shared.unsubscribe(id: Self.bridgeSubscriptionID)
|
||||
}
|
||||
bridge.isSubscriptionRegistered = {
|
||||
NostrRelayManager.shared.hasRegisteredSubscription(id: Self.bridgeSubscriptionID)
|
||||
}
|
||||
bridge.relaysConnected = { NostrRelayManager.shared.isConnected }
|
||||
bridge.locationCell = { [weak viewModel] in
|
||||
guard let location = viewModel?.locationManager else { return nil }
|
||||
|
||||
@@ -15,6 +15,11 @@ extension ChatViewModel {
|
||||
nostrCoordinator.subscriptions.resubscribeCurrentGeohash()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func ensureCurrentGeohashSubscribed() {
|
||||
nostrCoordinator.subscriptions.ensureCurrentGeohashSubscribed()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func switchLocationChannel(to channel: ChannelID) {
|
||||
nostrCoordinator.subscriptions.switchLocationChannel(to: channel)
|
||||
|
||||
@@ -150,6 +150,25 @@ final class GeohashSubscriptionManager {
|
||||
subscribeToActiveGeohash(channel, subscriptionID: subID)
|
||||
}
|
||||
|
||||
/// Re-establishes the active geohash chat + DM subscriptions only when at
|
||||
/// least one of them is not registered on the relay manager (e.g. the user
|
||||
/// opened or teleported into a location channel while offline or before
|
||||
/// `NetworkActivationService` opened the gate). Safe to call on initial
|
||||
/// connection without tearing down an already-live subscription.
|
||||
@MainActor
|
||||
func ensureCurrentGeohashSubscribed() {
|
||||
guard let context,
|
||||
case .location(let channel) = context.activeChannel else { return }
|
||||
let relayManager = context.nostrRelayManager ?? NostrRelayManager.shared
|
||||
let subID = context.geoSubscriptionID ?? "geo-\(channel.geohash)"
|
||||
let dmSubID = context.geoDmSubscriptionID ?? "geo-dm-\(channel.geohash)"
|
||||
guard !relayManager.hasRegisteredSubscription(id: subID)
|
||||
|| !relayManager.hasRegisteredSubscription(id: dmSubID) else {
|
||||
return
|
||||
}
|
||||
resubscribeCurrentGeohash()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func switchLocationChannel(to channel: ChannelID) {
|
||||
guard let context else { return }
|
||||
|
||||
@@ -1132,4 +1132,44 @@ struct AppArchitectureTests {
|
||||
#expect(payment.contentScan.lightningLinks == ["lightning:lnbc1test"])
|
||||
#expect(!payment.contentScan.isLongForDisplay)
|
||||
}
|
||||
|
||||
@Test("AppRuntime foreground reconnect covers both Everyday direct mode and Tor mode")
|
||||
func foregroundNostrReconnectActionCoversEverydayAndTorModes() {
|
||||
// Everyday Mode (Tor off): returning from background MUST reconnect directly.
|
||||
#expect(
|
||||
AppRuntime.resolveForegroundNostrReconnectAction(
|
||||
didEnterBackground: true,
|
||||
activationAllowed: true,
|
||||
userTorEnabled: false,
|
||||
torAutoStartAllowed: false
|
||||
) == .reconnectDirect
|
||||
)
|
||||
// Tor Mode (Tor on): returning from background awaits Tor readiness.
|
||||
#expect(
|
||||
AppRuntime.resolveForegroundNostrReconnectAction(
|
||||
didEnterBackground: true,
|
||||
activationAllowed: true,
|
||||
userTorEnabled: true,
|
||||
torAutoStartAllowed: true
|
||||
) == .awaitTorAndReconnect
|
||||
)
|
||||
// Offline / activation disallowed: never reconnect on foreground.
|
||||
#expect(
|
||||
AppRuntime.resolveForegroundNostrReconnectAction(
|
||||
didEnterBackground: true,
|
||||
activationAllowed: false,
|
||||
userTorEnabled: false,
|
||||
torAutoStartAllowed: false
|
||||
) == .none
|
||||
)
|
||||
// Fresh foreground (never backgrounded): no redundant reset.
|
||||
#expect(
|
||||
AppRuntime.resolveForegroundNostrReconnectAction(
|
||||
didEnterBackground: false,
|
||||
activationAllowed: true,
|
||||
userTorEnabled: false,
|
||||
torAutoStartAllowed: false
|
||||
) == .none
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,6 @@ private final class MockChatLifecycleContext: ChatLifecycleContext {
|
||||
var activeChannel: ChannelID = .mesh
|
||||
var nostrKeyMapping: [PeerID: String] = [:]
|
||||
var geoDMGeohashByPeerID: [PeerID: String] = [:]
|
||||
private(set) var derivedGeohashes: [String] = []
|
||||
private(set) var ownerLevelReadPasses: [PeerID] = []
|
||||
private(set) var managerReadMarks: [PeerID] = []
|
||||
|
||||
|
||||
@@ -324,6 +324,37 @@ struct ChatPeerIdentityCoordinatorContextTests {
|
||||
#expect(context.selectedPrivateChatPeer == newPeerID)
|
||||
// Unread moved to the new peer, then cleared for the now-open chat.
|
||||
#expect(context.unreadPrivateMessages.isEmpty)
|
||||
#expect(context.markedReadPeers == [newPeerID])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func startPrivateChat_offlineNoiseKeyPeerRetainsFingerprintAndMigratesOnBLEConnect() async {
|
||||
let context = MockChatPeerIdentityContext()
|
||||
let coordinator = ChatPeerIdentityCoordinator(context: context)
|
||||
let noiseKey = Data((1...32).map(UInt8.init))
|
||||
let stablePeerID = PeerID(hexData: noiseKey)
|
||||
let bleShortPeerID = stablePeerID.toShort()
|
||||
let expectedFingerprint = noiseKey.sha256Fingerprint()
|
||||
|
||||
context.privateChats[stablePeerID] = [
|
||||
makePrivateMessage(id: "offline-1", timestamp: Date(timeIntervalSince1970: 10))
|
||||
]
|
||||
|
||||
// Opening an offline 64-hex non-favorite chat retains its fingerprint
|
||||
// even though no live BLE/favorite mapping exists yet.
|
||||
coordinator.startPrivateChat(with: stablePeerID)
|
||||
#expect(context.selectedPrivateChatFingerprint == expectedFingerprint)
|
||||
context.selectedPrivateChatPeer = stablePeerID
|
||||
|
||||
// Peer reconnects on BLE with the matching fingerprint.
|
||||
context.connectedPeers = [bleShortPeerID]
|
||||
context.fingerprintsByPeerID[bleShortPeerID] = expectedFingerprint
|
||||
coordinator.updatePrivateChatPeerIfNeeded()
|
||||
|
||||
#expect(context.selectedPrivateChatPeer == bleShortPeerID)
|
||||
#expect(context.privateChats[stablePeerID] == nil)
|
||||
#expect(context.privateChats[bleShortPeerID]?.map(\.id) == ["offline-1"])
|
||||
#expect(context.markedReadPeers.last == bleShortPeerID)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
|
||||
@@ -121,10 +121,6 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
|
||||
}
|
||||
}
|
||||
|
||||
func privateChat(_ peerID: PeerID, containsMessageWithID messageID: String) -> Bool {
|
||||
privateChats[peerID]?.contains { $0.id == messageID } == true
|
||||
}
|
||||
|
||||
// Peers & identity
|
||||
var myPeerID = PeerID(str: "0011223344556677")
|
||||
var nicknamesByPeerID: [PeerID: String] = [:]
|
||||
|
||||
@@ -447,6 +447,39 @@ struct LocationNotesManagerTests {
|
||||
#expect(manager.state == .loading)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func networkBecameAvailable_refreshesConnectingNotesImmediately() async {
|
||||
var subscribeCount = 0
|
||||
var storedEOSE: (() -> Void)?
|
||||
let networkAvailable = PassthroughSubject<Void, Never>()
|
||||
var deps = LocationNotesDependencies(
|
||||
relayLookup: { _, _ in ["wss://relay.geo"] },
|
||||
subscribe: { _, _, _, _, eose in
|
||||
subscribeCount += 1
|
||||
storedEOSE = eose
|
||||
},
|
||||
unsubscribe: { _ in },
|
||||
sendEvent: { _, _ in },
|
||||
deriveIdentity: { _ in throw TestError.shouldNotDerive },
|
||||
now: { Date() }
|
||||
)
|
||||
deps.anyRelayConnected = { _ in false }
|
||||
deps.networkBecameAvailable = { networkAvailable.eraseToAnyPublisher() }
|
||||
|
||||
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
|
||||
#expect(subscribeCount == 1)
|
||||
storedEOSE?()
|
||||
#expect(manager.state == .connecting)
|
||||
|
||||
// Network returns online: manager refreshes immediately without waiting for poll.
|
||||
networkAvailable.send(())
|
||||
for _ in 0..<5 {
|
||||
await Task.yield()
|
||||
}
|
||||
#expect(subscribeCount == 2)
|
||||
#expect(manager.state == .loading)
|
||||
}
|
||||
|
||||
private enum TestError: Error {
|
||||
case shouldNotDerive
|
||||
}
|
||||
|
||||
@@ -58,6 +58,10 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting,
|
||||
|
||||
var connectedPeers: Set<PeerID> = []
|
||||
var reachablePeers: Set<PeerID> = []
|
||||
/// Mirrors `NostrTransport.canDeliverPromptly`: when `false`, `reachablePeers`
|
||||
/// still report reachable (known npub) while prompt delivery is unavailable
|
||||
/// (relays down / offline).
|
||||
var promptDelivery = true
|
||||
/// Peers with an established secure session. `nil` mirrors the protocol
|
||||
/// default (prompt delivery), so connected peers stay "secure" for tests
|
||||
/// that never care about the distinction.
|
||||
@@ -109,6 +113,10 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting,
|
||||
reachablePeers.contains(peerID) || connectedPeers.contains(peerID)
|
||||
}
|
||||
|
||||
func canDeliverPromptly(to peerID: PeerID) -> Bool {
|
||||
isPeerReachable(peerID) && promptDelivery
|
||||
}
|
||||
|
||||
func canDeliverSecurely(to peerID: PeerID) -> Bool {
|
||||
securePeers?.contains(peerID) ?? canDeliverPromptly(to: peerID)
|
||||
}
|
||||
|
||||
@@ -188,6 +188,26 @@ struct BridgeServiceTests {
|
||||
#expect(fixture.service.subscribedCells.count == 9)
|
||||
}
|
||||
|
||||
@Test func ensureSubscriptionOpenReopensOnlyWhenDroppedOffline() {
|
||||
let fixture = Fixture(enabled: true)
|
||||
var registered = false
|
||||
fixture.service.isSubscriptionRegistered = { registered }
|
||||
|
||||
// Enabled while offline: activeCell is set, initial subscribe dropped by gate.
|
||||
fixture.service.refreshRendezvous()
|
||||
#expect(fixture.service.activeCell == Self.cell)
|
||||
#expect(fixture.openedSubscriptions.count == 1)
|
||||
|
||||
// Relays come back online with no registered subscription -> reopens.
|
||||
fixture.service.ensureSubscriptionOpen()
|
||||
#expect(fixture.openedSubscriptions.count == 2)
|
||||
|
||||
// Once registered, ensureSubscriptionOpen is a no-op.
|
||||
registered = true
|
||||
fixture.service.ensureSubscriptionOpen()
|
||||
#expect(fixture.openedSubscriptions.count == 2)
|
||||
}
|
||||
|
||||
@Test func missingCellRequestsALocationFix() {
|
||||
// Field bug: the bridge waited passively for availableChannels,
|
||||
// which only flow while some other feature pumps location. Bridging
|
||||
|
||||
@@ -1416,6 +1416,137 @@ struct MessageRouterTests {
|
||||
|
||||
#expect(transport.sentPrivateMessages.map(\.messageID) == ["m1", "m2"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendPrivate_offlineNostrDoesNotBurnAttemptsAndFlushesOnReconnect() {
|
||||
let peerID = PeerID(str: "00000000000000f1")
|
||||
let ble = MockTransport()
|
||||
let nostr = MockTransport()
|
||||
nostr.reachablePeers.insert(peerID)
|
||||
nostr.promptDelivery = false // relays offline
|
||||
|
||||
let router = MessageRouter(transports: [ble, nostr])
|
||||
var dropped: [String] = []
|
||||
var sentNotifications: [String] = []
|
||||
router.onMessageDropped = { id, _ in dropped.append(id) }
|
||||
router.onMessageSent = { id, _ in sentNotifications.append(id) }
|
||||
|
||||
router.sendPrivate("Offline hello", to: peerID, recipientNickname: "Alice", messageID: "off-1")
|
||||
nostr.resetRecordings()
|
||||
|
||||
// Repeated flushes while offline must NOT send or burn attempts to failure.
|
||||
for _ in 0..<12 {
|
||||
router.flushAllOutbox()
|
||||
}
|
||||
#expect(nostr.sentPrivateMessages.isEmpty)
|
||||
#expect(dropped.isEmpty)
|
||||
#expect(sentNotifications.isEmpty)
|
||||
|
||||
// Relays come online: flushing delivers immediately and notifies `.sent`.
|
||||
nostr.promptDelivery = true
|
||||
router.flushAllOutbox()
|
||||
#expect(nostr.sentPrivateMessages.map(\.messageID) == ["off-1"])
|
||||
#expect(sentNotifications == ["off-1"])
|
||||
#expect(dropped.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendPrivate_staleBLERetentionStillDeliversOverLiveNostr() {
|
||||
let peerID = PeerID(str: "00000000000000f2")
|
||||
let ble = MockTransport()
|
||||
ble.reachablePeers.insert(peerID) // in 60s retention window, NOT connected
|
||||
let nostr = MockTransport()
|
||||
nostr.reachablePeers.insert(peerID)
|
||||
nostr.promptDelivery = true // DM relay connected
|
||||
|
||||
let router = MessageRouter(transports: [ble, nostr])
|
||||
router.sendPrivate("Crossing boundary", to: peerID, recipientNickname: "Alice", messageID: "edge-1")
|
||||
|
||||
#expect(ble.sentPrivateMessages.map(\.messageID) == ["edge-1"])
|
||||
#expect(nostr.sentPrivateMessages.map(\.messageID) == ["edge-1"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func failOverOutboxAfterMeshDisconnect_deliversUnackedBLEMessageOverLiveNostr() {
|
||||
let noiseKey = Data(repeating: 0xF3, count: 32)
|
||||
let stableID = PeerID(hexData: noiseKey)
|
||||
let shortID = PeerID(publicKey: noiseKey)
|
||||
let ble = MockTransport()
|
||||
ble.connectedPeers.insert(shortID)
|
||||
ble.securePeers = [shortID]
|
||||
let nostr = MockTransport()
|
||||
nostr.reachablePeers.formUnion([shortID, stableID])
|
||||
nostr.promptDelivery = true
|
||||
|
||||
let router = MessageRouter(transports: [ble, nostr])
|
||||
var sentNotifications: [String] = []
|
||||
router.onMessageSent = { id, _ in sentNotifications.append(id) }
|
||||
|
||||
// Sent while directly BLE-connected -> BLE only.
|
||||
router.sendPrivate("Before drop", to: shortID, recipientNickname: "Alice", messageID: "ble-drop-1")
|
||||
#expect(ble.sentPrivateMessages.map(\.messageID) == ["ble-drop-1"])
|
||||
#expect(nostr.sentPrivateMessages.isEmpty)
|
||||
|
||||
// BLE disconnects (even if BLE still reports stale reachability retention).
|
||||
ble.connectedPeers.remove(shortID)
|
||||
ble.reachablePeers.insert(shortID)
|
||||
router.failOverOutbox(for: [shortID, stableID], excluding: ble)
|
||||
|
||||
// Must immediately fail over to live Nostr without resending on BLE.
|
||||
#expect(ble.sentPrivateMessages.count == 1)
|
||||
#expect(nostr.sentPrivateMessages.map(\.messageID) == ["ble-drop-1"])
|
||||
#expect(sentNotifications == ["ble-drop-1"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func flushOutbox_offlineMessageHandedToPreHandshakeBLEDoesNotDuplicateOnAuth() {
|
||||
let noiseKey = Data(repeating: 0xF4, count: 32)
|
||||
let stableID = PeerID(hexData: noiseKey)
|
||||
let shortID = PeerID(publicKey: noiseKey)
|
||||
let ble = MockTransport()
|
||||
|
||||
let router = MessageRouter(
|
||||
transports: [ble],
|
||||
courierDirectory: CourierDirectory(noiseKey: { _ in nil }, isTrustedCourier: { _ in false })
|
||||
)
|
||||
|
||||
// Queued while completely offline (sendAttempts == 0).
|
||||
router.sendPrivate("Wait for BLE", to: stableID, recipientNickname: "Bob", messageID: "pre-hs-1")
|
||||
#expect(ble.sentPrivateMessages.isEmpty)
|
||||
|
||||
// Peer reconnects over BLE (not yet Noise-authenticated); outbox flushes
|
||||
// into BLE's pre-handshake queue.
|
||||
ble.connectedPeers.insert(shortID)
|
||||
ble.securePeers = []
|
||||
router.flushOutbox(for: shortID)
|
||||
#expect(ble.sentPrivateMessages.map(\.messageID) == ["pre-hs-1"])
|
||||
|
||||
// Noise authentication completes: BLE drains its own queue, so the
|
||||
// router's auth retry must NOT emit a duplicate copy.
|
||||
ble.securePeers = [shortID]
|
||||
router.retrySecurePrivateMessagesAfterAuthentication(for: [shortID, stableID])
|
||||
#expect(ble.sentPrivateMessages.map(\.messageID) == ["pre-hs-1"])
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendReadReceipt_returnsFalseWhenOnlyOfflineNostrIsReachable() {
|
||||
let peerID = PeerID(str: "00000000000000f5")
|
||||
let ble = MockTransport()
|
||||
let nostr = MockTransport()
|
||||
nostr.reachablePeers.insert(peerID)
|
||||
nostr.promptDelivery = false // relays offline
|
||||
|
||||
let router = MessageRouter(transports: [ble, nostr])
|
||||
let receipt = ReadReceipt(originalMessageID: "rr-offline", readerID: ble.myPeerID, readerNickname: "Me")
|
||||
|
||||
#expect(router.sendReadReceipt(receipt, to: peerID) == false)
|
||||
#expect(nostr.sentReadReceipts.isEmpty)
|
||||
|
||||
// Once relays come back online, the retry succeeds.
|
||||
nostr.promptDelivery = true
|
||||
#expect(router.sendReadReceipt(receipt, to: peerID) == true)
|
||||
#expect(nostr.sentReadReceipts.map(\.receipt.originalMessageID) == ["rr-offline"])
|
||||
}
|
||||
}
|
||||
|
||||
/// Mutable wall clock injected into `MessageRouter` so TTL expiry is testable
|
||||
|
||||
@@ -162,6 +162,48 @@ final class NetworkReachabilityGateTests: XCTestCase {
|
||||
XCTAssertGreaterThanOrEqual(ctx.torController.shutdownCompletelyCallCount, 1)
|
||||
}
|
||||
|
||||
func test_monitor_interfaceSwitchAndShortBlipEmitPathDidChange() {
|
||||
let clock = MutableDate(now: Date(timeIntervalSince1970: 1_784_000_000))
|
||||
let monitor = NWPathReachabilityMonitor(debounceInterval: 2.5, now: { clock.now })
|
||||
var pathChanges = 0
|
||||
let cancellable = monitor.pathDidChangePublisher.sink { pathChanges += 1 }
|
||||
defer { cancellable.cancel() }
|
||||
|
||||
let wifi = NetworkInterfaceSignature(usesWiFi: true)
|
||||
let cellular = NetworkInterfaceSignature(usesCellular: true)
|
||||
|
||||
// Initial Wi-Fi observation establishes baseline (no spurious path change).
|
||||
monitor.ingest(reachable: true, interfaceSignature: wifi)
|
||||
XCTAssertEqual(pathChanges, 0)
|
||||
|
||||
// Switching Wi-Fi → Cellular emits a path change while staying reachable.
|
||||
monitor.ingest(reachable: true, interfaceSignature: cellular)
|
||||
XCTAssertEqual(pathChanges, 1)
|
||||
XCTAssertTrue(monitor.isReachable)
|
||||
|
||||
// A brief (<2.5s) unsatisfied blip that recovers also emits a path change.
|
||||
monitor.ingest(reachable: false, interfaceSignature: nil)
|
||||
clock.now = clock.now.addingTimeInterval(0.8)
|
||||
monitor.ingest(reachable: true, interfaceSignature: cellular)
|
||||
XCTAssertEqual(pathChanges, 2)
|
||||
XCTAssertTrue(monitor.isReachable)
|
||||
}
|
||||
|
||||
func test_reachabilityRecoveryAndPathChange_driveRelayRecoveryHooks() async {
|
||||
let ctx = makeService(permission: .authorized, reachable: false)
|
||||
ctx.service.start()
|
||||
XCTAssertEqual(ctx.relayController.resetForNetworkRecoveryCallCount, 0)
|
||||
|
||||
ctx.reachability.set(true)
|
||||
let resumed = await waitUntil { ctx.service.activationAllowed }
|
||||
XCTAssertTrue(resumed)
|
||||
XCTAssertEqual(ctx.relayController.resetForNetworkRecoveryCallCount, 1)
|
||||
|
||||
ctx.reachability.emitPathChange()
|
||||
let recovered = await waitUntil { ctx.relayController.recoverFailedRelaysCallCount == 1 }
|
||||
XCTAssertTrue(recovered)
|
||||
}
|
||||
|
||||
// MARK: - Harness
|
||||
|
||||
private func makeService(
|
||||
@@ -223,6 +265,7 @@ private struct Context {
|
||||
@MainActor
|
||||
private final class ControllableReachabilityMonitor: NetworkReachabilityMonitoring {
|
||||
private let subject: CurrentValueSubject<Bool, Never>
|
||||
private let pathChangeSubject = PassthroughSubject<Void, Never>()
|
||||
private(set) var startCalled = false
|
||||
|
||||
init(initial: Bool) {
|
||||
@@ -233,9 +276,13 @@ private final class ControllableReachabilityMonitor: NetworkReachabilityMonitori
|
||||
var reachabilityPublisher: AnyPublisher<Bool, Never> {
|
||||
subject.removeDuplicates().dropFirst().eraseToAnyPublisher()
|
||||
}
|
||||
var pathDidChangePublisher: AnyPublisher<Void, Never> {
|
||||
pathChangeSubject.eraseToAnyPublisher()
|
||||
}
|
||||
func start() { startCalled = true }
|
||||
func stop() { startCalled = false }
|
||||
func set(_ reachable: Bool) { subject.send(reachable) }
|
||||
func emitPathChange() { pathChangeSubject.send(()) }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@@ -252,8 +299,17 @@ private final class GateMockTorController: NetworkActivationTorControlling {
|
||||
private final class GateMockRelayController: NetworkActivationRelayControlling {
|
||||
private(set) var connectCallCount = 0
|
||||
private(set) var disconnectCallCount = 0
|
||||
private(set) var resetForNetworkRecoveryCallCount = 0
|
||||
private(set) var recoverFailedRelaysCallCount = 0
|
||||
func connect() { connectCallCount += 1 }
|
||||
func disconnect() { disconnectCallCount += 1 }
|
||||
func resetForNetworkRecovery() {
|
||||
resetForNetworkRecoveryCallCount += 1
|
||||
connectCallCount += 1
|
||||
}
|
||||
func recoverFailedRelays() {
|
||||
recoverFailedRelaysCallCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
private final class GateMockProxyController: NetworkActivationProxyControlling {
|
||||
|
||||
@@ -1901,6 +1901,93 @@ final class NostrRelayManagerTests: XCTestCase {
|
||||
XCTAssertTrue(context.manager.relays.contains { $0.url == "wss://nos.lol" })
|
||||
}
|
||||
|
||||
// MARK: - Offline ↔ Online & Path Recovery
|
||||
|
||||
@MainActor
|
||||
func test_resetForNetworkRecovery_clearsPermanentDNSFailureAndReconnectsImmediately() async {
|
||||
let relayURL = "wss://offline-dns-recovery.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
context.sessionFactory.pingErrorByURL[relayURL] = NSError(
|
||||
domain: NSURLErrorDomain,
|
||||
code: NSURLErrorCannotFindHost,
|
||||
userInfo: [NSLocalizedDescriptionKey: "A server with the specified hostname could not be found."]
|
||||
)
|
||||
|
||||
// Simulate DNS failure during the 2.5s window before offline debounce commits.
|
||||
context.manager.ensureConnections(to: [relayURL])
|
||||
let markedPermanent = await waitUntil {
|
||||
context.manager.relays.first(where: { $0.url == relayURL })?.reconnectAttempts == TransportConfig.nostrRelayMaxReconnectAttempts
|
||||
}
|
||||
XCTAssertTrue(markedPermanent)
|
||||
|
||||
// Offline → Online: network comes back immediately (well inside the 10m cooldown).
|
||||
context.manager.disconnect()
|
||||
context.sessionFactory.pingErrorByURL[relayURL] = nil
|
||||
let requestsBefore = context.sessionFactory.requestedURLs.count
|
||||
|
||||
context.manager.resetForNetworkRecovery()
|
||||
|
||||
let recovered = await waitUntil {
|
||||
context.sessionFactory.requestedURLs.count == requestsBefore + 1 &&
|
||||
context.manager.relays.first(where: { $0.url == relayURL })?.isConnected == true &&
|
||||
context.manager.relays.first(where: { $0.url == relayURL })?.reconnectAttempts == 0 &&
|
||||
context.manager.relays.first(where: { $0.url == relayURL })?.lastError == nil
|
||||
}
|
||||
XCTAssertTrue(recovered)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func test_recoverFailedRelays_retriesFailedRelayWithoutDisruptingHealthyRelay() async {
|
||||
let healthyURL = "wss://healthy-path.example"
|
||||
let failedURL = "wss://dns-handoff.example"
|
||||
let context = makeContext(permission: .denied)
|
||||
context.sessionFactory.pingErrorByURL[failedURL] = NSError(
|
||||
domain: NSURLErrorDomain,
|
||||
code: NSURLErrorCannotFindHost,
|
||||
userInfo: [NSLocalizedDescriptionKey: "DNS failure"]
|
||||
)
|
||||
|
||||
context.manager.ensureConnections(to: [healthyURL, failedURL])
|
||||
let settled = await waitUntil {
|
||||
context.manager.relays.first(where: { $0.url == healthyURL })?.isConnected == true &&
|
||||
context.manager.relays.first(where: { $0.url == failedURL })?.reconnectAttempts == TransportConfig.nostrRelayMaxReconnectAttempts
|
||||
}
|
||||
XCTAssertTrue(settled)
|
||||
let originalHealthyConnection = context.sessionFactory.latestConnection(for: healthyURL)
|
||||
|
||||
// Network path switches (e.g. Wi-Fi → Cellular) without tripping offline debounce.
|
||||
context.sessionFactory.pingErrorByURL[failedURL] = nil
|
||||
context.manager.recoverFailedRelays()
|
||||
|
||||
let recovered = await waitUntil {
|
||||
context.manager.relays.first(where: { $0.url == failedURL })?.isConnected == true &&
|
||||
context.manager.relays.first(where: { $0.url == healthyURL })?.isConnected == true
|
||||
}
|
||||
XCTAssertTrue(recovered)
|
||||
// The already-healthy relay socket must remain undisturbed.
|
||||
XCTAssertTrue(context.sessionFactory.latestConnection(for: healthyURL) === originalHealthyConnection)
|
||||
XCTAssertEqual(originalHealthyConnection?.cancelCallCount, 0)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func test_subscribe_whileDisallowed_invokesEOSEImmediatelyAndReportsUnregistered() {
|
||||
let relayURL = "wss://offline-sub.example"
|
||||
let context = makeContext(permission: .denied, activationAllowed: false)
|
||||
var eoseCount = 0
|
||||
|
||||
context.manager.subscribe(
|
||||
filter: makeFilter(),
|
||||
id: "offline-notes-sub",
|
||||
relayUrls: [relayURL],
|
||||
handler: { _ in },
|
||||
onEOSE: { eoseCount += 1 }
|
||||
)
|
||||
|
||||
XCTAssertEqual(eoseCount, 1)
|
||||
XCTAssertFalse(context.manager.hasRegisteredSubscription(id: "offline-notes-sub"))
|
||||
XCTAssertTrue(context.sessionFactory.requestedURLs.isEmpty)
|
||||
}
|
||||
|
||||
private func makeContext(
|
||||
permission: LocationChannelManager.PermissionState,
|
||||
favorites: Set<Data> = [],
|
||||
|
||||
@@ -131,6 +131,47 @@ struct NostrTransportTests {
|
||||
#expect(undeliverable)
|
||||
}
|
||||
|
||||
@Test("Relay connectivity transition updates prompt delivery synchronously before callback")
|
||||
@MainActor
|
||||
func relayConnectivityChangeUpdatesPromptDeliveryBeforeCallback() async throws {
|
||||
let keychain = MockKeychain()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychain)
|
||||
let recipient = try NostrIdentity.generate()
|
||||
let noiseKey = Data((1..<33).map(UInt8.init))
|
||||
let peerID = PeerID(hexData: noiseKey)
|
||||
let relationship = makeRelationship(
|
||||
peerNoisePublicKey: noiseKey,
|
||||
peerNostrPublicKey: recipient.npub,
|
||||
peerNickname: "Alice"
|
||||
)
|
||||
let connectivity = CurrentValueSubject<Bool, Never>(false)
|
||||
|
||||
let transport = NostrTransport(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
dependencies: makeDependencies(
|
||||
loadFavorites: { [noiseKey: relationship] },
|
||||
relayConnectivity: { connectivity.eraseToAnyPublisher() }
|
||||
)
|
||||
)
|
||||
|
||||
var observedPromptStateInCallback: [Bool] = []
|
||||
transport.onRelayConnectivityChanged = { connected in
|
||||
// By the time the callback runs, canDeliverPromptly must already
|
||||
// match the new relay state (no async barrier race).
|
||||
observedPromptStateInCallback.append(transport.canDeliverPromptly(to: peerID) == connected)
|
||||
}
|
||||
|
||||
connectivity.send(true)
|
||||
#expect(transport.canDeliverPromptly(to: peerID) == true)
|
||||
let callbackFired = await TestHelpers.waitUntil(
|
||||
{ observedPromptStateInCallback.count == 1 },
|
||||
timeout: TestConstants.settleTimeout
|
||||
)
|
||||
#expect(callbackFired)
|
||||
#expect(observedPromptStateInCallback == [true])
|
||||
}
|
||||
|
||||
@Test("Private message resolves short peer ID and emits decryptable packet")
|
||||
@MainActor
|
||||
func sendPrivateMessageResolvesShortPeerID() async throws {
|
||||
|
||||
Reference in new issue
Block a user