-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathSyncCoordinator.swift
More file actions
57 lines (48 loc) · 1.97 KB
/
Copy pathSyncCoordinator.swift
File metadata and controls
57 lines (48 loc) · 1.97 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
/// Manages a connection task for a PowerSync database.
actor SyncCoordinator {
nonisolated let streams = StreamTracker()
private var activeSync: Task<Void, any Error>?
func connect(db: PowerSyncDatabaseImpl, connector: PowerSyncBackendConnectorProtocol, options: ConnectOptions, client: HttpClient?) async {
if let task = activeSync {
await self.finishSyncTask(task: task)
}
func defaultHttpClient() -> HttpClient {
let session = options.clientConfiguration?.urlSession ?? .shared
return PlatformHttpClient(session: session)
}
var client = client ?? defaultHttpClient()
if let logger = options.clientConfiguration?.requestLogger {
client = LoggingClient(inner: client, logger: logger)
}
let sync = StreamingSyncClient(db: db, connector: connector, httpClient: client, options: options)
activeSync = sync.run()
}
func disconnect() async {
guard let task = activeSync else {
return // Not connected
}
await self.finishSyncTask(task: task)
}
/// Runs ``Self/disconnect`` and `action` in a single actor message lock.
func disconnectAndThen<T>(action: () async throws -> T) async rethrows -> T {
await disconnect()
return try await action()
}
/// Executes an inner function, but only if no connection is active or scheduled.
func guardNotConnected<T>(inner: () async throws -> T, ifConnected: () async throws -> T) async rethrows -> T {
if activeSync == nil {
return try await inner();
} else {
return try await ifConnected()
}
}
private func finishSyncTask(task: Task<Void, any Error>) async {
self.activeSync = nil
task.cancel()
do {
try await task.value
} catch {
// Ignore here, the sync task itself handles errors by retrying.
}
}
}