Crossmate/Persistence/GameStore.swift (152487B)
1import CloudKit
2import CoreData
3import Foundation
4import Observation
5import Security
6
7
8
9
10private func playerEntities(for entity: GameEntity) -> [PlayerEntity] {
11 guard let context = entity.managedObjectContext else { return [] }
12 let request = NSFetchRequest<PlayerEntity>(entityName: "PlayerEntity")
13 request.predicate = NSPredicate(format: "game == %@", entity)
14 return (try? context.fetch(request)) ?? []
15}
16
17private func isMaterializedArchive(_ entity: GameEntity) -> Bool {
18 entity.ckRecordName.flatMap(Archive.originalGameID(fromName:)) != nil
19}
20
21
22
23
24private func archivedContributorAuthorIDs(_ entity: GameEntity) -> [String] {
25 guard isMaterializedArchive(entity) else { return [] }
26 var authorIDs = Set(playerEntities(for: entity).compactMap(\.authorID))
27 authorIDs.formUnion(
28 ((entity.cells as? Set<CellEntity>) ?? []).compactMap(\.letterAuthorID)
29 )
30 authorIDs.formUnion(
31 ((entity.journal as? Set<JournalEntity>) ?? []).compactMap(\.sourceAuthorID)
32 )
33 if let completedBy = entity.completedBy {
34 authorIDs.insert(completedBy)
35 }
36 authorIDs.remove("")
37 authorIDs.remove(CKCurrentUserDefaultName)
38 return authorIDs.sorted()
39}
40
41private func isArchivedSharedGame(_ entity: GameEntity) -> Bool {
42 guard isMaterializedArchive(entity) else { return false }
43 return entity.archiveParticipants != nil
44 || archivedContributorAuthorIDs(entity).count > 1
45}
46
47
48
49
50
51private func materializedArchiveGrid(_ entity: GameEntity) -> GridState? {
52 guard isMaterializedArchive(entity) else { return nil }
53 let cells = (entity.cells as? Set<CellEntity>) ?? []
54 let cached = Dictionary(
55 cells.map {
56 (
57 GridPosition(row: Int($0.row), col: Int($0.col)),
58 GridCell(
59 letter: $0.letter ?? "",
60 mark: CellMark(code: $0.markCode),
61 authorID: $0.letterAuthorID
62 )
63 )
64 },
65 uniquingKeysWith: { first, _ in first }
66 )
67 let hasMeaningfulCachedState = cached.values.contains {
68 !$0.letter.isEmpty || $0.mark != .none || $0.authorID != nil
69 }
70 guard !hasMeaningfulCachedState else { return cached }
71
72 let entries = ((entity.journal as? Set<JournalEntity>) ?? [])
73 .map(MovesJournal.value(from:))
74 guard !entries.isEmpty else { return cached }
75 let timeline = ReplayTimeline(merging: [entries])
76 return timeline.state(through: timeline.count).mapValues {
77 GridCell(
78 letter: $0.letter,
79 mark: $0.mark,
80 authorID: $0.cellAuthorID
81 )
82 }
83}
84
85
86
87enum GameThumbnailCell: Equatable {
88 case block
89 case empty
90 case filled
91}
92
93
94
95
96struct GameSummary: Identifiable, Equatable {
97
98 let id: UUID
99
100
101
102 let listID: UUID
103 let title: String
104 let publisher: String?
105 let puzzleDate: Date?
106 let updatedAt: Date?
107 let completedAt: Date?
108 let gridWidth: Int
109 let gridHeight: Int
110 let thumbnailCells: [GameThumbnailCell]
111
112 let isOwned: Bool
113
114
115 let isShared: Bool
116 let isAccessRevoked: Bool
117 let hasUnreadOtherMoves: Bool
118 let allParticipants: [GameParticipantSummary]
119
120
121
122
123 var stripParticipants: [GameParticipantSummary] {
124 ParticipantSummaries.sortedByScore(
125 allParticipants,
126 score: \.score,
127 name: \.name,
128 id: \.authorID
129 )
130 }
131
132 init?(
133 entity: GameEntity,
134 localAuthorID: String? = nil,
135 localName: String = "Player",
136 localColor: PlayerColor = .blue
137 ) {
138 guard let id = entity.id else { return nil }
139
140 let width: Int
141 let height: Int
142 let publisher: String?
143 let puzzleDate: Date?
144 let blocks: [Bool]
145
146 if entity.gridWidth > 0,
147 entity.gridHeight > 0,
148 let mask = entity.blockMask,
149 mask.count == Int(entity.gridWidth) * Int(entity.gridHeight) {
150
151
152 width = Int(entity.gridWidth)
153 height = Int(entity.gridHeight)
154 publisher = entity.cachedPublisher
155 puzzleDate = entity.cachedPuzzleDate
156 blocks = mask.map { $0 != 0 }
157 } else {
158
159
160
161 guard let source = entity.puzzleSource,
162 let xd = try? XD.parse(source) else {
163 return nil
164 }
165 let puzzle = Puzzle(xd: xd)
166 width = puzzle.width
167 height = puzzle.height
168 publisher = puzzle.publisher
169 puzzleDate = puzzle.date
170 var bs: [Bool] = []
171 bs.reserveCapacity(puzzle.width * puzzle.height)
172 for r in 0..<puzzle.height {
173 for c in 0..<puzzle.width {
174 bs.append(puzzle.cells[r][c].isBlock)
175 }
176 }
177 blocks = bs
178 }
179
180
181
182
183
184
185
186 let isCompleted = entity.completedAt != nil
187 var filledSet: Set<Int> = []
188 var scoreByAuthorID: [String: Int] = [:]
189 if !isCompleted {
190 let cellEntities = (entity.cells as? Set<CellEntity>) ?? []
191 for ce in cellEntities where !(ce.letter ?? "").isEmpty {
192 let index = Int(ce.row) * width + Int(ce.col)
193 filledSet.insert(index)
194 guard blocks.indices.contains(index), !blocks[index] else { continue }
195 guard !CellMark(code: ce.markCode).isRevealed,
196 let authorID = ce.letterAuthorID,
197 !authorID.isEmpty,
198 authorID != CKCurrentUserDefaultName else { continue }
199 scoreByAuthorID[authorID, default: 0] += 1
200 }
201 }
202
203 var thumbCells: [GameThumbnailCell] = []
204 thumbCells.reserveCapacity(width * height)
205 for r in 0..<height {
206 for c in 0..<width {
207 let idx = r * width + c
208 if blocks[idx] {
209 thumbCells.append(.block)
210 } else if isCompleted || filledSet.contains(idx) {
211 thumbCells.append(.filled)
212 } else {
213 thumbCells.append(.empty)
214 }
215 }
216 }
217
218 self.id = id
219 self.listID = entity.ckRecordName.flatMap(
220 Archive.originalGameID(fromName:)
221 ) ?? id
222 self.title = entity.title ?? "Untitled"
223 self.publisher = publisher
224 self.puzzleDate = puzzleDate
225 self.updatedAt = entity.updatedAt
226 self.completedAt = entity.completedAt
227 self.gridWidth = width
228 self.gridHeight = height
229 self.thumbnailCells = thumbCells
230 self.isOwned = entity.databaseScope == 0
231 self.isShared = entity.ckShareRecordName != nil
232 || entity.databaseScope == 1
233 || isArchivedSharedGame(entity)
234 self.isAccessRevoked = entity.isAccessRevoked
235 self.allParticipants = Self.computeParticipants(
236
237
238
239
240 gameID: self.listID,
241 entity: entity,
242 localAuthorID: localAuthorID,
243 localName: localName,
244 localColor: localColor,
245 scoreByAuthorID: scoreByAuthorID
246 )
247 self.hasUnreadOtherMoves = Self.computeHasUnread(
248 isShared: self.isShared,
249 latest: entity.latestOtherMoveAt,
250
251
252 readThrough: entity.readThroughAt
253 )
254 }
255
256
257
258
259
260
261 fileprivate static func computeHasUnread(
262 isShared: Bool,
263 latest: Date?,
264 readThrough: Date?
265 ) -> Bool {
266 guard isShared, let latest else { return false }
267 guard let readThrough else { return true }
268 return latest > readThrough
269 }
270
271 private static func computeParticipants(
272 gameID: UUID,
273 entity: GameEntity,
274 localAuthorID: String?,
275 localName: String,
276 localColor: PlayerColor,
277 scoreByAuthorID: [String: Int]
278 ) -> [GameParticipantSummary] {
279 guard entity.ckShareRecordName != nil
280 || entity.databaseScope == 1
281 || isArchivedSharedGame(entity)
282 else {
283 return []
284 }
285
286 var namesByAuthor: [String: String] = [:]
287 var playerAuthorIDs: [String] = []
288 for player in playerEntities(for: entity) {
289 guard let authorID = player.authorID, !authorID.isEmpty else { continue }
290 playerAuthorIDs.append(authorID)
291 if let name = player.name?.trimmingCharacters(in: .whitespacesAndNewlines),
292 !name.isEmpty {
293 namesByAuthor[authorID] = name
294 }
295 }
296
297 let movesEntities = (entity.moves as? Set<MovesEntity>) ?? []
298 var moveAuthorIDs: [String] = []
299 for moves in movesEntities {
300 guard let authorID = moves.authorID, !authorID.isEmpty else { continue }
301 moveAuthorIDs.append(authorID)
302 }
303
304 let nicknames = friendNicknames(in: entity.managedObjectContext)
305 return ParticipantSummaries.allParticipants(
306 gameID: gameID,
307 namesByAuthor: namesByAuthor,
308 moveAuthorIDs: moveAuthorIDs,
309 nicknamesByAuthor: nicknames,
310 localAuthorID: localAuthorID,
311 localName: localName,
312 localColor: localColor,
313 scoreByAuthorID: scoreByAuthorID,
314 additionalAuthorIDs: playerAuthorIDs
315 + archivedContributorAuthorIDs(entity)
316 )
317 }
318
319 private static func friendNicknames(in context: NSManagedObjectContext?) -> [String: String] {
320 guard let context else { return [:] }
321 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
322 req.predicate = NSPredicate(
323 format: "isBlocked == NO AND nickname != nil AND nickname != %@", ""
324 )
325 let friends = (try? context.fetch(req)) ?? []
326 var nicknames: [String: String] = [:]
327 for friend in friends {
328 guard let authorID = friend.authorID, !authorID.isEmpty,
329 let nickname = friend.nickname?.trimmingCharacters(in: .whitespacesAndNewlines),
330 !nickname.isEmpty
331 else { continue }
332 nicknames[authorID] = nickname
333 }
334 return nicknames
335 }
336}
337
338
339
340struct GameCloudDeletion: Sendable, Equatable {
341 let gameID: UUID
342 let databaseScope: DatabaseScope
343 let ckZoneName: String
344 let ckZoneOwnerName: String
345
346
347 let deletesLiveZone: Bool
348
349 let archiveRecordName: String?
350
351 let legacyArchiveZoneName: String?
352}
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367@MainActor
368final class GameSummaryCache {
369 private struct Key: Equatable {
370 let updatedAt: Date?
371 let completedAt: Date?
372 let latestOther: Date?
373 let readThrough: Date?
374 let scope: Int16
375 let shareName: String?
376 let revoked: Bool
377 let title: String?
378 let publisher: String?
379 let puzzleDate: Date?
380 let gridWidth: Int16
381 let gridHeight: Int16
382 let blockMask: Data?
383 let localAuthorID: String?
384 let localName: String
385 let localColorID: String
386 let playersSignature: [String]
387 let movesAuthorIDs: [String]
388 let nicknamesSignature: [String]
389 }
390 private var entries: [NSManagedObjectID: (key: Key, summary: GameSummary)] = [:]
391
392 func summary(
393 for entity: GameEntity,
394 localAuthorID: String? = nil,
395 localName: String = "Player",
396 localColor: PlayerColor = .blue
397 ) -> GameSummary? {
398 let key = Key(
399 updatedAt: entity.updatedAt,
400 completedAt: entity.completedAt,
401 latestOther: entity.latestOtherMoveAt,
402 readThrough: entity.readThroughAt,
403 scope: entity.databaseScope,
404 shareName: entity.ckShareRecordName,
405 revoked: entity.isAccessRevoked,
406 title: entity.title,
407 publisher: entity.cachedPublisher,
408 puzzleDate: entity.cachedPuzzleDate,
409 gridWidth: entity.gridWidth,
410 gridHeight: entity.gridHeight,
411 blockMask: entity.blockMask,
412 localAuthorID: localAuthorID,
413 localName: localName,
414 localColorID: localColor.id,
415 playersSignature: Self.playersSignature(for: entity),
416 movesAuthorIDs: Self.movesAuthorIDs(for: entity),
417 nicknamesSignature: Self.nicknamesSignature(in: entity.managedObjectContext)
418 )
419 if let hit = entries[entity.objectID], hit.key == key {
420 return hit.summary
421 }
422 guard let fresh = GameSummary(
423 entity: entity,
424 localAuthorID: localAuthorID,
425 localName: localName,
426 localColor: localColor
427 ) else { return nil }
428 entries[entity.objectID] = (key, fresh)
429 return fresh
430 }
431
432 private static func playersSignature(for entity: GameEntity) -> [String] {
433 playerEntities(for: entity).map { player in
434 "\(player.authorID ?? "")|\(player.name ?? "")|\(player.updatedAt?.timeIntervalSinceReferenceDate ?? 0)"
435 }
436 .sorted()
437 }
438
439 private static func movesAuthorIDs(for entity: GameEntity) -> [String] {
440 let moves = (entity.moves as? Set<MovesEntity>) ?? []
441 return Array(Set(moves.compactMap { $0.authorID })).sorted()
442 }
443
444 private static func nicknamesSignature(in context: NSManagedObjectContext?) -> [String] {
445 guard let context else { return [] }
446 let req = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
447 req.predicate = NSPredicate(
448 format: "isBlocked == NO AND nickname != nil AND nickname != %@", ""
449 )
450 let friends = (try? context.fetch(req)) ?? []
451 return friends.compactMap { friend in
452 guard let authorID = friend.authorID, !authorID.isEmpty else { return nil }
453 return "\(authorID)|\(friend.nickname ?? "")"
454 }
455 .sorted()
456 }
457}
458
459extension GameEntity {
460
461
462 static var visibleInGameListPredicate: NSPredicate {
463 NSPredicate(format: "isHidden == NO AND isSupersededByChronicle == NO")
464 }
465
466
467
468
469
470 func populateCachedSummaryFields(from puzzle: Puzzle) {
471 cachedPublisher = puzzle.publisher
472 cachedPuzzleDate = puzzle.date
473 gridWidth = Int16(puzzle.width)
474 gridHeight = Int16(puzzle.height)
475
476 var bytes = [UInt8]()
477 bytes.reserveCapacity(puzzle.width * puzzle.height)
478 for r in 0..<puzzle.height {
479 for c in 0..<puzzle.width {
480 bytes.append(puzzle.cells[r][c].isBlock ? 1 : 0)
481 }
482 }
483 blockMask = Data(bytes)
484 }
485
486
487
488
489
490
491
492 @discardableResult
493 static func reconcileBlockedFriendHiddenGames(
494 forAuthorIDs authorIDs: Set<String>,
495 in ctx: NSManagedObjectContext
496 ) -> Int {
497 let authorIDs = authorIDs.filter { !$0.isEmpty }
498 guard !authorIDs.isEmpty else { return 0 }
499 return reconcileBlockedFriendHiddenGames(
500 games: gamesFeaturingAnyAuthor(in: authorIDs, ctx: ctx),
501 blockedAuthorIDs: blockedAuthorIDs(in: ctx)
502 )
503 }
504
505 @discardableResult
506 static func reconcileBlockedFriendHiddenGames(
507 forGameIDs gameIDs: Set<UUID>,
508 in ctx: NSManagedObjectContext
509 ) -> Int {
510 guard !gameIDs.isEmpty else { return 0 }
511 let gameReq = NSFetchRequest<GameEntity>(entityName: "GameEntity")
512 gameReq.predicate = NSPredicate(format: "id IN %@", Array(gameIDs))
513 return reconcileBlockedFriendHiddenGames(
514 games: (try? ctx.fetch(gameReq)) ?? [],
515 blockedAuthorIDs: blockedAuthorIDs(in: ctx)
516 )
517 }
518
519 private static func reconcileBlockedFriendHiddenGames(
520 games: [GameEntity],
521 blockedAuthorIDs: Set<String>
522 ) -> Int {
523 var changed = 0
524 for game in games {
525 var didChange = false
526
527
528
529 if !game.isSupersededByChronicle,
530 hasMaterializedChronicle(for: game) {
531 game.isSupersededByChronicle = true
532 didChange = true
533 }
534 let authors = collaboratorAuthorIDs(for: game)
535 let shouldHide = !blockedAuthorIDs.isDisjoint(with: authors)
536 if game.isHidden != shouldHide {
537 game.isHidden = shouldHide
538 didChange = true
539 }
540 if didChange { changed += 1 }
541 }
542 return changed
543 }
544
545 private static func hasMaterializedChronicle(for game: GameEntity) -> Bool {
546 guard !isMaterializedArchive(game),
547 let gameID = game.id,
548 let ctx = game.managedObjectContext
549 else { return false }
550 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
551 request.predicate = NSPredicate(
552 format: "id == %@",
553 Archive.archiveGameID(for: gameID) as CVarArg
554 )
555 request.fetchLimit = 1
556 return (try? ctx.count(for: request)) == 1
557 }
558
559 static func blockedAuthorIDs(in ctx: NSManagedObjectContext) -> Set<String> {
560 let blockedReq = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
561 blockedReq.predicate = NSPredicate(format: "isBlocked == YES")
562 blockedReq.propertiesToFetch = ["authorID"]
563 return Set(((try? ctx.fetch(blockedReq)) ?? []).compactMap(\.authorID))
564 }
565
566 private static func gamesFeaturingAnyAuthor(
567 in authorIDs: Set<String>,
568 ctx: NSManagedObjectContext
569 ) -> [GameEntity] {
570 let authors = Array(authorIDs)
571 var games: [GameEntity] = []
572 var seen = Set<NSManagedObjectID>()
573
574 func append(_ game: GameEntity?) {
575 guard let game, !seen.contains(game.objectID) else { return }
576 seen.insert(game.objectID)
577 games.append(game)
578 }
579
580 let ownedReq = NSFetchRequest<GameEntity>(entityName: "GameEntity")
581 ownedReq.predicate = NSPredicate(format: "ckZoneOwnerName IN %@", authors)
582 for game in (try? ctx.fetch(ownedReq)) ?? [] {
583 append(game)
584 }
585
586 let playerReq = NSFetchRequest<PlayerEntity>(entityName: "PlayerEntity")
587 playerReq.predicate = NSPredicate(format: "authorID IN %@", authors)
588 for player in (try? ctx.fetch(playerReq)) ?? [] {
589 append(player.game)
590 }
591
592 let movesReq = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
593 movesReq.predicate = NSPredicate(format: "authorID IN %@", authors)
594 for moves in (try? ctx.fetch(movesReq)) ?? [] {
595 append(moves.game)
596 }
597
598 return games
599 }
600
601 private static func collaboratorAuthorIDs(for game: GameEntity) -> Set<String> {
602 var authors = Set<String>()
603 if let owner = game.ckZoneOwnerName, !owner.isEmpty {
604 authors.insert(owner)
605 }
606 let moves = (game.moves as? Set<MovesEntity>) ?? []
607 for move in moves {
608 if let authorID = move.authorID, !authorID.isEmpty {
609 authors.insert(authorID)
610 }
611 }
612 for player in playerEntities(for: game) {
613 if let authorID = player.authorID, !authorID.isEmpty {
614 authors.insert(authorID)
615 }
616 }
617 return authors
618 }
619}
620
621
622
623
624
625
626@MainActor
627@Observable
628final class GameStore {
629
630
631
632
633 static let realtimeCellEditMaxFutureSkew: TimeInterval = 120
634
635 let persistence: PersistenceController
636 private var context: NSManagedObjectContext { persistence.viewContext }
637
638 private(set) var currentGame: Game?
639 private(set) var currentMutator: GameMutator?
640 private(set) var currentEntity: GameEntity?
641
642 private let movesUpdater: MovesUpdater
643 private let movesJournal: MovesJournal
644
645
646
647
648 private let authorIDProvider: @MainActor () -> String?
649
650
651 private let onGameCreated: (String) -> Void
652
653
654 private let onGameDeleted: (GameCloudDeletion) -> Void
655
656
657
658 private let onGameUpdated: (String) -> Void
659
660
661
662
663
664
665 @ObservationIgnored
666 var onJournalComplete: (@MainActor (UUID, String, Bool, Bool) -> Void)?
667
668
669
670
671 @ObservationIgnored
672 var onUnreadOtherMovesChanged: (() -> Void)?
673 @ObservationIgnored
674 var onPushRegistrationMayNeedRefresh: (@MainActor () -> Void)?
675 @ObservationIgnored
676 var onLocalCellEdit: (@MainActor (RealtimeCellEdit) -> Void)?
677 @ObservationIgnored
678 var onLocalCellEditBatch: (@MainActor ([RealtimeCellEdit]) -> Void)?
679
680 private let eventLog: EventLog?
681
682 init(
683 persistence: PersistenceController,
684 movesUpdater: MovesUpdater,
685 authorIDProvider: @escaping @MainActor () -> String?,
686 onGameCreated: @escaping (String) -> Void,
687 onGameUpdated: @escaping (String) -> Void,
688 onGameDeleted: @escaping (GameCloudDeletion) -> Void,
689 eventLog: EventLog? = nil
690 ) {
691 self.persistence = persistence
692 self.movesUpdater = movesUpdater
693
694
695
696 self.movesJournal = MovesJournal(persistence: persistence)
697 self.authorIDProvider = authorIDProvider
698 self.onGameCreated = onGameCreated
699 self.onGameUpdated = onGameUpdated
700 self.onGameDeleted = onGameDeleted
701 self.eventLog = eventLog
702 }
703
704
705
706 @discardableResult
707 func reconcileBlockedFriendHiddenGames(forAuthorIDs authorIDs: Set<String>) async -> Int {
708 let ctx = persistence.container.newBackgroundContext()
709 let result: (changed: Int, errorMessage: String?) = await ctx.perform {
710 let changed = GameEntity.reconcileBlockedFriendHiddenGames(
711 forAuthorIDs: authorIDs,
712 in: ctx
713 )
714 if changed > 0 {
715 do {
716 try ctx.save()
717 } catch {
718 return (
719 changed: 0,
720 errorMessage: "GameStore: reconcileBlockedFriendHiddenGames save failed — \(error)"
721 )
722 }
723 }
724 return (changed: changed, errorMessage: nil)
725 }
726 if let errorMessage = result.errorMessage {
727 eventLog?.note(errorMessage, level: "error")
728 }
729 return result.changed
730 }
731
732
733
734
735 @discardableResult
736 func reconcileBlockedFriendHiddenGames(forGameIDs gameIDs: Set<UUID>) async -> Int {
737 let ctx = persistence.container.newBackgroundContext()
738 let result: (changed: Int, errorMessage: String?) = await ctx.perform {
739 let changed = GameEntity.reconcileBlockedFriendHiddenGames(
740 forGameIDs: gameIDs,
741 in: ctx
742 )
743 if changed > 0 {
744 do {
745 try ctx.save()
746 } catch {
747 return (
748 changed: 0,
749 errorMessage: "GameStore: reconcileBlockedFriendHiddenGames save failed — \(error)"
750 )
751 }
752 }
753 return (changed: changed, errorMessage: nil)
754 }
755 if let errorMessage = result.errorMessage {
756 eventLog?.note(errorMessage, level: "error")
757 }
758 return result.changed
759 }
760
761 private func saveContext(_ label: String) {
762 do {
763 try context.save()
764 } catch {
765 eventLog?.note("GameStore: \(label) save failed — \(error)", level: "error")
766 }
767 }
768
769 enum LoadError: Error {
770 case sampleResourceMissing
771 case persistedSourceMissing
772 case gameNotFound
773
774
775
776 case sharedZoneOwnedByCurrentUser
777 }
778
779
780
781
782
783 func refreshCurrentGame() {
784 guard let game = currentGame, let entity = currentEntity else { return }
785 refreshCurrentSyncState()
786
787
788
789
790
791 restore(game: game, from: entity, updateCache: false)
792 }
793
794
795
796
797 func refreshCurrentSyncState() {
798 guard let entity = currentEntity else { return }
799 currentMutator?.updateSyncVersion(
800 entity.syncVersion,
801 observedLogicalTick: maximumLogicalTick(for: entity)
802 )
803 }
804
805
806
807
808
809 func replayCellCaches(for gameIDs: Set<UUID>) async {
810 let bgCtx = persistence.container.newBackgroundContext()
811 bgCtx.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
812 await bgCtx.perform {
813 for gameID in gameIDs {
814 let req = NSFetchRequest<GameEntity>(entityName: "GameEntity")
815 req.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
816 req.fetchLimit = 1
817 guard let entity = try? bgCtx.fetch(req).first else { continue }
818
819 let movesReq = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
820 movesReq.predicate = NSPredicate(format: "game == %@", entity)
821 let values: [MovesValue] = ((try? bgCtx.fetch(movesReq)) ?? [])
822 .compactMap { Self.movesValue(from: $0) }
823 let grid = GridStateMerger.merge(values)
824 Self.applyCellCache(to: entity, from: grid, in: bgCtx)
825 }
826 if bgCtx.hasChanges {
827 try? bgCtx.save()
828 }
829 }
830 }
831
832
833
834
835
836
837 private var ledgerRequests: AsyncStream<Set<UUID>>.Continuation?
838 private var peerChangeLedgerBuildSerial = 0
839
840
841
842
843
844 func ensurePeerChangeLedgerSeeded(for gameID: UUID) {
845 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
846 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
847 request.fetchLimit = 1
848 guard let game = try? context.fetch(request).first,
849 game.completedAt == nil,
850 !game.hasSeededPeerChanges else { return }
851 enqueuePeerChangeLedgerUpdate(for: [gameID])
852 }
853
854
855
856
857
858 func enqueuePeerChangeLedgerUpdate(for gameIDs: Set<UUID>) {
859 guard !gameIDs.isEmpty else { return }
860 eventLog?.note(
861 "peer ledger enqueue: games=[\(gameIDs.map { String($0.uuidString.prefix(8)) }.sorted().joined(separator: ","))]"
862 )
863 if ledgerRequests == nil {
864 let (stream, continuation) = AsyncStream<Set<UUID>>.makeStream()
865 ledgerRequests = continuation
866
867
868
869 Task { [weak self] in
870 for await gameIDs in stream {
871 await self?.updatePeerChangeLedger(for: gameIDs)
872 }
873 }
874 }
875 ledgerRequests?.yield(gameIDs)
876 }
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898 func updatePeerChangeLedger(for gameIDs: Set<UUID>) async {
899 guard !gameIDs.isEmpty else { return }
900 peerChangeLedgerBuildSerial += 1
901 let serial = peerChangeLedgerBuildSerial
902 let startedAt = Date()
903 eventLog?.note(
904 "peer ledger build #\(serial) start: games=[\(gameIDs.map { String($0.uuidString.prefix(8)) }.sorted().joined(separator: ","))]"
905 )
906 let ctx = persistence.container.newBackgroundContext()
907 ctx.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
908 let result: (diagnostics: [String], errorMessage: String?) = await ctx.perform {
909 var diagnostics: [String] = []
910 var errorMessage: String?
911 for gameID in gameIDs {
912 let gameReq = NSFetchRequest<GameEntity>(entityName: "GameEntity")
913 gameReq.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
914 gameReq.fetchLimit = 1
915 guard let game = try? ctx.fetch(gameReq).first else {
916 diagnostics.append("\(gameID.uuidString.prefix(8)) missing-game")
917 continue
918 }
919
920 let ledgerReq = NSFetchRequest<PeerChangeEntity>(entityName: "PeerChangeEntity")
921 ledgerReq.predicate = NSPredicate(format: "gameID == %@", gameID as CVarArg)
922 let existingRows = (try? ctx.fetch(ledgerReq)) ?? []
923
924
925
926
927
928
929 if game.completedAt != nil {
930 for row in existingRows { ctx.delete(row) }
931 diagnostics.append(
932 "\(gameID.uuidString.prefix(8)) completed existing=\(existingRows.count) deleted"
933 )
934 continue
935 }
936
937 let movesReq = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
938 movesReq.predicate = NSPredicate(format: "game == %@", game)
939 let values: [MovesValue] = ((try? ctx.fetch(movesReq)) ?? [])
940 .compactMap { Self.movesValue(from: $0) }
941 let current = GridStateMerger.mergeWithProvenance(values)
942
943
944 let isSeeding = !game.hasSeededPeerChanges && existingRows.isEmpty
945
946 var rowByPosition: [GridPosition: PeerChangeEntity] = [:]
947 for row in existingRows {
948 rowByPosition[GridPosition(row: Int(row.row), col: Int(row.col))] = row
949 }
950 let recorded = rowByPosition.mapValues { Self.peerChange(from: $0) }
951
952 let upserts = PeerChangeLedger.upserts(
953 current: current,
954 recorded: recorded,
955 seeding: isSeeding
956 )
957 game.hasSeededPeerChanges = true
958 diagnostics.append(
959 "\(gameID.uuidString.prefix(8)) existing=\(existingRows.count) "
960 + "moves=\(values.count) current=\(current.count) "
961 + "seeding=\(isSeeding) upserts=\(upserts.count) "
962 + Self.peerChangeSampleSummary(upserts)
963 )
964 for change in upserts {
965
966
967
968 guard change.position.isPersistable(
969 gridWidth: game.gridWidth,
970 gridHeight: game.gridHeight
971 ) else { continue }
972 let row = rowByPosition[change.position] ?? PeerChangeEntity(context: ctx)
973 row.gameID = gameID
974 row.row = Int16(change.position.row)
975 row.col = Int16(change.position.col)
976 row.letter = change.letter
977 row.authorID = change.authorID
978 row.changedAt = change.changedAt
979 row.game = game
980 }
981 }
982 guard ctx.hasChanges else {
983 return (diagnostics: diagnostics, errorMessage: errorMessage)
984 }
985 do {
986 try ctx.save()
987 } catch {
988 errorMessage = "GameStore: peer change ledger save failed — \(error)"
989 }
990 return (diagnostics: diagnostics, errorMessage: errorMessage)
991 }
992 if let errorMessage = result.errorMessage {
993 eventLog?.note(errorMessage, level: "error")
994 }
995 let elapsed = Date().timeIntervalSince(startedAt)
996 eventLog?.note(
997 "peer ledger build #\(serial) end: elapsed=\(String(format: "%.3f", elapsed))s "
998 + result.diagnostics.joined(separator: " | ")
999 )
1000 }
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010 func noteIncomingMovesUpdate(gameIDs: Set<UUID>, currentAuthorID: String?) {
1011 guard let currentAuthorID, !gameIDs.isEmpty else { return }
1012
1013 for gameID in gameIDs {
1014 let gameReq = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1015 gameReq.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1016 gameReq.fetchLimit = 1
1017 guard let entity = try? context.fetch(gameReq).first else { continue }
1018
1019 let movesReq = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
1020 movesReq.predicate = NSPredicate(
1021 format: "game == %@ AND authorID != %@",
1022 entity,
1023 currentAuthorID
1024 )
1025 let rows = (try? context.fetch(movesReq)) ?? []
1026 guard let latest = rows.compactMap(\.updatedAt).max() else { continue }
1027
1028 if (entity.latestOtherMoveAt ?? .distantPast) < latest {
1029 entity.latestOtherMoveAt = latest
1030 }
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043 if NotificationState.isSuppressed(gameID: gameID),
1044 (entity.readThroughAt ?? .distantPast) < latest {
1045 entity.readThroughAt = latest
1046 }
1047 mirrorReadStateToChronicle(from: entity)
1048 }
1049
1050 if context.hasChanges {
1051 saveContext("mergeRemoteMoves")
1052 }
1053 onUnreadOtherMovesChanged?()
1054 }
1055
1056 @discardableResult
1057 func applyRealtimeCellEdit(_ edit: RealtimeCellEdit) -> Bool {
1058 applyRealtimeCellEdits([edit]) > 0
1059 }
1060
1061
1062
1063
1064
1065
1066
1067 @discardableResult
1068 func applyRealtimeCellEdits(_ edits: [RealtimeCellEdit]) -> Int {
1069
1070
1071
1072
1073
1074 let maxAcceptableUpdatedAt = Date().addingTimeInterval(Self.realtimeCellEditMaxFutureSkew)
1075 let groups = Dictionary(grouping: edits) { edit in
1076 RecordSerializer.recordName(
1077 forMovesInGame: edit.gameID,
1078 authorID: edit.authorID,
1079 deviceID: edit.deviceID
1080 )
1081 }
1082
1083 var applied = 0
1084 var rejected = 0
1085 var touchedGameIDs: Set<UUID> = []
1086 for (recordName, groupEdits) in groups {
1087 guard let sample = groupEdits.first,
1088 !sample.authorID.isEmpty,
1089 !sample.deviceID.isEmpty,
1090 sample.deviceID != RecordSerializer.localDeviceID,
1091 let entity = fetchGameEntity(id: sample.gameID)
1092 else { continue }
1093
1094
1095
1096
1097
1098
1099 let validEdits = groupEdits.filter { edit in
1100 GridPosition(row: edit.row, col: edit.col).isPersistable(
1101 gridWidth: entity.gridWidth,
1102 gridHeight: entity.gridHeight
1103 )
1104 }
1105 rejected += groupEdits.count - validEdits.count
1106 guard !validEdits.isEmpty else { continue }
1107
1108 let movesEntity = ensureMovesEntity(
1109 recordName: recordName,
1110 game: entity,
1111 authorID: sample.authorID,
1112 deviceID: sample.deviceID
1113 )
1114
1115 var cells: [GridPosition: TimestampedCell] = [:]
1116 if let data = movesEntity.cells, !data.isEmpty {
1117 cells = (try? MovesCodec.decode(data)) ?? [:]
1118 }
1119
1120 var latest = movesEntity.updatedAt ?? .distantPast
1121 var changed = false
1122 for edit in validEdits {
1123 let position = GridPosition(row: edit.row, col: edit.col)
1124 let clampedUpdatedAt = min(edit.updatedAt, maxAcceptableUpdatedAt)
1125 let incoming = TimestampedCell(
1126 letter: edit.letter,
1127 mark: edit.mark,
1128 updatedAt: clampedUpdatedAt,
1129 authorID: edit.cellAuthorID,
1130 tick: edit.tick
1131 )
1132 if let current = cells[position],
1133 current.compareRevision(to: incoming) == .orderedDescending {
1134 continue
1135 }
1136 cells[position] = incoming
1137 changed = true
1138 applied += 1
1139 if clampedUpdatedAt > latest { latest = clampedUpdatedAt }
1140 }
1141
1142 guard changed else { continue }
1143 movesEntity.cells = (try? MovesCodec.encode(cells)) ?? Data()
1144 if (movesEntity.updatedAt ?? .distantPast) < latest {
1145 movesEntity.updatedAt = latest
1146 }
1147 if (entity.updatedAt ?? .distantPast) < latest {
1148 entity.updatedAt = latest
1149 }
1150 touchedGameIDs.insert(sample.gameID)
1151 }
1152
1153 if rejected > 0 {
1154 eventLog?.note(
1155 "GameStore: rejected \(rejected) out-of-grid realtime cell edit(s)",
1156 level: "error"
1157 )
1158 }
1159 guard applied > 0 else { return 0 }
1160 saveContext("applyRealtimeCellEdits")
1161 if let openID = currentEntity?.id, touchedGameIDs.contains(openID) {
1162 refreshCurrentGame()
1163 }
1164 onUnreadOtherMovesChanged?()
1165 return applied
1166 }
1167
1168
1169
1170
1171 func unreadOtherMovesGameCount() -> Int {
1172 unreadOtherMovesGameTimes().count
1173 }
1174
1175
1176
1177
1178 func unreadOtherMovesGameIDs() -> Set<UUID> {
1179 Set(unreadOtherMovesGameTimes().keys)
1180 }
1181
1182 func hasUnreadOtherMoves(gameID: UUID) -> Bool {
1183 unreadOtherMovesGameIDs().contains(canonicalGameID(for: gameID))
1184 }
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194 func unreadOtherMovesGameTimes() -> [UUID: Date] {
1195 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1196 request.predicate = unreadOtherMovesPredicate
1197 request.propertiesToFetch = ["id", "latestOtherMoveAt"]
1198 let rows = (try? context.fetch(request)) ?? []
1199 var result: [UUID: Date] = [:]
1200 for row in rows {
1201 if let id = row.id, let at = row.latestOtherMoveAt {
1202 let canonicalID = row.ckRecordName.flatMap(
1203 Archive.originalGameID(fromName:)
1204 ) ?? id
1205 result[canonicalID] = max(result[canonicalID] ?? .distantPast, at)
1206 }
1207 }
1208 return result
1209 }
1210
1211
1212
1213
1214
1215
1216
1217 func pendingInviteGameIDs() -> Set<UUID> {
1218 let blockedRequest = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
1219 blockedRequest.predicate = NSPredicate(format: "isBlocked == YES")
1220 blockedRequest.propertiesToFetch = ["authorID"]
1221 let blocked = Set(((try? context.fetch(blockedRequest)) ?? []).compactMap(\.authorID))
1222
1223 let request = NSFetchRequest<InviteEntity>(entityName: "InviteEntity")
1224 request.predicate = NSPredicate(format: "status == %@", "pending")
1225 request.propertiesToFetch = ["gameID", "inviterAuthorID"]
1226 let rows = (try? context.fetch(request)) ?? []
1227 return Set(rows.compactMap { invite in
1228 guard let id = invite.gameID else { return nil }
1229 if let inviter = invite.inviterAuthorID, blocked.contains(inviter) { return nil }
1230 return id
1231 })
1232 }
1233
1234 private var unreadOtherMovesPredicate: NSPredicate {
1235
1236
1237
1238
1239
1240
1241 NSPredicate(
1242 format: "(databaseScope == 1 OR ckShareRecordName != nil "
1243 + "OR archiveParticipants != nil) "
1244 + "AND latestOtherMoveAt != nil "
1245 + "AND (readThroughAt == nil OR latestOtherMoveAt > readThroughAt)"
1246 )
1247 }
1248
1249
1250
1251
1252 func loadGame(id: UUID) throws -> (Game, GameMutator) {
1253 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1254 request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
1255 request.fetchLimit = 1
1256
1257 guard let entity = try context.fetch(request).first else {
1258 throw LoadError.gameNotFound
1259 }
1260 try upgradeOwnedGameSyncVersionIfNeeded(entity)
1261 let puzzle = try preparePuzzleForLoad(from: entity)
1262 let game = Game(puzzle: puzzle)
1263 restore(game: game, from: entity)
1264
1265 let mutator = makeMutator(game: game, entity: entity)
1266
1267 currentGame = game
1268 currentMutator = mutator
1269 currentEntity = entity
1270 markOtherMovesRead(for: entity)
1271
1272 return (game, mutator)
1273 }
1274
1275
1276
1277
1278
1279 func canonicalGameID(for storedGameID: UUID) -> UUID {
1280 guard let entity = fetchGameEntity(id: storedGameID),
1281 let recordName = entity.ckRecordName,
1282 let originalID = Archive.originalGameID(fromName: recordName)
1283 else { return storedGameID }
1284 return originalID
1285 }
1286
1287
1288
1289
1290
1291
1292 func isCompletedGameFamily(gameID: UUID) -> Bool {
1293 let canonicalID = canonicalGameID(for: gameID)
1294 return readStateEntities(canonicalGameID: canonicalID).contains {
1295 $0.completedAt != nil
1296 }
1297 }
1298
1299
1300
1301
1302
1303
1304 func findGameID(matching source: String) -> UUID? {
1305 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1306 request.predicate = NSPredicate(format: "puzzleSource == %@", source)
1307 request.fetchLimit = 1
1308 if let exact = try? context.fetch(request).first?.id {
1309 return exact
1310 }
1311
1312 guard let xd = try? XD.parse(source) else { return nil }
1313 let resourceID = PuzzleCatalog.resourceID(matching: source)
1314 let fallback = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1315 if let resourceID {
1316 fallback.predicate = NSPredicate(format: "puzzleResourceID == %@", resourceID)
1317 fallback.fetchLimit = 1
1318 if let match = try? context.fetch(fallback).first?.id {
1319 return match
1320 }
1321 }
1322
1323 guard resourceID != nil, let title = xd.title else { return nil }
1324 fallback.predicate = NSPredicate(format: "title == %@", title)
1325 fallback.fetchLimit = 1
1326 return (try? context.fetch(fallback).first?.id)
1327 }
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348 func nytPuzzleDatesInLibrary() -> Set<Date> {
1349 let request = NSFetchRequest<NSDictionary>(entityName: "GameEntity")
1350 request.resultType = .dictionaryResultType
1351 request.propertiesToFetch = ["cachedPuzzleDate"]
1352 request.returnsDistinctResults = true
1353 request.includesPendingChanges = false
1354 request.predicate = NSPredicate(
1355 format: "isHidden == NO AND cachedPublisher == %@ AND cachedPuzzleDate != nil",
1356 "New York Times"
1357 )
1358 let rows = (try? context.fetch(request)) ?? []
1359 var dates = rows.compactMap { $0["cachedPuzzleDate"] as? Date }
1360 dates.append(
1361 contentsOf: ChronicleLedgerEntity.puzzleDates(
1362 publisher: "New York Times",
1363 blockedAuthorIDs: GameEntity.blockedAuthorIDs(in: context),
1364 in: context
1365 )
1366 )
1367
1368 var calendar = Calendar(identifier: .gregorian)
1369 calendar.timeZone = TimeZone(identifier: "America/New_York") ?? .gmt
1370 return Set(dates.map { calendar.startOfDay(for: $0) })
1371 }
1372
1373
1374
1375
1376 func joinedSharedGameIDs() -> Set<UUID> {
1377 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1378 request.predicate = NSPredicate(
1379 format: "databaseScope == 1 AND puzzleSource != nil AND puzzleSource != %@",
1380 ""
1381 )
1382 return Set(((try? context.fetch(request)) ?? []).compactMap(\.id))
1383 }
1384
1385
1386
1387
1388 func createGame(from source: String) throws -> UUID {
1389 let xd = try XD.parse(source)
1390 let puzzle = Puzzle(xd: xd)
1391
1392 let now = Date()
1393 let gameID = UUID()
1394 let entity = GameEntity(context: context)
1395 entity.id = gameID
1396 entity.title = puzzle.title
1397 entity.puzzleSource = source
1398 entity.puzzleParserVersion = Int64(XD.currentParserVersion)
1399 entity.puzzleResourceID = PuzzleCatalog.resourceID(matching: source)
1400 entity.createdAt = now
1401 entity.updatedAt = now
1402 entity.ckRecordName = "game-\(gameID.uuidString)"
1403 entity.ckZoneName = "game-\(gameID.uuidString)"
1404 entity.databaseScope = 0
1405 entity.syncVersion = GameSyncVersion.current
1406 entity.populateCachedSummaryFields(from: puzzle)
1407
1408 try context.save()
1409 onGameCreated("game-\(gameID.uuidString)")
1410 return gameID
1411 }
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424 func constructJoinedGame(
1425 gameID: UUID,
1426 zoneID: CKRecordZone.ID,
1427 source: String,
1428 notification: String? = nil
1429 ) throws {
1430
1431
1432
1433
1434
1435
1436 guard zoneID.ownerName != CKCurrentUserDefaultName else {
1437 throw LoadError.sharedZoneOwnedByCurrentUser
1438 }
1439 let recordName = "game-\(gameID.uuidString)"
1440 let existing = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1441 existing.predicate = NSPredicate(format: "ckRecordName == %@", recordName)
1442 existing.fetchLimit = 1
1443 if let existingEntity = try? context.fetch(existing).first {
1444 if existingEntity.notification == nil, let notification {
1445 existingEntity.notification = notification
1446 GameEntity.rebuildContentKeyDirectory(in: context)
1447 try context.save()
1448 }
1449 return
1450 }
1451
1452 let xd = try XD.parse(source)
1453 let puzzle = Puzzle(xd: xd)
1454 let now = Date()
1455 let entity = GameEntity(context: context)
1456 entity.id = gameID
1457 entity.title = puzzle.title
1458 entity.puzzleSource = source
1459 entity.puzzleParserVersion = Int64(XD.currentParserVersion)
1460 entity.puzzleResourceID = PuzzleCatalog.resourceID(matching: source)
1461 entity.createdAt = now
1462 entity.updatedAt = now
1463 entity.ckRecordName = recordName
1464 entity.ckZoneName = zoneID.zoneName
1465 entity.ckZoneOwnerName = zoneID.ownerName
1466 entity.databaseScope = 1
1467 entity.syncVersion = GameSyncVersion.legacy
1468 entity.notification = notification
1469 entity.populateCachedSummaryFields(from: puzzle)
1470 if notification != nil {
1471 GameEntity.rebuildContentKeyDirectory(in: context)
1472 }
1473
1474 try context.save()
1475 }
1476
1477
1478
1479 func deleteGame(id: UUID) throws {
1480 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1481 request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
1482 request.fetchLimit = 1
1483
1484 guard let entity = try context.fetch(request).first else { return }
1485
1486 let materializedOriginalID = entity.ckRecordName.flatMap(
1487 Archive.originalGameID(fromName:)
1488 )
1489 let originalGameID = materializedOriginalID ?? id
1490 let isMaterializedArchive = materializedOriginalID != nil
1491 let hasArchive = isMaterializedArchive || entity.archivedAt != nil
1492 let deletion = GameCloudDeletion(
1493 gameID: id,
1494 databaseScope: DatabaseScope(entityValue: entity.databaseScope),
1495 ckZoneName: entity.ckZoneName ?? "game-\(id.uuidString)",
1496 ckZoneOwnerName: entity.ckZoneOwnerName ?? CKCurrentUserDefaultName,
1497 deletesLiveZone: !isMaterializedArchive,
1498 archiveRecordName: hasArchive
1499 ? Archive.recordName(forOriginalGameID: originalGameID)
1500 : nil,
1501 legacyArchiveZoneName: hasArchive
1502 ? Archive.legacyZoneID(forOriginalGameID: originalGameID).zoneName
1503 : nil
1504 )
1505
1506
1507 if currentEntity?.id == id {
1508 currentGame = nil
1509 currentMutator = nil
1510 currentEntity = nil
1511 }
1512
1513
1514
1515 if hasArchive {
1516 ChronicleLedgerEntity.remove(originalGameID: originalGameID, in: context)
1517 }
1518
1519 context.delete(entity)
1520 try context.save()
1521 onGameDeleted(deletion)
1522 onPushRegistrationMayNeedRefresh?()
1523 onUnreadOtherMovesChanged?()
1524 }
1525
1526
1527
1528
1529
1530
1531 func resignGame(id: UUID) throws {
1532 guard let existing = fetchGameEntity(id: id),
1533 !existing.isAccessRevoked,
1534 GameSyncVersion.supports(existing.syncVersion)
1535 else { return }
1536 let (game, mutator) = try loadGame(id: id)
1537 let allCells = game.puzzle.cells.flatMap { $0 }
1538 mutator.revealCells(allCells)
1539
1540 guard let entity = currentEntity else { return }
1541 let completedAt = Date()
1542 entity.completedAt = completedAt
1543 markObservedCompletionRead(for: entity, at: completedAt)
1544
1545
1546 entity.completedBy = nil
1547 entity.hasPendingSave = true
1548 try context.save()
1549 if let ckName = entity.ckRecordName {
1550 onGameUpdated(ckName)
1551 }
1552 Task { await movesUpdater.flush() }
1553 triggerJournalUpload(id: id, resigned: true, notifyPeers: true)
1554
1555
1556 currentGame = nil
1557 currentMutator = nil
1558 currentEntity = nil
1559 }
1560
1561
1562
1563
1564
1565
1566
1567
1568 func remapAuthorID(from oldID: String, to newID: String) {
1569 guard oldID != newID, !oldID.isEmpty, !newID.isEmpty else { return }
1570
1571 func fetch<T: NSManagedObject>(_ entityName: String, where predicate: NSPredicate) -> [T] {
1572 let request = NSFetchRequest<T>(entityName: entityName)
1573 request.predicate = predicate
1574 return (try? context.fetch(request)) ?? []
1575 }
1576
1577 let matchesOld = NSPredicate(format: "authorID == %@", oldID)
1578
1579
1580 for game: GameEntity in fetch("GameEntity", where: NSPredicate(format: "completedBy == %@", oldID)) {
1581 game.completedBy = newID
1582 }
1583 for cell: CellEntity in fetch("CellEntity", where: NSPredicate(format: "letterAuthorID == %@", oldID)) {
1584 cell.letterAuthorID = newID
1585 }
1586 for entry: JournalEntity in fetch("JournalEntity", where: NSPredicate(
1587 format: "actingAuthorID == %@ OR cellAuthorID == %@ OR beforeCellAuthorID == %@ OR sourceAuthorID == %@",
1588 oldID, oldID, oldID, oldID
1589 )) {
1590 if entry.actingAuthorID == oldID { entry.actingAuthorID = newID }
1591 if entry.cellAuthorID == oldID { entry.cellAuthorID = newID }
1592 if entry.beforeCellAuthorID == oldID { entry.beforeCellAuthorID = newID }
1593 if entry.sourceAuthorID == oldID { entry.sourceAuthorID = newID }
1594 }
1595
1596
1597
1598 for moves: MovesEntity in fetch("MovesEntity", where: matchesOld) {
1599 moves.authorID = newID
1600 if let gameID = moves.game?.id, let deviceID = moves.deviceID {
1601 moves.ckRecordName = RecordSerializer.recordName(
1602 forMovesInGame: gameID, authorID: newID, deviceID: deviceID
1603 )
1604 moves.ckSystemFields = nil
1605 }
1606 }
1607 for player: PlayerEntity in fetch("PlayerEntity", where: matchesOld) {
1608 player.authorID = newID
1609 if let gameID = player.game?.id {
1610 player.ckRecordName = RecordSerializer.recordName(
1611 forPlayerInGame: gameID, authorID: newID
1612 )
1613 player.ckSystemFields = nil
1614 }
1615 }
1616
1617 saveContext("remapAuthorID")
1618 }
1619
1620
1621
1622
1623
1624 @discardableResult
1625 func markCompleted(id: UUID) throws -> Bool {
1626 try persistCompletion(id: id, completedBy: authorIDProvider(), notifyPeers: true)
1627 }
1628
1629
1630
1631
1632 @discardableResult
1633 func markCompletedFromObservedSolvedState(id: UUID) throws -> Bool {
1634 let solver = inferredObservedCompletionAuthorID(for: id) ?? authorIDProvider()
1635 return try persistCompletion(id: id, completedBy: solver, notifyPeers: false)
1636 }
1637
1638 @discardableResult
1639 private func persistCompletion(
1640 id: UUID,
1641 completedBy authorID: String?,
1642 notifyPeers: Bool
1643 ) throws -> Bool {
1644 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1645 request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
1646 request.fetchLimit = 1
1647 guard let entity = try context.fetch(request).first,
1648 entity.completedAt == nil,
1649
1650
1651 !entity.isAccessRevoked,
1652 GameSyncVersion.supports(entity.syncVersion)
1653 else { return false }
1654 let completedAt = Date()
1655 entity.completedAt = completedAt
1656 markObservedCompletionRead(for: entity, at: completedAt)
1657
1658
1659 entity.completedBy = authorID
1660 entity.hasPendingSave = true
1661 try context.save()
1662
1663
1664 enqueuePeerChangeLedgerUpdate(for: [id])
1665
1666
1667 if currentEntity?.id == id {
1668 currentMutator?.isCompleted = true
1669 }
1670 if let ckName = entity.ckRecordName {
1671 onGameUpdated(ckName)
1672 }
1673 Task { await movesUpdater.flush() }
1674 triggerJournalUpload(id: id, resigned: false, notifyPeers: notifyPeers)
1675 return true
1676 }
1677
1678
1679
1680
1681
1682
1683
1684 private func markObservedCompletionRead(for entity: GameEntity, at completedAt: Date) {
1685 let isShared = entity.ckShareRecordName != nil || entity.databaseScope == 1
1686 guard isShared else { return }
1687 if (entity.readThroughAt ?? .distantPast) < completedAt {
1688 entity.readThroughAt = completedAt
1689 }
1690 mirrorReadStateToChronicle(from: entity)
1691 }
1692
1693
1694
1695
1696
1697
1698
1699 private func triggerJournalUpload(id: UUID, resigned: Bool, notifyPeers: Bool) {
1700 guard let authorID = authorIDProvider(), !authorID.isEmpty else { return }
1701 onJournalComplete?(id, authorID, resigned, notifyPeers)
1702 }
1703
1704
1705
1706
1707 func flushJournal() async {
1708 await movesJournal.flush()
1709 }
1710
1711
1712
1713
1714
1715
1716
1717 func flushCompletionWrites() async {
1718 await movesUpdater.flush()
1719 await movesJournal.flush()
1720 }
1721
1722
1723
1724
1725
1726 func localReplaySource(gameID: UUID) -> DeviceJournal? {
1727 guard let authorID = authorIDProvider(), !authorID.isEmpty else { return nil }
1728 let key = JournalDeviceKey(authorID: authorID, deviceID: RecordSerializer.localDeviceID)
1729 return DeviceJournal(key: key, entries: movesJournal.recordedEntries(gameID: gameID))
1730 }
1731
1732
1733
1734
1735
1736 func localJournalEntries(for gameID: UUID) -> [JournalValue] {
1737 movesJournal.recordedEntries(gameID: gameID)
1738 }
1739
1740
1741
1742
1743 func archivedReplayBlocker(forGameID gameID: UUID) async -> JournalReplayResult? {
1744 let ctx = persistence.container.newBackgroundContext()
1745 return await ctx.perform {
1746 let req = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1747 req.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1748 req.fetchLimit = 1
1749 guard let game = try? ctx.fetch(req).first else { return nil }
1750 if game.replayUnavailable { return .unavailable }
1751 if let missing = game.replayMissingDeviceCount?.intValue, missing > 0 {
1752 return .waiting(missing: missing)
1753 }
1754 return nil
1755 }
1756 }
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767 func cachedRemoteJournals(forGameID gameID: UUID) async -> [DeviceJournal]? {
1768 let ctx = persistence.container.newBackgroundContext()
1769 return await ctx.perform {
1770 let gameReq = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1771 gameReq.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1772 gameReq.fetchLimit = 1
1773 guard let game = try? ctx.fetch(gameReq).first, game.replayCacheComplete else {
1774 return nil
1775 }
1776 let req = NSFetchRequest<JournalEntity>(entityName: "JournalEntity")
1777 req.predicate = NSPredicate(
1778 format: "gameID == %@ AND sourceDeviceID != nil", gameID as CVarArg
1779 )
1780 req.sortDescriptors = [NSSortDescriptor(key: "seq", ascending: true)]
1781 let rows = (try? ctx.fetch(req)) ?? []
1782 var byDevice: [JournalDeviceKey: [JournalValue]] = [:]
1783 for row in rows {
1784 let key = JournalDeviceKey(
1785 authorID: row.sourceAuthorID ?? "",
1786 deviceID: row.sourceDeviceID ?? ""
1787 )
1788 byDevice[key, default: []].append(MovesJournal.value(from: row))
1789 }
1790 return byDevice.map { DeviceJournal(key: $0.key, entries: $0.value) }
1791 }
1792 }
1793
1794
1795
1796
1797
1798
1799 func cacheRemoteJournals(_ journals: [DeviceJournal], forGameID gameID: UUID) async {
1800 let ctx = persistence.container.newBackgroundContext()
1801 let eventLog = eventLog
1802 ctx.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
1803 await ctx.perform {
1804 let gameReq = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1805 gameReq.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1806 gameReq.fetchLimit = 1
1807 guard let game = try? ctx.fetch(gameReq).first else { return }
1808
1809 let stale = NSFetchRequest<JournalEntity>(entityName: "JournalEntity")
1810 stale.predicate = NSPredicate(
1811 format: "gameID == %@ AND sourceDeviceID != nil", gameID as CVarArg
1812 )
1813 for row in (try? ctx.fetch(stale)) ?? [] { ctx.delete(row) }
1814
1815
1816
1817
1818
1819 var skippedOutOfGrid = 0
1820 for journal in journals {
1821 for value in journal.entries {
1822 guard value.position.isPersistable(
1823 gridWidth: game.gridWidth,
1824 gridHeight: game.gridHeight
1825 ) else {
1826 skippedOutOfGrid += 1
1827 continue
1828 }
1829 let row = JournalEntity(context: ctx)
1830 MovesJournal.assign(value, to: row, gameID: gameID)
1831 row.sourceAuthorID = journal.key.authorID
1832 row.sourceDeviceID = journal.key.deviceID
1833 row.game = game
1834 }
1835 }
1836 if skippedOutOfGrid > 0 {
1837 let message = "GameStore: replay cache skipped \(skippedOutOfGrid) "
1838 + "out-of-grid remote journal entr(ies)"
1839 Task { @MainActor in
1840 eventLog?.note(message, level: "error")
1841 }
1842 }
1843 game.replayCacheComplete = true
1844 do {
1845 try ctx.save()
1846 } catch {
1847 let message = "GameStore: replay cache save failed — \(error)"
1848 Task { @MainActor in
1849 eventLog?.note(message, level: "error")
1850 }
1851 }
1852 }
1853 }
1854
1855
1856
1857
1858
1859
1860 func isCompleted(gameID: UUID) -> Bool {
1861 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1862 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1863 request.fetchLimit = 1
1864 return (try? context.fetch(request).first)?.completedAt != nil
1865 }
1866
1867
1868
1869 func engagement(for gameID: UUID) -> String? {
1870 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1871 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1872 request.fetchLimit = 1
1873 return (try? context.fetch(request).first)?.engagement
1874 }
1875
1876
1877
1878
1879
1880
1881 @discardableResult
1882 func setEngagement(_ encoded: String?, for gameID: UUID) -> Bool {
1883 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1884 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1885 request.fetchLimit = 1
1886 guard let entity = try? context.fetch(request).first else { return false }
1887 let isShared = entity.ckShareRecordName != nil || entity.databaseScope == 1
1888 guard isShared, entity.engagement != encoded else { return false }
1889 entity.engagement = encoded
1890 entity.hasPendingSave = true
1891 saveContext("setEngagement")
1892 if let ckName = entity.ckRecordName {
1893 onGameUpdated(ckName)
1894 }
1895 return true
1896 }
1897
1898
1899
1900 func notification(for gameID: UUID) -> String? {
1901 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1902 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1903 request.fetchLimit = 1
1904 return (try? context.fetch(request).first)?.notification
1905 }
1906
1907
1908
1909
1910
1911 @discardableResult
1912 func setNotification(_ encoded: String?, for gameID: UUID) -> Bool {
1913 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1914 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
1915 request.fetchLimit = 1
1916 guard let entity = try? context.fetch(request).first else { return false }
1917 let isShared = entity.ckShareRecordName != nil || entity.databaseScope == 1
1918 guard isShared, entity.notification != encoded else { return false }
1919 entity.notification = encoded
1920 entity.hasPendingSave = true
1921 saveContext("setNotification")
1922 GameEntity.rebuildContentKeyDirectory(in: context)
1923 if let ckName = entity.ckRecordName {
1924 onGameUpdated(ckName)
1925 }
1926 return true
1927 }
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937 @discardableResult
1938 func ensurePushCredentials(for gameID: UUID) -> GamePushCredentials? {
1939 if var existing = GamePushCredentials.decode(notification(for: gameID)) {
1940 if existing.contentKey != nil { return existing }
1941
1942
1943 guard let key = try? GamePushCredentials.freshContentKey() else { return existing }
1944 existing.contentKey = key
1945 guard let encoded = try? existing.encoded(), setNotification(encoded, for: gameID)
1946 else { return existing }
1947 return existing
1948 }
1949 guard let fresh = try? GamePushCredentials.fresh(),
1950 let encoded = try? fresh.encoded(),
1951 setNotification(encoded, for: gameID)
1952 else { return nil }
1953 return fresh
1954 }
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965 @discardableResult
1966 func rotatePushCredentials(for gameID: UUID) -> GamePushCredentials? {
1967 guard let current = GamePushCredentials.decode(notification(for: gameID)),
1968 let fresh = try? GamePushCredentials.rotated(after: current),
1969 let encoded = try? fresh.encoded(),
1970 setNotification(encoded, for: gameID)
1971 else { return nil }
1972 return fresh
1973 }
1974
1975
1976
1977
1978 func hasAnyGames() -> Bool {
1979 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
1980 return ((try? context.count(for: request)) ?? 0) > 0
1981 }
1982
1983
1984
1985
1986
1987
1988 func resetAllData() throws {
1989 for entity in try context.fetch(NSFetchRequest<GameEntity>(entityName: "GameEntity")) {
1990 context.delete(entity)
1991 }
1992 for entity in try context.fetch(NSFetchRequest<SyncStateEntity>(entityName: "SyncStateEntity")) {
1993 context.delete(entity)
1994 }
1995
1996
1997
1998 for entity in try context.fetch(NSFetchRequest<FriendEntity>(entityName: "FriendEntity")) {
1999 context.delete(entity)
2000 }
2001 for entity in try context.fetch(NSFetchRequest<InviteEntity>(entityName: "InviteEntity")) {
2002 context.delete(entity)
2003 }
2004
2005
2006
2007 for entity in try context.fetch(NSFetchRequest<JournalEntity>(entityName: "JournalEntity")) {
2008 context.delete(entity)
2009 }
2010 try context.save()
2011 currentGame = nil
2012 currentMutator = nil
2013 currentEntity = nil
2014 onUnreadOtherMovesChanged?()
2015 }
2016
2017
2018
2019
2020
2021
2022
2023 func loadOrCreateCurrentGame() throws -> (Game, GameMutator) {
2024 let entity: GameEntity
2025 let puzzle: Puzzle
2026
2027 if let existing = try fetchCurrentEntity() {
2028 entity = existing
2029 try upgradeOwnedGameSyncVersionIfNeeded(existing)
2030 puzzle = try preparePuzzleForLoad(from: existing)
2031 } else {
2032 (entity, puzzle) = try seedFromSample()
2033 }
2034
2035 let game = Game(puzzle: puzzle)
2036 restore(game: game, from: entity)
2037
2038 let mutator = makeMutator(game: game, entity: entity)
2039
2040 currentGame = game
2041 currentMutator = mutator
2042 currentEntity = entity
2043 markOtherMovesRead(for: entity)
2044
2045 return (game, mutator)
2046 }
2047
2048
2049
2050 private func fetchCurrentEntity() throws -> GameEntity? {
2051 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2052 request.sortDescriptors = [NSSortDescriptor(key: "updatedAt", ascending: false)]
2053 request.fetchLimit = 1
2054 return try context.fetch(request).first
2055 }
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071 @discardableResult
2072 func noteIncomingReadCursor(gameID: UUID, presenceUntil: Date) -> (previous: Date?, adopted: Bool) {
2073 let previous = fetchGameEntity(id: gameID)?.lastReadOtherMoveAt
2074 let adopted = setReadCursor(gameID: gameID, presenceUntil: presenceUntil)
2075 return (previous, adopted)
2076 }
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093 @discardableResult
2094 func setReadCursor(
2095 gameID: UUID,
2096 presenceUntil: Date,
2097 minimumExistingPresenceUntil: Date? = nil
2098 ) -> Bool {
2099 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2100 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2101 request.fetchLimit = 1
2102 guard let entity = try? context.fetch(request).first else { return false }
2103 let isShared = entity.ckShareRecordName != nil || entity.databaseScope == 1
2104 guard isShared else { return false }
2105 if let minimumExistingPresenceUntil,
2106 let current = entity.lastReadOtherMoveAt,
2107 current >= minimumExistingPresenceUntil {
2108 return false
2109 }
2110 guard entity.lastReadOtherMoveAt != presenceUntil else { return false }
2111 entity.lastReadOtherMoveAt = presenceUntil
2112 saveContext("updatePresenceUntil")
2113 onUnreadOtherMovesChanged?()
2114 return true
2115 }
2116
2117
2118
2119
2120
2121
2122
2123 @discardableResult
2124 func advanceReadThrough(gameID: UUID, through: Date) -> Bool {
2125 let canonicalID = canonicalGameID(for: gameID)
2126 let entities = readStateEntities(canonicalGameID: canonicalID)
2127 guard entities.contains(where: {
2128 $0.ckShareRecordName != nil
2129 || $0.databaseScope == 1
2130 || isArchivedSharedGame($0)
2131 }) else { return false }
2132 var changed = false
2133 for entity in entities where (entity.readThroughAt ?? .distantPast) < through {
2134 entity.readThroughAt = through
2135 changed = true
2136 }
2137 guard changed else { return false }
2138 saveContext("advanceReadThrough")
2139 onUnreadOtherMovesChanged?()
2140 return true
2141 }
2142
2143 private func markOtherMovesRead(for entity: GameEntity) {
2144 guard let storedID = entity.id else { return }
2145 let canonicalID = canonicalGameID(for: storedID)
2146 let entities = readStateEntities(canonicalGameID: canonicalID)
2147 let isShared = entities.contains {
2148 $0.ckShareRecordName != nil
2149 || $0.databaseScope == 1
2150 || isArchivedSharedGame($0)
2151 }
2152 guard isShared,
2153 let latest = entities.compactMap(\.latestOtherMoveAt).max()
2154 else { return }
2155
2156
2157
2158
2159 var changed = false
2160 for candidate in entities where (candidate.readThroughAt ?? .distantPast) < latest {
2161 candidate.readThroughAt = latest
2162 changed = true
2163 }
2164 guard changed else { return }
2165 saveContext("markOtherMovesRead")
2166 onUnreadOtherMovesChanged?()
2167 }
2168
2169 private func readStateEntities(canonicalGameID: UUID) -> [GameEntity] {
2170 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2171 request.predicate = NSPredicate(
2172 format: "id IN %@",
2173 [
2174 canonicalGameID,
2175 Archive.archiveGameID(for: canonicalGameID)
2176 ]
2177 )
2178 return (try? context.fetch(request)) ?? []
2179 }
2180
2181 private func mirrorReadStateToChronicle(from live: GameEntity) {
2182 guard let liveID = live.id else { return }
2183 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2184 request.predicate = NSPredicate(
2185 format: "id == %@",
2186 Archive.archiveGameID(for: liveID) as CVarArg
2187 )
2188 request.fetchLimit = 1
2189 guard let chronicle = try? context.fetch(request).first else { return }
2190 Archive.mirrorReadState(from: live, to: chronicle)
2191 }
2192
2193 private func seedFromSample() throws -> (GameEntity, Puzzle) {
2194 guard let url = Bundle.main.resourceURL?
2195 .appendingPathComponent("Puzzles/debug/sample.xd") else {
2196 throw LoadError.sampleResourceMissing
2197 }
2198 let source = try String(contentsOf: url, encoding: .utf8)
2199 let xd = try XD.parse(source)
2200 let puzzle = Puzzle(xd: xd)
2201
2202 let now = Date()
2203 let gameID = UUID()
2204 let entity = GameEntity(context: context)
2205 entity.id = gameID
2206 entity.title = puzzle.title
2207 entity.puzzleSource = source
2208 entity.puzzleParserVersion = Int64(XD.currentParserVersion)
2209 entity.puzzleResourceID = PuzzleCatalog.resourceID(matching: source)
2210 entity.createdAt = now
2211 entity.updatedAt = now
2212 entity.ckRecordName = "game-\(gameID.uuidString)"
2213 entity.ckZoneName = "game-\(gameID.uuidString)"
2214 entity.databaseScope = 0
2215 entity.syncVersion = GameSyncVersion.current
2216 entity.populateCachedSummaryFields(from: puzzle)
2217
2218 try context.save()
2219 onGameCreated("game-\(gameID.uuidString)")
2220 return (entity, puzzle)
2221 }
2222
2223 private func preparePuzzleForLoad(from entity: GameEntity) throws -> Puzzle {
2224 guard let source = entity.puzzleSource else {
2225 throw LoadError.persistedSourceMissing
2226 }
2227
2228 let currentVersion = Int64(XD.currentParserVersion)
2229 if entity.puzzleParserVersion != currentVersion {
2230 let catalogSource = PuzzleCatalog.source(
2231 matchingResourceID: entity.puzzleResourceID,
2232 title: try? XD.parse(source).title
2233 )
2234 let nextSource = (catalogSource.flatMap { try? $0.loadSource() }) ?? source
2235 let nextXD = try XD.parse(nextSource)
2236 let puzzle = Puzzle(xd: nextXD)
2237 entity.title = puzzle.title
2238 entity.puzzleSource = nextSource
2239 entity.puzzleParserVersion = currentVersion
2240 if let catalogSource {
2241 entity.puzzleResourceID = catalogSource.id
2242 } else if entity.puzzleResourceID == nil {
2243 entity.puzzleResourceID = PuzzleCatalog.resourceID(matching: nextSource)
2244 }
2245 entity.populateCachedSummaryFields(from: puzzle)
2246 try context.save()
2247 return puzzle
2248 }
2249
2250 if entity.puzzleResourceID == nil {
2251 entity.puzzleResourceID = PuzzleCatalog.resourceID(matching: source)
2252 if context.hasChanges { try context.save() }
2253 }
2254
2255 return Puzzle(xd: try XD.parse(source))
2256 }
2257
2258
2259
2260
2261 struct PuzzleInfo: Sendable {
2262 let gameID: UUID
2263 let source: String
2264 let isOwned: Bool
2265 }
2266
2267 func puzzleInfo(for id: UUID) -> PuzzleInfo? {
2268 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2269 request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
2270 request.fetchLimit = 1
2271 guard let entity = try? context.fetch(request).first,
2272 let source = entity.puzzleSource
2273 else { return nil }
2274 return PuzzleInfo(
2275 gameID: id,
2276 source: source,
2277
2278
2279
2280 isOwned: entity.databaseScope == 0
2281 && entity.completedAt == nil
2282 && !isMaterializedArchive(entity)
2283 )
2284 }
2285
2286
2287
2288
2289
2290
2291 func setViewedAt(_ viewedAt: Date?, gameID: UUID, authorID: String) {
2292 let entity: PlayerEntity
2293 if let existing = fetchPlayerEntity(gameID: gameID, authorID: authorID) {
2294 entity = existing
2295 } else {
2296 let gameRequest = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2297 gameRequest.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2298 gameRequest.fetchLimit = 1
2299 guard let game = try? context.fetch(gameRequest).first else { return }
2300 entity = PlayerEntity(context: context)
2301 entity.game = game
2302 entity.authorID = authorID
2303 entity.ckRecordName = RecordSerializer.recordName(
2304 forPlayerInGame: gameID,
2305 authorID: authorID
2306 )
2307 entity.updatedAt = Date()
2308 }
2309 entity.viewedAt = viewedAt
2310 saveContext("setViewedAt")
2311 }
2312
2313
2314
2315
2316
2317
2318
2319
2320 @discardableResult
2321 func openClockSession(
2322 gameID: UUID,
2323 authorID: String,
2324 reconcileStale: Bool = false,
2325 at now: Date = Date()
2326 ) -> Bool {
2327 mutateTimeLog(gameID: gameID, authorID: authorID) {
2328 $0.open(deviceID: RecordSerializer.localDeviceID, at: now, reconcileStale: reconcileStale)
2329 }
2330 }
2331
2332
2333 @discardableResult
2334 func sealClockSession(gameID: UUID, authorID: String, at now: Date = Date()) -> Bool {
2335 mutateTimeLog(gameID: gameID, authorID: authorID) {
2336 $0.seal(deviceID: RecordSerializer.localDeviceID, at: now)
2337 }
2338 }
2339
2340
2341
2342 @discardableResult
2343 func beatClockSession(gameID: UUID, authorID: String, at now: Date = Date()) -> Bool {
2344 mutateTimeLog(gameID: gameID, authorID: authorID) {
2345 $0.beat(deviceID: RecordSerializer.localDeviceID, at: now)
2346 }
2347 }
2348
2349
2350
2351 func completedAt(forGame gameID: UUID) -> Date? {
2352 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2353 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2354 request.fetchLimit = 1
2355 return (try? context.fetch(request).first)?.completedAt
2356 }
2357
2358
2359
2360 func isGameCompleted(gameID: UUID) -> Bool {
2361 completedAt(forGame: gameID) != nil
2362 }
2363
2364
2365
2366
2367
2368 func isGameShared(gameID: UUID) -> Bool {
2369 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2370 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2371 request.fetchLimit = 1
2372 guard let entity = try? context.fetch(request).first else { return false }
2373 return entity.ckShareRecordName != nil || entity.databaseScope == 1
2374 }
2375
2376
2377
2378
2379
2380
2381
2382 func isGameArchived(gameID: UUID) -> Bool {
2383 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2384 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2385 request.fetchLimit = 1
2386 guard let entity = try? context.fetch(request).first else { return false }
2387 return isGameArchived(entity)
2388 }
2389
2390
2391
2392 func isGameArchived(_ entity: GameEntity) -> Bool {
2393 isMaterializedArchive(entity)
2394 }
2395
2396
2397
2398
2399
2400
2401
2402 @discardableResult
2403 private func mutateTimeLog(
2404 gameID: UUID,
2405 authorID: String,
2406 _ change: (inout TimeLog) -> Void
2407 ) -> Bool {
2408 let entity: PlayerEntity
2409 if let existing = fetchPlayerEntity(gameID: gameID, authorID: authorID) {
2410 entity = existing
2411 } else {
2412 let gameRequest = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2413 gameRequest.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2414 gameRequest.fetchLimit = 1
2415 guard let game = try? context.fetch(gameRequest).first else { return false }
2416 entity = PlayerEntity(context: context)
2417 entity.game = game
2418 entity.authorID = authorID
2419 entity.ckRecordName = RecordSerializer.recordName(
2420 forPlayerInGame: gameID,
2421 authorID: authorID
2422 )
2423 entity.updatedAt = Date()
2424 }
2425 var log = TimeLog.decode(entity.timeLog)
2426 change(&log)
2427
2428
2429 guard !log.devices.isEmpty else { return false }
2430 let encoded = TimeLog.encode(log)
2431 guard entity.timeLog != encoded else { return false }
2432 entity.timeLog = encoded
2433 saveContext("updateTimeLog")
2434 return true
2435 }
2436
2437
2438
2439
2440
2441
2442
2443
2444 @discardableResult
2445 func setPushAddress(gameID: UUID, authorID: String, secret: String) -> String? {
2446 let entity: PlayerEntity
2447 if let existing = fetchPlayerEntity(gameID: gameID, authorID: authorID) {
2448 entity = existing
2449 } else {
2450 let gameRequest = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2451 gameRequest.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2452 gameRequest.fetchLimit = 1
2453 guard let game = try? context.fetch(gameRequest).first else { return nil }
2454 entity = PlayerEntity(context: context)
2455 entity.game = game
2456 entity.authorID = authorID
2457 entity.ckRecordName = RecordSerializer.recordName(
2458 forPlayerInGame: gameID,
2459 authorID: authorID
2460 )
2461 entity.updatedAt = Date()
2462 }
2463 let address = RecordSerializer.deriveGameAddress(secret: secret, gameID: gameID)
2464 guard entity.pushAddress != address else { return address }
2465 entity.pushAddress = address
2466
2467
2468 entity.updatedAt = Date()
2469 saveContext("setPushAddress")
2470 return address
2471 }
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483 func reconcileLocalPushAddresses(
2484 authorID: String,
2485 secret: String,
2486 republishPlayerRows: Bool = true
2487 ) -> (bindings: [PushAddressBinding], republishGameIDs: [UUID]) {
2488 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2489 request.predicate = NSPredicate(
2490 format: "databaseScope == 1 OR ckShareRecordName != nil"
2491 )
2492 let games = (try? context.fetch(request)) ?? []
2493 var bindings: [PushAddressBinding] = []
2494 var republishGameIDs: [UUID] = []
2495 var gameRecordUpdates: [String] = []
2496 var notificationCredentialsChanged = false
2497 var didChange = false
2498 for game in games {
2499 guard let gameID = game.id else { continue }
2500
2501
2502 var creds = GamePushCredentials.decode(game.notification)
2503 if creds == nil,
2504 let fresh = try? GamePushCredentials.fresh(),
2505 let encoded = try? fresh.encoded() {
2506 game.notification = encoded
2507 game.hasPendingSave = true
2508 creds = fresh
2509 notificationCredentialsChanged = true
2510 didChange = true
2511 if let ckName = game.ckRecordName { gameRecordUpdates.append(ckName) }
2512 }
2513 guard let credentials = creds else { continue }
2514 let address = RecordSerializer.deriveGameAddress(secret: secret, gameID: gameID)
2515 bindings.append(
2516 PushAddressBinding(gameID: gameID, address: address, credentials: credentials)
2517 )
2518
2519 guard republishPlayerRows,
2520 let player = fetchPlayerEntity(gameID: gameID, authorID: authorID),
2521 player.pushAddress != address
2522 else { continue }
2523 player.pushAddress = address
2524 player.updatedAt = Date()
2525 republishGameIDs.append(gameID)
2526 didChange = true
2527 }
2528 if didChange {
2529 saveContext("reconcileLocalPushAddresses")
2530 if notificationCredentialsChanged {
2531 GameEntity.rebuildContentKeyDirectory(in: context)
2532 }
2533 }
2534
2535
2536 for ckName in gameRecordUpdates {
2537 onGameUpdated(ckName)
2538 }
2539 return (bindings, republishGameIDs)
2540 }
2541
2542
2543
2544
2545
2546
2547 func playerUpdatedAt(for gameID: UUID, by authorID: String) -> Date? {
2548 fetchPlayerEntity(gameID: gameID, authorID: authorID)?.updatedAt
2549 }
2550
2551
2552
2553
2554
2555 func notifiedThrough(for gameID: UUID, by authorID: String) -> Date? {
2556 fetchPlayerEntity(gameID: gameID, authorID: authorID)?.notifiedThrough
2557 }
2558
2559
2560
2561
2562
2563
2564
2565
2566 func recordNotified(gameID: UUID, authorIDs: [String], through: Date) {
2567 guard !authorIDs.isEmpty else { return }
2568 var didChange = false
2569 for authorID in authorIDs {
2570 guard let player = fetchPlayerEntity(gameID: gameID, authorID: authorID) else {
2571 continue
2572 }
2573 if let current = player.notifiedThrough, current >= through { continue }
2574 player.notifiedThrough = through
2575 didChange = true
2576 }
2577 if didChange {
2578 saveContext("recordNotified")
2579 }
2580 }
2581
2582
2583
2584
2585
2586
2587
2588 func mergedAuthorCells(for gameID: UUID, by authorID: String) -> [TimestampedCell] {
2589 let request = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
2590 request.predicate = NSPredicate(
2591 format: "game.id == %@ AND authorID == %@",
2592 gameID as CVarArg,
2593 authorID
2594 )
2595 let entities = (try? context.fetch(request)) ?? []
2596 let values: [MovesValue] = entities.compactMap { Self.movesValue(from: $0) }
2597 guard !values.isEmpty else { return [] }
2598 return GridStateMerger.mergeWithProvenance(values).values.map(\.cell)
2599 }
2600
2601
2602
2603
2604
2605
2606
2607 func recentlyChangedCells(forGame gameID: UUID, since: Date) -> [GridPosition: String] {
2608 recentChanges(forGame: gameID, since: since).cells
2609 }
2610
2611
2612
2613
2614
2615
2616
2617 func recentChanges(forGame gameID: UUID, since: Date) -> RecentChanges.Changes {
2618 guard let localAuthorID = authorIDProvider() else { return .empty }
2619 let request = NSFetchRequest<PeerChangeEntity>(entityName: "PeerChangeEntity")
2620 request.predicate = NSPredicate(
2621 format: "gameID == %@ AND changedAt > %@",
2622 gameID as CVarArg,
2623 since as NSDate
2624 )
2625 let rows = (try? context.fetch(request)) ?? []
2626 guard !rows.isEmpty else { return .empty }
2627 let entries = rows.map { Self.peerChange(from: $0) }
2628 return RecentChanges.changes(in: entries, since: since, excludingAuthor: localAuthorID)
2629 }
2630
2631
2632
2633
2634
2635 func recentChangesDiagnosticSummary(forGame gameID: UUID, since: Date) -> String {
2636 let localAuthorID = authorIDProvider()
2637 let allReq = NSFetchRequest<PeerChangeEntity>(entityName: "PeerChangeEntity")
2638 allReq.predicate = NSPredicate(format: "gameID == %@", gameID as CVarArg)
2639 let allRows = (try? context.fetch(allReq)) ?? []
2640
2641 let newerRows = allRows.filter { ($0.changedAt ?? .distantPast) > since }
2642 let entries = newerRows.map { Self.peerChange(from: $0) }
2643 let changes = localAuthorID.map {
2644 RecentChanges.changes(in: entries, since: since, excludingAuthor: $0)
2645 } ?? .empty
2646 let counted = changes.counts.values.reduce(0) { $0 + $1.added + $1.cleared }
2647 let byAuthor = changes.counts.keys.sorted().map { authorID in
2648 let count = changes.counts[authorID] ?? RecentChanges.Count(added: 0, cleared: 0)
2649 return "\(authorID.prefix(8))=+\(count.added)/-\(count.cleared)"
2650 }.joined(separator: ",")
2651 let newest = allRows.compactMap(\.changedAt).max()
2652
2653 return "since=\(since.ISO8601Format()) "
2654 + "local=\(Self.shortAuthorID(localAuthorID)) "
2655 + "ledgerRows=\(allRows.count) newer=\(newerRows.count) "
2656 + "counted=\(counted) cells=\(changes.cells.count) "
2657 + "byAuthor=[\(byAuthor)] "
2658 + "newest=\(newest?.ISO8601Format() ?? "nil") "
2659 + Self.peerChangeEntitySampleSummary(newerRows)
2660 }
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670 func movesDiagnostics(for gameID: UUID, by authorID: String) -> PushPayload.Diagnostics? {
2671 let gReq = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2672 gReq.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2673 gReq.fetchLimit = 1
2674 guard let game = try? context.fetch(gReq).first else { return nil }
2675
2676 let mReq = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
2677 mReq.predicate = NSPredicate(
2678 format: "game.id == %@ AND authorID == %@",
2679 gameID as CVarArg,
2680 authorID
2681 )
2682 let entities = (try? context.fetch(mReq)) ?? []
2683 let values: [MovesValue] = entities.compactMap { Self.movesValue(from: $0) }
2684 let merged = GridStateMerger.mergeWithProvenance(values)
2685
2686 let width = Int(game.gridWidth)
2687 let height = Int(game.gridHeight)
2688 let puzzle = game.puzzleSource
2689 .flatMap { try? XD.parse($0) }
2690 .map(Puzzle.init(xd:))
2691
2692 var inBounds = 0
2693 var playable = 0
2694 var minRow = Int.max, maxRow = Int.min, minCol = Int.max, maxCol = Int.min
2695 var earliest: Date?
2696 var latest: Date?
2697 for (position, provenance) in merged {
2698 minRow = min(minRow, position.row); maxRow = max(maxRow, position.row)
2699 minCol = min(minCol, position.col); maxCol = max(maxCol, position.col)
2700 let updatedAt = provenance.cell.updatedAt
2701 if earliest == nil || updatedAt < earliest! { earliest = updatedAt }
2702 if latest == nil || updatedAt > latest! { latest = updatedAt }
2703 let within = position.row >= 0 && position.row < height
2704 && position.col >= 0 && position.col < width
2705 guard within else { continue }
2706 inBounds += 1
2707 if let puzzle, !puzzle.cells[position.row][position.col].isBlock {
2708 playable += 1
2709 }
2710 }
2711 let deviceCount = Set(entities.compactMap { $0.deviceID }).count
2712
2713 return PushPayload.Diagnostics(
2714 gridWidth: width,
2715 gridHeight: height,
2716 parserVersion: Int(game.puzzleParserVersion),
2717 mergedCells: merged.count,
2718 inBounds: inBounds,
2719 playable: playable,
2720 minRow: merged.isEmpty ? nil : minRow,
2721 maxRow: merged.isEmpty ? nil : maxRow,
2722 minCol: merged.isEmpty ? nil : minCol,
2723 maxCol: merged.isEmpty ? nil : maxCol,
2724 deviceCount: deviceCount,
2725 earliestEdit: earliest,
2726 latestEdit: latest
2727 )
2728 }
2729
2730
2731
2732
2733
2734
2735
2736
2737 func contributingDevices(for gameID: UUID) -> Set<JournalDeviceKey> {
2738 let request = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
2739 request.predicate = NSPredicate(format: "game.id == %@", gameID as CVarArg)
2740 let entities = (try? context.fetch(request)) ?? []
2741 var devices: Set<JournalDeviceKey> = []
2742 for entity in entities {
2743 guard let authorID = entity.authorID, !authorID.isEmpty,
2744 let deviceID = entity.deviceID, !deviceID.isEmpty else { continue }
2745 devices.insert(JournalDeviceKey(authorID: authorID, deviceID: deviceID))
2746 }
2747 return devices
2748 }
2749
2750
2751
2752
2753 func peerAuthorIDs(for gameID: UUID, excluding localAuthorID: String?) -> [String] {
2754 let request = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
2755 request.predicate = NSPredicate(format: "game.id == %@", gameID as CVarArg)
2756 let entities = (try? context.fetch(request)) ?? []
2757 var unique: Set<String> = []
2758 for entity in entities {
2759 guard let authorID = entity.authorID, !authorID.isEmpty else { continue }
2760 if let localAuthorID, authorID == localAuthorID { continue }
2761 unique.insert(authorID)
2762 }
2763 return Array(unique)
2764 }
2765
2766
2767
2768 func puzzleTitleForNotification(for gameID: UUID) -> String {
2769 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2770 request.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
2771 request.fetchLimit = 1
2772 let entity = try? context.fetch(request).first
2773 return PuzzleNotificationText.title(for: entity)
2774 }
2775
2776
2777
2778
2779 func playerName(for gameID: UUID, by authorID: String) -> String {
2780 return fetchPlayerEntity(gameID: gameID, authorID: authorID)?.name ?? ""
2781 }
2782
2783
2784
2785
2786
2787
2788 func friendNickname(for authorID: String) -> String? {
2789 guard !authorID.isEmpty else { return nil }
2790 let request = NSFetchRequest<FriendEntity>(entityName: "FriendEntity")
2791 request.predicate = NSPredicate(format: "authorID == %@", authorID)
2792 request.fetchLimit = 1
2793 guard let nickname = (try? context.fetch(request).first)?.nickname?
2794 .trimmingCharacters(in: .whitespacesAndNewlines),
2795 !nickname.isEmpty
2796 else { return nil }
2797 return nickname
2798 }
2799
2800
2801
2802
2803
2804 func presenceUntil(for gameID: UUID, by authorID: String) -> Date? {
2805 return fetchPlayerEntity(gameID: gameID, authorID: authorID)?.presenceUntil
2806 }
2807
2808
2809
2810
2811 func localPushAddress(gameID: UUID, authorID: String) -> String? {
2812 fetchPlayerEntity(gameID: gameID, authorID: authorID)?.pushAddress
2813 }
2814
2815
2816
2817
2818
2819 func participantAuthorIDs(gameID: UUID) -> [String] {
2820 guard let entity = fetchGameEntity(id: gameID),
2821 let summary = GameSummary(entity: entity, localAuthorID: authorIDProvider())
2822 else { return [] }
2823 return summary.allParticipants.map(\.authorID).filter { !$0.isEmpty }
2824 }
2825
2826 private func fetchPlayerEntity(gameID: UUID, authorID: String) -> PlayerEntity? {
2827 let request = NSFetchRequest<PlayerEntity>(entityName: "PlayerEntity")
2828 request.predicate = NSPredicate(
2829 format: "game.id == %@ AND authorID == %@",
2830 gameID as CVarArg,
2831 authorID
2832 )
2833 request.fetchLimit = 1
2834 return try? context.fetch(request).first
2835 }
2836
2837
2838
2839
2840
2841
2842
2843 func replacePuzzleSource(id: UUID, with newSource: String) {
2844 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2845 request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
2846 request.fetchLimit = 1
2847 guard let entity = try? context.fetch(request).first,
2848 let parsed = try? XD.parse(newSource) else { return }
2849 let puzzle = Puzzle(xd: parsed)
2850 entity.puzzleSource = newSource
2851 entity.title = puzzle.title
2852 entity.puzzleParserVersion = Int64(XD.currentParserVersion)
2853 entity.hasPushPending = true
2854 entity.hasPendingSave = true
2855 entity.populateCachedSummaryFields(from: puzzle)
2856 saveContext("upgradePuzzleSource")
2857 if let ckName = entity.ckRecordName {
2858 onGameUpdated(ckName)
2859 }
2860 }
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870 func stampConverterVersion(for id: UUID) {
2871 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
2872 request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
2873 request.fetchLimit = 1
2874 guard let entity = try? context.fetch(request).first,
2875 let source = entity.puzzleSource else { return }
2876 entity.puzzleSource = XD.settingConverterVersionHeader(
2877 in: source, to: XD.currentConverterVersion
2878 )
2879 saveContext("stampConverterVersion")
2880 }
2881
2882 private func restore(game: Game, from entity: GameEntity, updateCache: Bool = true) {
2883 let movesRequest = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
2884 movesRequest.predicate = NSPredicate(format: "game == %@", entity)
2885 let movesEntities = (try? context.fetch(movesRequest)) ?? []
2886 let values: [MovesValue] = movesEntities.compactMap { Self.movesValue(from: $0) }
2887
2888
2889
2890 let archiveGrid = materializedArchiveGrid(entity)
2891 let grid = archiveGrid ?? GridStateMerger.merge(values)
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904 if let completedAt = entity.completedAt {
2905 let sealedGrid = archiveGrid
2906 ?? GridStateMerger.merge(values, notAfter: completedAt)
2907 sealToSolution(game: game, mergedGrid: sealedGrid)
2908 if updateCache {
2909 updateCellCache(for: entity, from: grid)
2910 }
2911 return
2912 }
2913
2914
2915
2916
2917
2918
2919 let localDeviceID = RecordSerializer.localDeviceID
2920 let localAuthorID = authorIDProvider()
2921 let localCells: [GridPosition: TimestampedCell] = values.first {
2922 $0.deviceID == localDeviceID
2923 && (localAuthorID == nil || $0.authorID == localAuthorID)
2924 }?.cells ?? [:]
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935 var changed = false
2936 for (position, cell) in grid {
2937 let r = position.row
2938 let c = position.col
2939 guard r >= 0, r < game.puzzle.height, c >= 0, c < game.puzzle.width else { continue }
2940 let current = game.squares[r][c]
2941
2942
2943
2944
2945
2946 var clearEnqueued = false
2947 if let stamp = current.enqueuedAt {
2948 guard let landed = localCells[position],
2949 landed.updatedAt >= stamp
2950 else { continue }
2951 clearEnqueued = true
2952 }
2953 guard clearEnqueued
2954 || current.entry != cell.letter
2955 || current.mark != cell.mark
2956 || current.letterAuthorID != cell.authorID
2957 else { continue }
2958
2959
2960 var updated = current
2961 updated.enqueuedAt = clearEnqueued ? nil : current.enqueuedAt
2962 updated.entry = cell.letter
2963 updated.mark = cell.mark
2964 updated.letterAuthorID = cell.authorID
2965 game.squares[r][c] = updated
2966 changed = true
2967 }
2968 if changed {
2969 game.recomputeCompletionCache()
2970 }
2971
2972 if updateCache {
2973 updateCellCache(for: entity, from: grid)
2974 }
2975 }
2976
2977
2978
2979
2980
2981
2982
2983 private func sealToSolution(game: Game, mergedGrid: GridState) {
2984 for r in 0..<game.puzzle.height {
2985 for c in 0..<game.puzzle.width {
2986 let cell = game.puzzle.cells[r][c]
2987 guard !cell.isBlock else { continue }
2988 game.squares[r][c].enqueuedAt = nil
2989 let merged = mergedGrid[GridPosition(row: r, col: c)]
2990 if let merged, cell.accepts(merged.letter) {
2991
2992
2993
2994 game.squares[r][c].entry = merged.letter
2995 game.squares[r][c].mark = merged.mark.withoutWrongCheck
2996 game.squares[r][c].letterAuthorID = merged.authorID
2997 } else if let solution = cell.solution {
2998
2999 game.squares[r][c].entry = solution
3000 game.squares[r][c].mark = .none
3001 game.squares[r][c].letterAuthorID = merged?.authorID
3002 } else if let merged {
3003
3004 game.squares[r][c].entry = merged.letter
3005 game.squares[r][c].mark = merged.mark
3006 game.squares[r][c].letterAuthorID = merged.authorID
3007 }
3008 }
3009 }
3010 game.recomputeCompletionCache()
3011 }
3012
3013 private func updateCellCache(for gameEntity: GameEntity, from grid: GridState) {
3014 Self.applyCellCache(to: gameEntity, from: grid, in: context)
3015 saveContext("updateCellCache")
3016 }
3017
3018
3019
3020 fileprivate nonisolated static func movesValue(from entity: MovesEntity) -> MovesValue? {
3021 guard let gameID = entity.game?.id,
3022 let authorID = entity.authorID,
3023 let deviceID = entity.deviceID,
3024 let updatedAt = entity.updatedAt
3025 else { return nil }
3026 let cells = (entity.cells.flatMap { try? MovesCodec.decode($0) }) ?? [:]
3027 return MovesValue(
3028 gameID: gameID,
3029 authorID: authorID,
3030 deviceID: deviceID,
3031 cells: cells,
3032 updatedAt: updatedAt
3033 )
3034 }
3035
3036 fileprivate nonisolated static func peerChange(from entity: PeerChangeEntity) -> PeerChange {
3037 PeerChange(
3038 position: GridPosition(row: Int(entity.row), col: Int(entity.col)),
3039 letter: entity.letter ?? "",
3040 authorID: entity.authorID,
3041 changedAt: entity.changedAt ?? .distantPast
3042 )
3043 }
3044
3045 private nonisolated static func peerChangeSampleSummary(_ changes: [PeerChange]) -> String {
3046 guard !changes.isEmpty else { return "sample=[]" }
3047 let sample = changes
3048 .sorted { lhs, rhs in
3049 if lhs.changedAt != rhs.changedAt { return lhs.changedAt < rhs.changedAt }
3050 if lhs.position.row != rhs.position.row { return lhs.position.row < rhs.position.row }
3051 return lhs.position.col < rhs.position.col
3052 }
3053 .prefix(5)
3054 .map {
3055 "r\($0.position.row)c\($0.position.col):"
3056 + "\($0.letter.isEmpty ? "-" : $0.letter)"
3057 + "@\($0.changedAt.ISO8601Format())"
3058 + "#\(Self.shortAuthorID($0.authorID))"
3059 }
3060 .joined(separator: ",")
3061 return "sample=[\(sample)]"
3062 }
3063
3064 private nonisolated static func peerChangeEntitySampleSummary(_ rows: [PeerChangeEntity]) -> String {
3065 peerChangeSampleSummary(rows.map { peerChange(from: $0) })
3066 }
3067
3068 private nonisolated static func shortAuthorID(_ authorID: String?) -> String {
3069 guard let authorID else { return "nil" }
3070 return String(authorID.prefix(8))
3071 }
3072
3073 private func inferredObservedCompletionAuthorID(for id: UUID) -> String? {
3074 let request = NSFetchRequest<GameEntity>(entityName: "GameEntity")
3075 request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
3076 request.fetchLimit = 1
3077 guard let entity = try? context.fetch(request).first,
3078 let source = entity.puzzleSource,
3079 let xd = try? XD.parse(source)
3080 else { return nil }
3081
3082 let puzzle = Puzzle(xd: xd)
3083 let movesRequest = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
3084 movesRequest.predicate = NSPredicate(format: "game == %@", entity)
3085 let movesEntities = (try? context.fetch(movesRequest)) ?? []
3086 let values: [MovesValue] = movesEntities.compactMap { Self.movesValue(from: $0) }
3087 let provenance = GridStateMerger.mergeWithProvenance(values)
3088
3089 var latest: (date: Date, authorID: String)?
3090 for row in puzzle.cells {
3091 for cell in row {
3092 guard !cell.isBlock, cell.solution != nil else { continue }
3093 let position = GridPosition(row: cell.row, col: cell.col)
3094 guard let winner = provenance[position],
3095 !winner.cell.letter.isEmpty,
3096 cell.accepts(winner.cell.letter)
3097 else { return nil }
3098
3099 if latest.map({ winner.cell.updatedAt > $0.date }) ?? true {
3100 latest = (winner.cell.updatedAt, winner.writerAuthorID)
3101 }
3102 }
3103 }
3104 return latest?.authorID
3105 }
3106
3107
3108
3109
3110
3111 fileprivate nonisolated static func applyCellCache(
3112 to gameEntity: GameEntity,
3113 from grid: GridState,
3114 in ctx: NSManagedObjectContext
3115 ) {
3116 let cellEntities = (gameEntity.cells as? Set<CellEntity>) ?? []
3117 var existing: [GridPosition: CellEntity] = [:]
3118 for ce in cellEntities {
3119 existing[GridPosition(row: Int(ce.row), col: Int(ce.col))] = ce
3120 }
3121
3122 for (position, cell) in grid {
3123
3124
3125
3126 guard position.isPersistable(
3127 gridWidth: gameEntity.gridWidth,
3128 gridHeight: gameEntity.gridHeight
3129 ) else { continue }
3130 let ce: CellEntity
3131 if let found = existing[position] {
3132 ce = found
3133 } else {
3134 ce = CellEntity(context: ctx)
3135 ce.row = Int16(position.row)
3136 ce.col = Int16(position.col)
3137 ce.game = gameEntity
3138 }
3139 ce.letter = cell.letter
3140 ce.markCode = cell.mark.code
3141 ce.letterAuthorID = cell.authorID
3142 }
3143
3144 for (position, ce) in existing where grid[position] == nil {
3145 ce.letter = ""
3146 ce.markCode = 0
3147 ce.letterAuthorID = nil
3148 }
3149 }
3150
3151
3152
3153 func markAccessRevoked(gameID: UUID) {
3154 guard currentEntity?.id == gameID else { return }
3155 currentMutator?.isAccessRevoked = true
3156 }
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166 @discardableResult
3167 func handleRemoteRemoval(gameID: UUID) -> Bool {
3168 let wasOpen = currentEntity?.id == gameID
3169 if wasOpen {
3170 currentGame = nil
3171 currentMutator = nil
3172 currentEntity = nil
3173 }
3174 onUnreadOtherMovesChanged?()
3175 return wasOpen
3176 }
3177
3178
3179
3180
3181 func markShared(gameID: UUID) {
3182 guard currentEntity?.id == gameID else { return }
3183 currentMutator?.isShared = true
3184 }
3185
3186 private func makeMutator(game: Game, entity: GameEntity) -> GameMutator {
3187 guard let gameID = entity.id else {
3188 fatalError("GameEntity missing id — data model invariant violated")
3189 }
3190 return GameMutator(
3191 game: game,
3192 gameID: gameID,
3193 movesUpdater: movesUpdater,
3194 movesJournal: movesJournal,
3195 authorIDProvider: authorIDProvider,
3196 onLocalCellEdit: { [weak self] edit in
3197 self?.onLocalCellEdit?(edit)
3198 },
3199 onLocalCellEditBatch: { [weak self] edits in
3200 self?.onLocalCellEditBatch?(edits)
3201 },
3202 isOwned: entity.databaseScope == 0,
3203 isShared: entity.ckShareRecordName != nil || entity.databaseScope == 1,
3204 showsPlayerAttribution: entity.ckShareRecordName != nil
3205 || entity.databaseScope == 1
3206 || isArchivedSharedGame(entity),
3207 isArchived: isMaterializedArchive(entity),
3208 isAccessRevoked: entity.isAccessRevoked,
3209 isSyncSupported: GameSyncVersion.supports(entity.syncVersion),
3210 syncVersion: entity.syncVersion,
3211 initialLogicalTick: maximumLogicalTick(for: entity),
3212 isCompleted: entity.completedAt != nil
3213 )
3214 }
3215
3216
3217
3218
3219
3220 private func upgradeOwnedGameSyncVersionIfNeeded(_ entity: GameEntity) throws {
3221 let version = GameSyncVersion.normalized(entity.syncVersion)
3222 guard entity.databaseScope == DatabaseScope.private.rawValue,
3223 version < GameSyncVersion.current,
3224 GameSyncVersion.supports(version)
3225 else { return }
3226
3227 entity.syncVersion = GameSyncVersion.current
3228 entity.hasPendingSave = true
3229 try context.save()
3230 if let recordName = entity.ckRecordName {
3231 onGameUpdated(recordName)
3232 }
3233 }
3234
3235
3236
3237 private func maximumLogicalTick(for entity: GameEntity) -> Int64 {
3238 let moves = (entity.moves as? Set<MovesEntity>) ?? []
3239 var maximum: Int64 = 0
3240 for row in moves {
3241 guard let data = row.cells,
3242 let cells = try? MovesCodec.decode(data)
3243 else { continue }
3244 for cell in cells.values {
3245 maximum = max(maximum, cell.logicalValue)
3246 }
3247 }
3248 return maximum
3249 }
3250
3251 private func fetchGameEntity(id gameID: UUID) -> GameEntity? {
3252 let req = NSFetchRequest<GameEntity>(entityName: "GameEntity")
3253 req.predicate = NSPredicate(format: "id == %@", gameID as CVarArg)
3254 req.fetchLimit = 1
3255 return try? context.fetch(req).first
3256 }
3257
3258 private func ensureMovesEntity(
3259 recordName: String,
3260 game: GameEntity,
3261 authorID: String,
3262 deviceID: String
3263 ) -> MovesEntity {
3264 let req = NSFetchRequest<MovesEntity>(entityName: "MovesEntity")
3265 req.predicate = NSPredicate(format: "ckRecordName == %@", recordName)
3266 req.fetchLimit = 1
3267 if let existing = try? context.fetch(req).first {
3268 return existing
3269 }
3270
3271 let entity = MovesEntity(context: context)
3272 entity.game = game
3273 entity.ckRecordName = recordName
3274 entity.authorID = authorID
3275 entity.deviceID = deviceID
3276 entity.cells = Data()
3277 entity.updatedAt = Date()
3278 return entity
3279 }
3280
3281}