Crossmate/Services/CloudService.swift (20855B)
1import CloudKit
2
3enum CloudFailureCopy {
4 static let quotaJoinTitle = "Puzzle Unavailable"
5 static let quotaJoinBody =
6 "The puzzle could not be joined properly. This could be because your friend's iCloud storage is full."
7
8
9
10
11
12
13
14 static func joinFailure(for error: Error) -> (title: String, body: String) {
15 guard let accepted = error as? AcceptedShareError else {
16 return ("Accepting Failed", error.localizedDescription)
17 }
18 guard accepted.isQuotaExceeded else {
19 return ("Puzzle Unavailable", error.localizedDescription)
20 }
21 return (quotaJoinTitle, quotaJoinBody)
22 }
23}
24
25extension Notification.Name {
26 static let cloudShareAcceptanceStarted = Notification.Name("cloudShareAcceptanceStarted")
27 static let cloudShareAcceptanceCompleted = Notification.Name("cloudShareAcceptanceCompleted")
28}
29
30
31enum CloudServiceError: Error, LocalizedError, Equatable {
32
33
34
35 case containerVersionMismatch
36
37 var errorDescription: String? {
38 switch self {
39 case .containerVersionMismatch:
40 return "This game is from a different version of Crossmate. "
41 + "Make sure you and the other player are both on the latest version."
42 }
43 }
44}
45
46
47
48
49struct AcceptedShareError: Error, LocalizedError {
50 enum Kind: Equatable {
51 case removed
52 case temporarilyUnavailable
53 case unavailable
54 }
55
56 let kind: Kind
57 let underlyingError: Error
58
59 var errorDescription: String? {
60 if isQuotaExceeded { return CloudFailureCopy.quotaJoinBody }
61 return underlyingError.localizedDescription
62 }
63
64 var isQuotaExceeded: Bool {
65 CloudService.cloudErrorCode(underlyingError) == .quotaExceeded
66 }
67}
68
69@MainActor
70final class CloudService {
71 private let ckContainer: CKContainer
72 private let syncEngine: SyncEngine
73 private let syncMonitor: SyncMonitor
74 private let store: GameStore
75 private let shareController: ShareController
76
77
78
79
80 var onShareJoined: ((UUID) async -> Void)?
81
82 init(
83 container: CKContainer,
84 syncEngine: SyncEngine,
85 syncMonitor: SyncMonitor,
86 store: GameStore,
87 shareController: ShareController
88 ) {
89 self.ckContainer = container
90 self.syncEngine = syncEngine
91 self.syncMonitor = syncMonitor
92 self.store = store
93 self.shareController = shareController
94 }
95
96
97
98
99
100 enum AcceptOutcome {
101
102 case opened
103
104
105
106 case pendingSync
107
108 case cancelled
109 }
110
111
112
113
114
115 @discardableResult
116 func acceptShare(
117 url: URL,
118 prefetchedPuzzleSource: String? = nil,
119 prefetchedNotification: String? = nil
120 ) async throws -> AcceptOutcome {
121 let metadata = try await withCheckedThrowingContinuation {
122 (cont: CheckedContinuation<CKShare.Metadata, Error>) in
123 var found: CKShare.Metadata?
124 let op = CKFetchShareMetadataOperation(shareURLs: [url])
125 op.shouldFetchRootRecord = false
126 op.perShareMetadataResultBlock = { _, result in
127 if case .success(let m) = result { found = m }
128 }
129 op.fetchShareMetadataResultBlock = { result in
130 switch result {
131 case .success:
132 if let found {
133 cont.resume(returning: found)
134 } else {
135 cont.resume(throwing: CKError(.unknownItem))
136 }
137 case .failure(let error):
138 cont.resume(throwing: error)
139 }
140 }
141 ckContainer.add(op)
142 }
143 return try await acceptShare(
144 metadata: metadata,
145 prefetchedPuzzleSource: prefetchedPuzzleSource,
146 prefetchedNotification: prefetchedNotification
147 )
148 }
149
150 @discardableResult
151 func acceptShare(
152 metadata: CKShare.Metadata,
153 prefetchedPuzzleSource: String? = nil,
154 prefetchedNotification: String? = nil
155 ) async throws -> AcceptOutcome {
156 NotificationCenter.default.post(name: .cloudShareAcceptanceStarted, object: nil)
157
158 guard metadata.containerIdentifier == ckContainer.containerIdentifier else {
159 syncMonitor.note(
160 "acceptShare: container mismatch — metadata=\(metadata.containerIdentifier) " +
161 "expected=\(ckContainer.containerIdentifier ?? "nil")"
162 )
163 throw CloudServiceError.containerVersionMismatch
164 }
165
166
167
168
169
170 let sharedZoneID = metadata.share.recordID.zoneID
171 let sharedGameID = RecordSerializer.gameID(
172 fromGameRecordName: sharedZoneID.zoneName
173 )
174 var shareWasAccepted = false
175 do {
176 try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
177 let op = CKAcceptSharesOperation(shareMetadatas: [metadata])
178 op.acceptSharesResultBlock = { result in cont.resume(with: result) }
179 ckContainer.add(op)
180 }
181 shareWasAccepted = true
182 if let sharedGameID {
183
184
185
186
187
188
189 var constructed = false
190 if let prefetchedPuzzleSource, !prefetchedPuzzleSource.isEmpty {
191 do {
192 try store.constructJoinedGame(
193 gameID: sharedGameID,
194 zoneID: sharedZoneID,
195 source: prefetchedPuzzleSource,
196 notification: prefetchedNotification
197 )
198 constructed = true
199 syncMonitor.note("Share accepted — built game from invite; fetching remainder in background")
200 } catch {
201 syncMonitor.note("acceptShare: invite-source construct failed — \(error); fetching inline")
202 }
203 }
204 if constructed {
205 Task { @MainActor [weak self] in
206 guard let self else { return }
207 _ = await self.syncMonitor.run("share-accept background remainder fetch") {
208 try await self.syncEngine.fetchAcceptedSharedGameDirect(
209 gameID: sharedGameID,
210 zoneID: sharedZoneID
211 )
212 }
213 }
214 } else {
215 syncMonitor.note("Share accepted — fetching shared game")
216 do {
217 _ = try await syncEngine.fetchAcceptedSharedGameDirect(
218 gameID: sharedGameID,
219 zoneID: sharedZoneID
220 )
221 } catch {
222 guard Self.isRetryableJoinError(error) else { throw error }
223 syncMonitor.note(
224 "acceptShare: initial shared-game fetch will retry — " +
225 Self.describeCloudError(error)
226 )
227 }
228 }
229 } else {
230 syncMonitor.note("Share accepted — discovering shared zone")
231 await syncMonitor.run("share-accept shared discovery") {
232 _ = try await syncEngine.discoverNewZonesDirect(scope: .shared)
233 }
234 }
235
236
237
238
239
240 let joinedGameID = try await waitForPlayablePuzzle(
241 gameID: sharedGameID,
242 zoneID: sharedZoneID
243 )
244
245
246
247 guard !Task.isCancelled else { return .cancelled }
248 if let joinedGameID {
249 try await shareController.confirmSeatAfterJoin(gameID: joinedGameID)
250 }
251 NotificationCenter.default.post(
252 name: .cloudShareAcceptanceCompleted,
253 object: nil,
254 userInfo: joinedGameID.map { ["gameID": $0] }
255 )
256 if let joinedGameID, let onShareJoined {
257 await onShareJoined(joinedGameID)
258 }
259 return joinedGameID == nil ? .pendingSync : .opened
260 } catch {
261 syncMonitor.recordError("acceptShare", error)
262 if shareWasAccepted, !(error is AcceptedShareError) {
263 throw AcceptedShareError(
264 kind: Self.joinFailureKind(for: error),
265 underlyingError: error
266 )
267 }
268 throw error
269 }
270 }
271
272
273
274
275 private static let joinSyncTimeout: TimeInterval = 30
276 private static let joinSyncPollInterval: Duration = .seconds(1)
277
278
279
280
281 private static let joinSyncRefetchInterval: TimeInterval = 3
282
283
284
285
286
287
288
289
290 private func waitForPlayablePuzzle(
291 gameID: UUID?,
292 zoneID: CKRecordZone.ID?
293 ) async throws -> UUID? {
294 guard let gameID else { return nil }
295 if store.joinedSharedGameIDs().contains(gameID) { return gameID }
296 let deadline = Date().addingTimeInterval(Self.joinSyncTimeout)
297
298
299
300
301 var nextRefetch = Date().addingTimeInterval(Self.joinSyncRefetchInterval)
302 var lastRetryableError: Error?
303 while Date() < deadline {
304 if store.joinedSharedGameIDs().contains(gameID) { return gameID }
305
306 if Date() >= nextRefetch {
307 if let zoneID {
308
309
310
311 do {
312 _ = try await syncEngine.fetchAcceptedSharedGameDirect(
313 gameID: gameID,
314 zoneID: zoneID,
315 onlyGame: true
316 )
317 lastRetryableError = nil
318 } catch {
319 guard Self.isRetryableJoinError(error) else { throw error }
320 lastRetryableError = error
321 }
322 } else {
323 do {
324 _ = try await syncEngine.fetchGameDirect(
325 scope: .shared,
326 gameID: gameID
327 )
328 lastRetryableError = nil
329 } catch {
330 guard Self.isRetryableJoinError(error) else { throw error }
331 lastRetryableError = error
332 }
333 }
334 let retryAfter = lastRetryableError.flatMap(Self.retryAfter)
335 nextRefetch = Date().addingTimeInterval(
336 max(Self.joinSyncRefetchInterval, retryAfter ?? 0)
337 )
338 if store.joinedSharedGameIDs().contains(gameID) { return gameID }
339 }
340
341 do {
342 try await Task.sleep(for: Self.joinSyncPollInterval)
343 } catch {
344 return nil
345 }
346 }
347 syncMonitor.note(
348 "acceptShare: puzzle not playable within \(Int(Self.joinSyncTimeout))s " +
349 "for \(gameID.uuidString)"
350 )
351 if let lastRetryableError { throw lastRetryableError }
352 return nil
353 }
354
355 nonisolated static func joinFailureKind(for error: Error) -> AcceptedShareError.Kind {
356 let code = cloudErrorCode(error)
357 if code == .unknownItem || code == .zoneNotFound || code == .userDeletedZone {
358 return .removed
359 }
360 return isRetryableJoinError(error) ? .temporarilyUnavailable : .unavailable
361 }
362
363 nonisolated static func isRetryableJoinError(_ error: Error) -> Bool {
364 switch cloudErrorCode(error) {
365 case .internalError,
366 .networkUnavailable,
367 .networkFailure,
368 .serviceUnavailable,
369 .requestRateLimited,
370 .zoneBusy,
371 .operationCancelled,
372 .serverResponseLost,
373 .accountTemporarilyUnavailable:
374 return true
375 default:
376 return false
377 }
378 }
379
380 nonisolated static func retryAfter(_ error: Error) -> TimeInterval? {
381 let value = (unwrappedCloudError(error) as NSError)
382 .userInfo[CKErrorRetryAfterKey]
383 if let number = value as? NSNumber { return max(0, number.doubleValue) }
384 if let interval = value as? TimeInterval { return max(0, interval) }
385 return nil
386 }
387
388 nonisolated static func cloudErrorCode(_ error: Error) -> CKError.Code? {
389 let nsError = unwrappedCloudError(error) as NSError
390 guard nsError.domain == CKErrorDomain else { return nil }
391 return CKError.Code(rawValue: nsError.code)
392 }
393
394 nonisolated private static func unwrappedCloudError(_ error: Error) -> Error {
395 if let accepted = error as? AcceptedShareError {
396 return unwrappedCloudError(accepted.underlyingError)
397 }
398 return error
399 }
400
401 nonisolated private static func describeCloudError(_ error: Error) -> String {
402 let nsError = unwrappedCloudError(error) as NSError
403 let retry = retryAfter(error).map { " retryAfter=\($0)s" } ?? ""
404 return "domain=\(nsError.domain) code=\(nsError.code)\(retry) " +
405 nsError.localizedDescription
406 }
407
408 func resetAllData() async throws {
409 await syncEngine.resetSyncState()
410
411 async let privateCleanup: Void = deleteAllPrivateZones()
412 async let sharedCleanup: Void = leaveAllSharedZones()
413 _ = await (privateCleanup, sharedCleanup)
414
415 try store.resetAllData()
416 UserDefaults.standard.removeObject(forKey: "gamePlayerColors")
417 BadgeState.reset()
418 syncMonitor.note("Database reset — all games and sync state cleared")
419 }
420
421
422
423
424
425
426
427
428
429 func purgeLocalData() async throws {
430 try store.resetAllData()
431 UserDefaults.standard.removeObject(forKey: "gamePlayerColors")
432 BadgeState.reset()
433 await syncEngine.resetSyncState()
434 syncMonitor.note("Local store purged for account switch — previous account untouched in CloudKit")
435 }
436
437 private func deleteAllPrivateZones() async {
438 do {
439 let zones = try await ckContainer.privateCloudDatabase.allRecordZones()
440 guard !zones.isEmpty else { return }
441 let ids = zones.map(\.zoneID)
442 try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
443 let op = CKModifyRecordZonesOperation(
444 recordZonesToSave: nil,
445 recordZoneIDsToDelete: ids
446 )
447 op.modifyRecordZonesResultBlock = { result in cont.resume(with: result) }
448 ckContainer.privateCloudDatabase.add(op)
449 }
450 } catch {
451 syncMonitor.note("reset: private zone cleanup failed — \(error)")
452 }
453 }
454
455 private func leaveAllSharedZones() async {
456 do {
457 let zones = try await ckContainer.sharedCloudDatabase.allRecordZones()
458 for zone in zones {
459 try await ckContainer.sharedCloudDatabase.deleteRecordZone(withID: zone.zoneID)
460 }
461 } catch {
462 syncMonitor.note("reset: shared zone cleanup failed — \(error)")
463 }
464 }
465}