Inkspring / app · inkspring.ai / native-mac / Sources / InkspringSchedule / CloudScheduleStore.swift
| 1 | import CloudKit |
| 2 | import CryptoKit |
| 3 | import Foundation |
| 4 | #if os(macOS) |
| 5 | import Security |
| 6 | #endif |
| 7 | |
| 8 | @MainActor |
| 9 | public struct CloudScheduleStore { |
| 10 | public static let containerID = "iCloud.com.protomota.inkspring" |
| 11 | private static let recordID = CKRecord.ID(recordName: "inkspring-schedule-v1") |
| 12 | private static let recordType = "InkspringSchedule" |
| 13 | private let container: CKContainer |
| 14 | |
| 15 | public init() { |
| 16 | container = CKContainer(identifier: Self.containerID) |
| 17 | } |
| 18 | |
| 19 | #if os(macOS) |
| 20 | public static var hasEntitlement: Bool { |
| 21 | guard let task = SecTaskCreateFromSelf(nil), |
| 22 | let identifiers = SecTaskCopyValueForEntitlement(task, "com.apple.developer.icloud-container-identifiers" as CFString, nil) as? [String] else { |
| 23 | return false |
| 24 | } |
| 25 | return identifiers.contains(containerID) |
| 26 | } |
| 27 | #endif |
| 28 | |
| 29 | private var database: CKDatabase { container.privateCloudDatabase } |
| 30 | |
| 31 | private func libraryID(_ workspaceID: UUID) -> CKRecord.ID { |
| 32 | CKRecord.ID(recordName: "inkspring-library-\(workspaceID.uuidString.lowercased())") |
| 33 | } |
| 34 | |
| 35 | public func loadLibrary(workspaceID: UUID, account: String) async throws -> CompanionLibrary? { |
| 36 | try await verifyLibraryWorkspace(workspaceID, account: account) |
| 37 | let library = try await fetch(libraryID(workspaceID)).map(decodeLibrary) |
| 38 | try await requireAccount(account) |
| 39 | return library |
| 40 | } |
| 41 | |
| 42 | public func updateLibrary(workspaceID: UUID, account: String, create: Bool = false, |
| 43 | _ change: (inout CompanionLibrary) throws -> Void) async throws -> CompanionLibrary { |
| 44 | try await verifyLibraryWorkspace(workspaceID, account: account) |
| 45 | return try await writeLibrary(workspaceID: workspaceID, account: account, create: create, change) |
| 46 | } |
| 47 | |
| 48 | /// Clear the previous owner's mirrored content before disconnecting or transferring the schedule. |
| 49 | public func clearLibrary(workspaceID: UUID, account: String) async throws { |
| 50 | do { |
| 51 | _ = try await writeLibrary(workspaceID: workspaceID, account: account, create: false) { library in |
| 52 | if library.enabled { library.clear() } |
| 53 | } |
| 54 | } catch CompanionLibraryError.disabled { |
| 55 | // Older Mac releases never created a library. |
| 56 | } |
| 57 | try await requireAccount(account) |
| 58 | do { _ = try await database.deleteRecordZone(withID: textZone(workspaceID)) } |
| 59 | catch let error as CKError where error.code == .zoneNotFound || error.code == .unknownItem {} |
| 60 | } |
| 61 | |
| 62 | private func textZone(_ workspaceID: UUID) -> CKRecordZone.ID { |
| 63 | .init(zoneName: "inkspring-text-\(workspaceID.uuidString.lowercased())") |
| 64 | } |
| 65 | |
| 66 | private func textIndex(_ zone: CKRecordZone.ID) -> CKRecord.ID { |
| 67 | .init(recordName: "index", zoneID: zone) |
| 68 | } |
| 69 | |
| 70 | private func textPart(_ number: Int, _ version: CompanionLibrary.TextVersion, _ zone: CKRecordZone.ID) -> CKRecord.ID { |
| 71 | .init(recordName: "\(version.digest)-\(number)", zoneID: zone) |
| 72 | } |
| 73 | |
| 74 | private func mediaPart(_ number: Int, _ requestID: UUID, _ workspaceID: UUID) -> CKRecord.ID { |
| 75 | .init(recordName: "media-\(requestID.uuidString.lowercased())-\(number)", zoneID: textZone(workspaceID)) |
| 76 | } |
| 77 | |
| 78 | public func stageLibraryMedia(_ data: Data, change: CompanionLibrary.Change, workspaceID: UUID, account: String) async throws { |
| 79 | guard change.valid, let media = change.mediaDraft, media.matches(data) else { throw CompanionLibraryError.invalid } |
| 80 | try await verifyLibraryWorkspace(workspaceID, account: account) |
| 81 | let zone = textZone(workspaceID) |
| 82 | if try await fetchTextIndex(zone) == nil { _ = try await database.save(CKRecordZone(zoneID: zone)) } |
| 83 | let size = CompanionLibrary.TextVersion.partSize |
| 84 | for start in stride(from: 0, to: media.version.partCount, by: 2) { |
| 85 | try Task.checkCancellation() |
| 86 | try await requireAccount(account) |
| 87 | let batch = (start..<min(start + 2, media.version.partCount)).map { number in |
| 88 | let record = CKRecord(recordType: Self.recordType, recordID: mediaPart(number, change.id, workspaceID)) |
| 89 | let offset = number * size |
| 90 | record["schedule"] = data.subdata(in: offset..<min(offset + size, data.count)) as CKRecordValue |
| 91 | return record |
| 92 | } |
| 93 | let result = try await database.modifyRecords(saving: batch, deleting: [], savePolicy: .changedKeys, atomically: true) |
| 94 | for record in batch { |
| 95 | guard let saved = result.saveResults[record.recordID] else { throw CompanionScheduleError.changed } |
| 96 | _ = try saved.get() |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | public func loadLibraryMedia(_ change: CompanionLibrary.Change, workspaceID: UUID, account: String) async throws -> Data { |
| 102 | guard change.valid, let media = change.mediaDraft else { throw CompanionLibraryError.invalid } |
| 103 | try await verifyLibraryWorkspace(workspaceID, account: account) |
| 104 | var data = Data() |
| 105 | for start in stride(from: 0, to: media.version.partCount, by: 2) { |
| 106 | try Task.checkCancellation() |
| 107 | let ids = (start..<min(start + 2, media.version.partCount)).map { mediaPart($0, change.id, workspaceID) } |
| 108 | let records = try await database.records(for: ids) |
| 109 | for id in ids { |
| 110 | guard let part = try records[id]?.get()["schedule"] as? Data, |
| 111 | part.count <= CompanionLibrary.TextVersion.partSize, |
| 112 | data.count + part.count <= media.byteCount else { throw CompanionLibraryError.invalid } |
| 113 | data.append(part) |
| 114 | } |
| 115 | } |
| 116 | try await requireAccount(account) |
| 117 | guard media.matches(data) else { throw CompanionLibraryError.invalid } |
| 118 | return data |
| 119 | } |
| 120 | |
| 121 | public func deleteLibraryMedia(_ change: CompanionLibrary.Change, workspaceID: UUID, account: String) async throws { |
| 122 | guard change.valid, let media = change.mediaDraft else { return } |
| 123 | try await verifyLibraryWorkspace(workspaceID, account: account) |
| 124 | let ids = (0..<media.version.partCount).map { mediaPart($0, change.id, workspaceID) } |
| 125 | _ = try await database.modifyRecords(saving: [], deleting: ids, atomically: false) |
| 126 | } |
| 127 | |
| 128 | public func loadLibraryText(_ version: CompanionLibrary.TextVersion, workspaceID: UUID, account: String) async throws -> Data { |
| 129 | try await verifyLibraryWorkspace(workspaceID, account: account) |
| 130 | let zone = textZone(workspaceID) |
| 131 | var data = Data() |
| 132 | guard version.partCount > 0 else { throw CompanionScheduleError.changed } |
| 133 | for start in stride(from: 0, to: version.partCount, by: 2) { |
| 134 | try Task.checkCancellation() |
| 135 | let ids = (start..<min(start + 2, version.partCount)).map { textPart($0, version, zone) } |
| 136 | let records = try await database.records(for: ids) |
| 137 | for id in ids { |
| 138 | guard let part = try records[id]?.get()["schedule"] as? Data else { throw CompanionScheduleError.changed } |
| 139 | data.append(part) |
| 140 | } |
| 141 | } |
| 142 | try await requireAccount(account) |
| 143 | return data |
| 144 | } |
| 145 | |
| 146 | // Register the generation before saving its parts so a later sync can remove |
| 147 | // incomplete generations as well as ones replaced by an edit. |
| 148 | public func stageLibraryText(_ data: Data, version: CompanionLibrary.TextVersion, workspaceID: UUID, account: String) async throws { |
| 149 | try await verifyLibraryWorkspace(workspaceID, account: account) |
| 150 | let zone = textZone(workspaceID) |
| 151 | let indexID = textIndex(zone) |
| 152 | let existing = try await fetchTextIndex(zone) |
| 153 | if existing == nil { |
| 154 | _ = try await database.save(CKRecordZone(zoneID: zone)) |
| 155 | } |
| 156 | let index = existing ?? CKRecord(recordType: Self.recordType, recordID: indexID) |
| 157 | var versions = try decodeTextIndex(index) |
| 158 | if !versions.contains(version) { |
| 159 | versions.append(version) |
| 160 | index["schedule"] = try JSONEncoder().encode(versions) as CKRecordValue |
| 161 | _ = try await database.save(index) |
| 162 | } |
| 163 | let size = CompanionLibrary.TextVersion.partSize |
| 164 | for start in stride(from: 0, to: version.partCount, by: 2) { |
| 165 | try Task.checkCancellation() |
| 166 | try await requireAccount(account) |
| 167 | let records = (start..<min(start + 2, version.partCount)).map { number in |
| 168 | let record = CKRecord(recordType: Self.recordType, recordID: textPart(number, version, zone)) |
| 169 | let offset = number * size |
| 170 | record["schedule"] = data.subdata(in: offset..<min(offset + size, data.count)) as CKRecordValue |
| 171 | return record |
| 172 | } |
| 173 | let saved = try await database.modifyRecords(saving: records, deleting: [], savePolicy: .changedKeys, atomically: true) |
| 174 | for record in records { |
| 175 | guard let result = saved.saveResults[record.recordID] else { throw CompanionScheduleError.changed } |
| 176 | _ = try result.get() |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | public func pruneLibraryText(keeping version: CompanionLibrary.TextVersion?, workspaceID: UUID, account: String) async throws { |
| 182 | try await verifyLibraryWorkspace(workspaceID, account: account) |
| 183 | let zone = textZone(workspaceID) |
| 184 | guard let index = try await fetchTextIndex(zone) else { return } |
| 185 | let obsolete = try decodeTextIndex(index).filter { $0 != version } |
| 186 | guard !obsolete.isEmpty else { return } |
| 187 | for old in obsolete { |
| 188 | for start in stride(from: 0, to: old.partCount, by: 100) { |
| 189 | try await requireAccount(account) |
| 190 | let ids = (start..<min(start + 100, old.partCount)).map { textPart($0, old, zone) } |
| 191 | let removed = try await database.modifyRecords(saving: [], deleting: ids, atomically: false) |
| 192 | for id in ids { |
| 193 | do { |
| 194 | guard let result = removed.deleteResults[id] else { throw CompanionScheduleError.changed } |
| 195 | try result.get() |
| 196 | } catch let error as CKError where error.code == .unknownItem {} |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | index["schedule"] = try JSONEncoder().encode(version.map { [$0] } ?? []) as CKRecordValue |
| 201 | try await requireAccount(account) |
| 202 | _ = try await database.save(index) |
| 203 | } |
| 204 | |
| 205 | private func fetchTextIndex(_ zone: CKRecordZone.ID) async throws -> CKRecord? { |
| 206 | do { return try await fetch(textIndex(zone)) } |
| 207 | catch let error as CKError where error.code == .zoneNotFound { return nil } |
| 208 | } |
| 209 | |
| 210 | private func decodeTextIndex(_ record: CKRecord) throws -> [CompanionLibrary.TextVersion] { |
| 211 | guard let data = record["schedule"] as? Data else { return [] } |
| 212 | return try JSONDecoder().decode([CompanionLibrary.TextVersion].self, from: data) |
| 213 | } |
| 214 | |
| 215 | private func verifyLibraryWorkspace(_ workspaceID: UUID, account: String) async throws { |
| 216 | guard let schedule = try await load(confirmedAccount: account), schedule.sharing, |
| 217 | schedule.workspaceID == workspaceID else { throw CompanionLibraryError.disabled } |
| 218 | } |
| 219 | |
| 220 | private func writeLibrary(workspaceID: UUID, account: String, create: Bool, |
| 221 | _ change: (inout CompanionLibrary) throws -> Void) async throws -> CompanionLibrary { |
| 222 | let id = libraryID(workspaceID) |
| 223 | for _ in 0..<4 { |
| 224 | try await requireAccount(account) |
| 225 | let current = try await fetch(id) |
| 226 | guard current != nil || create else { throw CompanionLibraryError.disabled } |
| 227 | let record = current ?? CKRecord(recordType: Self.recordType, recordID: id) |
| 228 | let previous = try current.map(decodeLibrary) ?? CompanionLibrary(workspaceID: workspaceID) |
| 229 | guard previous.workspaceID == workspaceID else { throw CompanionScheduleError.changed } |
| 230 | var library = previous |
| 231 | try change(&library) |
| 232 | if current != nil && library == previous { return library } |
| 233 | let bytes = try JSONEncoder().encode(library) |
| 234 | // The CloudKit record limit is 1 MB, including record overhead. |
| 235 | // Allow the library index and outbox to share this record. |
| 236 | guard bytes.count < 800_000 else { throw CompanionScheduleError.oversized } |
| 237 | record["schedule"] = bytes as CKRecordValue |
| 238 | try await requireAccount(account) |
| 239 | do { |
| 240 | let result = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .ifServerRecordUnchanged) |
| 241 | guard let saved = result.saveResults[id] else { throw CompanionScheduleError.changed } |
| 242 | _ = try saved.get() |
| 243 | try await requireAccount(account) |
| 244 | return library |
| 245 | } catch let error as CKError where error.code == .serverRecordChanged || |
| 246 | (error.partialErrorsByItemID?[id] as? CKError)?.code == .serverRecordChanged { |
| 247 | continue |
| 248 | } |
| 249 | } |
| 250 | throw CompanionScheduleError.changed |
| 251 | } |
| 252 | |
| 253 | private func decodeLibrary(_ record: CKRecord) throws -> CompanionLibrary { |
| 254 | guard let data = record["schedule"] as? Data else { throw CompanionScheduleError.changed } |
| 255 | return try JSONDecoder().decode(CompanionLibrary.self, from: data) |
| 256 | } |
| 257 | |
| 258 | public func accountKey() async throws -> String { |
| 259 | try await checkAccount() |
| 260 | let accountID = try await container.userRecordID() |
| 261 | return SHA256.hash(data: Data(accountID.recordName.utf8)).map { String(format: "%02x", $0) }.joined() |
| 262 | } |
| 263 | |
| 264 | public func load(confirmedAccount: String) async throws -> CompanionSchedule? { |
| 265 | try await requireAccount(confirmedAccount) |
| 266 | let schedule = try await fetch().map(decode) |
| 267 | try await requireAccount(confirmedAccount) |
| 268 | return schedule |
| 269 | } |
| 270 | |
| 271 | @discardableResult |
| 272 | public func update(workspaceID: UUID, createIfMissing: Bool = false, expectedAccount: String, |
| 273 | _ mutation: (inout CompanionSchedule) throws -> Void) async throws -> CompanionSchedule { |
| 274 | try await requireAccount(expectedAccount) |
| 275 | for _ in 0..<4 { |
| 276 | let current = try await fetch() |
| 277 | try await requireAccount(expectedAccount) |
| 278 | let record: CKRecord |
| 279 | var schedule: CompanionSchedule |
| 280 | if let current { |
| 281 | record = current |
| 282 | schedule = try decode(current) |
| 283 | guard schedule.workspaceID == workspaceID else { throw CompanionScheduleError.anotherMac } |
| 284 | } else { |
| 285 | guard createIfMissing else { throw CompanionScheduleError.missing } |
| 286 | record = CKRecord(recordType: Self.recordType, recordID: Self.recordID) |
| 287 | schedule = CompanionSchedule(workspaceID: workspaceID, posts: []) |
| 288 | } |
| 289 | let previous = schedule |
| 290 | try mutation(&schedule) |
| 291 | if record.recordChangeTag != nil && schedule == previous { return schedule } |
| 292 | let bytes = try JSONEncoder().encode(schedule) |
| 293 | guard bytes.count < CompanionSchedule.maxEncodedSize else { throw CompanionScheduleError.oversized } |
| 294 | record["schedule"] = bytes as CKRecordValue |
| 295 | do { |
| 296 | let result = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .ifServerRecordUnchanged) |
| 297 | guard let saved = result.saveResults[Self.recordID] else { throw CompanionScheduleError.changed } |
| 298 | _ = try saved.get() |
| 299 | try await requireAccount(expectedAccount) |
| 300 | return schedule |
| 301 | } catch let error as CKError where error.code == .serverRecordChanged || |
| 302 | (error.partialErrorsByItemID?[Self.recordID] as? CKError)?.code == .serverRecordChanged { |
| 303 | continue |
| 304 | } |
| 305 | } |
| 306 | throw CompanionScheduleError.changed |
| 307 | } |
| 308 | |
| 309 | private func checkAccount() async throws { |
| 310 | let status = try await container.accountStatus() |
| 311 | if status == .temporarilyUnavailable { throw CompanionScheduleError.cloudTemporarilyUnavailable } |
| 312 | guard status == .available else { throw CompanionScheduleError.cloudUnavailable } |
| 313 | } |
| 314 | |
| 315 | private func requireAccount(_ expected: String) async throws { |
| 316 | guard try await accountKey() == expected else { throw CompanionScheduleError.accountChanged } |
| 317 | } |
| 318 | |
| 319 | private func fetch(_ id: CKRecord.ID = Self.recordID) async throws -> CKRecord? { |
| 320 | do { return try await database.record(for: id) } |
| 321 | catch let error as CKError where error.code == .unknownItem { return nil } |
| 322 | } |
| 323 | |
| 324 | private func decode(_ record: CKRecord) throws -> CompanionSchedule { |
| 325 | guard let data = record["schedule"] as? Data else { throw CompanionScheduleError.changed } |
| 326 | return try JSONDecoder().decode(CompanionSchedule.self, from: data) |
| 327 | } |
| 328 | } |