-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathAppSyncRealTimeSubscription.swift
More file actions
130 lines (107 loc) · 3.8 KB
/
Copy pathAppSyncRealTimeSubscription.swift
File metadata and controls
130 lines (107 loc) · 3.8 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
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import Amplify
import Combine
@preconcurrency import Combine
import Foundation
@_spi(WebSocket) import AWSPluginsCore
/**
AppSyncRealTimeSubscription reprensents one realtime subscription to AppSync realtime server.
*/
actor AppSyncRealTimeSubscription {
static let jsonEncoder = JSONEncoder()
enum State {
case none
case subscribing
case subscribed
case unsubscribing
case unsubscribed
case failure
}
/// internal state for tracking subscription status
private let state = CurrentValueSubject<State, Never>(.none)
/// publisher for monitoring subscription status
var publisher: AnyPublisher<State, Never> {
state.eraseToAnyPublisher()
}
private weak var appSyncRealTimeClient: AppSyncRealTimeClient?
let id: String
let query: String
init(id: String, query: String, appSyncRealTimeClient: AppSyncRealTimeClient) {
self.id = id
self.query = query
self.appSyncRealTimeClient = appSyncRealTimeClient
}
deinit {
self.state.send(completion: .finished)
}
func subscribe() async throws {
guard state.value != .subscribing else {
log.debug("[AppSyncRealTimeSubscription-\(id)] Subscription already in subscribing state")
return
}
guard state.value != .subscribed else {
log.debug("[AppSyncRealTimeSubscription-\(id)] Subscription already in subscribed state")
return
}
log.debug("[AppSyncRealTimeSubscription-\(id)] Start subscribing")
state.send(.subscribing)
do {
try await RetryWithJitter.execute(shouldRetryOnError: { error in
(error as? AppSyncRealTimeRequest.Error) == .maxSubscriptionsReached
}) { [weak self] in
guard let self else { return }
try await appSyncRealTimeClient?.sendRequest(
.start(.init(id: id, data: query, auth: nil))
)
}
} catch {
log.debug("[AppSyncRealTimeSubscription-\(id)] Failed to subscribe, error: \(error)")
state.send(.failure)
throw error
}
log.debug("[AppSyncRealTimeSubscription-\(id)] Subscribed")
state.send(.subscribed)
}
func unsubscribe() async throws {
guard state.value == .subscribed else {
log.debug("[AppSyncRealTimeSubscription-\(id)] Subscription should be subscribed to be unsubscribed")
return
}
log.debug("[AppSyncRealTimeSubscription-\(id)] Unsubscribing")
state.send(.unsubscribing)
do {
let request = AppSyncRealTimeRequest.stop(id)
try await appSyncRealTimeClient?.sendRequest(request)
} catch {
log.debug("[AppSyncRealTimeSubscription-\(id)] Failed to unsubscribe, error \(error)")
state.send(.failure)
throw error
}
log.debug("[AppSyncRealTimeSubscription-\(id)] Unsubscribed")
state.send(.unsubscribed)
}
private static func sendAppSyncRealTimeRequest(
_ request: AppSyncRealTimeRequest,
with webSocketClient: AppSyncWebSocketClientProtocol
) async throws {
guard let requestJson = try String(
data: jsonEncoder.encode(request),
encoding: .utf8
) else {
return
}
try await webSocketClient.write(message: requestJson)
}
}
extension AppSyncRealTimeSubscription: DefaultLogger {
static var log: Logger {
Amplify.Logging.logger(forCategory: CategoryType.api.displayName, forNamespace: String(describing: self))
}
nonisolated var log: Logger { Self.log }
}