mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 08:45:19 +00:00
* Consolidate duplicate BLE links after restore; suppress duplicate fragment streams; onChange coalescing
Field evidence (two-phone test after BLE state-restoration relaunches):
both phones held 2-3 simultaneous same-role connections to each other —
one side received every packet from three distinct centrals all bound to
the same peer — so every PTT voice frame arrived 3x, and a 41KB voice
file went out as TWO complete independent 89-fragment streams (different
assembly ids), both fully reassembled and the duplicate only dropped at
the very end by messageID dedup. 2-3x airtime/battery on all traffic
plus doubled reassembly memory.
Root causes and fixes:
- Duplicate links stayed unbound forever: announces (the only packet
that binds a link to a peer) went through the per-peer duplicate-link
collapse, so a peer's second/third link never received the announce it
needed to become bound — and unbound links pass the collapse untouched,
so every broadcast sprayed down all of them. Direct announces now
bypass the collapse and reach every live link (relayed announces keep
it); once bound, the existing collapse dedups all traffic.
- Same-role link retirement: a verified direct announce now consolidates
our central-role connections to that peer — keep the link the announce
arrived on (or the most recently bound one), cancel other connected
links bound to the same peer. One connection per role per peer is the
normal dual-role topology; only same-role duplicates are touched, only
links already announce-bound are retired (never pre-announce links),
at most one retirement per peer per rebind-cooldown window, and the
peer keeps a live link either way. Directness stays forgeable (TTL is
unsigned), so a replay could nominate the survivor — bounded by the
cooldown and by DM routing's existing canDeliverSecurely gate. A
rotation rebind now also cancels other stale links still bound to the
rotated-away ID, so the ghost identity retires promptly.
- Deterministic preferred-link collapse: when several bound links to one
peer are candidates, collapse now keeps the peer's most recently bound
link (the reverse-mapped one) instead of dictionary order; links
without a discovered characteristic are excluded from fanout (they
cannot be written to, and could silently eat a peer's collapsed copy).
links(to:) now reports all bound peripheral links, and removing one
duplicate no longer clobbers the reverse map of the survivor.
- Duplicate fragment streams: a transferId-less resend (gossip-sync
replay, spool) of file content already being fragmented out to a
covering audience is dropped at the outbound scheduler (broadcast
covers everyone; directed covers its recipient). App-initiated sends
carry an explicit transferId the progress UI tracks and always run.
A peer that asks after the stream completes still gets a resend.
- didUnsubscribeFrom no longer flaps a peer that is still live on other
links (the far side retiring its duplicate arrives as an unsubscribe);
didDisconnectPeripheral bookkeeping is skipped for self-retired links
by removing the store entry before cancelling.
Also: guard the DeliveryStatus onChange state write in TextMessageView/
MediaMessageView (unconditional per-row writes under a message storm
tripped SwiftUI's "tried to update multiple times per frame" warning).
The restore-path bgRemaining=∞ log was already fixed on main (#1425
review follow-up 07b5ac31: init-time seed + sampler-routed restore
captures); verified, no change needed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Review fixes: multi-link disconnect guard, characteristic-aware retirement
Adversarial review of the duplicate-link PR (merge-with-nits):
- didDisconnectPeripheral gets the same multi-link guard as the
unsubscribe path: when a duplicate link drops naturally while the peer
stays live on another (dual-role central link, or a second bound link
during the post-restore consolidation window), peer-disconnect
bookkeeping (markDisconnected + disconnect notify) no longer runs — a
UI blip until the next announce re-marked the peer connected. The
reverse map was just repaired onto a connected survivor, so
directLinkState is the accurate probe. Scan restart and connect-slot
refill stay unguarded: they respond to the physical drop regardless of
remaining logical links. (No unit test: driving the CBCentralManager
delegate requires CBPeripheral instances, which cannot be constructed
in tests; the policy pieces backing the guard are covered.)
- Retirement is now characteristic-aware: the policy snapshot carries
characteristic presence, and keptPeripheralUUID selects anchors only
among writable links while any exist — consolidation must not keep a
link mid-service-rediscovery (didModifyServices cleared its
characteristic) and cancel the writable duplicate, stranding outbound
traffic on the central link until rediscovery finishes. When neither
anchor is writable but a writable duplicate exists, consolidation
defers to a later announce instead of guessing. The reverse-map
survivor repair in removePeripheral prefers writable links for the
same reason. Three new policy tests cover charless-vs-writable.
Deferred with code comments per review: central-side collapse keeps the
oldest subscription (no recency signal; remote consolidates within its
cooldown), and the extra preferred-bindings bleQueue hop in
sendOnAllLinks (fold into a combined snapshot if profiling flags it).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
276 lines
9.4 KiB
Swift
276 lines
9.4 KiB
Swift
import BitFoundation
|
|
import CoreBluetooth
|
|
import Foundation
|
|
|
|
struct BLEPeripheralLinkState {
|
|
let peripheral: CBPeripheral
|
|
var characteristic: CBCharacteristic?
|
|
var peerID: PeerID?
|
|
var isConnecting: Bool
|
|
var isConnected: Bool
|
|
var lastConnectionAttempt: Date?
|
|
var assembler: NotificationStreamAssembler
|
|
}
|
|
|
|
struct BLEDirectLinkState: Equatable {
|
|
let hasPeripheral: Bool
|
|
let hasCentral: Bool
|
|
}
|
|
|
|
struct BLESubscribedCentralSnapshot {
|
|
let centrals: [CBCentral]
|
|
let peerIDsByCentralUUID: [String: PeerID]
|
|
|
|
func central(for peerID: PeerID) -> CBCentral? {
|
|
centrals.first { peerIDsByCentralUUID[$0.identifier.uuidString] == peerID }
|
|
}
|
|
}
|
|
|
|
/// Owns all BLE link state (peripheral connections we hold as central, and
|
|
/// central subscriptions we serve as peripheral). The store has no internal
|
|
/// locking: every access must happen on the single owning queue (the BLE
|
|
/// queue). Other queues must go through BLEService's `readLinkState`, which
|
|
/// hops to that queue. Call `assumeOwnership(of:)` to have debug builds trap
|
|
/// any access from the wrong queue.
|
|
final class BLELinkStateStore {
|
|
private(set) var peripherals: [String: BLEPeripheralLinkState] = [:]
|
|
private(set) var peerToPeripheralUUID: [PeerID: String] = [:]
|
|
private(set) var subscribedCentrals: [CBCentral] = []
|
|
private(set) var centralToPeerID: [String: PeerID] = [:]
|
|
|
|
#if DEBUG
|
|
private var ownerQueue: DispatchQueue?
|
|
#endif
|
|
|
|
/// Pin the store to its owning queue. Debug-only enforcement; release
|
|
/// builds are unchanged.
|
|
func assumeOwnership(of queue: DispatchQueue) {
|
|
#if DEBUG
|
|
ownerQueue = queue
|
|
#endif
|
|
}
|
|
|
|
@inline(__always)
|
|
private func assertOwned() {
|
|
#if DEBUG
|
|
if let queue = ownerQueue {
|
|
dispatchPrecondition(condition: .onQueue(queue))
|
|
}
|
|
#endif
|
|
}
|
|
|
|
var peripheralStates: [BLEPeripheralLinkState] {
|
|
assertOwned()
|
|
return Array(peripherals.values)
|
|
}
|
|
|
|
var subscribedCentralSnapshot: BLESubscribedCentralSnapshot {
|
|
assertOwned()
|
|
return BLESubscribedCentralSnapshot(
|
|
centrals: subscribedCentrals,
|
|
peerIDsByCentralUUID: centralToPeerID
|
|
)
|
|
}
|
|
|
|
var subscribedCentralCount: Int {
|
|
assertOwned()
|
|
return subscribedCentrals.count
|
|
}
|
|
|
|
var connectedOrConnectingPeripheralCount: Int {
|
|
assertOwned()
|
|
return peripherals.values.filter { $0.isConnected || $0.isConnecting }.count
|
|
}
|
|
|
|
func state(forPeripheralID peripheralID: String) -> BLEPeripheralLinkState? {
|
|
assertOwned()
|
|
return peripherals[peripheralID]
|
|
}
|
|
|
|
func setPeripheralState(_ state: BLEPeripheralLinkState, for peripheralID: String) {
|
|
assertOwned()
|
|
peripherals[peripheralID] = state
|
|
}
|
|
|
|
@discardableResult
|
|
func updatePeripheral(
|
|
_ peripheralID: String,
|
|
_ update: (inout BLEPeripheralLinkState) -> Void
|
|
) -> BLEPeripheralLinkState? {
|
|
assertOwned()
|
|
guard var state = peripherals[peripheralID] else { return nil }
|
|
update(&state)
|
|
peripherals[peripheralID] = state
|
|
return state
|
|
}
|
|
|
|
func beginConnecting(to peripheral: CBPeripheral, at date: Date) {
|
|
setPeripheralState(
|
|
BLEPeripheralLinkState(
|
|
peripheral: peripheral,
|
|
characteristic: nil,
|
|
peerID: nil,
|
|
isConnecting: true,
|
|
isConnected: false,
|
|
lastConnectionAttempt: date,
|
|
assembler: NotificationStreamAssembler()
|
|
),
|
|
for: peripheral.identifier.uuidString
|
|
)
|
|
}
|
|
|
|
func markConnected(_ peripheral: CBPeripheral) {
|
|
let peripheralID = peripheral.identifier.uuidString
|
|
if updatePeripheral(peripheralID, {
|
|
$0.isConnecting = false
|
|
$0.isConnected = true
|
|
}) == nil {
|
|
setPeripheralState(
|
|
BLEPeripheralLinkState(
|
|
peripheral: peripheral,
|
|
characteristic: nil,
|
|
peerID: nil,
|
|
isConnecting: false,
|
|
isConnected: true,
|
|
lastConnectionAttempt: nil,
|
|
assembler: NotificationStreamAssembler()
|
|
),
|
|
for: peripheralID
|
|
)
|
|
}
|
|
}
|
|
|
|
func updateCharacteristic(_ characteristic: CBCharacteristic, forPeripheralID peripheralID: String) {
|
|
updatePeripheral(peripheralID) {
|
|
$0.characteristic = characteristic
|
|
}
|
|
}
|
|
|
|
func directPeripheralState(for peerID: PeerID) -> BLEPeripheralLinkState? {
|
|
assertOwned()
|
|
return peerToPeripheralUUID[peerID].flatMap { peripherals[$0] }
|
|
}
|
|
|
|
func directLinkState(for peerID: PeerID) -> BLEDirectLinkState {
|
|
assertOwned()
|
|
let peripheralUUID = peerToPeripheralUUID[peerID]
|
|
let hasPeripheral = peripheralUUID.flatMap { peripherals[$0]?.isConnected } ?? false
|
|
let hasCentral = centralToPeerID.values.contains(peerID)
|
|
return BLEDirectLinkState(hasPeripheral: hasPeripheral, hasCentral: hasCentral)
|
|
}
|
|
|
|
func links(to peerID: PeerID?) -> Set<BLEIngressLinkID> {
|
|
assertOwned()
|
|
guard let peerID else { return [] }
|
|
|
|
var links: Set<BLEIngressLinkID> = []
|
|
// Scan all states rather than the 1:1 reverse map: after a state
|
|
// restoration the same device can hold several live peripheral links
|
|
// bound to one peer (it reappears under a fresh UUID while the
|
|
// restored connection lives on).
|
|
for (peripheralUUID, state) in peripherals where state.peerID == peerID {
|
|
links.insert(.peripheral(peripheralUUID))
|
|
}
|
|
for (centralUUID, mappedPeerID) in centralToPeerID where mappedPeerID == peerID {
|
|
links.insert(.central(centralUUID))
|
|
}
|
|
return links
|
|
}
|
|
|
|
/// The peer's most recently bound peripheral link, per peer. Used to keep
|
|
/// duplicate-link fanout collapse deterministic (see BLEFanoutSelector).
|
|
var preferredPeripheralBindings: [PeerID: String] {
|
|
assertOwned()
|
|
return peerToPeripheralUUID
|
|
}
|
|
|
|
func peerID(forPeripheralID peripheralID: String) -> PeerID? {
|
|
assertOwned()
|
|
return peripherals[peripheralID]?.peerID
|
|
}
|
|
|
|
func peerID(forCentralUUID centralUUID: String) -> PeerID? {
|
|
assertOwned()
|
|
return centralToPeerID[centralUUID]
|
|
}
|
|
|
|
func addSubscribedCentral(_ central: CBCentral) {
|
|
assertOwned()
|
|
guard !subscribedCentrals.contains(central) else { return }
|
|
subscribedCentrals.append(central)
|
|
}
|
|
|
|
func removeSubscribedCentral(_ central: CBCentral) -> PeerID? {
|
|
assertOwned()
|
|
let centralUUID = central.identifier.uuidString
|
|
subscribedCentrals.removeAll { $0.identifier == central.identifier }
|
|
return centralToPeerID.removeValue(forKey: centralUUID)
|
|
}
|
|
|
|
func bindCentral(_ centralUUID: String, to peerID: PeerID) {
|
|
assertOwned()
|
|
centralToPeerID[centralUUID] = peerID
|
|
}
|
|
|
|
func bindPeripheral(_ peripheralUUID: String, to peerID: PeerID) {
|
|
assertOwned()
|
|
var previousPeerID: PeerID?
|
|
let updated = updatePeripheral(peripheralUUID) {
|
|
previousPeerID = $0.peerID
|
|
$0.peerID = peerID
|
|
}
|
|
guard updated != nil else { return }
|
|
// Rebinding (peer-ID rotation): drop the retired ID's reverse mapping
|
|
// so the old peer no longer claims this link.
|
|
if let previousPeerID, previousPeerID != peerID,
|
|
peerToPeripheralUUID[previousPeerID] == peripheralUUID {
|
|
peerToPeripheralUUID.removeValue(forKey: previousPeerID)
|
|
}
|
|
peerToPeripheralUUID[peerID] = peripheralUUID
|
|
}
|
|
|
|
func removePeripheral(_ peripheralID: String) -> PeerID? {
|
|
assertOwned()
|
|
let peerID = peripherals.removeValue(forKey: peripheralID)?.peerID
|
|
// Only clear (or repair) the reverse map when it points at the removed
|
|
// link: with duplicate links to one peer, removing a stale duplicate
|
|
// must not strand the peer's surviving bound link.
|
|
if let peerID, peerToPeripheralUUID[peerID] == peripheralID {
|
|
// Prefer a writable survivor: repairing onto a link that is
|
|
// mid-service-rediscovery would strand directed sends until the
|
|
// characteristic comes back.
|
|
let survivors = peripherals.filter { $0.value.peerID == peerID && $0.value.isConnected }
|
|
if let survivorUUID = survivors.first(where: { $0.value.characteristic != nil })?.key ?? survivors.first?.key {
|
|
peerToPeripheralUUID[peerID] = survivorUUID
|
|
} else {
|
|
peerToPeripheralUUID.removeValue(forKey: peerID)
|
|
}
|
|
}
|
|
return peerID
|
|
}
|
|
|
|
func clearPeripherals() -> [PeerID] {
|
|
assertOwned()
|
|
let peerIDs = peripherals.compactMap { $0.value.peerID }
|
|
peripherals.removeAll()
|
|
peerToPeripheralUUID.removeAll()
|
|
return peerIDs
|
|
}
|
|
|
|
func clearCentrals() -> [PeerID] {
|
|
assertOwned()
|
|
let peerIDs = Array(centralToPeerID.values)
|
|
subscribedCentrals.removeAll()
|
|
centralToPeerID.removeAll()
|
|
return peerIDs
|
|
}
|
|
|
|
func clearAll() {
|
|
assertOwned()
|
|
peripherals.removeAll()
|
|
peerToPeripheralUUID.removeAll()
|
|
subscribedCentrals.removeAll()
|
|
centralToPeerID.removeAll()
|
|
}
|
|
}
|