-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathAppSyncRealTimeClientTests.swift
More file actions
203 lines (175 loc) · 7.64 KB
/
Copy pathAppSyncRealTimeClientTests.swift
File metadata and controls
203 lines (175 loc) · 7.64 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
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Combine
import XCTest
@testable import Amplify
@testable import AWSAPIPlugin
@testable @_spi(WebSocket) import AWSPluginsCore
@testable import InternalAmplifyCredentials
class AppSyncRealTimeClientTests: XCTestCase {
let subscriptionRequest = """
subscription MySubscription {
onCreatePost {
content
createdAt
draft
id
rating
status
title
updatedAt
}
}
"""
var appSyncRealTimeClient: AppSyncRealTimeClient?
override func setUp() async throws {
do {
Amplify.Logging.logLevel = .verbose
let data = try TestConfigHelper.retrieve(
forResource: GraphQLModelBasedTests.amplifyConfiguration
)
let amplifyConfig = try JSONDecoder().decode(JSONValue.self, from: data)
let (endpoint, apiKey) = (amplifyConfig.api?.plugins?.awsAPIPlugin?.asObject?.values
.map { ($0.endpoint?.stringValue, $0.apiKey?.stringValue)}
.first { $0.0 != nil && $0.1 != nil }
.map { ($0.0!, $0.1!) })!
let webSocketClient = WebSocketClient(
url: AppSyncRealTimeClientFactory.appSyncRealTimeEndpoint(URL(string: endpoint)!),
handshakeHttpHeaders: [
URLRequestConstants.Header.webSocketSubprotocols: "graphql-ws",
URLRequestConstants.Header.userAgent: AmplifyAWSServiceConfiguration.userAgentLib + " (intg-test)"
],
interceptor: APIKeyAuthInterceptor(apiKey: apiKey)
)
appSyncRealTimeClient = AppSyncRealTimeClient(
endpoint: URL(string: endpoint)!,
requestInterceptor: APIKeyAuthInterceptor(apiKey: apiKey),
webSocketClient: webSocketClient
)
} catch {
XCTFail("Failed to setup appSyncRealTimeClient: \(error)")
}
}
override func tearDown() async throws {
await appSyncRealTimeClient?.reset()
appSyncRealTimeClient = nil
}
func testSubscribe_withSubscriptionConnection() async throws {
var cancellables = Set<AnyCancellable>()
let subscribedExpectation = expectation(description: "Subscription established")
try await appSyncRealTimeClient?.connect()
try await makeOneSubscription { event in
if case .subscribed = event {
subscribedExpectation.fulfill()
}
}?.store(in: &cancellables)
await fulfillment(of: [subscribedExpectation], timeout: 5)
withExtendedLifetime(cancellables) { }
}
func testMultThreads_withConnectedClient_subscribeAndUnsubscribe() async throws {
var cancellables = [AnyCancellable?]()
let concurrentFactor = 90
let expectedSubscription = expectation(description: "Multi threads subscription")
expectedSubscription.expectedFulfillmentCount = concurrentFactor
let expectedUnsubscription = expectation(description: "Multi threads unsubscription")
expectedUnsubscription.expectedFulfillmentCount = concurrentFactor
cancellables = try await withThrowingTaskGroup(
of: AnyCancellable?.self,
returning: [AnyCancellable?].self
) { taskGroup in
for index in 0 ..< concurrentFactor {
let id = UUID().uuidString
taskGroup.addTask { [weak self] () -> AnyCancellable? in
guard let self else { return nil }
let subscription = try await makeOneSubscription(id: id) {
if case .subscribed = $0 {
expectedSubscription.fulfill()
Task {
try await self.appSyncRealTimeClient?.unsubscribe(id: id)
}
} else if case .unsubscribed = $0 {
expectedUnsubscription.fulfill()
}
}
return subscription
}
}
return try await taskGroup.reduce([AnyCancellable?]()) { $0 + [$1] }
}
await fulfillment(of: [expectedSubscription, expectedUnsubscription], timeout: 3)
withExtendedLifetime(cancellables) { }
}
func testMaxSubscriptionReached_throwMaxSubscriptionsReachedError() async throws {
let numOfMaxSubscriptionCount = 200
let maxSubsctiptionsSuccess = expectation(description: "Client can subscribe to max subscription count")
maxSubsctiptionsSuccess.expectedFulfillmentCount = numOfMaxSubscriptionCount
var cancellables = try await withThrowingTaskGroup(
of: AnyCancellable?.self,
returning: [AnyCancellable?].self
) { taskGroup in
for index in 0 ..< numOfMaxSubscriptionCount {
let id = UUID().uuidString
taskGroup.addTask { [weak self] () -> AnyCancellable? in
guard let self else { return nil }
let subscription = try await makeOneSubscription(id: id) {
if case .subscribed = $0 {
maxSubsctiptionsSuccess.fulfill()
}
}
return subscription
}
}
return try await taskGroup.reduce([AnyCancellable?]()) { $0 + [$1] }
}
await fulfillment(of: [maxSubsctiptionsSuccess], timeout: 2)
let maxSubscriptionReachedError = expectation(description: "Should return max subscription reached error")
maxSubscriptionReachedError.assertForOverFulfill = false
let retryTriggerredAndSucceed = expectation(description: "Retry on max subscription reached error and succeed")
try await cancellables.append(makeOneSubscription { event in
if case .error(let errors) = event {
XCTAssertTrue(errors.count == 1)
XCTAssertTrue(errors[0] is AppSyncRealTimeRequest.Error)
if case .maxSubscriptionsReached = errors[0] as! AppSyncRealTimeRequest.Error {
maxSubscriptionReachedError.fulfill()
cancellables.dropLast(10).forEach { $0?.cancel() }
}
} else if case .subscribed = event {
retryTriggerredAndSucceed.fulfill()
}
})
await fulfillment(of: [maxSubscriptionReachedError, retryTriggerredAndSucceed], timeout: 5, enforceOrder: true)
withExtendedLifetime(cancellables) { }
}
private func makeOneSubscription(
id: String = UUID().uuidString,
onSubscriptionEvents: ((AppSyncSubscriptionEvent) -> Void)?
) async throws -> AnyCancellable? {
let subscription = try await appSyncRealTimeClient?.subscribe(
id: id,
query: Self.appSyncQuery(with: subscriptionRequest)
).sink(receiveValue: {
onSubscriptionEvents?($0)
})
return AnyCancellable {
subscription?.cancel()
Task { [weak self] in
try? await self?.appSyncRealTimeClient?.unsubscribe(id: id)
}
}
}
private static func appSyncQuery(
with query: String,
variables: [String: JSONValue] = [:]
) throws -> String {
let payload: JSONValue = .object([
"query": .string(query),
"variables": variables.isEmpty ? .null : .object(variables)
])
let data = try JSONEncoder().encode(payload)
return String(data: data, encoding: .utf8)!
}
}