Repository Public License
1// SyncEngine — optional iCloud relay for the sync core (CloudKit private database).2//3// NOT VERIFIED. The app has no iCloud container entitlement yet, so nothing in this file has ever talked to4// CloudKit: it compiles, and that is all that is known. It is off by default (`isEnabled: false`), no other5// type depends on it, and every call throws `CloudSyncError.disabled` until it is explicitly enabled.6import CloudKit7import Foundation8import NavigatorCore9import Persistence1011public enum CloudSyncError: Error, Sendable, Equatable, CustomStringConvertible {12 case disabled13 case accountUnavailable(String)14 case malformedRecord(String)1516 public var description: String {17 switch self {18 case .disabled: return "iCloud sync is turned off."19 case .accountUnavailable(let detail): return "iCloud is not available (\(detail))."20 case .malformedRecord(let name): return "An iCloud record could not be read (\(name))."21 }22 }23}2425/// A place that stores sync changes between sessions so devices need not be online together. The sync core26/// does not depend on it: `SyncCoordinator.apply` and `changes(for:)` are all an adapter needs.27public protocol CloudSyncAdapter: Sendable {28 var isEnabled: Bool { get }29 /// Stores changes remotely (latest stamp per key).30 func push(_ changes: [SyncChange]) async throws31 /// Changes stored remotely since the previous pull.32 func pull() async throws -> [SyncChange]33 /// Deletes everything this adapter stored remotely.34 func removeAllRemoteData() async throws35}3637/// The adapter used when cloud sync is off: it does nothing and stores nothing.38public struct DisabledCloudSync: CloudSyncAdapter {39 public init() {}40 public var isEnabled: Bool { false }41 public func push(_ changes: [SyncChange]) async throws { throw CloudSyncError.disabled }42 public func pull() async throws -> [SyncChange] { throw CloudSyncError.disabled }43 public func removeAllRemoteData() async throws { throw CloudSyncError.disabled }44}4546/// CloudKit adapter: one record per sync key in a custom zone of the user's **private** database, fetched47/// incrementally with a server change token.48///49/// Conflict handling is the sync core's: records are written with "last save wins" and every device applies50/// what it pulls through `SyncCoordinator.apply`, which keeps the greatest stamp. A device whose newer change51/// was overwritten on the server still holds it and pushes it again.52public actor CloudKitBridge: CloudSyncAdapter {53 public static let zoneName = "OrixBridge"54 public static let recordType = "SyncChange"55 static let changeTokenKey = SettingKey<String>("sync.cloudkit.change_token", default: "")56 /// Payloads above this size go into a CKAsset (a record is limited to about 1 MB).57 static let inlinePayloadLimit = 512 * 102458 static let batchSize = 3005960 public nonisolated let isEnabled: Bool61 private let containerIdentifier: String62 private let database: NavigatorDatabase63 private var zoneIsReady = false6465 /// - Parameter isEnabled: must be passed as `true` explicitly, and only once the app carries the iCloud66 /// container entitlement; creating a `CKContainer` without it terminates the process.67 public init(containerIdentifier: String, database: NavigatorDatabase, isEnabled: Bool = false) {68 self.containerIdentifier = containerIdentifier; self.database = database; self.isEnabled = isEnabled69 }7071 private var zoneID: CKRecordZone.ID { CKRecordZone.ID(zoneName: Self.zoneName, ownerName: CKCurrentUserDefaultName) }7273 /// The private database, after checking that it is enabled and that an iCloud account is signed in.74 private func cloud() async throws -> CKDatabase {75 guard isEnabled else { throw CloudSyncError.disabled }76 let container = CKContainer(identifier: containerIdentifier)77 let status = try await container.accountStatus()78 guard status == .available else { throw CloudSyncError.accountUnavailable("account status \(status.rawValue)") }79 let cloud = container.privateCloudDatabase80 if !zoneIsReady {81 _ = try await cloud.modifyRecordZones(saving: [CKRecordZone(zoneID: zoneID)], deleting: [])82 zoneIsReady = true83 }84 return cloud85 }8687 private func record(for change: SyncChange, temporaryFiles: inout [URL]) throws -> CKRecord {88 let stamp = change.stamp89 let record = CKRecord(recordType: Self.recordType, recordID: CKRecord.ID(recordName: "\(stamp.entity.rawValue):\(stamp.entityID)", zoneID: zoneID))90 record["entity"] = stamp.entity.rawValue91 record["entityID"] = stamp.entityID92 record["version"] = stamp.version93 record["deviceID"] = stamp.deviceID94 record["modifiedAt"] = stamp.modifiedAt95 record["deletedAt"] = stamp.deletedAt96 record["payloadHash"] = stamp.payloadHash97 // Content goes into encrypted fields: CloudKit encrypts them with keys from the user's iCloud Keychain.98 record.encryptedValues["profileHint"] = change.profileHint99 if let payload = change.payload {100 if payload.count <= Self.inlinePayloadLimit {101 record.encryptedValues["payload"] = payload102 } else {103 let file = FileManager.default.temporaryDirectory.appending(path: "orix-sync-\(UUID().uuidString).bin")104 try payload.write(to: file, options: [.atomic])105 temporaryFiles.append(file)106 record["payloadAsset"] = CKAsset(fileURL: file)107 }108 }109 return record110 }111112 private func change(from record: CKRecord) throws -> SyncChange {113 guard let entityName = record["entity"] as? String, let entity = SyncRecord.Entity(rawValue: entityName),114 let entityID = record["entityID"] as? String, let version = record["version"] as? Int64,115 let deviceID = record["deviceID"] as? String, let modifiedAt = record["modifiedAt"] as? Double else {116 throw CloudSyncError.malformedRecord(record.recordID.recordName)117 }118 var payload = record.encryptedValues["payload"] as? Data119 if payload == nil, let asset = record["payloadAsset"] as? CKAsset, let file = asset.fileURL { payload = try? Data(contentsOf: file) }120 let stamp = SyncStamp(entity: entity, entityID: entityID, version: version, deviceID: deviceID, modifiedAt: modifiedAt,121 deletedAt: record["deletedAt"] as? Double, payloadHash: record["payloadHash"] as? String)122 return SyncChange(stamp: stamp, payload: payload, profileHint: record.encryptedValues["profileHint"] as? String)123 }124125 public func push(_ changes: [SyncChange]) async throws {126 let cloud = try await cloud()127 var temporaryFiles: [URL] = []128 defer { for file in temporaryFiles { try? FileManager.default.removeItem(at: file) } }129 let wellFormed = changes.filter(\.isWellFormed)130 for start in stride(from: 0, to: wellFormed.count, by: Self.batchSize) {131 let records = try wellFormed[start..<min(start + Self.batchSize, wellFormed.count)].map { try record(for: $0, temporaryFiles: &temporaryFiles) }132 let (saved, _) = try await cloud.modifyRecords(saving: records, deleting: [], savePolicy: .allKeys, atomically: false)133 for (_, result) in saved { _ = try result.get() }134 }135 }136137 public func pull() async throws -> [SyncChange] {138 let cloud = try await cloud()139 var token: CKServerChangeToken?140 let stored = try await database.settings.value(Self.changeTokenKey)141 if let data = Data(base64Encoded: stored), !data.isEmpty {142 token = try? NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: data)143 }144 var changes: [SyncChange] = []145 var moreComing = true146 while moreComing {147 let result = try await cloud.recordZoneChanges(inZoneWith: zoneID, since: token)148 for (_, modification) in result.modificationResultsByID {149 // A record that cannot be read is skipped, not fatal: the others still sync.150 if let record = try? modification.get().record, let change = try? change(from: record), change.isWellFormed { changes.append(change) }151 }152 token = result.changeToken153 moreComing = result.moreComing154 }155 if let token, let data = try? NSKeyedArchiver.archivedData(withRootObject: token, requiringSecureCoding: true) {156 try await database.settings.set(Self.changeTokenKey, to: data.base64EncodedString())157 }158 return changes.sorted { $0.key < $1.key }159 }160161 /// Deletes the whole zone from the user's iCloud and forgets the change token. Part of "remove this162 /// device's data from sync" when the user also wants the cloud copy gone (it is shared by all their devices).163 public func removeAllRemoteData() async throws {164 let cloud = try await cloud()165 _ = try await cloud.modifyRecordZones(saving: [], deleting: [zoneID])166 zoneIsReady = false167 try await database.settings.remove(Self.changeTokenKey.name)168 }169}170