forked from grpc/grpc-swift-nio-transport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGRPCChannelTests.swift
894 lines (747 loc) · 28.9 KB
/
GRPCChannelTests.swift
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
/*
* Copyright 2024, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import GRPCCore
import GRPCNIOTransportCore
import NIOCore
import NIOHTTP2
import NIOPosix
import XCTest
final class GRPCChannelTests: XCTestCase {
func testDefaultServiceConfig() throws {
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
serviceConfig.methodConfig = [MethodConfig(names: [MethodConfig.Name(.echoGet)])]
serviceConfig.retryThrottling = try ServiceConfig.RetryThrottling(
maxTokens: 100,
tokenRatio: 0.1
)
let channel = GRPCChannel(
resolver: .static(endpoints: []),
connector: .never,
config: .defaults,
defaultServiceConfig: serviceConfig
)
XCTAssertNotNil(channel.config(forMethod: .echoGet))
XCTAssertNil(channel.config(forMethod: .echoUpdate))
let throttle = try XCTUnwrap(channel.retryThrottle)
XCTAssertEqual(throttle.maxTokens, 100)
XCTAssertEqual(throttle.tokenRatio, 0.1)
}
func testServiceConfigFromResolver() async throws {
// Verify that service config from the resolver takes precedence over the default service
// config. This is done indirectly by checking method config and retry throttle config.
// Create a service config to provide via the resolver.
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
serviceConfig.methodConfig = [MethodConfig(names: [MethodConfig.Name(.echoGet)])]
serviceConfig.retryThrottling = try ServiceConfig.RetryThrottling(
maxTokens: 100,
tokenRatio: 0.1
)
// Need a server to connect to, no RPCs will be created though.
let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address = try await server.bind()
let channel = GRPCChannel(
resolver: .static(endpoints: [Endpoint(addresses: [address])], serviceConfig: serviceConfig),
connector: .posix(),
config: .defaults,
defaultServiceConfig: ServiceConfig()
)
// Not resolved yet so the default (empty) service config is used.
XCTAssertNil(channel.config(forMethod: .echoGet))
XCTAssertNil(channel.config(forMethod: .echoUpdate))
XCTAssertNil(channel.retryThrottle)
try await withThrowingDiscardingTaskGroup { group in
group.addTask {
try await server.run(.never)
}
group.addTask {
await channel.connect()
}
for await event in channel.connectivityState {
switch event {
case .ready:
// When the channel is ready it must have the service config from the resolver.
XCTAssertNotNil(channel.config(forMethod: .echoGet))
XCTAssertNil(channel.config(forMethod: .echoUpdate))
let throttle = try XCTUnwrap(channel.retryThrottle)
XCTAssertEqual(throttle.maxTokens, 100)
XCTAssertEqual(throttle.tokenRatio, 0.1)
// Now close.
channel.beginGracefulShutdown()
default:
()
}
}
group.cancelAll()
}
}
func testServiceConfigFromResolverAfterUpdate() async throws {
// Verify that the channel uses service config from the resolver and that it uses the latest
// version provided by the resolver. This is done indirectly by checking method config and retry
// throttle config.
let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address = try await server.bind()
let (resolver, continuation) = NameResolver.dynamic(updateMode: .push)
let channel = GRPCChannel(
resolver: resolver,
connector: .posix(),
config: .defaults,
defaultServiceConfig: ServiceConfig()
)
// Not resolved yet so the default (empty) service config is used.
XCTAssertNil(channel.config(forMethod: .echoGet))
XCTAssertNil(channel.config(forMethod: .echoUpdate))
XCTAssertNil(channel.retryThrottle)
// Yield the first address list and service config.
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
serviceConfig.methodConfig = [MethodConfig(names: [MethodConfig.Name(.echoGet)])]
serviceConfig.retryThrottling = try ServiceConfig.RetryThrottling(
maxTokens: 100,
tokenRatio: 0.1
)
let resolutionResult = NameResolutionResult(
endpoints: [Endpoint(address)],
serviceConfig: .success(serviceConfig)
)
continuation.yield(resolutionResult)
try await withThrowingDiscardingTaskGroup { group in
group.addTask {
try await server.run(.never)
}
group.addTask {
await channel.connect()
}
for await event in channel.connectivityState {
switch event {
case .ready:
// When the channel it must have the service config from the resolver.
XCTAssertNotNil(channel.config(forMethod: .echoGet))
XCTAssertNil(channel.config(forMethod: .echoUpdate))
let throttle = try XCTUnwrap(channel.retryThrottle)
XCTAssertEqual(throttle.maxTokens, 100)
XCTAssertEqual(throttle.tokenRatio, 0.1)
// Now yield a new service config with the same addresses.
var resolutionResult = resolutionResult
serviceConfig.methodConfig = [MethodConfig(names: [MethodConfig.Name(.echoUpdate)])]
serviceConfig.retryThrottling = nil
resolutionResult.serviceConfig = .success(serviceConfig)
continuation.yield(resolutionResult)
// This should be propagated quickly.
try await XCTPoll(every: .milliseconds(10)) {
let noConfigForGet = channel.config(forMethod: .echoGet) == nil
let configForUpdate = channel.config(forMethod: .echoUpdate) != nil
let noThrottle = channel.retryThrottle == nil
return noConfigForGet && configForUpdate && noThrottle
}
channel.beginGracefulShutdown()
default:
()
}
}
group.cancelAll()
}
}
func testPushBasedResolutionUpdates() async throws {
// Verify that the channel responds to name resolution changes which are pushed into
// the resolver. Do this by starting two servers and only making the address of one available
// via the resolver at a time. Server identity is provided via metadata in the RPC.
// Start a few servers.
let server1 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address1 = try await server1.bind()
let server2 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address2 = try await server2.bind()
// Setup a resolver and push some changes into it.
let (resolver, continuation) = NameResolver.dynamic(updateMode: .push)
let resolution1 = NameResolutionResult(endpoints: [Endpoint(address1)], serviceConfig: nil)
continuation.yield(resolution1)
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
let channel = GRPCChannel(
resolver: resolver,
connector: .posix(),
config: .defaults,
defaultServiceConfig: serviceConfig
)
try await withThrowingDiscardingTaskGroup { group in
// Servers respond with their own address in the trailing metadata.
for (server, address) in [(server1, address1), (server2, address2)] {
group.addTask {
try await server.run { inbound, outbound in
let status = Status(code: .ok, message: "")
let metadata: Metadata = ["server-addr": "\(address)"]
try await outbound.write(.status(status, metadata))
outbound.finish()
}
}
}
group.addTask {
await channel.connect()
}
// The stream will be queued until the channel is ready.
let serverAddress1 = try await channel.serverAddress()
XCTAssertEqual(serverAddress1, "\(address1)")
XCTAssertEqual(server1.clients.count, 1)
XCTAssertEqual(server2.clients.count, 0)
// Yield the second address. Because this happens asynchronously there's no guarantee that
// the next stream will be made against the same server, so poll until the servers have the
// appropriate connections.
let resolution2 = NameResolutionResult(endpoints: [Endpoint(address2)], serviceConfig: nil)
continuation.yield(resolution2)
try await XCTPoll(every: .milliseconds(10)) {
server1.clients.count == 0 && server2.clients.count == 1
}
let serverAddress2 = try await channel.serverAddress()
XCTAssertEqual(serverAddress2, "\(address2)")
group.cancelAll()
}
}
func testPullBasedResolutionUpdates() async throws {
// Verify that the channel responds to name resolution changes which are pulled because a
// subchannel asked the channel to re-resolve. Do this by starting two servers and changing
// which is available via resolution updates. Server identity is provided via metadata in
// the RPC.
// Start a few servers.
let server1 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address1 = try await server1.bind()
let server2 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address2 = try await server2.bind()
// Setup a resolve which we push changes into.
let (resolver, continuation) = NameResolver.dynamic(updateMode: .pull)
// Yield the addresses.
for address in [address1, address2] {
let resolution = NameResolutionResult(endpoints: [Endpoint(address)], serviceConfig: nil)
continuation.yield(resolution)
}
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
let channel = GRPCChannel(
resolver: resolver,
connector: .posix(),
config: .defaults,
defaultServiceConfig: serviceConfig
)
try await withThrowingDiscardingTaskGroup { group in
// Servers respond with their own address in the trailing metadata.
for (server, address) in [(server1, address1), (server2, address2)] {
group.addTask {
try await server.run { inbound, outbound in
let status = Status(code: .ok, message: "")
let metadata: Metadata = ["server-addr": "\(address)"]
try await outbound.write(.status(status, metadata))
outbound.finish()
}
}
}
group.addTask {
await channel.connect()
}
// The stream will be queued until the channel is ready.
let serverAddress1 = try await channel.serverAddress()
XCTAssertEqual(serverAddress1, "\(address1)")
XCTAssertEqual(server1.clients.count, 1)
XCTAssertEqual(server2.clients.count, 0)
// Tell the first server to GOAWAY. This will cause the subchannel to re-resolve.
let server1Client = try XCTUnwrap(server1.clients.first)
let goAway = HTTP2Frame(
streamID: .rootStream,
payload: .goAway(lastStreamID: 1, errorCode: .noError, opaqueData: nil)
)
try await server1Client.writeAndFlush(goAway)
// Poll until the first client drops, addresses are re-resolved, and a connection is
// established to server2.
try await XCTPoll(every: .milliseconds(10)) {
server1.clients.count == 0 && server2.clients.count == 1
}
let serverAddress2 = try await channel.serverAddress()
XCTAssertEqual(serverAddress2, "\(address2)")
group.cancelAll()
}
}
func testCloseWhenRPCsAreInProgress() async throws {
// Verify that closing the channel while there are RPCs in progress allows the RPCs to finish
// gracefully.
let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address = try await server.bind()
try await withThrowingDiscardingTaskGroup { group in
group.addTask {
try await server.run(.echo)
}
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
let channel = GRPCChannel(
resolver: .static(endpoints: [Endpoint(address)]),
connector: .posix(),
config: .defaults,
defaultServiceConfig: serviceConfig
)
group.addTask {
await channel.connect()
}
try await channel.withStream(descriptor: .echoGet, options: .defaults) { stream, _ in
try await stream.outbound.write(.metadata([:]))
var iterator = stream.inbound.makeAsyncIterator()
let part1 = try await iterator.next()
switch part1 {
case .metadata:
// Got metadata, close the channel.
channel.beginGracefulShutdown()
case .message, .status, .none:
XCTFail("Expected metadata, got \(String(describing: part1))")
}
for await state in channel.connectivityState {
switch state {
case .shutdown:
// Happens when shutting-down has been initiated, so finish the RPC.
await stream.outbound.finish()
let part2 = try await iterator.next()
switch part2 {
case .status(let status, _):
XCTAssertEqual(status.code, .ok)
case .metadata, .message, .none:
XCTFail("Expected status, got \(String(describing: part2))")
}
default:
()
}
}
}
group.cancelAll()
}
}
func testQueueRequestsWhileNotReady() async throws {
// Verify that requests are queued until the channel becomes ready. As creating streams
// will race with the channel becoming ready, we add numerous tasks to the task group which
// each create a stream before making the server address known to the channel via the resolver.
// This isn't perfect as the resolution _could_ happen before attempting to create all streams
// although this is unlikely.
let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address = try await server.bind()
let (resolver, continuation) = NameResolver.dynamic(updateMode: .push)
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
let channel = GRPCChannel(
resolver: resolver,
connector: .posix(),
config: .defaults,
defaultServiceConfig: serviceConfig
)
enum Subtask { case rpc, other }
try await withThrowingTaskGroup(of: Subtask.self) { group in
// Run the server.
group.addTask {
try await server.run { inbound, outbound in
for try await part in inbound {
switch part {
case .metadata:
try await outbound.write(.metadata([:]))
case .message(let bytes):
try await outbound.write(.message(bytes))
}
}
let status = Status(code: .ok, message: "")
try await outbound.write(.status(status, [:]))
outbound.finish()
}
return .other
}
group.addTask {
await channel.connect()
return .other
}
// Start a bunch of requests. These won't start until an address is yielded, they should
// be queued though.
for _ in 1 ... 100 {
group.addTask {
try await channel.withStream(descriptor: .echoGet, options: .defaults) { stream, _ in
try await stream.outbound.write(.metadata([:]))
await stream.outbound.finish()
for try await part in stream.inbound {
switch part {
case .metadata, .message:
()
case .status(let status, _):
XCTAssertEqual(status.code, .ok)
}
}
}
return .rpc
}
}
// At least some of the RPCs should have been queued by now.
let resolution = NameResolutionResult(endpoints: [Endpoint(address)], serviceConfig: nil)
continuation.yield(resolution)
var outstandingRPCs = 100
for try await subtask in group {
switch subtask {
case .rpc:
outstandingRPCs -= 1
// All RPCs done, close the channel and cancel the group to stop the server.
if outstandingRPCs == 0 {
channel.beginGracefulShutdown()
group.cancelAll()
}
case .other:
()
}
}
}
}
func testQueueRequestsFailFast() async throws {
// Verifies that if 'waitsForReady' is 'false', that queued requests are failed when there is
// a transient failure. The transient failure is triggered by attempting to connect to a
// non-existent server.
let (resolver, continuation) = NameResolver.dynamic(updateMode: .push)
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
let channel = GRPCChannel(
resolver: resolver,
connector: .posix(),
config: .defaults,
defaultServiceConfig: serviceConfig
)
enum Subtask { case rpc, other }
try await withThrowingTaskGroup(of: Subtask.self) { group in
group.addTask {
await channel.connect()
return .other
}
for _ in 1 ... 100 {
group.addTask {
var options = CallOptions.defaults
options.waitForReady = false
await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
try await channel.withStream(descriptor: .echoGet, options: options) { _, _ in
XCTFail("Unexpected stream")
}
} errorHandler: { error in
XCTAssertEqual(error.code, .unavailable)
}
return .rpc
}
}
// At least some of the RPCs should have been queued by now.
let resolution = NameResolutionResult(
endpoints: [Endpoint(.unixDomainSocket(path: "/test-queue-requests-fail-fast"))],
serviceConfig: nil
)
continuation.yield(resolution)
var outstandingRPCs = 100
for try await subtask in group {
switch subtask {
case .rpc:
outstandingRPCs -= 1
// All RPCs done, close the channel and cancel the group to stop the server.
if outstandingRPCs == 0 {
channel.beginGracefulShutdown()
group.cancelAll()
}
case .other:
()
}
}
}
}
func testLoadBalancerChangingFromRoundRobinToPickFirst() async throws {
// The test will push different configs to the resolver, first a round-robin LB, then a
// pick-first LB.
let (resolver, continuation) = NameResolver.dynamic(updateMode: .push)
let channel = GRPCChannel(
resolver: resolver,
connector: .posix(),
config: .defaults,
defaultServiceConfig: ServiceConfig()
)
// Start a few servers.
let server1 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address1 = try await server1.bind()
let server2 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address2 = try await server2.bind()
let server3 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address3 = try await server3.bind()
try await withThrowingTaskGroup(of: Void.self) { group in
// Run the servers, no RPCs will be run against them.
for server in [server1, server2, server3] {
group.addTask {
try await server.run(.never)
}
}
group.addTask {
await channel.connect()
}
for await event in channel.connectivityState {
switch event {
case .idle:
let endpoints = [address1, address2].map { Endpoint(addresses: [$0]) }
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.roundRobin]
let resolutionResult = NameResolutionResult(
endpoints: endpoints,
serviceConfig: .success(serviceConfig)
)
// Push the first resolution result which uses round robin. This will result in the
// channel becoming ready.
continuation.yield(resolutionResult)
case .ready:
// Channel is ready, server 1 and 2 should have clients shortly.
try await XCTPoll(every: .milliseconds(10)) {
server1.clients.count == 1 && server2.clients.count == 1 && server3.clients.count == 0
}
// Both subchannels are ready, prepare and yield an update to the resolver.
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.pickFirst(shuffleAddressList: false)]
let resolutionResult = NameResolutionResult(
endpoints: [Endpoint(addresses: [address3])],
serviceConfig: .success(serviceConfig)
)
continuation.yield(resolutionResult)
// Only server 3 should have a connection.
try await XCTPoll(every: .milliseconds(10)) {
server1.clients.count == 0 && server2.clients.count == 0 && server3.clients.count == 1
}
channel.beginGracefulShutdown()
case .shutdown:
group.cancelAll()
default:
()
}
}
}
}
func testPickFirstShufflingAddressList() async throws {
// This test checks that the pick first load-balancer has its address list shuffled. We can't
// assert this deterministically, so instead we'll run an experiment a number of times. Each
// round will create N servers and provide them as endpoints to the pick-first load balancer.
// The channel will establish a connection to one of the servers and its identity will be noted.
let numberOfRounds = 100
let numberOfServers = 2
let servers = (0 ..< numberOfServers).map { _ in
TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
}
var addresses = [GRPCNIOTransportCore.SocketAddress]()
for server in servers {
let address = try await server.bind()
addresses.append(address)
}
let endpoint = Endpoint(addresses: addresses)
var counts = Array(repeating: 0, count: addresses.count)
// Supply service config on init, not via the load-balancer.
var serviceConfig = ServiceConfig()
serviceConfig.loadBalancingConfig = [.pickFirst(shuffleAddressList: true)]
try await withThrowingDiscardingTaskGroup { group in
// Run the servers.
for server in servers {
group.addTask {
try await server.run(.never)
}
}
// Run the experiment.
for _ in 0 ..< numberOfRounds {
let channel = GRPCChannel(
resolver: .static(endpoints: [endpoint]),
connector: .posix(),
config: .defaults,
defaultServiceConfig: serviceConfig
)
group.addTask {
await channel.connect()
}
for await state in channel.connectivityState {
switch state {
case .ready:
for index in servers.indices {
if servers[index].clients.count == 1 {
counts[index] += 1
break
}
}
channel.beginGracefulShutdown()
default:
()
}
}
}
// Stop the servers.
group.cancelAll()
}
// The address list is shuffled, so there's no guarantee how many times we'll hit each server.
// Assert that the minimum a server should be hit is 10% of the time.
let expected = Double(numberOfRounds) / Double(numberOfServers)
let minimum = expected * 0.1
XCTAssert(counts.allSatisfy({ Double($0) >= minimum }), "\(counts)")
}
func testPickFirstIsFallbackPolicy() async throws {
// Start a few servers.
let server1 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address1 = try await server1.bind()
let server2 = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address2 = try await server2.bind()
// Prepare a channel with an empty service config.
let channel = GRPCChannel(
resolver: .static(endpoints: [Endpoint(address1, address2)]),
connector: .posix(),
config: .defaults,
defaultServiceConfig: ServiceConfig()
)
try await withThrowingDiscardingTaskGroup { group in
// Run the servers.
for server in [server1, server2] {
group.addTask {
try await server.run(.never)
}
}
group.addTask {
await channel.connect()
}
for try await state in channel.connectivityState {
switch state {
case .ready:
// Only server 1 should have a connection.
try await XCTPoll(every: .milliseconds(10)) {
server1.clients.count == 1 && server2.clients.count == 0
}
channel.beginGracefulShutdown()
default:
()
}
}
group.cancelAll()
}
}
func testQueueRequestsThenClose() async throws {
// Set a high backoff so the channel stays in transient failure for long enough.
var config = GRPCChannel.Config.defaults
config.backoff.initial = .seconds(120)
let channel = GRPCChannel(
resolver: .static(
endpoints: [
Endpoint(.unixDomainSocket(path: "/testQueueRequestsThenClose"))
]
),
connector: .posix(),
config: .defaults,
defaultServiceConfig: ServiceConfig()
)
try await withThrowingDiscardingTaskGroup { group in
group.addTask {
await channel.connect()
}
for try await state in channel.connectivityState {
switch state {
case .transientFailure:
group.addTask {
// Sleep a little to increase the chances of the stream being queued before the channel
// reacts to the close.
try await Task.sleep(for: .milliseconds(10))
channel.beginGracefulShutdown()
}
// Try to open a new stream.
await XCTAssertThrowsErrorAsync(ofType: RPCError.self) {
try await channel.withStream(descriptor: .echoGet, options: .defaults) { stream, _ in
XCTFail("Unexpected new stream")
}
} errorHandler: { error in
XCTAssertEqual(error.code, .unavailable)
}
default:
()
}
}
group.cancelAll()
}
}
func testMakeStreamAfterIdleTimeout() async throws {
let server = TestServer(eventLoopGroup: .singletonMultiThreadedEventLoopGroup)
let address = try await server.bind()
// Configure a low idle time.
let channel = GRPCChannel(
resolver: .static(endpoints: [Endpoint(address)]),
connector: .posix(maxIdleTime: .milliseconds(50)),
config: .defaults,
defaultServiceConfig: ServiceConfig()
)
try await withThrowingDiscardingTaskGroup { group in
group.addTask {
// Just respond with 'ok'.
try await server.run { inbound, outbound in
let status = Status(code: .ok, message: "")
try await outbound.write(.status(status, [:]))
outbound.finish()
}
}
group.addTask {
await channel.connect()
}
func doAnRPC() async throws {
try await channel.withStream(descriptor: .echoGet, options: .defaults) { stream, _ in
try await stream.outbound.write(.metadata([:]))
await stream.outbound.finish()
let response = try await stream.inbound.reduce(into: []) { $0.append($1) }
switch response.first {
case .status(let status, _):
XCTAssertEqual(status.code, .ok)
default:
XCTFail("Expected status")
}
}
}
// Do an RPC.
try await doAnRPC()
// Wait for the idle time to pass.
try await Task.sleep(for: .milliseconds(100))
// Do another RPC.
try await doAnRPC()
group.cancelAll()
}
}
}
extension GRPCChannel.Config {
static var defaults: Self {
Self(
http2: .defaults,
backoff: .defaults,
connection: .defaults,
compression: .defaults
)
}
}
extension Endpoint {
init(_ addresses: GRPCNIOTransportCore.SocketAddress...) {
self.init(addresses: addresses)
}
}
extension GRPCChannel {
fileprivate func serverAddress() async throws -> String? {
let values: Metadata.StringValues? = try await self.withStream(
descriptor: .echoGet,
options: .defaults
) { stream, _ in
try await stream.outbound.write(.metadata([:]))
await stream.outbound.finish()
for try await part in stream.inbound {
switch part {
case .metadata, .message:
XCTFail("Unexpected part: \(part)")
case .status(_, let metadata):
return metadata[stringValues: "server-addr"]
}
}
return nil
}
return values?.first(where: { _ in true })
}
}