Crossmate/Sync/Archive.swift (46053B)
1import CloudKit
2import Compression
3import CoreData
4import CryptoKit
5import Foundation
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29enum Archive {
30
31
32 static let recordType = "Chronicle"
33
34 static let legacyRecordType = "Archive"
35 static let zoneName = "completed-archives"
36 static let payloadKey = "payload"
37
38
39
40
41
42 static let payloadDesiredKeys = ["completedAt", payloadKey]
43
44
45
46
47
48
49 static let maxCellsAssetBytes = 2_097_152
50
51
52
53
54
55
56 static let maxJournalsAssetBytes = 8_388_608
57
58
59
60
61
62 static let maxPayloadAssetBytes = 12_582_912
63 static let maxDecodedPayloadBytes = 16_777_216
64 static let currentPayloadFormatVersion = 3
65 private static let maxParticipantCount = 64
66
67
68
69 static let maxCellCount = XD.maxGridDimension * XD.maxGridDimension
70
71
72
73
74 static let maxJournalDeviceCount = 64
75
76
77
78
79 private static let namespace = UUID(uuidString: "1F8B0E2A-3C4D-5E6F-7A8B-9C0D1E2F3A4B")!
80
81
82
83
84
85
86
87
88 static func archiveGameID(for originalGameID: UUID) -> UUID {
89 var hasher = Insecure.SHA1()
90 hasher.update(data: withUnsafeBytes(of: namespace.uuid) { Data($0) })
91 hasher.update(data: withUnsafeBytes(of: originalGameID.uuid) { Data($0) })
92 let digest = Array(hasher.finalize())
93 var bytes = Array(digest.prefix(16))
94
95 bytes[6] = (bytes[6] & 0x0F) | 0x50
96 bytes[8] = (bytes[8] & 0x3F) | 0x80
97 let uuid = (
98 bytes[0], bytes[1], bytes[2], bytes[3],
99 bytes[4], bytes[5], bytes[6], bytes[7],
100 bytes[8], bytes[9], bytes[10], bytes[11],
101 bytes[12], bytes[13], bytes[14], bytes[15]
102 )
103 return UUID(uuid: uuid)
104 }
105
106 static var zoneID: CKRecordZone.ID {
107 CKRecordZone.ID(
108 zoneName: zoneName,
109 ownerName: CKCurrentUserDefaultName
110 )
111 }
112
113
114
115 static func legacyZoneID(forOriginalGameID gameID: UUID) -> CKRecordZone.ID {
116 CKRecordZone.ID(
117 zoneName: "archive-\(gameID.uuidString)",
118 ownerName: CKCurrentUserDefaultName
119 )
120 }
121
122 static func recordName(forOriginalGameID gameID: UUID) -> String {
123 "chronicle-\(gameID.uuidString)"
124 }
125
126 static func legacyRecordName(forOriginalGameID gameID: UUID) -> String {
127 "archive-\(gameID.uuidString)"
128 }
129
130
131
132 static func originalGameID(fromName name: String) -> UUID? {
133 for prefix in ["chronicle-", "archive-"] where name.hasPrefix(prefix) {
134 return UUID(uuidString: String(name.dropFirst(prefix.count)))
135 }
136 return nil
137 }
138
139
140
141
142
143
144 static func mirrorReadState(from live: GameEntity, to chronicle: GameEntity) {
145 if let latest = live.latestOtherMoveAt,
146 (chronicle.latestOtherMoveAt ?? .distantPast) < latest {
147 chronicle.latestOtherMoveAt = latest
148 }
149 if let readThrough = live.readThroughAt,
150 (chronicle.readThroughAt ?? .distantPast) < readThrough {
151 chronicle.readThroughAt = readThrough
152 }
153 }
154
155 static func isArchiveZone(_ zoneName: String) -> Bool {
156 zoneName == self.zoneName || zoneName.hasPrefix("archive-")
157 }
158
159
160
161
162
163 struct Cell: Codable, Equatable {
164 let row: Int16
165 let col: Int16
166 let letter: String
167 let markCode: Int16
168 let letterAuthorID: String?
169 }
170
171
172
173
174 struct Participant: Codable, Equatable {
175 let authorID: String
176 let name: String?
177 }
178
179 private static func encodeCells(_ cells: [Cell]) throws -> Data {
180 try JSONEncoder().encode(cells.sorted {
181 ($0.row, $0.col) < ($1.row, $1.col)
182 })
183 }
184
185
186
187
188 enum LimitError: Error, CustomStringConvertible {
189 case tooManyCells(count: Int)
190 case tooManyDeviceJournals(count: Int)
191 case tooManyParticipants(count: Int)
192
193 var description: String {
194 switch self {
195 case .tooManyCells(let count):
196 return "cells asset exceeds \(maxCellCount) cells (\(count))"
197 case .tooManyDeviceJournals(let count):
198 return "journals asset exceeds \(maxJournalDeviceCount) device journals (\(count))"
199 case .tooManyParticipants(let count):
200 return "archive payload exceeds \(maxParticipantCount) participants (\(count))"
201 }
202 }
203 }
204
205 private static func decodeCells(_ data: Data) throws -> [Cell] {
206 let cells = try JSONDecoder().decode([Cell].self, from: data)
207 guard cells.count <= maxCellCount else {
208 throw LimitError.tooManyCells(count: cells.count)
209 }
210 return cells
211 }
212
213
214
215
216
217
218 private struct DeviceJournalWire: Codable {
219 let authorID: String
220 let deviceID: String
221 let entries: Data
222 }
223
224
225
226
227
228
229 private struct Blob: Codable {
230 let formatVersion: Int
231 let originalGameID: UUID
232 let archiveGameID: UUID
233 let title: String
234 let puzzleSource: String
235 let completedAt: Date
236 let completedBy: String?
237 let solveSeconds: Int
238 let replayAvailable: Bool
239
240
241 let replayMissingDeviceCount: Int?
242 let cells: [Cell]
243 let journals: [DeviceJournalWire]
244
245
246 let wasShared: Bool?
247 let participants: [Participant]?
248 }
249
250 private static let envelopeMagic = Data("CMARCH01".utf8)
251 private static let envelopeHeaderBytes = 8 + MemoryLayout<UInt64>.size + 32
252
253 enum PayloadError: Error, CustomStringConvertible {
254 case oversizedCompressedPayload(bytes: Int)
255 case oversizedDecodedPayload(bytes: Int)
256 case malformedEnvelope
257 case unsupportedFormat(Int)
258 case decompressionFailed
259 case digestMismatch
260 case identityMismatch
261 case oversizedPuzzleSource(bytes: Int)
262
263 var description: String {
264 switch self {
265 case .oversizedCompressedPayload(let bytes):
266 return "archive payload exceeds \(maxPayloadAssetBytes) compressed bytes (\(bytes))"
267 case .oversizedDecodedPayload(let bytes):
268 return "archive payload exceeds \(maxDecodedPayloadBytes) decoded bytes (\(bytes))"
269 case .malformedEnvelope:
270 return "archive payload envelope is malformed"
271 case .unsupportedFormat(let version):
272 return "archive payload format \(version) is unsupported"
273 case .decompressionFailed:
274 return "archive payload decompression failed"
275 case .digestMismatch:
276 return "archive payload digest does not match"
277 case .identityMismatch:
278 return "archive payload identity does not match its record"
279 case .oversizedPuzzleSource(let bytes):
280 return "archive puzzle source exceeds \(XD.maxSourceBytes) bytes (\(bytes))"
281 }
282 }
283 }
284
285 private static func encodeEnvelope(_ decoded: Data) throws -> Data {
286 guard decoded.count <= maxDecodedPayloadBytes else {
287 throw PayloadError.oversizedDecodedPayload(bytes: decoded.count)
288 }
289 let compressed = try (decoded as NSData).compressed(using: .lzfse) as Data
290 var result = Data()
291 result.reserveCapacity(envelopeHeaderBytes + compressed.count)
292 result.append(envelopeMagic)
293 var length = UInt64(decoded.count).bigEndian
294 withUnsafeBytes(of: &length) { result.append(contentsOf: $0) }
295 result.append(contentsOf: SHA256.hash(data: decoded))
296 result.append(compressed)
297 guard result.count <= maxPayloadAssetBytes else {
298 throw PayloadError.oversizedCompressedPayload(bytes: result.count)
299 }
300 return result
301 }
302
303 private static func decodeEnvelope(_ envelope: Data) throws -> Data {
304 guard envelope.count >= envelopeHeaderBytes,
305 envelope.prefix(envelopeMagic.count) == envelopeMagic
306 else { throw PayloadError.malformedEnvelope }
307
308 let lengthRange = envelopeMagic.count..<(envelopeMagic.count + MemoryLayout<UInt64>.size)
309 let decodedLength = envelope[lengthRange].reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }
310 guard decodedLength <= UInt64(maxDecodedPayloadBytes),
311 let decodedCount = Int(exactly: decodedLength),
312 decodedCount > 0
313 else {
314 throw PayloadError.oversizedDecodedPayload(bytes: Int(clamping: decodedLength))
315 }
316
317 let digestStart = lengthRange.upperBound
318 let digestEnd = digestStart + 32
319 let expectedDigest = envelope[digestStart..<digestEnd]
320 let compressed = envelope[digestEnd...]
321 guard !compressed.isEmpty else { throw PayloadError.malformedEnvelope }
322 var decoded = Data(count: decodedCount)
323 let written = decoded.withUnsafeMutableBytes { destination in
324 compressed.withUnsafeBytes { source in
325 compression_decode_buffer(
326 destination.bindMemory(to: UInt8.self).baseAddress!,
327 decodedCount,
328 source.bindMemory(to: UInt8.self).baseAddress!,
329 compressed.count,
330 nil,
331 COMPRESSION_LZFSE
332 )
333 }
334 }
335 guard written == decodedCount else { throw PayloadError.decompressionFailed }
336 guard Data(SHA256.hash(data: decoded)) == expectedDigest else {
337 throw PayloadError.digestMismatch
338 }
339 return decoded
340 }
341
342 private static func encodeJournals(_ journals: [DeviceJournal]) throws -> Data {
343 try JSONEncoder().encode(journalWire(journals))
344 }
345
346 private static func journalWire(_ journals: [DeviceJournal]) throws -> [DeviceJournalWire] {
347 try journals
348 .sorted { ($0.key.authorID, $0.key.deviceID) < ($1.key.authorID, $1.key.deviceID) }
349 .map {
350 DeviceJournalWire(
351 authorID: $0.key.authorID,
352 deviceID: $0.key.deviceID,
353 entries: try JournalCodec.encode($0.entries)
354 )
355 }
356 }
357
358 private static func decodeJournals(_ data: Data) throws -> [DeviceJournal] {
359 let wire = try JSONDecoder().decode([DeviceJournalWire].self, from: data)
360 return try decodeJournals(wire)
361 }
362
363 private static func decodeJournals(_ wire: [DeviceJournalWire]) throws -> [DeviceJournal] {
364 guard wire.count <= maxJournalDeviceCount else {
365 throw LimitError.tooManyDeviceJournals(count: wire.count)
366 }
367 return wire.map {
368 DeviceJournal(
369 key: JournalDeviceKey(authorID: $0.authorID, deviceID: $0.deviceID),
370
371
372
373 entries: (try? JournalCodec.decode($0.entries)) ?? []
374 )
375 }
376 }
377
378
379
380
381
382 struct Snapshot {
383 let originalGameID: UUID
384 let title: String
385 let puzzleSource: String
386 let completedAt: Date
387 let completedBy: String?
388
389
390
391
392
393
394 let solveSeconds: Int
395 let wasShared: Bool
396 let participants: [Participant]
397 let cells: [Cell]
398
399
400
401
402 let journal: [DeviceJournal]
403
404 init(
405 originalGameID: UUID,
406 title: String,
407 puzzleSource: String,
408 completedAt: Date,
409 completedBy: String?,
410 solveSeconds: Int,
411 wasShared: Bool = false,
412 participants: [Participant] = [],
413 cells: [Cell],
414 journal: [DeviceJournal]
415 ) {
416 self.originalGameID = originalGameID
417 self.title = title
418 self.puzzleSource = puzzleSource
419 self.completedAt = completedAt
420 self.completedBy = completedBy
421 self.solveSeconds = solveSeconds
422 self.wasShared = wasShared
423 self.participants = participants
424 self.cells = cells
425 self.journal = journal
426 }
427 }
428
429
430
431
432
433
434
435 static func snapshot(
436 forGameID gameID: UUID,
437 originalGameID: UUID? = nil,
438 in ctx: NSManagedObjectContext
439 ) -> Snapshot? {
440 let req = NSFetchRequest<GameEntity>(entityName: "GameEntity")
441 req.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
442 req.fetchLimit = 1
443 guard let entity = try? ctx.fetch(req).first,
444 let completedAt = entity.completedAt,
445 let source = entity.puzzleSource, !source.isEmpty
446 else { return nil }
447
448 let cellEntities = (entity.cells as? Set<CellEntity>) ?? []
449 let cells = cellEntities.map {
450 Cell(
451 row: $0.row,
452 col: $0.col,
453 letter: $0.letter ?? "",
454 markCode: $0.markCode,
455 letterAuthorID: $0.letterAuthorID
456 )
457 }
458
459 let journal = localDeviceJournals(forGameID: gameID, in: ctx)
460 var participantsByAuthor: [String: Participant] = [:]
461 let playerReq = NSFetchRequest<PlayerEntity>(entityName: "PlayerEntity")
462 playerReq.predicate = NSPredicate(format: "game == %@", entity)
463 for player in (try? ctx.fetch(playerReq)) ?? [] {
464 guard let authorID = player.authorID, !authorID.isEmpty else { continue }
465 let trimmedName = player.name?.trimmingCharacters(
466 in: .whitespacesAndNewlines
467 )
468 participantsByAuthor[authorID] = Participant(
469 authorID: authorID,
470 name: trimmedName?.isEmpty == false ? trimmedName : nil
471 )
472 }
473 for encoded in [entity.archiveParticipants, entity.shareParticipants] {
474 for authorID in encoded?.split(separator: ",").map(String.init) ?? [] {
475 guard !authorID.isEmpty else { continue }
476 participantsByAuthor[authorID] = participantsByAuthor[authorID]
477 ?? Participant(authorID: authorID, name: nil)
478 }
479 }
480 for deviceJournal in journal where !deviceJournal.key.authorID.isEmpty {
481 let authorID = deviceJournal.key.authorID
482 participantsByAuthor[authorID] = participantsByAuthor[authorID]
483 ?? Participant(authorID: authorID, name: nil)
484 }
485
486 return Snapshot(
487 originalGameID: originalGameID ?? gameID,
488 title: entity.title ?? "",
489 puzzleSource: source,
490 completedAt: completedAt,
491 completedBy: entity.completedBy,
492 solveSeconds: solveSeconds(forGameID: gameID, asOf: completedAt, in: ctx),
493 wasShared: entity.ckShareRecordName != nil || entity.databaseScope == 1,
494 participants: participantsByAuthor.values.sorted {
495 $0.authorID < $1.authorID
496 },
497 cells: cells,
498 journal: journal
499 )
500 }
501
502
503
504
505 private static func solveSeconds(
506 forGameID gameID: UUID,
507 asOf: Date,
508 in ctx: NSManagedObjectContext
509 ) -> Int {
510 let req = NSFetchRequest<PlayerEntity>(entityName: "PlayerEntity")
511 req.predicate = NSPredicate(format: "game.id == %@", gameID as CVarArg)
512 let logs = ((try? ctx.fetch(req)) ?? []).map { TimeLog.decode($0.timeLog) }
513 return Int(TimeLog.accumulatedSeconds(
514 forLogs: logs,
515 localDeviceID: RecordSerializer.localDeviceID,
516 asOf: asOf
517 ))
518 }
519
520
521
522
523 static func localDeviceJournals(
524 forGameID gameID: UUID,
525 in ctx: NSManagedObjectContext
526 ) -> [DeviceJournal] {
527 let req = NSFetchRequest<JournalEntity>(entityName: "JournalEntity")
528 req.predicate = NSPredicate(format: "gameID == %@", gameID as CVarArg)
529 req.sortDescriptors = [NSSortDescriptor(key: "seq", ascending: true)]
530 let rows = (try? ctx.fetch(req)) ?? []
531
532 var byKey: [JournalDeviceKey: [JournalValue]] = [:]
533 for row in rows {
534 let key: JournalDeviceKey
535 if let device = row.sourceDeviceID {
536 key = JournalDeviceKey(authorID: row.sourceAuthorID ?? "", deviceID: device)
537 } else {
538
539
540 key = JournalDeviceKey(
541 authorID: row.actingAuthorID ?? "",
542 deviceID: RecordSerializer.localDeviceID
543 )
544 }
545 byKey[key, default: []].append(MovesJournal.value(from: row))
546 }
547 return byKey.map { DeviceJournal(key: $0.key, entries: $0.value) }
548 }
549
550
551
552
553 static func merging(
554 _ snapshot: Snapshot,
555 peerJournals: [DeviceJournal]
556 ) -> Snapshot {
557 var byKey: [JournalDeviceKey: [JournalValue]] = [:]
558 for journal in peerJournals { byKey[journal.key] = journal.entries }
559 for journal in snapshot.journal { byKey[journal.key] = journal.entries }
560 return Snapshot(
561 originalGameID: snapshot.originalGameID,
562 title: snapshot.title,
563 puzzleSource: snapshot.puzzleSource,
564 completedAt: snapshot.completedAt,
565 completedBy: snapshot.completedBy,
566 solveSeconds: snapshot.solveSeconds,
567 wasShared: snapshot.wasShared,
568 participants: snapshot.participants,
569 cells: snapshot.cells,
570 journal: byKey.map { DeviceJournal(key: $0.key, entries: $0.value) }
571 )
572 }
573
574
575
576 struct RecordPackage {
577 let record: CKRecord
578 let temporaryAssetFileURLs: [URL]
579 }
580
581 static func recordPackage(
582 from snapshot: Snapshot,
583 replayState: ReplayState = .available,
584 formatVersion: Int = currentPayloadFormatVersion
585 ) throws -> RecordPackage {
586 let zone = zoneID
587 let recordID = CKRecord.ID(
588 recordName: recordName(forOriginalGameID: snapshot.originalGameID),
589 zoneID: zone
590 )
591 let record = CKRecord(recordType: recordType, recordID: recordID)
592
593 let replayAvailable = replayState == .available
594 let blob = Blob(
595 formatVersion: formatVersion,
596 originalGameID: snapshot.originalGameID,
597 archiveGameID: archiveGameID(for: snapshot.originalGameID),
598 title: snapshot.title,
599 puzzleSource: snapshot.puzzleSource,
600 completedAt: snapshot.completedAt,
601 completedBy: snapshot.completedBy,
602 solveSeconds: snapshot.solveSeconds,
603 replayAvailable: replayAvailable,
604 replayMissingDeviceCount: {
605 guard formatVersion >= 3,
606 case .waiting(let missing) = replayState
607 else { return nil }
608 return missing
609 }(),
610 cells: snapshot.cells.sorted { ($0.row, $0.col) < ($1.row, $1.col) },
611 journals: replayAvailable ? try journalWire(snapshot.journal) : [],
612 wasShared: formatVersion >= 2 ? snapshot.wasShared : nil,
613 participants: formatVersion >= 2 ? snapshot.participants : nil
614 )
615 let encoded = try JSONEncoder().encode(blob)
616 let payload = try asset(for: encodeEnvelope(encoded), ext: "cmarchive")
617 record["completedAt"] = snapshot.completedAt
618 record[payloadKey] = payload.asset
619 return RecordPackage(
620 record: record,
621 temporaryAssetFileURLs: [payload.url]
622 )
623 }
624
625 private static func asset(for data: Data, ext: String) throws -> (asset: CKAsset, url: URL) {
626 let url = FileManager.default.temporaryDirectory
627 .appendingPathComponent(UUID().uuidString)
628 .appendingPathExtension(ext)
629 try data.write(to: url, options: .atomic)
630 return (CKAsset(fileURL: url), url)
631 }
632
633
634
635
636 struct Payload {
637 let formatVersion: Int
638 let originalGameID: UUID
639 let archiveGameID: UUID
640 let title: String
641 let puzzleSource: String
642 let completedAt: Date
643 let completedBy: String?
644
645
646 let solveSeconds: Int?
647 let replayState: ReplayState
648 var replayAvailable: Bool { replayState == .available }
649 let wasShared: Bool
650 let participants: [Participant]
651 let cells: [Cell]
652 let journal: [DeviceJournal]
653 }
654
655 enum ReplayState: Equatable {
656 case available
657 case waiting(missing: Int)
658 case unavailable
659 }
660
661
662
663
664
665 static func payload(
666 from snapshot: Snapshot,
667 replayState: ReplayState = .available
668 ) -> Payload {
669 let replayAvailable = replayState == .available
670 return Payload(
671 formatVersion: currentPayloadFormatVersion,
672 originalGameID: snapshot.originalGameID,
673 archiveGameID: archiveGameID(for: snapshot.originalGameID),
674 title: snapshot.title,
675 puzzleSource: snapshot.puzzleSource,
676 completedAt: snapshot.completedAt,
677 completedBy: snapshot.completedBy,
678 solveSeconds: snapshot.solveSeconds,
679 replayState: replayState,
680 wasShared: snapshot.wasShared,
681 participants: snapshot.participants,
682 cells: snapshot.cells,
683 journal: replayAvailable ? snapshot.journal : []
684 )
685 }
686
687 static func payload(
688 from record: CKRecord,
689 onDiagnostic: ((String) -> Void)? = nil
690 ) -> Payload? {
691 switch record.recordType {
692 case recordType:
693 return blobPayload(from: record, onDiagnostic: onDiagnostic)
694 case legacyRecordType:
695 return legacyPayload(from: record, onDiagnostic: onDiagnostic)
696 default:
697 return nil
698 }
699 }
700
701 private static func blobPayload(
702 from record: CKRecord,
703 onDiagnostic: ((String) -> Void)?
704 ) -> Payload? {
705 guard record.recordType == recordType,
706 let recordOriginalID = originalGameID(fromName: record.recordID.recordName),
707 record.recordID.recordName == recordName(
708 forOriginalGameID: recordOriginalID
709 ),
710 let asset = record[payloadKey] as? CKAsset,
711 let url = asset.fileURL
712 else { return nil }
713 do {
714 let envelope = try RecordSerializer.boundedAssetData(
715 at: url,
716 limit: maxPayloadAssetBytes
717 )
718 let decoded = try decodeEnvelope(envelope)
719 let blob = try JSONDecoder().decode(Blob.self, from: decoded)
720 guard (1...currentPayloadFormatVersion).contains(blob.formatVersion) else {
721 throw PayloadError.unsupportedFormat(blob.formatVersion)
722 }
723 guard let recordCompletedAt = record["completedAt"] as? Date else {
724 throw PayloadError.identityMismatch
725 }
726 let completionMetadataMatches = abs(
727 blob.completedAt.timeIntervalSince(recordCompletedAt)
728 ) < 0.001
729 guard blob.originalGameID == recordOriginalID,
730 blob.archiveGameID == archiveGameID(for: recordOriginalID),
731 completionMetadataMatches
732 else { throw PayloadError.identityMismatch }
733 let sourceBytes = blob.puzzleSource.utf8.count
734 guard sourceBytes <= XD.maxSourceBytes else {
735 throw PayloadError.oversizedPuzzleSource(bytes: sourceBytes)
736 }
737 guard blob.cells.count <= maxCellCount else {
738 throw LimitError.tooManyCells(count: blob.cells.count)
739 }
740 let journals = blob.replayAvailable ? try decodeJournals(blob.journals) : []
741 let replayState: ReplayState
742 if blob.replayAvailable {
743 replayState = .available
744 } else if let missing = blob.replayMissingDeviceCount,
745 (1...maxJournalDeviceCount).contains(missing) {
746 replayState = .waiting(missing: missing)
747 } else if blob.replayMissingDeviceCount != nil {
748
749
750
751
752
753 replayState = .unavailable
754 } else {
755 replayState = .unavailable
756 }
757 let participants = try validatedParticipants(
758 blob.participants ?? inferredParticipants(
759 journals: journals,
760 cells: blob.cells,
761 completedBy: blob.completedBy
762 )
763 )
764 return Payload(
765 formatVersion: blob.formatVersion,
766 originalGameID: blob.originalGameID,
767 archiveGameID: blob.archiveGameID,
768 title: blob.title,
769 puzzleSource: blob.puzzleSource,
770 completedAt: blob.completedAt,
771 completedBy: blob.completedBy,
772 solveSeconds: blob.solveSeconds,
773 replayState: replayState,
774 wasShared: blob.wasShared
775 ?? (Set(participants.map(\.authorID)).count > 1),
776 participants: participants,
777 cells: blob.cells,
778 journal: journals
779 )
780 } catch {
781 onDiagnostic?("archive payload rejected for \(record.recordID.recordName): \(error)")
782 return nil
783 }
784 }
785
786 private static func legacyPayload(
787 from record: CKRecord,
788 onDiagnostic: ((String) -> Void)?
789 ) -> Payload? {
790 guard record.recordType == legacyRecordType,
791 let originalString = record["originalGameID"] as? String,
792 let originalGameID = UUID(uuidString: originalString),
793 let archiveString = record["archiveGameID"] as? String,
794 let archiveGameID = UUID(uuidString: archiveString),
795 let completedAt = record["completedAt"] as? Date,
796 record.recordID.recordName == legacyRecordName(
797 forOriginalGameID: originalGameID
798 ),
799 archiveGameID == self.archiveGameID(for: originalGameID)
800 else { return nil }
801
802
803
804
805
806
807 func decoded<T>(
808 _ key: String,
809 limit: Int,
810 _ decode: (Data) throws -> T
811 ) -> T? {
812 guard let asset = record[key] as? CKAsset, let url = asset.fileURL
813 else { return nil }
814 do {
815 let data = try RecordSerializer.boundedAssetData(at: url, limit: limit)
816 return try decode(data)
817 } catch {
818 onDiagnostic?(
819 "archive \(key) rejected for " +
820 "\(record.recordID.recordName): \(error)"
821 )
822 return nil
823 }
824 }
825
826 let puzzleSource = decoded("puzzleSource", limit: XD.maxSourceBytes) {
827 String(data: $0, encoding: .utf8) ?? ""
828 } ?? ""
829 let cells = decoded("cells", limit: maxCellsAssetBytes, decodeCells) ?? []
830 let journal = decoded("journals", limit: maxJournalsAssetBytes, decodeJournals) ?? []
831 let participants: [Participant]
832 do {
833 participants = try validatedParticipants(
834 inferredParticipants(
835 journals: journal,
836 cells: cells,
837 completedBy: record["completedBy"] as? String
838 )
839 )
840 } catch {
841 onDiagnostic?(
842 "archive participants rejected for " +
843 "\(record.recordID.recordName): \(error)"
844 )
845 return nil
846 }
847
848 return Payload(
849 formatVersion: 0,
850 originalGameID: originalGameID,
851 archiveGameID: archiveGameID,
852 title: record["title"] as? String ?? "",
853 puzzleSource: puzzleSource,
854 completedAt: completedAt,
855 completedBy: record["completedBy"] as? String,
856 solveSeconds: (record["solveSeconds"] as? Int64).map(Int.init),
857 replayState: .available,
858 wasShared: Set(journal.map(\.key.authorID).filter { !$0.isEmpty }).count > 1,
859 participants: participants,
860 cells: cells,
861 journal: journal
862 )
863 }
864
865
866
867
868
869
870
871
872
873
874
875
876 @discardableResult
877 static func materialize(
878 _ payload: Payload,
879 in ctx: NSManagedObjectContext
880 ) -> GameEntity? {
881 guard !payload.puzzleSource.isEmpty else { return nil }
882 let archiveID = payload.archiveGameID
883
884 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
885 request.predicate = NSPredicate(format: "id == %@", archiveID as CVarArg)
886 request.fetchLimit = 1
887 let entity: GameEntity
888 if let existing = try? ctx.fetch(request).first {
889 entity = existing
890 for cell in (existing.cells as? Set<CellEntity>) ?? [] {
891 ctx.delete(cell)
892 }
893 for journal in (existing.journal as? Set<JournalEntity>) ?? [] {
894 ctx.delete(journal)
895 }
896 for player in (existing.players as? Set<PlayerEntity>) ?? [] {
897 ctx.delete(player)
898 }
899 } else {
900 entity = GameEntity(context: ctx)
901 entity.id = archiveID
902 }
903
904
905
906
907 entity.ckRecordName = recordName(forOriginalGameID: payload.originalGameID)
908 entity.ckZoneName = zoneID.zoneName
909 entity.ckZoneOwnerName = nil
910 entity.databaseScope = 0
911 entity.syncVersion = GameSyncVersion.legacy
912 entity.title = payload.title
913 entity.puzzleSource = payload.puzzleSource
914
915
916
917
918
919
920 if let xd = try? XD.parse(payload.puzzleSource) {
921 entity.populateCachedSummaryFields(from: Puzzle(xd: xd))
922 }
923 entity.completedAt = payload.completedAt
924 entity.completedBy = payload.completedBy
925
926
927 if let solveSeconds = payload.solveSeconds {
928 entity.finalSolveSeconds = NSNumber(value: solveSeconds)
929 }
930 entity.createdAt = payload.completedAt
931 entity.updatedAt = payload.completedAt
932 entity.archivedAt = payload.completedAt
933 entity.archiveGameID = archiveID
934 entity.archiveParticipants = payload.wasShared
935 ? payload.participants.map(\.authorID).sorted().joined(separator: ",")
936 : nil
937 entity.isSupersededByChronicle = false
938
939
940
941 ChronicleLedgerEntity.upsert(
942 originalGameID: payload.originalGameID,
943 publisher: entity.cachedPublisher,
944 puzzleDate: entity.cachedPuzzleDate,
945 participants: entity.archiveParticipants,
946 in: ctx
947 )
948
949
950
951
952 let liveRequest = NSFetchRequest<GameEntity>(entityName: "GameEntity")
953 liveRequest.predicate = NSPredicate(
954 format: "id == %@",
955 payload.originalGameID as CVarArg
956 )
957 liveRequest.fetchLimit = 1
958 if let live = try? ctx.fetch(liveRequest).first {
959 mirrorReadState(from: live, to: entity)
960 }
961
962
963
964 switch payload.replayState {
965 case .available:
966 entity.replayMissingDeviceCount = nil
967 entity.replayUnavailable = false
968 case .waiting(let missing):
969 entity.replayMissingDeviceCount = NSNumber(value: missing)
970 entity.replayUnavailable = false
971 case .unavailable:
972 entity.replayMissingDeviceCount = nil
973 entity.replayUnavailable = true
974 }
975 entity.replayCacheComplete = payload.replayAvailable
976
977 for cell in payload.cells {
978
979
980 guard cell.row >= 0, cell.col >= 0 else { continue }
981 let row = CellEntity(context: ctx)
982 row.game = entity
983 row.row = cell.row
984 row.col = cell.col
985 row.letter = cell.letter
986 row.markCode = cell.markCode
987 row.letterAuthorID = cell.letterAuthorID
988 }
989
990 for participant in payload.participants {
991 let player = PlayerEntity(context: ctx)
992 player.game = entity
993 player.authorID = participant.authorID
994 player.name = participant.name ?? ""
995 player.ckRecordName = RecordSerializer.recordName(
996 forPlayerInGame: archiveID,
997 authorID: participant.authorID
998 )
999 player.updatedAt = payload.completedAt
1000 }
1001
1002
1003
1004
1005
1006 for deviceJournal in payload.replayAvailable ? payload.journal : [] {
1007 for value in deviceJournal.entries {
1008 let row = JournalEntity(context: ctx)
1009 row.game = entity
1010 MovesJournal.assign(value, to: row, gameID: archiveID)
1011 row.sourceAuthorID = deviceJournal.key.authorID
1012 row.sourceDeviceID = deviceJournal.key.deviceID
1013 }
1014 }
1015
1016 return entity
1017 }
1018
1019 private static func inferredParticipants(
1020 journals: [DeviceJournal],
1021 cells: [Cell],
1022 completedBy: String?
1023 ) -> [Participant] {
1024 var authorIDs = Set(journals.map(\.key.authorID))
1025 authorIDs.formUnion(cells.compactMap(\.letterAuthorID))
1026 if let completedBy { authorIDs.insert(completedBy) }
1027 authorIDs.remove("")
1028 authorIDs.remove(CKCurrentUserDefaultName)
1029 return authorIDs.sorted().map { Participant(authorID: $0, name: nil) }
1030 }
1031
1032 private static func validatedParticipants(
1033 _ participants: [Participant]
1034 ) throws -> [Participant] {
1035 guard participants.count <= maxParticipantCount else {
1036 throw LimitError.tooManyParticipants(count: participants.count)
1037 }
1038 var byAuthor: [String: Participant] = [:]
1039 for participant in participants where !participant.authorID.isEmpty {
1040 byAuthor[participant.authorID] = participant
1041 }
1042 return byAuthor.values.sorted { $0.authorID < $1.authorID }
1043 }
1044}