forked from grpc/grpc-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectionPoolTests.swift
1419 lines (1191 loc) · 47.8 KB
/
ConnectionPoolTests.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
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
/*
* Copyright 2021, 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.
*/
@testable import GRPC
import Logging
import NIOCore
import NIOEmbedded
import NIOHTTP2
import XCTest
final class ConnectionPoolTests: GRPCTestCase {
private enum TestError: Error {
case noChannelExpected
}
private var eventLoop: EmbeddedEventLoop!
private var tearDownBlocks: [() throws -> Void] = []
override func setUp() {
super.setUp()
self.eventLoop = EmbeddedEventLoop()
}
override func tearDown() {
XCTAssertNoThrow(try self.eventLoop.close())
self.tearDownBlocks.forEach { try? $0() }
super.tearDown()
}
private func noChannelExpected(
_: ConnectionManager,
_ eventLoop: EventLoop,
line: UInt = #line
) -> EventLoopFuture<Channel> {
XCTFail("Channel unexpectedly created", line: line)
return eventLoop.makeFailedFuture(TestError.noChannelExpected)
}
private func makePool(
waiters: Int = 1000,
reservationLoadThreshold: Double = 0.9,
now: @escaping () -> NIODeadline = { .now() },
connectionBackoff: ConnectionBackoff = ConnectionBackoff(),
delegate: GRPCConnectionPoolDelegate? = nil,
onReservationReturned: @escaping (Int) -> Void = { _ in },
onMaximumReservationsChange: @escaping (Int) -> Void = { _ in },
channelProvider: ConnectionManagerChannelProvider
) -> ConnectionPool {
return ConnectionPool(
eventLoop: self.eventLoop,
maxWaiters: waiters,
reservationLoadThreshold: reservationLoadThreshold,
assumedMaxConcurrentStreams: 100,
connectionBackoff: connectionBackoff,
channelProvider: channelProvider,
streamLender: HookedStreamLender(
onReturnStreams: onReservationReturned,
onUpdateMaxAvailableStreams: onMaximumReservationsChange
),
delegate: delegate,
logger: self.logger.wrapped,
now: now
)
}
private func makePool(
waiters: Int = 1000,
delegate: GRPCConnectionPoolDelegate? = nil,
makeChannel: @escaping (ConnectionManager, EventLoop) -> EventLoopFuture<Channel>
) -> ConnectionPool {
return self.makePool(
waiters: waiters,
delegate: delegate,
channelProvider: HookedChannelProvider(makeChannel)
)
}
private func setUpPoolAndController(
waiters: Int = 1000,
reservationLoadThreshold: Double = 0.9,
now: @escaping () -> NIODeadline = { .now() },
connectionBackoff: ConnectionBackoff = ConnectionBackoff(),
delegate: GRPCConnectionPoolDelegate? = nil,
onReservationReturned: @escaping (Int) -> Void = { _ in },
onMaximumReservationsChange: @escaping (Int) -> Void = { _ in }
) -> (ConnectionPool, ChannelController) {
let controller = ChannelController()
let pool = self.makePool(
waiters: waiters,
reservationLoadThreshold: reservationLoadThreshold,
now: now,
connectionBackoff: connectionBackoff,
delegate: delegate,
onReservationReturned: onReservationReturned,
onMaximumReservationsChange: onMaximumReservationsChange,
channelProvider: controller
)
self.tearDownBlocks.append {
let shutdown = pool.shutdown()
self.eventLoop.run()
XCTAssertNoThrow(try shutdown.wait())
controller.finish()
}
return (pool, controller)
}
func testEmptyConnectionPool() {
let pool = self.makePool {
self.noChannelExpected($0, $1)
}
XCTAssertEqual(pool.sync.connections, 0)
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.availableStreams, 0)
XCTAssertEqual(pool.sync.reservedStreams, 0)
pool.initialize(connections: 20)
XCTAssertEqual(pool.sync.connections, 20)
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.availableStreams, 0)
XCTAssertEqual(pool.sync.reservedStreams, 0)
let shutdownFuture = pool.shutdown()
self.eventLoop.run()
XCTAssertNoThrow(try shutdownFuture.wait())
}
func testShutdownEmptyPool() {
let pool = self.makePool {
self.noChannelExpected($0, $1)
}
XCTAssertNoThrow(try pool.shutdown().wait())
// Shutting down twice should also be fine.
XCTAssertNoThrow(try pool.shutdown().wait())
}
func testMakeStreamWhenShutdown() {
let pool = self.makePool {
self.noChannelExpected($0, $1)
}
XCTAssertNoThrow(try pool.shutdown().wait())
let stream = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertThrowsError(try stream.wait()) { error in
XCTAssert((error as? ConnectionPoolError).isShutdown)
}
}
func testMakeStreamWhenWaiterQueueIsFull() {
let maxWaiters = 5
let pool = self.makePool(waiters: maxWaiters) {
self.noChannelExpected($0, $1)
}
let waiting = (0 ..< maxWaiters).map { _ in
return pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
}
let tooManyWaiters = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertThrowsError(try tooManyWaiters.wait()) { error in
XCTAssert((error as? ConnectionPoolError).isTooManyWaiters)
}
XCTAssertNoThrow(try pool.shutdown().wait())
// All 'waiting' futures will be failed by the shutdown promise.
for waiter in waiting {
XCTAssertThrowsError(try waiter.wait()) { error in
XCTAssert((error as? ConnectionPoolError).isShutdown)
}
}
}
func testWaiterTimingOut() {
let pool = self.makePool {
self.noChannelExpected($0, $1)
}
let waiter = pool.makeStream(deadline: .uptimeNanoseconds(10), logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertEqual(pool.sync.waiters, 1)
self.eventLoop.advanceTime(to: .uptimeNanoseconds(10))
XCTAssertThrowsError(try waiter.wait()) { error in
XCTAssert((error as? ConnectionPoolError).isDeadlineExceeded)
}
XCTAssertEqual(pool.sync.waiters, 0)
}
func testWaiterTimingOutInPast() {
let pool = self.makePool {
self.noChannelExpected($0, $1)
}
self.eventLoop.advanceTime(to: .uptimeNanoseconds(10))
let waiter = pool.makeStream(deadline: .uptimeNanoseconds(5), logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertEqual(pool.sync.waiters, 1)
self.eventLoop.run()
XCTAssertThrowsError(try waiter.wait()) { error in
XCTAssert((error as? ConnectionPoolError).isDeadlineExceeded)
}
XCTAssertEqual(pool.sync.waiters, 0)
}
func testMakeStreamTriggersChannelCreation() {
let (pool, controller) = self.setUpPoolAndController()
pool.initialize(connections: 1)
XCTAssertEqual(pool.sync.connections, 1)
// No channels yet.
XCTAssertEqual(controller.count, 0)
let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
// We should have been asked for a channel now.
XCTAssertEqual(controller.count, 1)
// The connection isn't ready yet though, so no streams available.
XCTAssertEqual(pool.sync.availableStreams, 0)
// Make the connection 'ready'.
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
// We have a multiplexer and a 'ready' connection.
XCTAssertEqual(pool.sync.reservedStreams, 1)
XCTAssertEqual(pool.sync.availableStreams, 9)
XCTAssertEqual(pool.sync.waiters, 0)
// Run the loop to create the stream, we need to fire the event too.
self.eventLoop.run()
XCTAssertNoThrow(try waiter.wait())
controller.openStreamInChannel(atIndex: 0)
// Now close the stream.
controller.closeStreamInChannel(atIndex: 0)
XCTAssertEqual(pool.sync.reservedStreams, 0)
XCTAssertEqual(pool.sync.availableStreams, 10)
}
func testMakeStreamWhenConnectionIsAlreadyAvailable() {
let (pool, controller) = self.setUpPoolAndController()
pool.initialize(connections: 1)
let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
XCTAssertEqual(controller.count, 1)
// Fire up the connection.
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
// Run the loop to create the stream, we need to fire the stream creation event too.
self.eventLoop.run()
XCTAssertNoThrow(try waiter.wait())
controller.openStreamInChannel(atIndex: 0)
// Now we can create another stream, but as there's already an available stream on an active
// connection we won't have to wait.
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.reservedStreams, 1)
let notWaiting = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Still no waiters.
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.reservedStreams, 2)
// Run the loop to create the stream, we need to fire the stream creation event too.
self.eventLoop.run()
XCTAssertNoThrow(try notWaiting.wait())
controller.openStreamInChannel(atIndex: 0)
}
func testMakeMoreWaitersThanConnectionCanHandle() {
var returnedStreams: [Int] = []
let (pool, controller) = self.setUpPoolAndController(onReservationReturned: {
returnedStreams.append($0)
})
pool.initialize(connections: 1)
// Enqueue twice as many waiters as the connection will be able to handle.
let maxConcurrentStreams = 10
let waiters = (0 ..< maxConcurrentStreams * 2).map { _ in
return pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
}
XCTAssertEqual(pool.sync.waiters, 2 * maxConcurrentStreams)
// Fire up the connection.
self.eventLoop.run()
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: maxConcurrentStreams)
// We should have assigned a bunch of streams to waiters now.
XCTAssertEqual(pool.sync.waiters, maxConcurrentStreams)
XCTAssertEqual(pool.sync.reservedStreams, maxConcurrentStreams)
XCTAssertEqual(pool.sync.availableStreams, 0)
// Do the stream creation and make sure the first batch are succeeded.
self.eventLoop.run()
let firstBatch = waiters.prefix(maxConcurrentStreams)
var others = waiters.dropFirst(maxConcurrentStreams)
for waiter in firstBatch {
XCTAssertNoThrow(try waiter.wait())
controller.openStreamInChannel(atIndex: 0)
}
// Close a stream.
controller.closeStreamInChannel(atIndex: 0)
XCTAssertEqual(returnedStreams, [1])
// We have another stream so a waiter should be succeeded.
XCTAssertEqual(pool.sync.waiters, maxConcurrentStreams - 1)
self.eventLoop.run()
XCTAssertNoThrow(try others.popFirst()?.wait())
// Shutdown the pool: the remaining waiters should be failed.
let shutdown = pool.shutdown()
self.eventLoop.run()
XCTAssertNoThrow(try shutdown.wait())
for waiter in others {
XCTAssertThrowsError(try waiter.wait()) { error in
XCTAssert((error as? ConnectionPoolError).isShutdown)
}
}
}
func testDropConnectionWithOutstandingReservations() {
var streamsReturned: [Int] = []
let (pool, controller) = self.setUpPoolAndController(
onReservationReturned: { streamsReturned.append($0) }
)
pool.initialize(connections: 1)
let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
XCTAssertEqual(controller.count, 1)
// Fire up the connection.
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
// Run the loop to create the stream, we need to fire the stream creation event too.
self.eventLoop.run()
XCTAssertNoThrow(try waiter.wait())
controller.openStreamInChannel(atIndex: 0)
// Create a handful of streams.
XCTAssertEqual(pool.sync.availableStreams, 9)
for _ in 0 ..< 5 {
let notWaiting = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
self.eventLoop.run()
XCTAssertNoThrow(try notWaiting.wait())
controller.openStreamInChannel(atIndex: 0)
}
XCTAssertEqual(pool.sync.availableStreams, 4)
XCTAssertEqual(pool.sync.reservedStreams, 6)
// Blast the connection away. We'll be notified about dropped reservations.
XCTAssertEqual(streamsReturned, [])
controller.throwError(ChannelError.ioOnClosedChannel, inChannelAtIndex: 0)
controller.fireChannelInactiveForChannel(atIndex: 0)
XCTAssertEqual(streamsReturned, [6])
XCTAssertEqual(pool.sync.availableStreams, 0)
XCTAssertEqual(pool.sync.reservedStreams, 0)
}
func testDropConnectionWithOutstandingReservationsAndWaiters() {
var streamsReturned: [Int] = []
let (pool, controller) = self.setUpPoolAndController(
onReservationReturned: { streamsReturned.append($0) }
)
pool.initialize(connections: 1)
// Reserve a bunch of streams.
let waiters = (0 ..< 10).map { _ in
return pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
}
// Connect and setup all the streams.
self.eventLoop.run()
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
self.eventLoop.run()
for waiter in waiters {
XCTAssertNoThrow(try waiter.wait())
controller.openStreamInChannel(atIndex: 0)
}
// All streams should be reserved.
XCTAssertEqual(pool.sync.availableStreams, 0)
XCTAssertEqual(pool.sync.reservedStreams, 10)
// Add a waiter.
XCTAssertEqual(pool.sync.waiters, 0)
let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertEqual(pool.sync.waiters, 1)
// Now bork the connection. We'll be notified about the 10 dropped reservation but not the one
// waiter .
XCTAssertEqual(streamsReturned, [])
controller.throwError(ChannelError.ioOnClosedChannel, inChannelAtIndex: 0)
controller.fireChannelInactiveForChannel(atIndex: 0)
XCTAssertEqual(streamsReturned, [10])
// The connection dropped, let the reconnect kick in.
self.eventLoop.run()
XCTAssertEqual(controller.count, 2)
controller.connectChannel(atIndex: 1)
controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: 10)
self.eventLoop.run()
XCTAssertNoThrow(try waiter.wait())
controller.openStreamInChannel(atIndex: 1)
controller.closeStreamInChannel(atIndex: 1)
XCTAssertEqual(streamsReturned, [10, 1])
XCTAssertEqual(pool.sync.availableStreams, 10)
XCTAssertEqual(pool.sync.reservedStreams, 0)
}
func testDeadlineExceededInSameTickAsSucceedingWaiters() {
// deadline must be exceeded just as servicing waiter is done
// - setup waiter with deadline x
// - start connecting
// - set time to x
// - finish connecting
let (pool, controller) = self.setUpPoolAndController(now: {
return NIODeadline.uptimeNanoseconds(12)
})
pool.initialize(connections: 1)
let waiter1 = pool.makeStream(deadline: .uptimeNanoseconds(10), logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
let waiter2 = pool.makeStream(deadline: .uptimeNanoseconds(15), logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
XCTAssertEqual(controller.count, 1)
// Fire up the connection.
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
// The deadline for the first waiter is already after 'now', so it'll fail with deadline
// exceeded.
self.eventLoop.run()
// We need to advance the time to fire the timeout to fail the waiter.
self.eventLoop.advanceTime(to: .uptimeNanoseconds(10))
XCTAssertThrowsError(try waiter1.wait()) { error in
XCTAssert((error as? ConnectionPoolError).isDeadlineExceeded)
}
self.eventLoop.run()
XCTAssertNoThrow(try waiter2.wait())
controller.openStreamInChannel(atIndex: 0)
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.reservedStreams, 1)
XCTAssertEqual(pool.sync.availableStreams, 9)
controller.closeStreamInChannel(atIndex: 0)
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.reservedStreams, 0)
XCTAssertEqual(pool.sync.availableStreams, 10)
}
func testConnectionsAreBroughtUpAtAppropriateTimes() {
let (pool, controller) = self.setUpPoolAndController(reservationLoadThreshold: 0.2)
// We'll allow 3 connections and configure max concurrent streams to 10. With our reservation
// threshold we'll bring up a new connection after enqueueing the 1st, 2nd and 4th waiters.
pool.initialize(connections: 3)
let maxConcurrentStreams = 10
// No demand so all three connections are idle.
XCTAssertEqual(pool.sync.idleConnections, 3)
let w1 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// demand=1, available=0, load=infinite, one connection should be non-idle
XCTAssertEqual(pool.sync.idleConnections, 2)
// Connect the first channel and write the first settings frame; this allows us to lower the
// default max concurrent streams value (from 100).
self.eventLoop.run()
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: maxConcurrentStreams)
self.eventLoop.run()
XCTAssertNoThrow(try w1.wait())
controller.openStreamInChannel(atIndex: 0)
let w2 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
self.eventLoop.run()
XCTAssertNoThrow(try w2.wait())
controller.openStreamInChannel(atIndex: 0)
// demand=2, available=10, load=0.2; only one idle connection now.
XCTAssertEqual(pool.sync.idleConnections, 1)
// Add more demand before the second connection comes up.
let w3 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// demand=3, available=20, load=0.15; still one idle connection.
XCTAssertEqual(pool.sync.idleConnections, 1)
// Connection the next channel
self.eventLoop.run()
controller.connectChannel(atIndex: 1)
controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: maxConcurrentStreams)
XCTAssertNoThrow(try w3.wait())
controller.openStreamInChannel(atIndex: 1)
}
func testQuiescingConnectionIsReplaced() {
var reservationsReturned: [Int] = []
let (pool, controller) = self.setUpPoolAndController(onReservationReturned: {
reservationsReturned.append($0)
})
pool.initialize(connections: 1)
XCTAssertEqual(pool.sync.connections, 1)
let w1 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
// Make the connection 'ready'.
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0)
// Run the loop to create the stream.
self.eventLoop.run()
XCTAssertNoThrow(try w1.wait())
controller.openStreamInChannel(atIndex: 0)
// One stream reserved by 'w1' on the only connection in the pool (which isn't idle).
XCTAssertEqual(pool.sync.reservedStreams, 1)
XCTAssertEqual(pool.sync.connections, 1)
XCTAssertEqual(pool.sync.idleConnections, 0)
// Quiesce the connection. It should be punted from the pool and any active RPCs allowed to run
// their course. A new (idle) connection should replace it in the pool.
controller.sendGoAwayToChannel(atIndex: 0)
// The quiescing connection had 1 stream reserved, it's now returned to the outer pool and we
// have a new idle connection in place of the old one.
XCTAssertEqual(reservationsReturned, [1])
// The inner pool still knows about the reserved stream.
XCTAssertEqual(pool.sync.reservedStreams, 1)
XCTAssertEqual(pool.sync.availableStreams, 0)
XCTAssertEqual(pool.sync.idleConnections, 1)
// Ask for another stream: this will be on the new idle connection.
let w2 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
self.eventLoop.run()
XCTAssertEqual(controller.count, 2)
// Make the connection 'ready'.
controller.connectChannel(atIndex: 1)
controller.sendSettingsToChannel(atIndex: 1)
self.eventLoop.run()
XCTAssertNoThrow(try w2.wait())
controller.openStreamInChannel(atIndex: 1)
// The stream on the quiescing connection is still reserved.
XCTAssertEqual(pool.sync.reservedStreams, 2)
XCTAssertEqual(pool.sync.availableStreams, 99)
// Return a stream for the _quiescing_ connection: nothing should change in the pool.
controller.closeStreamInChannel(atIndex: 0)
XCTAssertEqual(pool.sync.reservedStreams, 1)
XCTAssertEqual(pool.sync.availableStreams, 99)
// Return a stream for the new connection.
controller.closeStreamInChannel(atIndex: 1)
XCTAssertEqual(reservationsReturned, [1, 1])
XCTAssertEqual(pool.sync.reservedStreams, 0)
XCTAssertEqual(pool.sync.availableStreams, 100)
}
func testBackoffIsUsedForReconnections() {
// Fix backoff to always be 1 second.
let backoff = ConnectionBackoff(
initialBackoff: 1.0,
maximumBackoff: 1.0,
multiplier: 1.0,
jitter: 0.0
)
let (pool, controller) = self.setUpPoolAndController(connectionBackoff: backoff)
pool.initialize(connections: 1)
XCTAssertEqual(pool.sync.connections, 1)
let w1 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
// Make the connection 'ready'.
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0)
self.eventLoop.run()
XCTAssertNoThrow(try w1.wait())
controller.openStreamInChannel(atIndex: 0)
// Close the connection. It should hit the transient failure state.
controller.fireChannelInactiveForChannel(atIndex: 0)
// Now nothing is available in the pool.
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.availableStreams, 0)
XCTAssertEqual(pool.sync.reservedStreams, 0)
XCTAssertEqual(pool.sync.idleConnections, 0)
// Enqueue two waiters. One to time out before the reconnect happens.
let w2 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
let w3 = pool.makeStream(
deadline: .uptimeNanoseconds(UInt64(TimeAmount.milliseconds(500).nanoseconds)),
logger: self.logger.wrapped
) {
$0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertEqual(pool.sync.waiters, 2)
// Time out w3.
self.eventLoop.advanceTime(by: .milliseconds(500))
XCTAssertThrowsError(try w3.wait())
XCTAssertEqual(pool.sync.waiters, 1)
// Wait a little more for the backoff to pass. The controller should now have a second channel.
self.eventLoop.advanceTime(by: .milliseconds(500))
XCTAssertEqual(controller.count, 2)
// Start up the next channel.
controller.connectChannel(atIndex: 1)
controller.sendSettingsToChannel(atIndex: 1)
self.eventLoop.run()
XCTAssertNoThrow(try w2.wait())
controller.openStreamInChannel(atIndex: 1)
}
func testFailedWaiterWithError() throws {
// We want to check a few things in this test:
//
// 1. When an active channel throws an error that any waiter in the connection pool which has
// its deadline exceeded or any waiter which exceeds the waiter limit fails with an error
// which includes the underlying channel error.
// 2. When a reconnect happens and the pool is just busy, no underlying error is passed through
// to failing waiters.
// Fix backoff to always be 1 second. This is necessary to figure out timings later on when
// we try to establish a new connection.
let backoff = ConnectionBackoff(
initialBackoff: 1.0,
maximumBackoff: 1.0,
multiplier: 1.0,
jitter: 0.0
)
let (pool, controller) = self.setUpPoolAndController(waiters: 10, connectionBackoff: backoff)
pool.initialize(connections: 1)
// First we'll create two streams which will fail for different reasons.
// - w1 will fail because of a timeout (no channel came up before the waiters own deadline
// passed but no connection has previously failed)
// - w2 will fail because of a timeout but after the underlying channel has failed to connect so
// should have that additional failure information.
let w1 = pool.makeStream(deadline: .uptimeNanoseconds(10), logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
let w2 = pool.makeStream(deadline: .uptimeNanoseconds(20), logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
XCTAssertEqual(controller.count, 1)
// Fire up the connection.
controller.connectChannel(atIndex: 0)
// Advance time to fail the w1.
self.eventLoop.advanceTime(to: .uptimeNanoseconds(10))
XCTAssertThrowsError(try w1.wait()) { error in
switch error as? ConnectionPoolError {
case .some(.deadlineExceeded(.none)):
// Deadline exceeded but no underlying error, as expected.
()
default:
XCTFail("Expected ConnectionPoolError.deadlineExceeded(.none) but got \(error)")
}
}
// Now fail the connection and timeout w2.
struct DummyError: Error {}
controller.throwError(DummyError(), inChannelAtIndex: 0)
controller.fireChannelInactiveForChannel(atIndex: 0)
self.eventLoop.advanceTime(to: .uptimeNanoseconds(20))
XCTAssertThrowsError(try w2.wait()) { error in
switch error as? ConnectionPoolError {
case let .some(.deadlineExceeded(.some(wrappedError))):
// Deadline exceeded and we have the underlying error.
XCTAssert(wrappedError is DummyError)
default:
XCTFail("Expected ConnectionPoolError.deadlineExceeded(.some) but got \(error)")
}
}
// For the next part of the test we want to validate that when a new channel is created after
// the backoff period passes that no additional errors are attached when the pool is just busy
// but otherwise operational.
//
// To do this we'll create a bunch of waiters. These will be succeeded when the new connection
// comes up and, importantly, use up all available streams on that connection.
//
// We'll then enqueue enough waiters to fill the waiter queue. We'll then validate that one more
// waiter trips over the queue limit but does not include the connection error we saw earlier.
// We'll then timeout the waiters in the queue and validate the same thing.
// These streams should succeed when the new connection is up. We'll limit the connection to 10
// streams when we bring it up.
let streams = (0 ..< 10).map { _ in
pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
}
// The connection is backing off; advance time to create another channel.
XCTAssertEqual(controller.count, 1)
self.eventLoop.advanceTime(by: .seconds(1))
XCTAssertEqual(controller.count, 2)
controller.connectChannel(atIndex: 1)
controller.sendSettingsToChannel(atIndex: 1, maxConcurrentStreams: 10)
self.eventLoop.run()
// Make sure the streams are succeeded.
for stream in streams {
XCTAssertNoThrow(try stream.wait())
controller.openStreamInChannel(atIndex: 1)
}
// All streams should be reserved.
XCTAssertEqual(pool.sync.availableStreams, 0)
XCTAssertEqual(pool.sync.reservedStreams, 10)
XCTAssertEqual(pool.sync.waiters, 0)
// We configured the pool to allow for 10 waiters, so let's enqueue that many which will time
// out at a known point in time.
let now = NIODeadline.now()
self.eventLoop.advanceTime(to: now)
let waiters = (0 ..< 10).map { _ in
pool.makeStream(deadline: now + .seconds(1), logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
}
// This is one waiter more than is allowed so it should hit too-many-waiters. We don't expect
// an inner error though, the connection is just busy.
let tooManyWaiters = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertThrowsError(try tooManyWaiters.wait()) { error in
switch error as? ConnectionPoolError {
case .some(.tooManyWaiters(.none)):
()
default:
XCTFail("Expected ConnectionPoolError.tooManyWaiters(.none) but got \(error)")
}
}
// Finally, timeout the remaining waiters. Again, no inner error, the connection is just busy.
self.eventLoop.advanceTime(by: .seconds(1))
for waiter in waiters {
XCTAssertThrowsError(try waiter.wait()) { error in
switch error as? ConnectionPoolError {
case .some(.deadlineExceeded(.none)):
()
default:
XCTFail("Expected ConnectionPoolError.deadlineExceeded(.none) but got \(error)")
}
}
}
}
func testWaiterStoresItsScheduledTask() throws {
let deadline = NIODeadline.uptimeNanoseconds(42)
let promise = self.eventLoop.makePromise(of: Channel.self)
let waiter = ConnectionPool.Waiter(deadline: deadline, promise: promise) {
return $0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertNil(waiter._scheduledTimeout)
waiter.scheduleTimeout(on: self.eventLoop) {
waiter.fail(ConnectionPoolError.deadlineExceeded(connectionError: nil))
}
XCTAssertNotNil(waiter._scheduledTimeout)
self.eventLoop.advanceTime(to: deadline)
XCTAssertThrowsError(try promise.futureResult.wait())
XCTAssertNil(waiter._scheduledTimeout)
}
func testReturnStreamAfterConnectionCloses() throws {
var returnedStreams = 0
let (pool, controller) = self.setUpPoolAndController(onReservationReturned: { returned in
returnedStreams += returned
})
pool.initialize(connections: 1)
let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
XCTAssertEqual(controller.count, 1)
// Fire up the connection.
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
// Run the loop to create the stream, we need to fire the stream creation event too.
self.eventLoop.run()
XCTAssertNoThrow(try waiter.wait())
controller.openStreamInChannel(atIndex: 0)
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.availableStreams, 9)
XCTAssertEqual(pool.sync.reservedStreams, 1)
XCTAssertEqual(pool.sync.connections, 1)
// Close all streams on connection 0.
let error = GRPCStatus(code: .internalError, message: nil)
controller.throwError(error, inChannelAtIndex: 0)
controller.fireChannelInactiveForChannel(atIndex: 0)
XCTAssertEqual(returnedStreams, 1)
XCTAssertEqual(pool.sync.waiters, 0)
XCTAssertEqual(pool.sync.availableStreams, 0)
XCTAssertEqual(pool.sync.reservedStreams, 0)
XCTAssertEqual(pool.sync.connections, 1)
// The connection is closed so the stream shouldn't be returned again.
controller.closeStreamInChannel(atIndex: 0)
XCTAssertEqual(returnedStreams, 1)
}
func testConnectionPoolDelegate() throws {
let recorder = EventRecordingConnectionPoolDelegate()
let (pool, controller) = self.setUpPoolAndController(delegate: recorder)
pool.initialize(connections: 2)
func assertConnectionAdded(
_ event: EventRecordingConnectionPoolDelegate.Event?
) throws -> GRPCConnectionID {
let unwrappedEvent = try XCTUnwrap(event)
switch unwrappedEvent {
case let .connectionAdded(id):
return id
default:
throw EventRecordingConnectionPoolDelegate.UnexpectedEvent(unwrappedEvent)
}
}
let connID1 = try assertConnectionAdded(recorder.popFirst())
let connID2 = try assertConnectionAdded(recorder.popFirst())
let waiter = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
// Start creating the channel.
self.eventLoop.run()
let startedConnecting = recorder.popFirst()
let firstConn: GRPCConnectionID
let secondConn: GRPCConnectionID
if startedConnecting == .startedConnecting(connID1) {
firstConn = connID1
secondConn = connID2
} else if startedConnecting == .startedConnecting(connID2) {
firstConn = connID2
secondConn = connID1
} else {
return XCTFail("Unexpected event")
}
// Connect the connection.
self.eventLoop.run()
controller.connectChannel(atIndex: 0)
controller.sendSettingsToChannel(atIndex: 0, maxConcurrentStreams: 10)
XCTAssertEqual(recorder.popFirst(), .connectSucceeded(firstConn, 10))
// Open a stream for the waiter.
controller.openStreamInChannel(atIndex: 0)
XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, 1, 10))
self.eventLoop.run()
XCTAssertNoThrow(try waiter.wait())
// Okay, more utilization!
for n in 2 ... 8 {
let w = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
controller.openStreamInChannel(atIndex: 0)
XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, n, 10))
self.eventLoop.run()
XCTAssertNoThrow(try w.wait())
}
// The utilisation threshold before bringing up a new connection is 0.9; we have 8 open streams
// (out of 10) now so opening the next should trigger a connect on the other connection.
let w9 = pool.makeStream(deadline: .distantFuture, logger: self.logger.wrapped) {
$0.eventLoop.makeSucceededVoidFuture()
}
XCTAssertEqual(recorder.popFirst(), .startedConnecting(secondConn))
// Deal with the 9th stream.
controller.openStreamInChannel(atIndex: 0)
XCTAssertEqual(recorder.popFirst(), .connectionUtilizationChanged(firstConn, 9, 10))
self.eventLoop.run()
XCTAssertNoThrow(try w9.wait())
// Bring up the next connection.