SPB Git

Repository Public License

BridgeSession.swift 6.8 KB 147 lines swift

1// SyncEngine — one sync exchange between two paired devices over a secure channel.2import Diagnostics3import Foundation4import NavigatorCore56/// The messages of a Bridge session (JSON inside encrypted frames).7enum BridgeMessage: Codable, Sendable {8    case hello(protocolVersion: Int, deviceID: String, deviceName: String)9    /// A slice of the sender's stamps; `last` marks the end of the list.10    case index(stamps: [SyncStamp], last: Bool)11    case request(keys: [SyncKey])12    case changes([SyncChange])13    /// The sender has answered the request it received.14    case done(sent: Int)15    case failure(String)16}1718public struct BridgeSyncReport: Sendable, Hashable {19    public var peerDeviceID: String20    public var peerDeviceName: String21    /// Changes (with payload) sent to the peer.22    public var sent: Int23    /// Changes received, deletions included.24    public var received: Int25    public var applied: SyncApplyReport26}2728/// Runs the symmetric exchange: both devices send the list of what they hold, each asks the other for what it29/// is missing or has an older version of, and each applies what it receives with `SyncCoordinator`.30/// There is no server and no account: only the two devices and the channel between them.31public struct BridgeSyncSession: Sendable {32    public static let protocolVersion = 133    static let stampsPerMessage = 2_00034    static let bytesPerBatch = 1024 * 102435    /// A single payload above this cannot travel in one frame and is left for a later version of the protocol.36    static let maximumPayloadBytes = 12 * 1024 * 10243738    private let coordinator: SyncCoordinator39    private let channel: BridgeSecureChannel40    private let deviceName: String4142    public init(coordinator: SyncCoordinator, channel: BridgeSecureChannel, deviceName: String) {43        self.coordinator = coordinator; self.channel = channel; self.deviceName = deviceName44    }4546    private func send(_ message: BridgeMessage) async throws {47        try await channel.send(try JSONEncoder().encode(message))48    }4950    private func receive() async throws -> BridgeMessage {51        let data = try await channel.receive()52        guard let message = try? JSONDecoder().decode(BridgeMessage.self, from: data) else { throw BridgeError.protocolViolation("unreadable message") }53        return message54    }5556    /// Runs one exchange to completion and closes the channel. Both devices call this at the same time.57    public func run() async throws -> BridgeSyncReport {58        do {59            let report = try await exchange()60            await channel.close()61            return report62        } catch {63            try? await send(.failure("\(error)".prefix(200).description))64            await channel.close()65            throw error66        }67    }6869    private func exchange() async throws -> BridgeSyncReport {70        let deviceID = try await coordinator.deviceID()71        let stamps = try await coordinator.index()72        // Sending and receiving run concurrently: neither device waits for the other to finish talking, so two73        // large lists cannot block each other.74        async let announced: Void = announce(deviceID: deviceID, stamps: stamps)7576        var peerID = "", peerName = ""77        var remoteStamps: [SyncStamp] = []78        var incoming: [SyncChange] = []79        var tombstones: [SyncStamp] = []80        var sent = 0, receivedDone = false, sentDone = false, sawHello = false81        while !(receivedDone && sentDone) {82            switch try await receive() {83            case .hello(let version, let id, let name):84                guard version == Self.protocolVersion else { throw BridgeError.incompatibleVersion(version) }85                guard !sawHello, id != deviceID else { throw BridgeError.protocolViolation("hello") }86                sawHello = true; peerID = id; peerName = String(name.prefix(100))87            case .index(let slice, let last):88                guard sawHello, remoteStamps.count + slice.count <= 5_000_000 else { throw BridgeError.protocolViolation("index") }89                remoteStamps += slice90                if last {91                    let plan = try await coordinator.plan(remote: remoteStamps)92                    tombstones = plan.tombstones93                    remoteStamps = []94                    for start in stride(from: 0, to: max(plan.request.count, 1), by: Self.stampsPerMessage) {95                        try await send(.request(keys: Array(plan.request[min(start, plan.request.count)..<min(start + Self.stampsPerMessage, plan.request.count)])))96                    }97                    try await send(.request(keys: []))   // an empty request ends the list98                }99            case .request(let keys):100                guard sawHello else { throw BridgeError.protocolViolation("request before hello") }101                if keys.isEmpty {102                    try await send(.done(sent: sent))103                    sentDone = true104                    continue105                }106                var batch: [SyncChange] = [], size = 0107                for change in try await coordinator.changes(for: keys) {108                    let bytes = change.payload?.count ?? 0109                    guard bytes <= Self.maximumPayloadBytes else {110                        Log.sync.error("Bridge: one change is too large to send and was skipped")111                        continue112                    }113                    if !batch.isEmpty, size + bytes > Self.bytesPerBatch {114                        try await send(.changes(batch))115                        batch = []; size = 0116                    }117                    batch.append(change)118                    size += bytes119                    sent += 1120                }121                if !batch.isEmpty { try await send(.changes(batch)) }122            case .changes(let batch):123                guard sawHello, incoming.count + batch.count <= 5_000_000 else { throw BridgeError.protocolViolation("changes") }124                incoming += batch125            case .done:126                receivedDone = true127            case .failure(let reason):128                throw BridgeError.protocolViolation("the other device stopped: \(reason.prefix(200))")129            }130        }131        try await announced132        let all = incoming + tombstones.map { SyncChange(stamp: $0, payload: nil) }133        let applied = try await coordinator.apply(all)134        return BridgeSyncReport(peerDeviceID: peerID, peerDeviceName: peerName, sent: sent, received: all.count, applied: applied)135    }136137    private func announce(deviceID: String, stamps: [SyncStamp]) async throws {138        try await send(.hello(protocolVersion: Self.protocolVersion, deviceID: deviceID, deviceName: deviceName))139        var start = 0140        repeat {141            let end = min(start + Self.stampsPerMessage, stamps.count)142            try await send(.index(stamps: Array(stamps[start..<end]), last: end == stamps.count))143            start = end144        } while start < stamps.count145    }146}147
Files main
Menu

Theme