Crossmate/Persistence/GameMutator.swift (19392B)
1import Foundation
2
3
4
5
6
7
8
9
10
11
12
13@MainActor
14@Observable
15final class GameMutator {
16 private let game: Game
17 let gameID: UUID
18 private let movesUpdater: MovesUpdater?
19 private let movesJournal: MovesJournal?
20 private let authorIDProvider: (@MainActor () -> String?)?
21 private let onLocalCellEdit: (@MainActor (RealtimeCellEdit) -> Void)?
22 private let onLocalCellEditBatch: (@MainActor ([RealtimeCellEdit]) -> Void)?
23
24
25
26 private var journalRevision = 0
27
28
29
30
31
32 private var batchBroadcastBuffer: [RealtimeCellEdit]?
33
34
35 let isOwned: Bool
36
37
38
39
40 var isShared: Bool
41
42
43
44
45
46 var showsPlayerAttribution: Bool {
47 isShared || hasArchivedPlayerAttribution
48 }
49 private let hasArchivedPlayerAttribution: Bool
50
51
52
53
54 let isArchived: Bool
55
56
57
58
59
60 var isAccessRevoked: Bool
61
62
63
64 var isSyncSupported: Bool
65
66
67
68
69 private var usesLogicalTicks: Bool
70 private var logicalTick: Int64
71
72
73
74
75
76
77
78 var isCompleted: Bool
79
80
81
82
83
84
85
86
87 var isEditable: Bool { !isCompleted && !isAccessRevoked && isSyncSupported }
88
89 init(
90 game: Game,
91 gameID: UUID,
92 movesUpdater: MovesUpdater?,
93 movesJournal: MovesJournal? = nil,
94 authorIDProvider: (@MainActor () -> String?)? = nil,
95 onLocalCellEdit: (@MainActor (RealtimeCellEdit) -> Void)? = nil,
96 onLocalCellEditBatch: (@MainActor ([RealtimeCellEdit]) -> Void)? = nil,
97 isOwned: Bool = true,
98 isShared: Bool = false,
99 showsPlayerAttribution: Bool? = nil,
100 isArchived: Bool = false,
101 isAccessRevoked: Bool = false,
102 isSyncSupported: Bool = true,
103 syncVersion: Int64 = GameSyncVersion.current,
104 initialLogicalTick: Int64 = 0,
105 isCompleted: Bool = false
106 ) {
107 self.game = game
108 self.gameID = gameID
109 self.movesUpdater = movesUpdater
110 self.movesJournal = movesJournal
111 self.authorIDProvider = authorIDProvider
112 self.onLocalCellEdit = onLocalCellEdit
113 self.onLocalCellEditBatch = onLocalCellEditBatch
114 self.isOwned = isOwned
115 self.isShared = isShared
116 self.hasArchivedPlayerAttribution = showsPlayerAttribution ?? isShared
117 self.isArchived = isArchived
118 self.isAccessRevoked = isAccessRevoked
119 self.isSyncSupported = isSyncSupported
120 self.usesLogicalTicks = GameSyncVersion.normalized(syncVersion) >= GameSyncVersion.logicalTicks
121 self.logicalTick = max(0, initialLogicalTick)
122 self.isCompleted = isCompleted
123 prefetchJournal()
124 }
125
126
127
128
129 func updateSyncVersion(_ version: Int64, observedLogicalTick: Int64) {
130 isSyncSupported = GameSyncVersion.supports(version)
131 usesLogicalTicks = GameSyncVersion.normalized(version) >= GameSyncVersion.logicalTicks
132 logicalTick = max(logicalTick, observedLogicalTick)
133 }
134
135
136
137 func setLetter(_ letter: String, atRow row: Int, atCol col: Int, pencil: Bool, direction: Puzzle.Direction? = nil) {
138 guard isEditable else { return }
139 let before = cellState(atRow: row, atCol: col)
140 game.setLetter(letter, atRow: row, atCol: col, pencil: pencil, authorID: authorIDProvider?())
141 emitMove(
142 atRow: row,
143 atCol: col,
144 beforeState: before,
145 journalKind: kind(.input, ifChangedFrom: before, atRow: row, atCol: col),
146 direction: direction
147 )
148 }
149
150 func clearLetter(atRow row: Int, atCol col: Int, direction: Puzzle.Direction? = nil) {
151 guard isEditable else { return }
152 let before = cellState(atRow: row, atCol: col)
153 game.clearLetter(atRow: row, atCol: col)
154 emitMove(
155 atRow: row,
156 atCol: col,
157 beforeState: before,
158 journalKind: kind(.input, ifChangedFrom: before, atRow: row, atCol: col),
159 direction: direction
160 )
161 }
162
163
164
165
166
167
168
169
170
171 func checkCells(_ cells: [Puzzle.Cell]) {
172 applyBulk(cells, kind: .check) { game.checkCells($0) }
173 }
174
175 func revealCells(_ cells: [Puzzle.Cell]) {
176 applyBulk(cells, kind: .reveal) { game.revealCells($0) }
177 }
178
179 func clearCells(_ cells: [Puzzle.Cell]) {
180 applyBulk(cells, kind: .clear) { game.clearCells($0) }
181 }
182
183 private func applyBulk(
184 _ cells: [Puzzle.Cell],
185 kind: JournalKind,
186 _ mutate: ([Puzzle.Cell]) -> Void
187 ) {
188
189
190
191 guard isEditable else { return }
192 let applicable = cells.filter { !$0.isBlock }
193 guard !applicable.isEmpty else { return }
194 let before = applicable.map { cellState(atRow: $0.row, atCol: $0.col) }
195 mutate(applicable)
196 let batch = UUID()
197 collectingBroadcast {
198 for (cell, priorState) in zip(applicable, before) {
199 let journalKind = self.kind(kind, ifChangedFrom: priorState, atRow: cell.row, atCol: cell.col)
200 if journalKind == nil, kind != .reveal { continue }
201 emitMove(
202 atRow: cell.row,
203 atCol: cell.col,
204 beforeState: priorState,
205 journalKind: journalKind,
206 batchID: batch
207 )
208 }
209 }
210 }
211
212
213
214
215
216
217
218 struct CursorLanding {
219 let position: GridPosition
220 let direction: Puzzle.Direction?
221 }
222
223
224
225
226 var canUndo: Bool {
227 _ = journalRevision
228 guard isEditable, let movesJournal else { return false }
229 return movesJournal.canUndo(gameID: gameID)
230 }
231
232 var canRedo: Bool {
233 _ = journalRevision
234 guard isEditable, let movesJournal else { return false }
235 return movesJournal.canRedo(gameID: gameID)
236 }
237
238 func prefetchJournal() {
239 guard let movesJournal else { return }
240 Task { @MainActor [weak self, movesJournal, gameID] in
241 await movesJournal.preload(gameID: gameID)
242 guard let self, self.gameID == gameID else { return }
243 self.journalRevision += 1
244 }
245 }
246
247
248
249
250
251
252
253
254
255
256 @discardableResult
257 func undo() -> CursorLanding? {
258 guard isEditable, let movesJournal else { return nil }
259 while let plan = movesJournal.planUndo(gameID: gameID) {
260 if applyRestores(plan.restores, kind: .undo) { return cursorTarget(for: plan) }
261 movesJournal.markUndoConsumed(stepID: plan.stepID, gameID: gameID)
262 journalRevision += 1
263 }
264 return nil
265 }
266
267
268 @discardableResult
269 func redo() -> CursorLanding? {
270 guard isEditable, let movesJournal else { return nil }
271 while let plan = movesJournal.planRedo(gameID: gameID) {
272 if applyRestores(plan.restores, kind: .redo) { return cursorTarget(for: plan) }
273 movesJournal.markRedoConsumed(stepID: plan.stepID, gameID: gameID)
274 journalRevision += 1
275 }
276 return nil
277 }
278
279
280
281
282 private func cursorTarget(for plan: JournalPlan) -> CursorLanding? {
283 guard plan.kind == .input, let position = plan.restores.first?.position else { return nil }
284 return CursorLanding(position: position, direction: plan.direction)
285 }
286
287
288
289 private func applyRestores(_ restores: [JournalRestore], kind: JournalKind) -> Bool {
290 let batch = UUID()
291 var appliedAny = false
292 collectingBroadcast {
293 for restore in restores {
294 let row = restore.position.row
295 let col = restore.position.col
296 let square = game.squares[row][col]
297 let current = JournalCellState(
298 letter: square.entry,
299 mark: square.mark,
300 cellAuthorID: square.letterAuthorID
301 )
302 guard current.letterMatches(restore.expectedCurrent) else { continue }
303 game.applyCellState(
304 restore.restoreTo.letter,
305 mark: restore.restoreTo.mark,
306 authorID: restore.restoreTo.cellAuthorID,
307 atRow: row, atCol: col
308 )
309 emitMove(
310 atRow: row,
311 atCol: col,
312 beforeState: current,
313 journalKind: kind,
314 batchID: batch,
315 targetSeq: restore.targetSeq
316 )
317 appliedAny = true
318 }
319 }
320 return appliedAny
321 }
322
323
324
325 private func cellState(atRow row: Int, atCol col: Int) -> JournalCellState {
326 let square = game.squares[row][col]
327 return JournalCellState(letter: square.entry, mark: square.mark, cellAuthorID: square.letterAuthorID)
328 }
329
330
331
332
333 private func kind(_ kind: JournalKind, ifChangedFrom before: JournalCellState, atRow row: Int, atCol col: Int) -> JournalKind? {
334 let square = game.squares[row][col]
335 let changed = square.entry != before.letter || square.mark != before.mark
336 return changed ? kind : nil
337 }
338
339
340
341
342
343
344
345
346
347 private func collectingBroadcast(_ body: () -> Void) {
348 batchBroadcastBuffer = []
349 body()
350 let edits = batchBroadcastBuffer ?? []
351 batchBroadcastBuffer = nil
352 switch edits.count {
353 case 0: break
354 case 1: onLocalCellEdit?(edits[0])
355 default: onLocalCellEditBatch?(edits)
356 }
357 }
358
359 private func emitMove(
360 atRow row: Int,
361 atCol col: Int,
362 beforeState: JournalCellState? = nil,
363 journalKind: JournalKind? = nil,
364 batchID: UUID? = nil,
365 targetSeq: Int64? = nil,
366 direction: Puzzle.Direction? = nil
367 ) {
368 guard !isAccessRevoked, isSyncSupported else { return }
369 let square = game.squares[row][col]
370 let mark = square.mark
371 let id = gameID
372 let letter = square.entry
373
374
375
376 let cellAuthorID = square.letterAuthorID
377 let actingAuthorID = authorIDProvider?()
378
379
380
381
382 if let journalKind {
383 movesJournal?.record(
384 gameID: id,
385 position: GridPosition(row: row, col: col),
386 beforeState: beforeState,
387 state: JournalCellState(letter: letter, mark: square.mark, cellAuthorID: cellAuthorID),
388 actingAuthorID: actingAuthorID,
389 kind: journalKind,
390 targetSeq: targetSeq,
391 batchID: batchID,
392 direction: direction
393 )
394 journalRevision += 1
395 }
396
397 guard let movesUpdater else { return }
398
399
400
401
402
403
404
405 let enqueuedAt = Date()
406 let tick = nextLogicalTick()
407 game.squares[row][col].enqueuedAt = enqueuedAt
408 if let actingAuthorID, !actingAuthorID.isEmpty {
409 let edit = RealtimeCellEdit(
410 gameID: id,
411 authorID: actingAuthorID,
412 deviceID: RecordSerializer.localDeviceID,
413 row: row,
414 col: col,
415 letter: letter,
416 mark: mark,
417 updatedAt: enqueuedAt,
418 cellAuthorID: cellAuthorID,
419 tick: tick
420 )
421 if batchBroadcastBuffer != nil {
422 batchBroadcastBuffer?.append(edit)
423 } else {
424 onLocalCellEdit?(edit)
425 }
426 }
427 Task {
428 await movesUpdater.enqueue(
429 gameID: id,
430 row: row, col: col,
431 letter: letter,
432 mark: mark,
433 authorID: cellAuthorID,
434 enqueuedAt: enqueuedAt,
435 tick: tick
436 )
437 }
438 }
439
440 private func nextLogicalTick() -> Int64? {
441 guard usesLogicalTicks else { return nil }
442 if logicalTick < Int64.max { logicalTick += 1 }
443 return logicalTick
444 }
445}