forked from apple/swift-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodecTest.swift
More file actions
2018 lines (1737 loc) · 79.4 KB
/
Copy pathCodecTest.swift
File metadata and controls
2018 lines (1737 loc) · 79.4 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
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOConcurrencyHelpers
import NIOEmbedded
import XCTest
@testable import NIOCore
@testable import NIOPosix
private let testDecoderIsNotQuadratic_mallocs = NIOLockedValueBox(0)
private let testDecoderIsNotQuadratic_reallocs = NIOLockedValueBox(0)
private func testDecoderIsNotQuadratic_freeHook(_ ptr: UnsafeMutableRawPointer) {
free(ptr)
}
private func testDecoderIsNotQuadratic_mallocHook(_ size: Int) -> UnsafeMutableRawPointer? {
testDecoderIsNotQuadratic_mallocs.withLockedValue { $0 += 1 }
return malloc(size)
}
private func testDecoderIsNotQuadratic_reallocHook(
_ ptr: UnsafeMutableRawPointer?,
_ count: Int
) -> UnsafeMutableRawPointer? {
testDecoderIsNotQuadratic_reallocs.withLockedValue { $0 += 1 }
return realloc(ptr, count)
}
private func testDecoderIsNotQuadratic_memcpyHook(_ dst: UnsafeMutableRawPointer, _ src: UnsafeRawPointer, _ count: Int)
{
_ = memcpy(dst, src, count)
}
private final class ChannelInactivePromiser: ChannelInboundHandler {
typealias InboundIn = Any
let channelInactivePromise: EventLoopPromise<Void>
init(channel: Channel) {
channelInactivePromise = channel.eventLoop.makePromise()
}
func channelInactive(context: ChannelHandlerContext) {
channelInactivePromise.succeed(())
}
}
final class ByteToMessageDecoderTest: XCTestCase {
private final class ByteToInt32Decoder: ByteToMessageDecoder {
typealias InboundIn = ByteBuffer
typealias InboundOut = Int32
func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState {
guard buffer.readableBytes >= MemoryLayout<Int32>.size else {
return .needMoreData
}
context.fireChannelRead(Self.wrapInboundOut(buffer.readInteger()!))
return .continue
}
func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState
{
XCTAssertTrue(seenEOF)
return self.decode(context: context, buffer: &buffer)
}
}
private final class ForeverDecoder: ByteToMessageDecoder {
typealias InboundIn = ByteBuffer
typealias InboundOut = Never
func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState {
.needMoreData
}
func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState
{
XCTAssertTrue(seenEOF)
return self.decode(context: context, buffer: &buffer)
}
}
private final class LargeChunkDecoder: ByteToMessageDecoder {
typealias InboundIn = ByteBuffer
typealias InboundOut = ByteBuffer
func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState {
guard case .some(let buffer) = buffer.readSlice(length: 512) else {
return .needMoreData
}
context.fireChannelRead(Self.wrapInboundOut(buffer))
return .continue
}
func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState
{
XCTAssertTrue(seenEOF)
return self.decode(context: context, buffer: &buffer)
}
}
// A special case decoder that decodes only once there is 5,120 bytes in the buffer,
// at which point it decodes exactly 2kB of memory.
private final class OnceDecoder: ByteToMessageDecoder {
typealias InboundIn = ByteBuffer
typealias InboundOut = ByteBuffer
func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState {
guard buffer.readableBytes >= 5120 else {
return .needMoreData
}
context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 2048)!))
return .continue
}
func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState
{
XCTAssertTrue(seenEOF)
return self.decode(context: context, buffer: &buffer)
}
}
func testDecoder() throws {
let channel = EmbeddedChannel()
_ = try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(ByteToInt32Decoder()))
var buffer = channel.allocator.buffer(capacity: 32)
buffer.writeInteger(Int32(1))
let writerIndex = buffer.writerIndex
buffer.moveWriterIndex(to: writerIndex - 1)
channel.pipeline.fireChannelRead(buffer)
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
buffer.moveWriterIndex(to: writerIndex)
channel.pipeline.fireChannelRead(buffer.getSlice(at: writerIndex - 1, length: 1)!)
var buffer2 = channel.allocator.buffer(capacity: 32)
buffer2.writeInteger(Int32(2))
buffer2.writeInteger(Int32(3))
channel.pipeline.fireChannelRead(buffer2)
XCTAssertNoThrow(try channel.finish())
XCTAssertNoThrow(XCTAssertEqual(Int32(1), try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual(Int32(2), try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual(Int32(3), try channel.readInbound()))
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
}
func testDecoderPropagatesChannelInactive() throws {
let channel = EmbeddedChannel()
defer {
XCTAssertNoThrow(try channel.finish())
}
let inactivePromiser = ChannelInactivePromiser(channel: channel)
try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(ByteToInt32Decoder()))
try channel.pipeline.syncOperations.addHandler(inactivePromiser)
var buffer = channel.allocator.buffer(capacity: 32)
buffer.writeInteger(Int32(1))
channel.pipeline.fireChannelRead(buffer)
XCTAssertNoThrow(XCTAssertEqual(Int32(1), try channel.readInbound()))
XCTAssertFalse(inactivePromiser.channelInactivePromise.futureResult.isFulfilled)
channel.pipeline.fireChannelInactive()
XCTAssertTrue(inactivePromiser.channelInactivePromise.futureResult.isFulfilled)
}
func testDecoderIsNotQuadratic() throws {
let channel = EmbeddedChannel()
defer {
XCTAssertNoThrow(try channel.finish())
}
XCTAssertEqual(testDecoderIsNotQuadratic_mallocs.withLockedValue { $0 }, 0)
XCTAssertEqual(testDecoderIsNotQuadratic_reallocs.withLockedValue { $0 }, 0)
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(ForeverDecoder())))
let dummyAllocator = ByteBufferAllocator(
hookedMalloc: testDecoderIsNotQuadratic_mallocHook,
hookedRealloc: testDecoderIsNotQuadratic_reallocHook,
hookedFree: testDecoderIsNotQuadratic_freeHook,
hookedMemcpy: testDecoderIsNotQuadratic_memcpyHook
)
channel.allocator = dummyAllocator
var inputBuffer = dummyAllocator.buffer(capacity: 8)
inputBuffer.writeStaticString("whatwhat")
for _ in 0..<10 {
channel.pipeline.fireChannelRead(inputBuffer)
}
// We get one extra malloc the first time around the loop, when we have aliased the buffer. From then on it's
// all reallocs of the underlying buffer.
XCTAssertEqual(testDecoderIsNotQuadratic_mallocs.withLockedValue { $0 }, 2)
XCTAssertEqual(testDecoderIsNotQuadratic_reallocs.withLockedValue { $0 }, 3)
}
func testMemoryIsReclaimedIfMostIsConsumed() {
let channel = EmbeddedChannel()
defer {
XCTAssertNoThrow(XCTAssertTrue(try channel.finish().isClean))
}
let decoder = ByteToMessageHandler(LargeChunkDecoder())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(decoder))
// We're going to send in 513 bytes. This will cause a chunk to be passed on, and will leave
// a 512-byte empty region in a byte buffer with a capacity of 1024 bytes. Since 512 empty
// bytes are exactly 50% of the buffers capacity and not one tiny bit more, the empty space
// will not be reclaimed.
var buffer = channel.allocator.buffer(capacity: 513)
buffer.writeBytes(Array(repeating: 0x04, count: 513))
XCTAssertNoThrow(XCTAssertTrue(try channel.writeInbound(buffer).isFull))
XCTAssertNoThrow(XCTAssertEqual(ByteBuffer(repeating: 0x04, count: 512), try channel.readInbound()))
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
XCTAssertEqual(decoder.cumulationBuffer!.capacity, 1024)
XCTAssertEqual(decoder.cumulationBuffer!.readableBytes, 1)
XCTAssertEqual(decoder.cumulationBuffer!.readerIndex, 512)
// Next we're going to send in another 513 bytes. This will cause another chunk to be passed
// into our decoder buffer, which has a capacity of 1024 bytes, before we pass in another
// 513 bytes. Since we already have written to 513 bytes, there isn't enough space in the
// buffer, which will cause a resize to a new underlying storage with 2048 bytes. Since the
// `LargeChunkDecoder` has consumed another 512 bytes, there are now two bytes left to read
// (513 + 513) - (512 + 512). The reader index is at 1024. The empty space has not been
// reclaimed: While the capacity is more than 1024 bytes (2048 bytes), the reader index is
// now at 1024. This means the buffer is exactly 50% consumed and not a tiny bit more, which
// means no space will be reclaimed.
XCTAssertNoThrow(XCTAssertTrue(try channel.writeInbound(buffer).isFull))
XCTAssertNoThrow(XCTAssertEqual(ByteBuffer(repeating: 0x04, count: 512), try channel.readInbound()))
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
XCTAssertEqual(decoder.cumulationBuffer!.capacity, 2048)
XCTAssertEqual(decoder.cumulationBuffer!.readableBytes, 2)
XCTAssertEqual(decoder.cumulationBuffer!.readerIndex, 1024)
// Finally we're going to send in another 513 bytes. This will cause another chunk to be
// passed into our decoder buffer, which has a capacity of 2048 bytes. Since the buffer has
// enough available space (1022 bytes) there will be no buffer resize before the decoding.
// After the decoding of another 512 bytes, the buffer will have 1536 empty bytes
// (3 * 512 bytes). This means that 75% of the buffer's capacity can now be reclaimed, which
// will lead to a reclaim. The resulting buffer will have a capacity of 2048 bytes (based
// on its previous growth), with 3 readable bytes remaining.
XCTAssertNoThrow(XCTAssertTrue(try channel.writeInbound(buffer).isFull))
XCTAssertNoThrow(XCTAssertEqual(ByteBuffer(repeating: 0x04, count: 512), try channel.readInbound()))
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
XCTAssertEqual(decoder.cumulationBuffer!.capacity, 2048)
XCTAssertEqual(decoder.cumulationBuffer!.readableBytes, 3)
XCTAssertEqual(decoder.cumulationBuffer!.readerIndex, 0)
}
func testMemoryIsReclaimedIfLotsIsAvailable() {
let channel = EmbeddedChannel()
defer {
XCTAssertNoThrow(XCTAssertTrue(try channel.finish().isClean))
}
let decoder = ByteToMessageHandler(OnceDecoder())
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(decoder))
// We're going to send in 5119 bytes. This will be held.
var buffer = channel.allocator.buffer(capacity: 5119)
buffer.writeBytes(Array(repeating: 0x04, count: 5119))
XCTAssertNoThrow(XCTAssertTrue(try channel.writeInbound(buffer).isEmpty))
XCTAssertEqual(decoder.cumulationBuffer!.readableBytes, 5119)
XCTAssertEqual(decoder.cumulationBuffer!.readerIndex, 0)
// Now we're going to send in one more byte. This will cause a chunk to be passed on,
// shrinking the held memory to 3072 bytes. However, memory will be reclaimed.
XCTAssertNoThrow(XCTAssertTrue(try channel.writeInbound(buffer.getSlice(at: 0, length: 1)).isFull))
XCTAssertNoThrow(XCTAssertEqual(ByteBuffer(repeating: 0x04, count: 2048), try channel.readInbound()))
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
XCTAssertEqual(decoder.cumulationBuffer!.readableBytes, 3072)
XCTAssertEqual(decoder.cumulationBuffer!.readerIndex, 0)
}
func testWeDoNotCallShouldReclaimMemoryAsLongAsWeContinue() {
class Decoder: ByteToMessageDecoder {
typealias InboundOut = ByteBuffer
var numberOfDecodeCalls = 0
var numberOfShouldReclaimCalls = 0
func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
self.numberOfDecodeCalls += 1
guard
buffer.readSlice(
length: [
2048, 1024, 512, 256,
128, 64, .max,
][self.numberOfDecodeCalls - 1]
) != nil
else {
return .needMoreData
}
XCTAssertEqual(0, self.numberOfShouldReclaimCalls)
return .continue
}
func shouldReclaimBytes(buffer: ByteBuffer) -> Bool {
XCTAssertEqual(7, self.numberOfDecodeCalls)
XCTAssertEqual(64, buffer.readableBytes)
self.numberOfShouldReclaimCalls += 1
return false
}
func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertEqual(64, buffer.readableBytes)
XCTAssertTrue(seenEOF)
return .needMoreData
}
}
let decoder = Decoder()
let channel = EmbeddedChannel(handler: ByteToMessageHandler(decoder))
defer {
XCTAssertNoThrow(XCTAssertTrue(try channel.finish().isClean))
}
let buffer = ByteBuffer(repeating: 0, count: 4096)
XCTAssertEqual(4096, buffer.storageCapacity)
// We're sending 4096 bytes. The decoder will do:
// 1. read 2048 -> .continue
// 2. read 1024 -> .continue
// 3. read 512 -> .continue
// 4. read 256 -> .continue
// 5. read 128 -> .continue
// 6. read 64 -> .continue
// 7. read Int.max -> .needMoreData
//
// So we're expecting 7 decode calls but only 1 call to shouldReclaimBytes (at the end).
XCTAssertNoThrow(try channel.writeInbound(buffer))
XCTAssertEqual(7, decoder.numberOfDecodeCalls)
XCTAssertEqual(1, decoder.numberOfShouldReclaimCalls)
}
func testDecoderReentranceChannelRead() throws {
let channel = EmbeddedChannel()
defer {
XCTAssertNoThrow(try channel.finish())
}
class TestDecoder: ByteToMessageDecoder {
typealias InboundIn = ByteBuffer
typealias InboundOut = ByteBuffer
var numberOfDecodeCalls = 0
var hasReentranced = false
func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
self.numberOfDecodeCalls += 1
var reentrantWriteBuffer = context.channel.allocator.buffer(capacity: 1)
if self.numberOfDecodeCalls == 2 {
// this is the first time, let's fireChannelRead
self.hasReentranced = true
reentrantWriteBuffer.clear()
reentrantWriteBuffer.writeStaticString("3")
context.channel.pipeline.syncOperations.fireChannelRead(Self.wrapInboundOut(reentrantWriteBuffer))
}
context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: 1)!))
if self.numberOfDecodeCalls == 2 {
reentrantWriteBuffer.clear()
reentrantWriteBuffer.writeStaticString("4")
context.channel.pipeline.syncOperations.fireChannelRead(Self.wrapInboundOut(reentrantWriteBuffer))
}
return .continue
}
func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertTrue(seenEOF)
return .needMoreData
}
}
let testDecoder = TestDecoder()
XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(testDecoder)))
var inputBuffer = channel.allocator.buffer(capacity: 4)
// 1
inputBuffer.writeStaticString("1")
XCTAssertTrue(try channel.writeInbound(inputBuffer).isFull)
inputBuffer.clear()
// 2
inputBuffer.writeStaticString("2")
XCTAssertTrue(try channel.writeInbound(inputBuffer).isFull)
inputBuffer.clear()
// 3
inputBuffer.writeStaticString("5")
XCTAssertTrue(try channel.writeInbound(inputBuffer).isFull)
inputBuffer.clear()
func readOneInboundString() -> String {
do {
switch try channel.readInbound(as: ByteBuffer.self) {
case .some(let buffer):
return String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self)
case .none:
XCTFail("expected ByteBuffer found nothing")
return "no, error from \(#line)"
}
} catch {
XCTFail("unexpected error: \(error)")
return "no, error from \(#line)"
}
}
channel.embeddedEventLoop.run()
XCTAssertEqual("1", readOneInboundString())
XCTAssertEqual("2", readOneInboundString())
XCTAssertEqual("3", readOneInboundString())
XCTAssertEqual("4", readOneInboundString())
XCTAssertEqual("5", readOneInboundString())
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound(as: IOData.self)))
XCTAssertTrue(testDecoder.hasReentranced)
}
func testTrivialDecoderDoesSensibleStuffWhenCloseInRead() {
class HandItThroughDecoder: ByteToMessageDecoder {
typealias InboundOut = ByteBuffer
var decodeLastCalls = 0
func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
let originalBuffer = buffer
context.fireChannelRead(Self.wrapInboundOut(buffer.readSlice(length: buffer.readableBytes)!))
if originalBuffer.readableBytesView.last == "0".utf8.last {
context.close().whenFailure { error in
XCTFail("unexpected error: \(error)")
}
}
return .needMoreData
}
func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertTrue(seenEOF)
self.decodeLastCalls += 1
XCTAssertEqual(1, self.decodeLastCalls)
return .needMoreData
}
}
let decoder = HandItThroughDecoder()
let channel = EmbeddedChannel(handler: ByteToMessageHandler(decoder))
XCTAssertNoThrow(try channel.connect(to: SocketAddress(ipAddress: "1.2.3.4", port: 5678)).wait())
XCTAssertTrue(channel.isActive)
var buffer = channel.allocator.buffer(capacity: 16)
buffer.clear()
buffer.writeStaticString("1")
XCTAssertNoThrow(try channel.writeInbound(buffer))
buffer.clear()
buffer.writeStaticString("23")
XCTAssertNoThrow(try channel.writeInbound(buffer))
buffer.clear()
buffer.writeStaticString("4567890")
XCTAssertNoThrow(try channel.writeInbound(buffer))
channel.embeddedEventLoop.run()
XCTAssertFalse(channel.isActive)
XCTAssertNoThrow(
XCTAssertEqual(
"1",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"23",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"4567890",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
XCTAssertEqual(1, decoder.decodeLastCalls)
}
func testLeftOversMakeDecodeLastCalled() {
let lastPromise = EmbeddedEventLoop().makePromise(of: ByteBuffer.self)
let channel = EmbeddedChannel(handler: ByteToMessageHandler(PairOfBytesDecoder(lastPromise: lastPromise)))
var buffer = channel.allocator.buffer(capacity: 16)
buffer.clear()
buffer.writeStaticString("1")
XCTAssertNoThrow(try channel.writeInbound(buffer))
buffer.clear()
buffer.writeStaticString("23")
XCTAssertNoThrow(try channel.writeInbound(buffer))
buffer.clear()
buffer.writeStaticString("4567890x")
XCTAssertNoThrow(try channel.writeInbound(buffer))
XCTAssertNoThrow(try channel.close().wait())
XCTAssertFalse(channel.isActive)
XCTAssertNoThrow(
XCTAssertEqual(
"12",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"34",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"56",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"78",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"90",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
XCTAssertNoThrow(
XCTAssertEqual(
"x",
String(
decoding: try lastPromise.futureResult.wait().readableBytesView,
as: Unicode.UTF8.self
)
)
)
}
func testRemovingHandlerMakesLeftoversAppearInDecodeLast() {
let lastPromise = EmbeddedEventLoop().makePromise(of: ByteBuffer.self)
let decoder = PairOfBytesDecoder(lastPromise: lastPromise)
let channel = EmbeddedChannel(handler: ByteToMessageHandler(decoder))
defer {
XCTAssertNoThrow(XCTAssertTrue(try channel.finish().isClean))
}
var buffer = channel.allocator.buffer(capacity: 16)
buffer.clear()
buffer.writeStaticString("1")
XCTAssertNoThrow(try channel.writeInbound(buffer))
buffer.clear()
buffer.writeStaticString("23")
XCTAssertNoThrow(try channel.writeInbound(buffer))
buffer.clear()
buffer.writeStaticString("4567890x")
XCTAssertNoThrow(try channel.writeInbound(buffer))
channel.pipeline.context(handlerType: ByteToMessageHandler<PairOfBytesDecoder>.self).flatMap { context in
channel.pipeline.syncOperations.removeHandler(context: context)
}.whenFailure { error in
XCTFail("unexpected error: \(error)")
}
XCTAssertNoThrow(
XCTAssertEqual(
"12",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"34",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"56",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"78",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"90",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
channel.embeddedEventLoop.run()
XCTAssertNoThrow(
XCTAssertEqual(
"x",
String(
decoding: try lastPromise.futureResult.wait().readableBytesView,
as: Unicode.UTF8.self
)
)
)
XCTAssertEqual(1, decoder.decodeLastCalls)
}
func testStructsWorkAsByteToMessageDecoders() {
struct WantsOneThenTwoBytesDecoder: ByteToMessageDecoder {
typealias InboundOut = Int
var state: Int = 1
mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
if buffer.readSlice(length: self.state) != nil {
defer {
self.state += 1
}
context.fireChannelRead(Self.wrapInboundOut(self.state))
return .continue
} else {
return .needMoreData
}
}
mutating func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertTrue(seenEOF)
context.fireChannelRead(Self.wrapInboundOut(buffer.readableBytes * -1))
return .needMoreData
}
}
let channel = EmbeddedChannel(handler: ByteToMessageHandler(WantsOneThenTwoBytesDecoder()))
var buffer = channel.allocator.buffer(capacity: 16)
buffer.clear()
buffer.writeStaticString("1")
XCTAssertNoThrow(try channel.writeInbound(buffer))
buffer.clear()
buffer.writeStaticString("23")
XCTAssertNoThrow(try channel.writeInbound(buffer))
buffer.clear()
buffer.writeStaticString("4567890qwer")
XCTAssertNoThrow(try channel.writeInbound(buffer))
XCTAssertNoThrow(XCTAssertEqual(1, try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual(2, try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual(3, try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual(4, try channel.readInbound()))
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
XCTAssertNoThrow(try channel.close().wait())
XCTAssertFalse(channel.isActive)
XCTAssertNoThrow(XCTAssertEqual(-4, try channel.readInbound()))
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
}
func testReentrantChannelReadWhileWholeBufferIsBeingProcessed() {
struct ProcessAndReentrantylyProcessExponentiallyLessStuffDecoder: ByteToMessageDecoder {
typealias InboundOut = String
var state = 16
mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
XCTAssertGreaterThan(self.state, 0)
if let slice = buffer.readSlice(length: self.state) {
self.state >>= 1
for i in 0..<self.state {
XCTAssertNoThrow(
try (context.channel as! EmbeddedChannel).writeInbound(slice.getSlice(at: i, length: 1))
)
}
context.fireChannelRead(
Self.wrapInboundOut(String(decoding: slice.readableBytesView, as: Unicode.UTF8.self))
)
return .continue
} else {
return .needMoreData
}
}
mutating func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertTrue(seenEOF)
return try self.decode(context: context, buffer: &buffer)
}
}
let channel = EmbeddedChannel(
handler: ByteToMessageHandler(ProcessAndReentrantylyProcessExponentiallyLessStuffDecoder())
)
var buffer = channel.allocator.buffer(capacity: 16)
buffer.writeStaticString("0123456789abcdef")
XCTAssertNoThrow(try channel.writeInbound(buffer))
XCTAssertNoThrow(XCTAssertEqual("0123456789abcdef", try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual("01234567", try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual("0123", try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual("01", try channel.readInbound()))
XCTAssertNoThrow(XCTAssertEqual("0", try channel.readInbound()))
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
}
func testReentrantChannelCloseInChannelRead() {
struct Take16BytesThenCloseAndPassOnDecoder: ByteToMessageDecoder {
typealias InboundOut = ByteBuffer
mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
if let slice = buffer.readSlice(length: 16) {
context.fireChannelRead(Self.wrapInboundOut(slice))
context.channel.close().whenFailure { error in
XCTFail("unexpected error: \(error)")
}
return .continue
} else {
return .needMoreData
}
}
mutating func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertTrue(seenEOF)
context.fireChannelRead(Self.wrapInboundOut(buffer))
return .needMoreData
}
}
let channel = EmbeddedChannel(handler: ByteToMessageHandler(Take16BytesThenCloseAndPassOnDecoder()))
var buffer = channel.allocator.buffer(capacity: 16)
buffer.writeStaticString("0123456789abcdefQWER")
XCTAssertNoThrow(try channel.writeInbound(buffer))
XCTAssertNoThrow(
XCTAssertEqual(
"0123456789abcdef",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(
XCTAssertEqual(
"QWER",
try channel.readInbound(as: ByteBuffer.self).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
}
func testHandlerRemoveInChannelRead() {
struct Take16BytesThenCloseAndPassOnDecoder: ByteToMessageDecoder {
typealias InboundOut = ByteBuffer
mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
if let slice = buffer.readSlice(length: 16) {
context.fireChannelRead(Self.wrapInboundOut(slice))
context.pipeline.syncOperations.removeHandler(context: context).whenFailure { error in
XCTFail("unexpected error: \(error)")
}
return .continue
} else {
return .needMoreData
}
}
mutating func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertFalse(seenEOF)
context.fireChannelRead(Self.wrapInboundOut(buffer))
return .needMoreData
}
}
let channel = EmbeddedChannel(handler: ByteToMessageHandler(Take16BytesThenCloseAndPassOnDecoder()))
var buffer = channel.allocator.buffer(capacity: 16)
buffer.writeStaticString("0123456789abcdefQWER")
XCTAssertNoThrow(try channel.writeInbound(buffer))
XCTAssertEqual(
"0123456789abcdef",
(try channel.readInbound() as ByteBuffer?).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
channel.embeddedEventLoop.run()
XCTAssertEqual(
"QWER",
(try channel.readInbound() as ByteBuffer?).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound()))
}
func testChannelCloseInChannelRead() {
struct Take16BytesThenCloseAndPassOnDecoder: ByteToMessageDecoder {
typealias InboundOut = ByteBuffer
mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
if let slice = buffer.readSlice(length: 16) {
context.fireChannelRead(Self.wrapInboundOut(slice))
context.close().whenFailure { error in
XCTFail("unexpected error: \(error)")
}
return .continue
} else {
return .needMoreData
}
}
mutating func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertTrue(seenEOF)
return .needMoreData
}
}
class DoNotForwardChannelInactiveHandler: ChannelInboundHandler {
typealias InboundIn = Never
func channelInactive(context: ChannelHandlerContext) {
// just eat this event
}
}
let channel = EmbeddedChannel(handler: ByteToMessageHandler(Take16BytesThenCloseAndPassOnDecoder()))
XCTAssertNoThrow(
try channel.pipeline.syncOperations.addHandler(DoNotForwardChannelInactiveHandler(), position: .first)
)
var buffer = channel.allocator.buffer(capacity: 16)
buffer.writeStaticString("0123456789abcdefQWER")
XCTAssertNoThrow(try channel.writeInbound(buffer))
XCTAssertNoThrow(
XCTAssertEqual(
"0123456789abcdef",
(try channel.readInbound() as ByteBuffer?).map {
String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)
}
)
)
channel.embeddedEventLoop.run()
XCTAssertNoThrow(XCTAssertNil(try channel.readInbound())) // no leftovers are forwarded
}
func testDecodeLoopGetsInterruptedWhenRemovalIsTriggered() {
struct Decoder: ByteToMessageDecoder {
typealias InboundOut = String
var callsToDecode = 0
var callsToDecodeLast = 0
mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState {
XCTAssertEqual(9, buffer.readableBytes)
self.callsToDecode += 1
XCTAssertEqual(1, self.callsToDecode)
context.fireChannelRead(
Self.wrapInboundOut(
String(
decoding: buffer.readBytes(length: 1)!,
as: Unicode.UTF8.self
)
)
)
context.pipeline.syncOperations.removeHandler(context: context).whenFailure { error in
XCTFail("unexpected error: \(error)")
}
return .continue
}
mutating func decodeLast(
context: ChannelHandlerContext,
buffer: inout ByteBuffer,
seenEOF: Bool
) throws -> DecodingState {
XCTAssertFalse(seenEOF)
self.callsToDecodeLast += 1
XCTAssertLessThanOrEqual(self.callsToDecodeLast, 2)
context.fireChannelRead(
Self.wrapInboundOut(
String(
decoding: buffer.readBytes(length: 4) ?? [ // "no bytes"
0x6e, 0x6f, 0x20,
0x62, 0x79, 0x74, 0x65, 0x73,
],
as: Unicode.UTF8.self
) + "#\(self.callsToDecodeLast)"
)
)
return .continue
}
}
let handler = ByteToMessageHandler(Decoder())
let channel = EmbeddedChannel(handler: handler)
defer {
XCTAssertNoThrow(XCTAssertTrue(try channel.finish().isClean))
}
var buffer = channel.allocator.buffer(capacity: 9)
buffer.writeStaticString("012345678")
XCTAssertNoThrow(try channel.writeInbound(buffer))
channel.embeddedEventLoop.run()
XCTAssertEqual(1, handler.decoder?.callsToDecode)
XCTAssertEqual(2, handler.decoder?.callsToDecodeLast)
for expected in ["0", "1234#1", "5678#2"] {
func workaroundSR9815() {
XCTAssertNoThrow(XCTAssertEqual(expected, try channel.readInbound()))
}
workaroundSR9815()
}
}
func testDecodeLastIsInvokedOnceEvenIfNothingEverArrivedOnChannelClosed() {
class Decoder: ByteToMessageDecoder {
typealias InboundOut = ()