← All repositories

crossmate

A collaborative crossword app for iPhone and iPad

git clone https://code.inqk.net/crossmate.git


Notes/AppServices.md (5193B)

1# AppServices Architecture Note
2
3I would not try to "remove the god object" by scattering construction
4everywhere. `AppServices` is doing something valuable: it gives the app one
5obvious ownership point for long-lived services, keeps SwiftUI environment setup
6simple, and makes startup ordering explicit. Those are real advantages.
7
8The thing I would change is not the centralisation itself, but the number of
9responsibilities inside that central class.
10
11Right now `AppServices` is both:
12
131. The composition root: constructs `PersistenceController`, `GameStore`,
14   `SyncEngine`, `NYTAuthService`, etc.
152. The lifecycle coordinator: handles startup, foreground/background sync,
16   remote notifications, share acceptance, reset, and import URLs.
173. The wiring layer: connects `GameStore` callbacks to `SyncEngine`, connects
18   `SyncEngine` callbacks back to `GameStore`, installs tracing, and refreshes
19   identity.
204. A small service locator used by views.
21
22That is why it feels dense. The problem is less "many properties" and more
23"many behavior loops in one file."
24
25## Recommendation
26
27Keep `AppServices` as the composition root.
28
29I would still have something like:
30
31```swift
32@MainActor
33final class AppServices {
34    let persistence: PersistenceController
35    let store: GameStore
36    let sync: SyncCoordinator
37    let sharing: SharingCoordinator
38    let imports: ImportCoordinator
39    let nytAuth: NYTAuthService
40    let nytFetcher: NYTPuzzleFetcher
41    let driveMonitor: DriveMonitor
42}
43```
44
45So the app still has one root object. SwiftUI can still receive `services`.
46Tests and previews still have a single place to swap dependencies later.
47Startup is still discoverable.
48
49## Extract Orchestration By Domain
50
51The first extraction I would make is a `SyncCoordinator`.
52
53It would own the current sync lifecycle behavior:
54
55- `start(preferences:)`
56- `syncOnForeground()`
57- `syncOnBackground()`
58- `handleRemoteNotification()`
59- identity refresh
60- `SyncMonitor` tracing
61- `SyncEngine` callback wiring
62- `MoveBuffer` construction/wiring, if you want to group move flushing with sync
63
64That would remove the densest closure wiring from `AppServices` while preserving
65the existing behavior.
66
67Then `AppServices.start(...)` becomes mostly:
68
69```swift
70func start(appDelegate: AppDelegate, preferences: PlayerPreferences) async {
71    guard !started else { return }
72    started = true
73
74    nytAuth.loadStoredSession()
75    driveMonitor.start()
76
77    appDelegate.onRemoteNotification = { await self.sync.handleRemoteNotification() }
78    appDelegate.onAcceptShare = { await self.sharing.acceptShare(metadata: $0) }
79
80    await sync.start(preferences: preferences)
81}
82```
83
84That is a good shape for a composition root: it says what starts, not how every
85subsystem talks internally.
86
87## Extract CloudKit Share And Reset Operations
88
89`acceptShare(metadata:)`, `deleteAllPrivateZones()`, and `leaveAllSharedZones()`
90are a coherent CloudKit-sharing/admin concern. I would put those in something
91like `SharingCoordinator` or `CloudKitMaintenanceService`.
92
93That class would depend on:
94
95- `CKContainer`
96- `SyncEngine`
97- `SyncMonitor`
98- maybe `GameStore` for reset
99
100This keeps the dangerous operations, especially reset and zone deletion, out of
101the general app service bag.
102
103## Extract URL Import
104
105`handleOpenURL(_:)` is also separable. It coordinates:
106
107- file security scope
108- XD file loading
109- Drive import
110- duplicate game lookup
111- game creation
112
113That could become:
114
115```swift
116@MainActor
117final class GameImportService {
118    func importGame(from url: URL) -> UUID?
119}
120```
121
122This is a nice extraction because it has a clear input/output and little
123lifecycle complexity.
124
125## Avoid Over-Abstracting The Simple Services
126
127I would not introduce protocols everywhere yet. For example, I would not
128immediately create `GameStoreProtocol`, `SyncEngineProtocol`, `DriveMonitoring`,
129`PuzzleFetching`, etc. unless tests or previews need them. That would make the
130code feel more "architected" without reducing the actual complexity.
131
132I would also avoid splitting into tiny factories like `PersistenceFactory`,
133`SyncFactory`, or `AuthFactory`. The construction code is not the main problem.
134The callback graph is.
135
136## Target Shape
137
138A reasonable end state would be:
139
140- `AppServices`: owns and exposes app-wide services; starts coordinators.
141- `SyncCoordinator`: owns sync lifecycle, move buffering, sync callbacks,
142  identity, and monitoring.
143- `SharingCoordinator`: accepts shares and maybe handles CloudKit zone
144  cleanup/reset support.
145- `GameImportService`: handles `.xd` URLs and Drive import.
146- `PlayerNamePublisher`: stays as-is.
147- `GameStore`: still stores callback hooks, though over time those could become
148  a more explicit event sink.
149
150The important design rule: `AppServices` can know about everything, but
151everything should not require new business logic inside `AppServices`.
152
153So I would treat the current class as acceptable but past the point where new
154responsibilities should keep landing there. The next time you touch sync
155lifecycle, share acceptance, reset, or file import, extract that domain then. I
156would not do a big architecture-only rewrite unless you already have bugs around
157startup ordering or sync callbacks.