Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / UWB / UwbInbox.swift

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