SPB Git

Repository Public License

BridgeNetworkTransport.swift 9.9 KB 214 lines swift

1// SyncEngine — Bridge over the local network: Bonjour discovery and a TCP link (Network.framework).2//3// NOT VERIFIED ON TWO REAL DEVICES. This file compiles for macOS and iOS and a test runs the TCP path over the4// loopback interface on one Mac. Bonjour advertising and browsing, the local-network permission prompt and5// peer-to-peer Wi-Fi between two physical devices have not been exercised. See docs/BRIDGE.md.6import Foundation7import Network8import Synchronization910/// Resumes a continuation at most once, from whichever callback fires first (ready, failed, timeout).11private final class ResumeOnce: Sendable {12    private let continuation: Mutex<CheckedContinuation<Void, any Error>?>1314    init(_ continuation: CheckedContinuation<Void, any Error>) { self.continuation = Mutex(continuation) }1516    func finish(_ result: Result<Void, any Error>) {17        let pending = continuation.withLock { stored -> CheckedContinuation<Void, any Error>? in18            defer { stored = nil }19            return stored20        }21        pending?.resume(with: result)22    }23}2425/// A TCP connection carrying length-prefixed frames. No TLS: the link is not trusted, `BridgeSecureChannel`26/// encrypts and authenticates above it.27public final class NetworkBridgeTransport: BridgeTransport {28    public static let maximumFrameBytes = BridgeSecureChannel.maximumMessageBytes + 642930    private let connection: NWConnection31    private let queue = DispatchQueue(label: "dev.orixlab.navigator.bridge.connection")3233    init(connection: NWConnection) { self.connection = connection }3435    /// Opens a connection to a discovered peer (or to a host and port) and waits until it is ready.36    public static func connect(to endpoint: NWEndpoint, timeout: Duration = .seconds(15)) async throws -> NetworkBridgeTransport {37        let transport = NetworkBridgeTransport(connection: NWConnection(to: endpoint, using: BridgeNetwork.parameters()))38        try await transport.start(timeout: timeout)39        return transport40    }4142    func start(timeout: Duration) async throws {43        let connection = self.connection, queue = self.queue44        let milliseconds = Int(timeout.components.seconds) * 1_000 + Int(timeout.components.attoseconds / 1_000_000_000_000_000)45        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in46            let once = ResumeOnce(continuation)47            connection.stateUpdateHandler = { state in48                switch state {49                case .ready: once.finish(.success(()))50                case .failed(let error): once.finish(.failure(BridgeError.transport(error.localizedDescription)))51                case .cancelled: once.finish(.failure(BridgeError.closed))52                default: break53                }54            }55            connection.start(queue: queue)56            queue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { once.finish(.failure(BridgeError.timedOut)) }57        }58    }5960    public func send(_ frame: Data) async throws {61        guard frame.count <= Self.maximumFrameBytes else { throw BridgeError.frameTooLarge(frame.count) }62        var packet = withUnsafeBytes(of: UInt32(frame.count).bigEndian) { Data($0) }63        packet.append(frame)64        let connection = self.connection65        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in66            connection.send(content: packet, completion: .contentProcessed { error in67                if let error { continuation.resume(throwing: BridgeError.transport(error.localizedDescription)) } else { continuation.resume() }68            })69        }70    }7172    private func read(exactly count: Int) async throws -> Data {73        guard count > 0 else { return Data() }74        let connection = self.connection75        return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Data, any Error>) in76            connection.receive(minimumIncompleteLength: count, maximumLength: count) { data, _, isComplete, error in77                if let data, data.count == count {78                    continuation.resume(returning: data)79                } else if let error {80                    continuation.resume(throwing: BridgeError.transport(error.localizedDescription))81                } else if isComplete {82                    continuation.resume(throwing: BridgeError.closed)83                } else {84                    continuation.resume(throwing: BridgeError.protocolViolation("short read"))85                }86            }87        }88    }8990    public func receive() async throws -> Data {91        let header = try await read(exactly: 4)92        let length = header.reduce(0) { ($0 << 8) | Int($1) }93        // The length comes from the network: bound it before reading that many bytes.94        guard length <= Self.maximumFrameBytes else { throw BridgeError.frameTooLarge(length) }95        return try await read(exactly: length)96    }9798    public func close() async { connection.cancel() }99}100101public enum BridgeNetwork {102    /// Bonjour service type of the Bridge. The app's Info.plist must list it under `NSBonjourServices` and103    /// give an `NSLocalNetworkUsageDescription`.104    public static let serviceType = "_orixbridge._tcp"105106    static func parameters() -> NWParameters {107        let parameters = NWParameters.tcp108        // Lets two devices find each other without a common Wi-Fi network (AWDL).109        parameters.includePeerToPeer = true110        return parameters111    }112}113114/// A peer advertising the Bridge service nearby.115public struct BridgePeer: Sendable, Hashable, Identifiable {116    public var name: String117    public var endpoint: NWEndpoint118    public var id: String { "\(endpoint)" }119}120121/// Accepts incoming Bridge connections, optionally advertising the service over Bonjour.122public final class BridgeNetworkListener: Sendable {123    private let listener: NWListener124    private let queue = DispatchQueue(label: "dev.orixlab.navigator.bridge.listener")125    private let stream: AsyncStream<NetworkBridgeTransport>126    private let continuation: AsyncStream<NetworkBridgeTransport>.Continuation127128    /// - Parameter serviceName: the name shown to nearby devices; `nil` listens without advertising (the peer129    ///   must then be given the port, as the loopback test does).130    public init(serviceName: String?, port: NWEndpoint.Port = .any) throws {131        do { listener = try NWListener(using: BridgeNetwork.parameters(), on: port) } catch { throw BridgeError.transport(error.localizedDescription) }132        if let serviceName { listener.service = NWListener.Service(name: serviceName, type: BridgeNetwork.serviceType) }133        (stream, continuation) = AsyncStream<NetworkBridgeTransport>.makeStream()134    }135136    /// Starts listening and returns the port once the listener is ready.137    @discardableResult138    public func start(timeout: Duration = .seconds(10)) async throws -> NWEndpoint.Port {139        let listener = self.listener, continuation = self.continuation, queue = self.queue140        let seconds = Int(timeout.components.seconds)141        try await withCheckedThrowingContinuation { (ready: CheckedContinuation<Void, any Error>) in142            let once = ResumeOnce(ready)143            listener.stateUpdateHandler = { state in144                switch state {145                case .ready: once.finish(.success(()))146                case .failed(let error): once.finish(.failure(BridgeError.transport(error.localizedDescription)))147                case .cancelled: once.finish(.failure(BridgeError.closed)); continuation.finish()148                default: break149                }150            }151            listener.newConnectionHandler = { connection in152                let transport = NetworkBridgeTransport(connection: connection)153                Task {154                    do {155                        try await transport.start(timeout: .seconds(15))156                        continuation.yield(transport)157                    } catch {158                        await transport.close()159                    }160                }161            }162            listener.start(queue: queue)163            queue.asyncAfter(deadline: .now() + .seconds(seconds)) { once.finish(.failure(BridgeError.timedOut)) }164        }165        guard let port = listener.port else { throw BridgeError.transport("no port") }166        return port167    }168169    /// Incoming connections, ready to be handed to `BridgePairingOffer.accept`.170    public var connections: AsyncStream<NetworkBridgeTransport> { stream }171172    public func stop() {173        listener.cancel()174        continuation.finish()175    }176}177178/// Finds nearby devices advertising the Bridge service.179public final class BridgeNetworkBrowser: Sendable {180    private let browser: NWBrowser181    private let queue = DispatchQueue(label: "dev.orixlab.navigator.bridge.browser")182    private let stream: AsyncStream<[BridgePeer]>183    private let continuation: AsyncStream<[BridgePeer]>.Continuation184185    public init() {186        browser = NWBrowser(for: .bonjour(type: BridgeNetwork.serviceType, domain: nil), using: BridgeNetwork.parameters())187        (stream, continuation) = AsyncStream<[BridgePeer]>.makeStream()188    }189190    /// The current list of peers, re-emitted whenever it changes.191    public var peers: AsyncStream<[BridgePeer]> { stream }192193    public func start() {194        let continuation = self.continuation195        browser.browseResultsChangedHandler = { results, _ in196            let peers = results.compactMap { result -> BridgePeer? in197                guard case .service(let name, _, _, _) = result.endpoint else { return nil }198                return BridgePeer(name: name, endpoint: result.endpoint)199            }200            continuation.yield(peers.sorted { $0.name < $1.name })201        }202        browser.stateUpdateHandler = { state in203            if case .failed = state { continuation.finish() }204            if case .cancelled = state { continuation.finish() }205        }206        browser.start(queue: queue)207    }208209    public func stop() {210        browser.cancel()211        continuation.finish()212    }213}214
Files main
Menu

Theme