Branchwell

Graphley / app · graphley.ai / Sources / AnalyticsKit / SnapshotSync.swift

Raw 6.8 KB on d80f63aea8f10988b2fe7107ba87bf71b30173fb
1import Foundation
2import CloudKit
3import Security
4
5/// iCloud sync without a server: the Mac writes one snapshot record to the user's private CloudKit
6/// database, the iPhone reads it. Only the numbers travel; keys and tokens never leave the Keychain.
7/// (Same model as Inkspring's companion: the Mac is the source of truth, the phone is a viewer.)
8public actor SnapshotSync {
9 public static let containerID = "iCloud.com.protomota.graphley"
10 static let zone = CKRecordZone.ID(zoneName: "Analytics", ownerName: CKCurrentUserDefaultName)
11 static let recordID = CKRecord.ID(recordName: "latest-snapshot", zoneID: zone)
12 static let subscriptionID = "snapshot-changes"
13
14 let containerID: String
15 /// Nil when the build has no iCloud entitlement (unsigned dev builds): CloudKit traps instead of
16 /// throwing in that case, so sync reports itself unavailable and the rest of the app keeps working.
17 let database: CKDatabase?
18
19 public init(containerID: String = SnapshotSync.containerID) {
20 self.containerID = containerID
21 database = Self.hasCloudKitEntitlement ? CKContainer(identifier: containerID).privateCloudDatabase : nil
22 }
23
24 public nonisolated var isAvailable: Bool { database != nil }
25
26 public func accountReady() async -> Bool {
27 guard isAvailable else { return false }
28 return (try? await CKContainer(identifier: containerID).accountStatus()) == .available
29 }
30
31 /// "Connected" or "Unavailable", the Apple Account values the house iCloud Sync settings show
32 /// (copied from Inkspring's MobileLibrary). Throws when iCloud can't be asked at all.
33 public func accountStatusText() async throws -> String {
34 guard isAvailable else { throw AnalyticsError.notAllowed("iCloud sync needs a signed build with the iCloud entitlement.") }
35 return try await CKContainer(identifier: containerID).accountStatus() == .available ? "Connected" : "Unavailable"
36 }
37
38 /// When the snapshot in iCloud was refreshed on the Mac, or nil when iCloud has none.
39 /// Reads only the date, not the payload, so the Mac can check its own push cheaply.
40 public func remoteSnapshotDate() async throws -> Date? {
41 let database = try requireDatabase()
42 do {
43 let results = try await database.records(for: [Self.recordID], desiredKeys: ["refreshedAt"])
44 guard let result = results[Self.recordID] else { return nil }
45 return try result.get()["refreshedAt"] as? Date
46 } catch let e as CKError where e.code == .unknownItem || e.code == .zoneNotFound {
47 return nil
48 }
49 }
50
51 /// Mac: write the latest snapshot. The JSON goes in a CKAsset so 90 days of data fits easily.
52 public func push(_ snapshot: Snapshot) async throws {
53 let database = try requireDatabase()
54 try await ensureZone()
55 let file = FileManager.default.temporaryDirectory.appendingPathComponent("snapshot-\(UUID().uuidString).json")
56 try JSONEncoder.analytics.encode(snapshot).write(to: file)
57 defer { try? FileManager.default.removeItem(at: file) }
58
59 let record: CKRecord
60 if let existing = try? await database.record(for: Self.recordID) { record = existing }
61 else { record = CKRecord(recordType: "Snapshot", recordID: Self.recordID) }
62 record["refreshedAt"] = snapshot.refreshedAt as NSDate
63 record["payload"] = CKAsset(fileURL: file)
64 // modifyRecords only throws for the whole request; a rejected record (for example a record type
65 // missing from the Production schema) comes back in the per-record results and must be checked.
66 let (saved, _) = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .changedKeys)
67 if case .failure(let error)? = saved[Self.recordID] { throw error }
68 }
69
70 /// iPhone: read the latest snapshot, or nil before the Mac has synced once.
71 public func pull() async throws -> Snapshot? {
72 let database = try requireDatabase()
73 do {
74 let record = try await database.record(for: Self.recordID)
75 guard let url = (record["payload"] as? CKAsset)?.fileURL else { return nil }
76 return try JSONDecoder.analytics.decode(Snapshot.self, from: Data(contentsOf: url))
77 } catch let e as CKError where e.code == .unknownItem || e.code == .zoneNotFound {
78 return nil
79 }
80 }
81
82 /// iPhone: silent push when the Mac writes a new snapshot, so widgets and the app refresh.
83 public func subscribe() async throws {
84 let sub = CKRecordZoneSubscription(zoneID: Self.zone, subscriptionID: Self.subscriptionID)
85 let info = CKSubscription.NotificationInfo(); info.shouldSendContentAvailable = true
86 sub.notificationInfo = info
87 _ = try await requireDatabase().modifySubscriptions(saving: [sub], deleting: [])
88 }
89
90 private func ensureZone() async throws {
91 _ = try await requireDatabase().modifyRecordZones(saving: [CKRecordZone(zoneID: Self.zone)], deleting: [])
92 }
93
94 private func requireDatabase() throws -> CKDatabase {
95 guard let database else { throw AnalyticsError.notAllowed("iCloud sync needs a signed build with the iCloud entitlement.") }
96 return database
97 }
98
99 /// macOS can read its own entitlements. iOS can't, but an iOS app only runs signed with the
100 /// entitlements from project.yml, so it is assumed there.
101 static var hasCloudKitEntitlement: Bool {
102 #if os(macOS)
103 guard let task = SecTaskCreateFromSelf(nil),
104 let value = SecTaskCopyValueForEntitlement(task, "com.apple.developer.icloud-services" as CFString, nil)
105 else { return false }
106 return (value as? [String])?.contains("CloudKit") ?? false
107 #else
108 return true
109 #endif
110 }
111}
112
113/// What the house "iCloud Sync" and "Diagnostics" settings show. Same fields and values as
114/// Inkspring's MobileLibrary (accountStatus, lastCheck, lastCloudContact, error, syncErrorCode), so every
115/// Protomota iCloud app reports sync the same way. See the app-factory skill.
116public struct CloudSyncStatus: Equatable, Sendable {
117 /// "Not checked", "Connected" or "Unavailable".
118 public var accountStatus = "Not checked"
119 public var lastCheck: Date?
120 public var lastCloudContact: Date?
121 /// Whether iCloud has the Mac's snapshot; nil until checked.
122 public var snapshotFound: Bool?
123 /// When the snapshot in iCloud was refreshed on the Mac.
124 public var snapshotDate: Date?
125 public var error: String?
126 /// "<NSError domain> (<code>)", e.g. "CKErrorDomain (12)".
127 public var syncErrorCode: String?
128
129 public init() {}
130
131 public mutating func record(_ error: Error) {
132 let failure = error as NSError
133 syncErrorCode = "\(failure.domain) (\(failure.code))"
134 self.error = error.localizedDescription
135 }
136
137 public mutating func clearError() { error = nil; syncErrorCode = nil }
138}
139