Branchwell

Bucksley / app · bucksley.ai / Sources / BucksleyKit / CloudSync.swift

1import Foundation
2import CloudKit
3import CryptoKit
4import Security
5
6/// What the Mac shares with the iPhone: the workspace (accounts, categories, rules, budgets), recent
7/// transactions with their edits, and a year of balances. Keys and tokens never travel.
8public struct Snapshot: Codable, Sendable {
9 public var sharedAt: Date
10 public var workspace: Workspace
11 public var transactions: [Transaction]
12 public var edits: [TransactionEdit]
13 public var balances: [BalancePoint]
14}
15
16/// Two-way iCloud sync in the user's private CloudKit database, with no server:
17/// - the Mac writes one `Snapshot` record (a CKAsset) after each bank sync or edit;
18/// - both devices write one `Edit` record per edited transaction (reviewed, category, note, …) and
19/// read the other's through zone changes. The newer edit wins field by field, and an edit always
20/// wins over bank data because it is stored apart from it;
21/// - the iPhone writes a `WalletImport` record with its Apple Wallet (FinanceKit) data, which the
22/// Mac files under an Apple Wallet connection.
23public actor CloudSync {
24 public static let containerID = "iCloud.com.protomota.bucksley"
25 static let zone = CKRecordZone.ID(zoneName: "Bucksley", ownerName: CKCurrentUserDefaultName)
26 static let snapshotID = CKRecord.ID(recordName: "mac-snapshot", zoneID: zone)
27 static let walletID = CKRecord.ID(recordName: "wallet-import", zoneID: zone)
28 static let subscriptionID = "bucksley-zone-changes"
29
30 let containerID: String
31 /// Nil without the iCloud entitlement (unsigned dev builds): CloudKit traps instead of throwing
32 /// there, so sync reports itself unavailable and the rest of the app keeps working.
33 let database: CKDatabase?
34 let stateURL: URL
35
36 public init(store: WorkspaceStore, containerID: String = CloudSync.containerID) {
37 self.containerID = containerID
38 stateURL = store.folder.appendingPathComponent("sync-state.json")
39 database = Self.hasCloudKitEntitlement ? CKContainer(identifier: containerID).privateCloudDatabase : nil
40 }
41
42 public nonisolated var isAvailable: Bool { database != nil }
43
44 public func accountReady() async -> Bool {
45 guard isAvailable else { return false }
46 return (try? await CKContainer(identifier: containerID).accountStatus()) == .available
47 }
48
49 // MARK: Snapshot (Mac → iPhone)
50
51 public static func snapshot(from store: WorkspaceStore, days: Int = 180) throws -> Snapshot {
52 var ws = try store.load()
53 ws.agentLog = []
54 let cutoff = DayKey.adding(-days, to: DayKey.today)
55 let txs = try store.transactions().filter { $0.day >= cutoff }
56 let ids = Set(txs.map(\.id))
57 return Snapshot(sharedAt: .now, workspace: ws, transactions: txs,
58 edits: try store.edits().values.filter { ids.contains($0.transactionID) },
59 balances: try store.balances().filter { $0.day >= DayKey.adding(-370, to: DayKey.today) })
60 }
61
62 public func pushSnapshot(_ snapshot: Snapshot) async throws {
63 let database = try requireDatabase()
64 try await ensureZone()
65 let file = FileManager.default.temporaryDirectory.appendingPathComponent("bucksley-snapshot-\(UUID().uuidString).json")
66 try JSONEncoder.bucksley.encode(snapshot).write(to: file)
67 defer { try? FileManager.default.removeItem(at: file) }
68 let record = (try? await database.record(for: Self.snapshotID)) ?? CKRecord(recordType: "Snapshot", recordID: Self.snapshotID)
69 record["sharedAt"] = snapshot.sharedAt as NSDate
70 record["payload"] = CKAsset(fileURL: file)
71 _ = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .changedKeys)
72 }
73
74 public func pullSnapshot() async throws -> Snapshot? {
75 let database = try requireDatabase()
76 do {
77 let record = try await database.record(for: Self.snapshotID)
78 guard let url = (record["payload"] as? CKAsset)?.fileURL else { return nil }
79 return try JSONDecoder.bucksley.decode(Snapshot.self, from: Data(contentsOf: url))
80 } catch let e as CKError where e.code == .unknownItem || e.code == .zoneNotFound {
81 return nil
82 }
83 }
84
85 // MARK: Edits (both ways)
86
87 static func editRecordID(_ transactionID: String) -> CKRecord.ID {
88 let hash = SHA256.hash(data: Data(transactionID.utf8)).map { String(format: "%02x", $0) }.joined()
89 return CKRecord.ID(recordName: "edit-" + hash, zoneID: zone)
90 }
91
92 /// Sends this device's edits made since the last push.
93 @discardableResult
94 public func pushEdits(from store: WorkspaceStore) async throws -> Int {
95 let database = try requireDatabase()
96 try await ensureZone()
97 var state = loadState()
98 let since = state.lastEditPush ?? .distantPast
99 let pending = try store.edits().values.filter { $0.updatedAt > since }
100 guard !pending.isEmpty else { return 0 }
101 for chunk in stride(from: 0, to: pending.count, by: 300).map({ Array(pending[$0..<min($0 + 300, pending.count)]) }) {
102 let records = try chunk.map { edit -> CKRecord in
103 let record = CKRecord(recordType: "Edit", recordID: Self.editRecordID(edit.transactionID))
104 record["transactionID"] = edit.transactionID as NSString
105 record["updatedAt"] = edit.updatedAt as NSDate
106 record["payload"] = String(decoding: try JSONEncoder.bucksley.encode(edit), as: UTF8.self) as NSString
107 return record
108 }
109 _ = try await database.modifyRecords(saving: records, deleting: [], savePolicy: .allKeys, atomically: false)
110 }
111 state.lastEditPush = pending.map(\.updatedAt).max()
112 saveState(state)
113 return pending.count
114 }
115
116 /// Reads edits (and an Apple Wallet import) that changed since the last pull and merges the edits
117 /// into the store. Returns the number of edits merged and any wallet import found.
118 public func pullChanges(into store: WorkspaceStore) async throws -> (edits: Int, wallet: BankPull?, snapshotChanged: Bool) {
119 let database = try requireDatabase()
120 var state = loadState()
121 var token = state.zoneToken.flatMap { try? NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: $0) }
122 var edits: [TransactionEdit] = [], wallet: BankPull?, snapshotChanged = false
123 var more = true
124 do {
125 while more {
126 let changes = try await database.recordZoneChanges(inZoneWith: Self.zone, since: token)
127 for (_, result) in changes.modificationResultsByID {
128 guard case .success(let modification) = result else { continue }
129 let record = modification.record
130 switch record.recordType {
131 case "Edit":
132 if let text = record["payload"] as? String, let edit = try? JSONDecoder.bucksley.decode(TransactionEdit.self, from: Data(text.utf8)) { edits.append(edit) }
133 case "WalletImport":
134 if let url = (record["payload"] as? CKAsset)?.fileURL, let data = try? Data(contentsOf: url) { wallet = try? JSONDecoder.bucksley.decode(WalletPayload.self, from: data).pull.pull }
135 case "Snapshot":
136 snapshotChanged = true
137 default: break
138 }
139 }
140 token = changes.changeToken
141 more = changes.moreComing
142 }
143 } catch let e as CKError where e.code == .zoneNotFound {
144 return (0, nil, false)
145 } catch let e as CKError where e.code == .changeTokenExpired {
146 state.zoneToken = nil; saveState(state)
147 return try await pullChanges(into: store)
148 }
149 let merged = try store.mergeEdits(edits)
150 state.zoneToken = token.flatMap { try? NSKeyedArchiver.archivedData(withRootObject: $0, requiringSecureCoding: true) }
151 saveState(state)
152 return (merged, wallet, snapshotChanged)
153 }
154
155 // MARK: Apple Wallet (iPhone → Mac)
156
157 struct WalletPayload: Codable { var importedAt: Date; var pull: BankPullCodable }
158
159 public func pushWallet(_ pull: BankPull) async throws {
160 let database = try requireDatabase()
161 try await ensureZone()
162 let file = FileManager.default.temporaryDirectory.appendingPathComponent("bucksley-wallet-\(UUID().uuidString).json")
163 try JSONEncoder.bucksley.encode(WalletPayload(importedAt: .now, pull: BankPullCodable(pull))).write(to: file)
164 defer { try? FileManager.default.removeItem(at: file) }
165 let record = (try? await database.record(for: Self.walletID)) ?? CKRecord(recordType: "WalletImport", recordID: Self.walletID)
166 record["importedAt"] = Date.now as NSDate
167 record["payload"] = CKAsset(fileURL: file)
168 _ = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .changedKeys)
169 }
170
171 // MARK: Push notifications
172
173 /// Silent push on any change in the zone, so the other device refreshes right away.
174 public func subscribe() async throws {
175 let database = try requireDatabase()
176 try await ensureZone()
177 let sub = CKRecordZoneSubscription(zoneID: Self.zone, subscriptionID: Self.subscriptionID)
178 let info = CKSubscription.NotificationInfo(); info.shouldSendContentAvailable = true
179 sub.notificationInfo = info
180 _ = try await database.modifySubscriptions(saving: [sub], deleting: [])
181 }
182
183 // MARK: Plumbing
184
185 struct State: Codable { var zoneToken: Data?; var lastEditPush: Date? }
186 func loadState() -> State { (try? JSONDecoder.bucksley.decode(State.self, from: Data(contentsOf: stateURL))) ?? State() }
187 func saveState(_ state: State) { try? JSONEncoder.bucksley.encode(state).write(to: stateURL, options: .atomic) }
188
189 private var zoneReady = false
190 private func ensureZone() async throws {
191 guard !zoneReady else { return }
192 _ = try await requireDatabase().modifyRecordZones(saving: [CKRecordZone(zoneID: Self.zone)], deleting: [])
193 zoneReady = true
194 }
195
196 private func requireDatabase() throws -> CKDatabase {
197 guard let database else { throw BucksleyError.notAllowed("iCloud sync needs a signed build with the iCloud entitlement.") }
198 return database
199 }
200
201 /// macOS can read its own entitlements. iOS can't, but an iOS app only runs signed with the
202 /// entitlements from project.yml, so it is assumed there (except in the simulator test host).
203 static var hasCloudKitEntitlement: Bool {
204 if ProcessInfo.processInfo.environment["BUCKSLEY_NO_ICLOUD"] != nil { return false }
205 #if os(macOS)
206 guard let task = SecTaskCreateFromSelf(nil),
207 let value = SecTaskCopyValueForEntitlement(task, "com.apple.developer.icloud-services" as CFString, nil)
208 else { return false }
209 return (value as? [String])?.contains("CloudKit") ?? false
210 #else
211 return true
212 #endif
213 }
214}
215
216/// BankPull as Codable for the Apple Wallet hand-off.
217struct BankPullCodable: Codable {
218 var accounts: [Account]
219 var transactions: [Transaction]
220 init(_ pull: BankPull) { accounts = pull.accounts; transactions = pull.transactions }
221 var pull: BankPull { var p = BankPull(); p.accounts = accounts; p.transactions = transactions; return p }
222}
223
224public extension WorkspaceStore {
225 /// iPhone: replaces its cache with the Mac's snapshot, then lays the Mac's edits under its own.
226 func adopt(_ snapshot: Snapshot) throws {
227 try update { ws in
228 let log = ws.agentLog
229 ws = snapshot.workspace; ws.agentLog = log
230 }
231 try removeTransactions { _ in true }
232 try upsert(snapshot.transactions)
233 try replaceBalances(snapshot.balances)
234 try mergeEdits(snapshot.edits)
235 }
236}