Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / apple / FindFamily / FindFamilyiOS / UWB / UwbInbox.swift
UwbInbox.swift50 lines · 1.9 KiBRaw
| 1 | import Foundation |
| 2 | import Combine |
| 3 | |
| 4 | /// Process-global UWB envelope inbox. |
| 5 | /// |
| 6 | /// Producer: [BackgroundTask.handleIncomingUwb], fed by relay-socket pushes |
| 7 | /// ([RelaySocket]) and by the HTTP `/api/uwb/receive_pqc` drain (once per wake, |
| 8 | /// and every heartbeat tick while the socket is down). |
| 9 | /// |
| 10 | /// Consumer: [RangingSession] subscribes while the Precision Finding screen |
| 11 | /// is open to drive the WaitingForPeer handshake. When the view isn't alive |
| 12 | /// (e.g. peer wakes a backgrounded app), the [BackgroundTask] itself posts |
| 13 | /// a notification offering to open the screen. |
| 14 | /// |
| 15 | /// PassthroughSubject — envelopes are one-shot. Missed envelopes (e.g. screen |
| 16 | /// closed before they arrived) are dropped on the floor intentionally — |
| 17 | /// EXCEPT incoming REQUEST envelopes, which we cache in [pendingRequests] so |
| 18 | /// a notification-launched screen can find them. |
| 19 | final class UwbInbox: @unchecked Sendable { |
| 20 | static let shared = UwbInbox() |
| 21 | private init() {} |
| 22 | |
| 23 | let publisher = PassthroughSubject<UwbEnvelope, Never>() |
| 24 | |
| 25 | private let queue = DispatchQueue(label: "cc.findfamily.uwb.inbox") |
| 26 | private var pendingRequests: [Int64: UwbEnvelope] = [:] |
| 27 | |
| 28 | func emit(_ envelope: UwbEnvelope) { |
| 29 | cacheIfRequest(envelope) |
| 30 | publisher.send(envelope) |
| 31 | } |
| 32 | |
| 33 | /// Retrieve and remove the most recent pending REQUEST from [peerUserId], if any. |
| 34 | func consumePendingRequest(from peerUserId: Int64) -> UwbEnvelope? { |
| 35 | queue.sync { |
| 36 | pendingRequests.removeValue(forKey: peerUserId) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | private func cacheIfRequest(_ envelope: UwbEnvelope) { |
| 41 | let senderId = Int64(bitPattern: envelope.sender) |
| 42 | queue.sync { |
| 43 | if envelope.kind == UwbEnvelopeKind.request { |
| 44 | pendingRequests[senderId] = envelope |
| 45 | } else if envelope.kind == UwbEnvelopeKind.cancel { |
| 46 | pendingRequests.removeValue(forKey: senderId) |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | } |