-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathSyncEngine.swift
More file actions
2451 lines (2310 loc) · 87.5 KB
/
SyncEngine.swift
File metadata and controls
2451 lines (2310 loc) · 87.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if canImport(CloudKit)
import CloudKit
import ConcurrencyExtras
import Dependencies
import OrderedCollections
import OSLog
import Observation
import StructuredQueriesCore
import SwiftData
import TabularData
#if canImport(UIKit)
import UIKit
#endif
/// An object that manages the synchronization of local and remote SQLite data.
///
/// See <doc:CloudKit> for more information.
@available(iOS 17, macOS 14, tvOS 17, watchOS 10, *)
public final class SyncEngine: Observable, Sendable {
package let userDatabase: UserDatabase
package let logger: Logger
package let metadatabase: any DatabaseWriter
package let tables: [any SynchronizableTable]
package let privateTables: [any SynchronizableTable]
let tablesByName: [String: any SynchronizableTable]
private let tablesByOrder: [String: Int]
let foreignKeysByTableName: [String: [ForeignKey]]
package let syncEngines = LockIsolated<SyncEngines>(SyncEngines())
package let defaultZone: CKRecordZone
let delegate: (any SyncEngineDelegate)?
let defaultSyncEngines:
@Sendable (any DatabaseReader, SyncEngine)
-> (private: any SyncEngineProtocol, shared: any SyncEngineProtocol)
package let container: any CloudContainer
let dataManager = Dependency(\.dataManager)
private let observationRegistrar = ObservationRegistrar()
private let notificationsObserver = LockIsolated<(any NSObjectProtocol)?>(nil)
private let activityCounts = LockIsolated(ActivityCounts())
private let startTask = LockIsolated<Task<Void, Never>?>(nil)
/// The error message used when a write occurs to a record for which the current user does not
/// have permission.
///
/// This error is thrown from any database write to a row for which the current user does
/// not have permissions to write, as determined by its `CKShare` (if applicable). To catch
/// this error try casting it to `DatabaseError` and checking its message:
///
/// ```swift
/// do {
/// try await database.write { db in
/// Reminder.find(id)
/// .update { $0.title = "Personal" }
/// .execute(db)
/// }
/// } catch let error as DatabaseError where error.message == SyncEngine.writePermissionError {
/// // User does not have permission to write to this record.
/// }
/// ```
public static let writePermissionError =
"co.pointfree.SQLiteData.CloudKit.write-permission-error"
public static let invalidRecordNameError =
"co.pointfree.SQLiteData.CloudKit.invalid-record-name-error"
/// Initialize a sync engine.
///
/// - Parameters:
/// - database: The database to synchronize to CloudKit.
/// - tables: A list of tables that you want to synchronize _and_ that you want to be
/// shareable with other users on CloudKit.
/// - privateTables: A list of tables that you want to synchronize to CloudKit but that
/// you do not want to be shareable with other users.
/// - containerIdentifier: The container identifier in CloudKit to synchronize to. If omitted
/// the container will be determined from the entitlements of your app.
/// - defaultZone: The zone for all records to be stored in.
/// - startImmediately: Determines if the sync engine starts right away or requires an
/// explicit call to ``start()``. By default this argument is `true`.
/// - delegate: A delegate object that can be notified of events and override default sync
/// engine behavior.
/// - logger: The logger used to log events in the sync engine. By default a `.disabled`
/// logger is used, which means logs are not printed.
public convenience init<
each T1: PrimaryKeyedTable & _SendableMetatype,
each T2: PrimaryKeyedTable & _SendableMetatype
>(
for database: any DatabaseWriter,
tables: repeat (each T1).Type,
privateTables: repeat (each T2).Type,
containerIdentifier: String? = nil,
defaultZone: CKRecordZone = CKRecordZone(zoneName: "co.pointfree.SQLiteData.defaultZone"),
startImmediately: Bool = true,
delegate: (any SyncEngineDelegate)? = nil,
logger: Logger = isTesting
? Logger(.disabled) : Logger(subsystem: "SQLiteData", category: "CloudKit")
) throws
where
repeat (each T1).PrimaryKey.QueryOutput: IdentifierStringConvertible,
repeat (each T1).TableColumns.PrimaryColumn: WritableTableColumnExpression,
repeat (each T2).PrimaryKey.QueryOutput: IdentifierStringConvertible,
repeat (each T2).TableColumns.PrimaryColumn: WritableTableColumnExpression
{
let containerIdentifier =
containerIdentifier
?? ModelConfiguration(groupContainer: .automatic).cloudKitContainerIdentifier
var allTables: [any SynchronizableTable] = []
var allPrivateTables: [any SynchronizableTable] = []
for table in repeat each tables {
allTables.append(SynchronizedTable(for: table))
}
for privateTable in repeat each privateTables {
allPrivateTables.append(SynchronizedTable(for: privateTable))
}
let userDatabase = UserDatabase(database: database)
@Dependency(\.context) var context
guard context == .live
else {
let privateDatabase = MockCloudDatabase(databaseScope: .private)
let sharedDatabase = MockCloudDatabase(databaseScope: .shared)
let container = MockCloudContainer(
containerIdentifier: containerIdentifier ?? "iCloud.co.pointfree.SQLiteData.Tests",
privateCloudDatabase: privateDatabase,
sharedCloudDatabase: sharedDatabase
)
privateDatabase.set(container: container)
sharedDatabase.set(container: container)
try self.init(
container: container,
defaultZone: defaultZone,
defaultSyncEngines: { _, syncEngine in
(
private: MockSyncEngine(
database: privateDatabase,
parentSyncEngine: syncEngine,
state: MockSyncEngineState()
),
shared: MockSyncEngine(
database: sharedDatabase,
parentSyncEngine: syncEngine,
state: MockSyncEngineState()
)
)
},
userDatabase: userDatabase,
logger: logger,
delegate: delegate,
tables: allTables,
privateTables: allPrivateTables
)
try setUpSyncEngine()
if startImmediately {
_ = try start()
}
return
}
guard let containerIdentifier else {
throw SchemaError.noCloudKitContainer
}
let container = CKContainer(identifier: containerIdentifier)
try self.init(
container: container,
defaultZone: defaultZone,
defaultSyncEngines: { metadatabase, syncEngine in
(
private: CKSyncEngine(
CKSyncEngine.Configuration(
database: container.privateCloudDatabase,
stateSerialization: try? metadatabase.read { db in
try StateSerialization
.find(#bind(.private))
.select(\.data)
.fetchOne(db)
},
delegate: syncEngine
)
),
shared: CKSyncEngine(
CKSyncEngine.Configuration(
database: container.sharedCloudDatabase,
stateSerialization: try? metadatabase.read { db in
try StateSerialization
.find(#bind(.shared))
.select(\.data)
.fetchOne(db)
},
delegate: syncEngine
)
)
)
},
userDatabase: userDatabase,
logger: logger,
delegate: delegate,
tables: allTables,
privateTables: allPrivateTables
)
try setUpSyncEngine()
if startImmediately {
_ = try start()
}
}
package init(
container: any CloudContainer,
defaultZone: CKRecordZone,
defaultSyncEngines:
@escaping @Sendable (
any DatabaseReader,
SyncEngine
) -> (private: any SyncEngineProtocol, shared: any SyncEngineProtocol),
userDatabase: UserDatabase,
logger: Logger,
delegate: (any SyncEngineDelegate)?,
tables: [any SynchronizableTable],
privateTables: [any SynchronizableTable] = []
) throws {
let allTables = Set((tables + privateTables).map(HashableSynchronizedTable.init))
.map(\.type)
self.tables = allTables
self.privateTables = privateTables
self.delegate = delegate
let foreignKeysByTableName = Dictionary(
uniqueKeysWithValues: try userDatabase.read { db in
try allTables.map { table -> (String, [ForeignKey]) in
func open<T>(
_: some SynchronizableTable<T>
) throws -> (String, [ForeignKey]) {
(
T.tableName,
try PragmaForeignKeyList<T>
.join(PragmaTableInfo<T>.all) { $0.from.eq($1.name) }
.select {
ForeignKey.Columns(
table: $0.table,
from: $0.from,
to: $0.to,
onUpdate: $0.onUpdate,
onDelete: $0.onDelete,
isNotNull: $1.isNotNull
)
}
.fetchAll(db)
)
}
return try open(table)
}
}
)
self.container = container
self.defaultZone = defaultZone
self.defaultSyncEngines = defaultSyncEngines
self.userDatabase = userDatabase
self.logger = logger
self.metadatabase = try defaultMetadatabase(
logger: logger,
url: try URL.metadatabase(
databasePath: userDatabase.path,
containerIdentifier: container.containerIdentifier
)
)
self.tablesByName = Dictionary(
uniqueKeysWithValues: self.tables.map { ($0.base.tableName, $0) }
)
self.foreignKeysByTableName = foreignKeysByTableName
tablesByOrder = try SQLiteData.tablesByOrder(
userDatabase: userDatabase,
tables: allTables,
tablesByName: tablesByName
)
#if os(iOS)
@Dependency(\.defaultNotificationCenter) var defaultNotificationCenter
notificationsObserver.withValue {
$0 = defaultNotificationCenter.addObserver(
forName: UIApplication.willResignActiveNotification,
object: nil,
queue: nil
) { [syncEngines] _ in
Task { @MainActor in
let taskIdentifier = UIApplication.shared.beginBackgroundTask()
defer { UIApplication.shared.endBackgroundTask(taskIdentifier) }
let (privateSyncEngine, sharedSyncEngine) = syncEngines.withValue {
($0.private, $0.shared)
}
try await privateSyncEngine?.sendChanges(CKSyncEngine.SendChangesOptions())
try await sharedSyncEngine?.sendChanges(CKSyncEngine.SendChangesOptions())
}
}
}
#endif
try validateSchema()
}
deinit {
notificationsObserver.withValue {
guard let observer = $0
else { return }
NotificationCenter.default.removeObserver(observer)
}
}
nonisolated package func setUpSyncEngine() throws {
try userDatabase.write { db in
try setUpSyncEngine(writableDB: db)
}
}
nonisolated package func setUpSyncEngine(writableDB db: Database) throws {
let attachedMetadatabasePath: String? =
try PragmaDatabaseList
.where { $0.name.eq(String.sqliteDataCloudKitSchemaName) }
.select(\.file)
.fetchOne(db)
if let attachedMetadatabasePath {
let metadatabaseName =
metadatabase.path.isEmpty
? try URL.metadatabase(
databasePath: "",
containerIdentifier: self.container.containerIdentifier
)
.lastPathComponent
: URL(filePath: metadatabase.path).lastPathComponent
let attachedMetadatabaseName =
URL(string: attachedMetadatabasePath)?.lastPathComponent ?? ""
if metadatabaseName != attachedMetadatabaseName {
throw SchemaError(
reason: .metadatabaseMismatch(
attachedPath: attachedMetadatabasePath,
syncEngineConfiguredPath: metadatabase.path
),
debugDescription: """
Metadatabase attached in 'prepareDatabase' does not match metadatabase prepared in \
'SyncEngine.init'. Are different CloudKit container identifiers being provided?
"""
)
}
} else {
try #sql(
"""
ATTACH DATABASE \(bind: metadatabase.path) AS \(quote: .sqliteDataCloudKitSchemaName)
"""
)
.execute(db)
}
db.add(function: $currentTime)
db.add(function: $syncEngineIsSynchronizingChanges)
db.add(function: $didUpdate)
db.add(function: $didDelete)
db.add(function: $hasPermission)
db.add(function: $currentZoneName)
db.add(function: $currentOwnerName)
for trigger in SyncMetadata.callbackTriggers(for: self) {
try trigger.execute(db)
}
for table in tables {
try table.base.createTriggers(
foreignKeysByTableName: foreignKeysByTableName,
tablesByName: tablesByName,
defaultZone: defaultZone,
privateTables: privateTables,
db: db
)
}
}
/// Starts the sync engine if it is stopped.
///
/// When a sync engine is started it will upload all data stored locally that has not yet
/// been synchronized to CloudKit, and will download all changes from CloudKit since the
/// last time it synchronized.
///
/// > Note: By default, sync engines start syncing when initialized.
public func start() async throws {
try await start().value
}
/// Determines if the sync engine is currently sending local changes to the CloudKit server.
///
/// It is an observable value, which means if it is accessed in a SwiftUI view, or some other
/// observable context, then the view will automatically re-render when the value changes. As
/// such, it can be useful for displaying a progress view to indicate that work is currently
/// being done to synchronize changes.
public var isSendingChanges: Bool {
sendingChangesCount > 0
}
/// Determines if the sync engine is currently processing changes being sent to the device
/// from CloudKit.
///
/// It is an observable value, which means if it is accessed in a SwiftUI view, or some other
/// observable context, then the view will automatically re-render when the value changes. As
/// such, it can be useful for displaying a progress view to indicate that work is currently
/// being done to synchronize changes.
public var isFetchingChanges: Bool {
fetchingChangesCount > 0
}
/// Determines if the sync engine is currently sending or receiving changes from CloudKit.
///
/// This value is true if either of ``isSendingChanges`` or ``isFetchingChanges`` is true.
/// It is an observable value, which means if it is accessed in a SwiftUI view, or some other
/// observable context, then the view will automatically re-render when the value changes. As
/// such, it can be useful for displaying a progress view to indicate that work is currently
/// being done to synchronize changes.
public var isSynchronizing: Bool {
isSendingChanges || isFetchingChanges
}
/// Stops the sync engine if it is running.
///
/// All edits made after stopping the sync engine will not be synchronized to CloudKit.
/// You must start the sync engine again using ``start()`` to synchronize the changes.
public func stop() {
guard isRunning else { return }
observationRegistrar.withMutation(of: self, keyPath: \.isRunning) {
syncEngines.withValue {
$0 = SyncEngines()
}
}
}
/// Determines if the sync engine is currently running or not.
public var isRunning: Bool {
observationRegistrar.access(self, keyPath: \.isRunning)
return syncEngines.withValue {
$0.isRunning
}
}
private func start() throws -> Task<Void, Never> {
guard !isRunning else { return Task {} }
observationRegistrar.withMutation(of: self, keyPath: \.isRunning) {
syncEngines.withValue {
let (privateSyncEngine, sharedSyncEngine) = defaultSyncEngines(metadatabase, self)
$0 = SyncEngines(
private: privateSyncEngine,
shared: sharedSyncEngine
)
}
}
let previousRecordTypes = try metadatabase.read { db in
try RecordType.all.fetchAll(db)
}
let currentRecordTypes = try userDatabase.read { db in
let namesAndSchemas =
try SQLiteSchema
.where {
$0.type.eq(#bind(.table))
&& $0.tableName.in(tables.map { $0.base.tableName })
}
.fetchAll(db)
return try namesAndSchemas.compactMap { schema -> RecordType? in
guard let sql = schema.sql, let table = tablesByName[schema.name]
else { return nil }
func open<T>(_: some SynchronizableTable<T>) throws -> RecordType {
try RecordType(
tableName: schema.name,
schema: sql,
tableInfo: Set(
PragmaTableInfo<T>
.select {
TableInfo.Columns(
defaultValue: $0.defaultValue,
isPrimaryKey: $0.isPrimaryKey,
name: $0.name,
isNotNull: $0.isNotNull,
type: $0.type
)
}
.fetchAll(db)
)
)
}
return try open(table)
}
}
let previousRecordTypeByTableName = Dictionary(
uniqueKeysWithValues: previousRecordTypes.map {
($0.tableName, $0)
}
)
let currentRecordTypeByTableName = Dictionary(
uniqueKeysWithValues: currentRecordTypes.map {
($0.tableName, $0)
}
)
let startTask = Task<Void, Never> {
await withErrorReporting(.sqliteDataCloudKitFailure) {
guard try await container.accountStatus() == .available
else { return }
syncEngines.withValue {
$0.private?.state.add(pendingDatabaseChanges: [.saveZone(defaultZone)])
}
try await uploadRecordsToCloudKit(
previousRecordTypeByTableName: previousRecordTypeByTableName,
currentRecordTypeByTableName: currentRecordTypeByTableName
)
try await updateLocalFromSchemaChange(
previousRecordTypeByTableName: previousRecordTypeByTableName,
currentRecordTypeByTableName: currentRecordTypeByTableName
)
try await cacheUserTables(recordTypes: currentRecordTypes)
}
}
self.startTask.withValue { $0 = startTask }
return startTask
}
/// Fetches pending remote changes from the server.
///
/// Use this method to ensure the sync engine immediately fetches all pending remote changes
/// before your app continues. This isn't necessary in normal use, as the engine automatically
/// syncs your app's records. It is useful, however, in scenarios where you require more control
/// over sync, such as pull-to-refresh.
///
/// - Parameter options: The options to use when fetching changes.
public func fetchChanges(
_ options: CKSyncEngine.FetchChangesOptions = CKSyncEngine.FetchChangesOptions()
) async throws {
await startTask.withValue(\.self)?.value
let (privateSyncEngine, sharedSyncEngine) = syncEngines.withValue {
($0.private, $0.shared)
}
guard let privateSyncEngine, let sharedSyncEngine
else { return }
async let `private`: Void = privateSyncEngine.fetchChanges(options)
async let shared: Void = sharedSyncEngine.fetchChanges(options)
_ = try await (`private`, shared)
}
/// Sends pending local changes to the server.
///
/// Use this method to ensure the sync engine sends all pending local changes to the server
/// before your app continues. This isn't necessary in normal use, as the engine automatically
/// syncs your app's records. It is useful, however, in scenarios where you require greater
/// control over sync, such as a "Backup now" button.
///
/// - Parameter options: The options to use when sending changes.
public func sendChanges(
_ options: CKSyncEngine.SendChangesOptions = CKSyncEngine.SendChangesOptions()
) async throws {
await startTask.withValue(\.self)?.value
let (privateSyncEngine, sharedSyncEngine) = syncEngines.withValue {
($0.private, $0.shared)
}
guard let privateSyncEngine, let sharedSyncEngine
else { return }
async let `private`: Void = privateSyncEngine.sendChanges(options)
async let shared: Void = sharedSyncEngine.sendChanges(options)
_ = try await (`private`, shared)
}
/// Synchronizes local and remote pending changes.
///
/// Use this method to ensure the sync engine immediately fetches all pending remote changes
/// _and_ sends all pending local changes to the server. This isn't necessary in normal use,
/// as the engine automatically syncs your app's records. It is useful, however, in scenarios
/// where you require greater control over sync.
///
/// - Parameters:
/// - fetchOptions: The options to use when fetching changes.
/// - sendOptions: The options to use when sending changes.
public func syncChanges(
fetchOptions: CKSyncEngine.FetchChangesOptions = CKSyncEngine.FetchChangesOptions(),
sendOptions: CKSyncEngine.SendChangesOptions = CKSyncEngine.SendChangesOptions()
) async throws {
try await fetchChanges(fetchOptions)
try await sendChanges(sendOptions)
}
private func cacheUserTables(recordTypes: [RecordType]) async throws {
try await userDatabase.write { db in
try RecordType
.upsert { recordTypes.map { RecordType.Draft($0) } }
.execute(db)
}
}
private func uploadRecordsToCloudKit(
previousRecordTypeByTableName: [String: RecordType],
currentRecordTypeByTableName: [String: RecordType]
) async throws {
try await enqueueLocallyPendingChanges()
try await userDatabase.write { db in
try PendingRecordZoneChange.delete().execute(db)
let newTableNames = currentRecordTypeByTableName.keys.filter { tableName in
previousRecordTypeByTableName[tableName] == nil
}
try $_isSynchronizingChanges.withValue(false) {
for tableName in newTableNames {
try self.uploadRecordsToCloudKit(tableName: tableName, db: db)
}
}
}
}
private func enqueueLocallyPendingChanges() async throws {
let pendingRecordZoneChanges = try await metadatabase.read { db in
try PendingRecordZoneChange
.select(\.pendingRecordZoneChange)
.fetchAll(db)
}
let changesByIsPrivate = Dictionary(grouping: pendingRecordZoneChanges) {
switch $0 {
case .deleteRecord(let recordID), .saveRecord(let recordID):
recordID.zoneID.ownerName == CKCurrentUserDefaultName
@unknown default:
false
}
}
syncEngines.withValue {
$0.private?.state.add(pendingRecordZoneChanges: changesByIsPrivate[true] ?? [])
$0.shared?.state.add(pendingRecordZoneChanges: changesByIsPrivate[false] ?? [])
}
}
private func enqueueUnknownRecordsForCloudKit() async throws {
try await userDatabase.write { db in
try $_isSynchronizingChanges.withValue(false) {
try SyncMetadata
.where { !$0.hasLastKnownServerRecord }
.update { $0.recordPrimaryKey = $0.recordPrimaryKey }
.execute(db)
}
}
}
private func uploadRecordsToCloudKit<T>(
table: some SynchronizableTable<T>,
db: Database
) throws {
// try T.update { $0.primaryKey = $0.primaryKey }.execute(db)
try #sql(
"""
UPDATE \(T.self) SET \(quote: T.primaryKey.name) = \(quote: T.primaryKey.name)
"""
)
.execute(db)
}
private func uploadRecordsToCloudKit(tableName: String, db: Database) throws {
guard let table = self.tablesByName[tableName]
else { return }
func open<T>(_ table: some SynchronizableTable<T>) throws {
try uploadRecordsToCloudKit(table: table, db: db)
}
try open(table)
}
private func updateLocalFromSchemaChange(
previousRecordTypeByTableName: [String: RecordType],
currentRecordTypeByTableName: [String: RecordType]
) async throws {
let tablesWithChangedSchemas = currentRecordTypeByTableName.filter { tableName, recordType in
previousRecordTypeByTableName[tableName]?.schema != recordType.schema
}
for (tableName, currentRecordType) in tablesWithChangedSchemas {
guard let table = tablesByName[tableName]
else { continue }
func open<T>(_ table: some SynchronizableTable<T>) async throws {
let previousRecordType = previousRecordTypeByTableName[tableName]
let changedColumns = currentRecordType.tableInfo.subtracting(
previousRecordType?.tableInfo ?? []
)
.map(\.name)
let lastKnownServerRecords = try await metadatabase.read { db in
try SyncMetadata
.where { $0.recordType.eq(tableName) }
.select(\._lastKnownServerRecordAllFields)
.fetchAll(db)
}
for case .some(let lastKnownServerRecord) in lastKnownServerRecords {
let query = try await updateQuery(
for: table,
record: lastKnownServerRecord,
columnNames: T.TableColumns.writableColumns.map(\.name),
changedColumnNames: changedColumns
)
try await userDatabase.write { db in
try #sql(query).execute(db)
}
}
}
try await open(table)
}
}
package func tearDownSyncEngine() throws {
try userDatabase.write { db in
for table in tables.reversed() {
try table.base
.dropTriggers(defaultZone: defaultZone, privateTables: privateTables, db: db)
}
for trigger in SyncMetadata.callbackTriggers(for: self).reversed() {
try trigger.drop().execute(db)
}
}
try metadatabase.erase()
try migrate(metadatabase: metadatabase)
}
/// Deletes synchronized data locally on device and restarts the sync engine.
///
/// This method is called automatically by the sync engine when it detects the device's iCloud
/// account has logged out or changed. To customize this behavior, provide a
/// ``SyncEngineDelegate`` to the sync engine and implement
/// ``SyncEngineDelegate/syncEngine(_:accountChanged:)``.
///
/// > Important: It is only appropriate to call this method when the device's iCloud account
/// > logs out or changes.
public func deleteLocalData() async throws {
stop()
try tearDownSyncEngine()
await withErrorReporting(.sqliteDataCloudKitFailure) {
try await userDatabase.write { db in
for table in tables {
func open<T>(_: some SynchronizableTable<T>) {
withErrorReporting(.sqliteDataCloudKitFailure) {
try T.delete().execute(db)
}
}
open(table)
}
try setUpSyncEngine(writableDB: db)
}
}
try await start()
}
@DatabaseFunction(
"sqlitedata_icloud_didUpdate",
as: ((
String,
String,
String,
String,
String,
[String]?.JSONRepresentation
) -> Void).self
)
func didUpdate(
recordName: String,
zoneName: String,
ownerName: String,
oldZoneName: String,
oldOwnerName: String,
descendantRecordNames: [String]?
) {
var oldChanges: [CKSyncEngine.PendingRecordZoneChange] = []
var newChanges: [CKSyncEngine.PendingRecordZoneChange] = []
let oldZoneID = CKRecordZone.ID(zoneName: oldZoneName, ownerName: oldOwnerName)
let zoneID = CKRecordZone.ID(zoneName: zoneName, ownerName: ownerName)
if oldZoneID != zoneID {
oldChanges.append(.deleteRecord(CKRecord.ID(recordName: recordName, zoneID: oldZoneID)))
for descendantRecordName in descendantRecordNames ?? [] {
oldChanges.append(
.deleteRecord(CKRecord.ID(recordName: descendantRecordName, zoneID: oldZoneID))
)
}
newChanges.append(.saveRecord(CKRecord.ID(recordName: recordName, zoneID: zoneID)))
for descendantRecordName in descendantRecordNames ?? [] {
newChanges.append(
.saveRecord(CKRecord.ID(recordName: descendantRecordName, zoneID: zoneID))
)
}
} else {
newChanges.append(
.saveRecord(CKRecord.ID(recordName: recordName, zoneID: zoneID))
)
}
guard isRunning else {
// TODO: Perform this work in a trigger instead of a task.
Task { [changes = oldChanges + newChanges] in
await withErrorReporting(.sqliteDataCloudKitFailure) {
try await userDatabase.write { db in
try PendingRecordZoneChange
.insert {
for change in changes {
PendingRecordZoneChange(change)
}
}
.execute(db)
}
}
}
return
}
let oldSyncEngine = self.syncEngines.withValue {
oldZoneID.ownerName == CKCurrentUserDefaultName ? $0.private : $0.shared
}
let syncEngine = self.syncEngines.withValue {
zoneID.ownerName == CKCurrentUserDefaultName ? $0.private : $0.shared
}
oldSyncEngine?.state.add(pendingRecordZoneChanges: oldChanges)
syncEngine?.state.add(pendingRecordZoneChanges: newChanges)
}
@DatabaseFunction(
"sqlitedata_icloud_didDelete",
as: ((String, CKRecord?.SystemFieldsRepresentation, CKShare?.SystemFieldsRepresentation)
-> Void).self
)
func didDelete(recordName: String, record: CKRecord?, share: CKShare?) {
let zoneID = record?.recordID.zoneID ?? defaultZone.zoneID
var changes: [CKSyncEngine.PendingRecordZoneChange] = [
.deleteRecord(
CKRecord.ID(
recordName: recordName,
zoneID: zoneID
)
)
]
if let share {
changes.append(.deleteRecord(share.recordID))
}
guard isRunning else {
Task { [changes] in
await withErrorReporting(.sqliteDataCloudKitFailure) {
try await userDatabase.write { db in
try PendingRecordZoneChange
.insert { changes.map { PendingRecordZoneChange($0) } }
.execute(db)
}
}
}
return
}
let syncEngine = self.syncEngines.withValue {
zoneID.ownerName == CKCurrentUserDefaultName ? $0.private : $0.shared
}
syncEngine?.state.add(pendingRecordZoneChanges: changes)
}
package func acceptShare(metadata: ShareMetadata) async throws {
guard let rootRecordID = metadata.hierarchicalRootRecordID
else {
reportIssue("Attempting to share without root record information.")
return
}
let container = type(of: container).createContainer(identifier: metadata.containerIdentifier)
_ = try await container.accept(metadata)
try await syncEngines.shared?.fetchChanges(
CKSyncEngine.FetchChangesOptions(
scope: .zoneIDs([rootRecordID.zoneID]),
operationGroup: nil
)
)
}
/// A query expression that can be used in SQL queries to determine if the ``SyncEngine``
/// is currently writing changes to the database.
///
/// See <doc:CloudKit#Updating-triggers-to-be-compatible-with-synchronization> for more info.
public static func isSynchronizingChanges() -> some QueryExpression<Bool> {
$syncEngineIsSynchronizingChanges()
}
private var sendingChangesCount: Int {
get {
observationRegistrar.access(self, keyPath: \.isSendingChanges)
return activityCounts.withValue(\.sendingChangesCount)
}
set {
observationRegistrar.withMutation(of: self, keyPath: \.isSendingChanges) {
activityCounts.withValue { $0.sendingChangesCount = newValue }
}
}
}
private var fetchingChangesCount: Int {
get {
observationRegistrar.access(self, keyPath: \.isFetchingChanges)
return activityCounts.withValue(\.fetchingChangesCount)
}
set {
observationRegistrar.withMutation(of: self, keyPath: \.isFetchingChanges) {
activityCounts.withValue { $0.fetchingChangesCount = newValue }
}
}
}
}
extension PrimaryKeyedTable {
@available(iOS 17, macOS 14, tvOS 17, watchOS 10, *)
fileprivate static func createTriggers(
foreignKeysByTableName: [String: [ForeignKey]],
tablesByName: [String: any SynchronizableTable],
defaultZone: CKRecordZone,
privateTables: [any SynchronizableTable],
db: Database
) throws {
let parentForeignKey =
foreignKeysByTableName[tableName]?.count == 1
? foreignKeysByTableName[tableName]?.first
: nil
for trigger in metadataTriggers(
parentForeignKey: parentForeignKey,
defaultZone: defaultZone,
privateTables: privateTables
) {
try trigger.execute(db)
}
}
@available(iOS 17, macOS 14, tvOS 17, watchOS 10, *)
fileprivate static func dropTriggers(
defaultZone: CKRecordZone,
privateTables: [any SynchronizableTable],
db: Database
) throws {
for trigger in metadataTriggers(
parentForeignKey: nil,
defaultZone: defaultZone,
privateTables: privateTables
)
.reversed() {
try trigger.drop().execute(db)
}
}
}
@available(iOS 17, macOS 14, tvOS 17, watchOS 10, *)
extension SyncEngine: CKSyncEngineDelegate {
public func handleEvent(_ event: CKSyncEngine.Event, syncEngine: CKSyncEngine) async {
guard let event = Event(event)
else {
reportIssue("Unrecognized event received: \(event)")
return
}
await handleEvent(event, syncEngine: syncEngine)
}
package func handleEvent(_ event: Event, syncEngine: any SyncEngineProtocol) async {
#if DEBUG
logger.log(event, syncEngine: syncEngine)
#endif
switch event {
case .accountChange(let changeType):
await handleAccountChange(changeType: changeType, syncEngine: syncEngine)
case .stateUpdate(let stateSerialization):
await handleStateUpdate(stateSerialization: stateSerialization, syncEngine: syncEngine)
case .fetchedDatabaseChanges(let modifications, let deletions):
await handleFetchedDatabaseChanges(
modifications: modifications,
deletions: deletions,
syncEngine: syncEngine
)
case .sentDatabaseChanges:
break
case .fetchedRecordZoneChanges(let modifications, let deletions):
await handleFetchedRecordZoneChanges(
modifications: modifications,
deletions: deletions,
syncEngine: syncEngine
)
case .sentRecordZoneChanges(
let savedRecords,
let failedRecordSaves,
let deletedRecordIDs,
let failedRecordDeletes
):
await handleSentRecordZoneChanges(
savedRecords: savedRecords,
failedRecordSaves: failedRecordSaves,
deletedRecordIDs: deletedRecordIDs,
failedRecordDeletes: failedRecordDeletes,
syncEngine: syncEngine
)
case .willFetchRecordZoneChanges:
await MainActor.run {
fetchingChangesCount += 1
}
case .didFetchRecordZoneChanges:
await MainActor.run {
fetchingChangesCount -= 1
}
case .willFetchChanges:
await MainActor.run {
fetchingChangesCount += 1
}
case .didFetchChanges:
await MainActor.run {