-
Notifications
You must be signed in to change notification settings - Fork 13
/
SlicTransportTests.cs
1285 lines (1098 loc) · 53.4 KB
/
SlicTransportTests.cs
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 (c) ZeroC, Inc.
using IceRpc.Internal;
using IceRpc.Tests.Common;
using IceRpc.Transports;
using IceRpc.Transports.Internal;
using IceRpc.Transports.Slic;
using IceRpc.Transports.Slic.Internal;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using System.Buffers;
using System.IO.Pipelines;
using System.Security.Authentication;
using ZeroC.Slice;
namespace IceRpc.Tests.Transports.Slic;
/// <summary>Unit tests for slic transport.</summary>
[Parallelizable(ParallelScope.All)]
public class SlicTransportTests
{
private static IEnumerable<TestCaseData> InvalidConnectionFrames
{
get
{
// TestCase(FrameType frameType, bool emptyBody)
yield return new TestCaseData(nameof(FrameType.Close), false);
yield return new TestCaseData(nameof(FrameType.Close), true);
yield return new TestCaseData(nameof(FrameType.Ping), false);
yield return new TestCaseData(nameof(FrameType.Ping), true);
yield return new TestCaseData(nameof(FrameType.Pong), false);
yield return new TestCaseData(nameof(FrameType.Pong), true);
}
}
private static IEnumerable<TestCaseData> ConnectionProtocolErrors
{
get
{
// Unexpected frames after connection establishment.
foreach (FrameType frameType in new FrameType[] {
FrameType.Initialize,
FrameType.InitializeAck,
FrameType.Version
})
{
yield return new TestCaseData(
(IDuplexConnection connection) => WriteFrameAsync(connection, frameType),
$"Received unexpected {frameType} frame.");
}
// Pong frame without Ping frame.
yield return new TestCaseData(
(IDuplexConnection connection) => WriteFrameAsync(connection, FrameType.Pong, new PongBody(64).Encode),
$"Received unexpected {nameof(FrameType.Pong)} frame.");
// Stream frames which are not supposed to be sent on a non-started stream.
foreach (FrameType frameType in new FrameType[] {
FrameType.StreamReadsClosed,
FrameType.StreamWindowUpdate,
FrameType.StreamWritesClosed
})
{
yield return new TestCaseData(
(IDuplexConnection connection) => WriteStreamFrameAsync(connection, frameType, streamId: 4ul),
$"Received {frameType} frame for unknown stream.");
}
// Bogus stream frame with FrameSize=0 (stream ID not encoded)
yield return new TestCaseData((IDuplexConnection connection) =>
WriteFrameAsync(connection, FrameType.StreamLast, (ref SliceEncoder encoder) => { }),
"Invalid stream frame size.");
// Encode a stream frame with a frame size inferior to the stream ID size.
yield return new TestCaseData((IDuplexConnection connection) =>
{
var writer = new MemoryBufferWriter(new byte[1024]);
{
var encoder = new SliceEncoder(writer, SliceEncoding.Slice2);
encoder.EncodeFrameType(FrameType.Stream);
encoder.EncodeSize(1);
encoder.EncodeVarUInt62(int.MaxValue);
}
return connection.WriteAsync(new ReadOnlySequence<byte>(writer.WrittenMemory), default).AsTask();
},
"Invalid stream frame size.");
}
}
/// <summary>Verifies that create stream fails if called before connect.</summary>
[Test]
public async Task Create_stream_before_calling_connect_fails()
{
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
// Act/Assert
Assert.That(
async () => await sut.Client.CreateStreamAsync(bidirectional: true, default),
Throws.TypeOf<InvalidOperationException>());
}
/// <summary>Verifies that accept stream fails if called before connect.</summary>
[Test]
public async Task Accepting_stream_before_calling_connect_fails()
{
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
// Act/Assert
Assert.That(
async () => await sut.Client.AcceptStreamAsync(default),
Throws.TypeOf<InvalidOperationException>());
}
[Test]
public async Task Connect_called_twice_throws_invalid_operation_exception()
{
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
// Act/Assert
Assert.That(async () => await sut.Client.ConnectAsync(default), Throws.TypeOf<InvalidOperationException>());
}
[TestCase(false, false, DuplexTransportOperations.Connect)]
[TestCase(false, false, DuplexTransportOperations.Read)]
[TestCase(false, true, DuplexTransportOperations.Connect)]
[TestCase(true, false, DuplexTransportOperations.Connect)]
[TestCase(true, false, DuplexTransportOperations.Read)]
[TestCase(true, true, DuplexTransportOperations.Connect)]
public async Task Connect_exception_handling_on_transport_failure(
bool serverSide,
bool authenticationException,
DuplexTransportOperations operation)
{
// Arrange
Exception exception = authenticationException ?
new AuthenticationException() :
new IceRpcException(IceRpcError.ConnectionRefused);
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.AddTestDuplexTransportDecorator(
clientOperationsOptions: new()
{
Fail = serverSide ? DuplexTransportOperations.None : operation,
FailureException = exception
},
serverOperationsOptions: new()
{
Fail = serverSide ? operation : DuplexTransportOperations.None,
FailureException = exception
})
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
Func<Task> connectCall = serverSide ?
async () =>
{
using var clientConnectTcs = new CancellationTokenSource();
Task connectTask = sut.Client.ConnectAsync(clientConnectTcs.Token);
try
{
await sut.AcceptAsync();
}
finally
{
try
{
clientConnectTcs.Cancel();
await connectTask;
}
catch (OperationCanceledException)
{
// Prevents unobserved task exceptions.
}
}
}
:
async () =>
{
_ = AcceptAsync();
_ = await sut.Client.ConnectAsync(default);
async Task AcceptAsync()
{
try
{
await sut.AcceptAsync();
}
catch
{
// Prevents unobserved task exceptions.
}
}
};
// Act/Assert
Exception? caughtException = Assert.CatchAsync(() => connectCall());
Assert.That(caughtException, Is.EqualTo(exception));
}
[Test]
public async Task Connect_exception_handling_on_protocol_error([Values] bool clientSide)
{
// Arrange
var operationsOptions = new DuplexTransportOperationsOptions()
{
ReadDecorator = async (decoratee, buffer, cancellationToken) =>
{
int count = await decoratee.ReadAsync(buffer, cancellationToken);
buffer.Span[0] = 0xFF; // Bogus frame type.
return count;
}
};
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.AddTestDuplexTransportDecorator(
serverOperationsOptions: clientSide ? null : operationsOptions,
clientOperationsOptions: clientSide ? operationsOptions : null)
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
Task connectTask;
Task? clientConnectTask = null;
using var clientConnectCts = new CancellationTokenSource();
if (clientSide)
{
connectTask = sut.AcceptAndConnectAsync();
}
else
{
clientConnectTask = sut.Client.ConnectAsync(clientConnectCts.Token);
connectTask = sut.AcceptAsync();
}
// Assert
IceRpcException? exception = Assert.ThrowsAsync<IceRpcException>(async () => await connectTask);
Assert.That(
exception?.IceRpcError,
Is.EqualTo(IceRpcError.IceRpcError),
$"The test failed with an unexpected IceRpcError {exception}");
if (clientConnectTask is not null)
{
clientConnectCts.Cancel();
try
{
await clientConnectTask;
}
catch (OperationCanceledException)
{
}
}
}
/// <summary>Verifies that ConnectAsync can be canceled.</summary>
[Test]
public async Task Connect_cancellation()
{
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
using var cts = new CancellationTokenSource();
var listener = provider.GetRequiredService<IListener<IMultiplexedConnection>>();
var clientTransport = provider.GetRequiredService<IMultiplexedClientTransport>();
var clientConnection = clientTransport.CreateConnection(
listener.ServerAddress,
new MultiplexedConnectionOptions(),
clientAuthenticationOptions: null);
var connectTask = clientConnection.ConnectAsync(cts.Token);
// Act
cts.Cancel();
// Assert
Assert.That(async () => await connectTask, Throws.InstanceOf<OperationCanceledException>());
}
[TestCase(false, DuplexTransportOperations.Connect)]
[TestCase(false, DuplexTransportOperations.Read)]
[TestCase(false, DuplexTransportOperations.Write)]
[TestCase(true, DuplexTransportOperations.Connect)]
[TestCase(true, DuplexTransportOperations.Read)]
public async Task Connect_cancellation_on_transport_hang(bool serverSide, DuplexTransportOperations operation)
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.AddTestDuplexTransportDecorator(
clientOperationsOptions: new() { Hold = serverSide ? DuplexTransportOperations.None : operation },
serverOperationsOptions: new() { Hold = serverSide ? operation : DuplexTransportOperations.None })
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
using var connectCts = new CancellationTokenSource(100);
Func<Task> connectCall = serverSide ?
async () =>
{
using var clientConnectTcs = new CancellationTokenSource();
Task connectTask = sut.Client.ConnectAsync(clientConnectTcs.Token);
try
{
await sut.AcceptAsync(connectCts.Token);
}
finally
{
try
{
clientConnectTcs.Cancel();
await connectTask;
}
catch (OperationCanceledException)
{
// Prevents unobserved task exceptions.
}
}
}
:
async () =>
{
_ = AcceptAsync();
_ = await sut.Client.ConnectAsync(connectCts.Token);
async Task AcceptAsync()
{
try
{
await sut.AcceptAsync();
}
catch
{
// Prevents unobserved task exceptions.
}
}
};
// Act/Assert
Assert.That(
() => connectCall(),
Throws.InstanceOf<OperationCanceledException>().With.Property(
"CancellationToken").EqualTo(connectCts.Token));
}
[Test]
public async Task Connect_with_slic_version_unsupported_by_the_server()
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var duplexClientTransport = provider.GetRequiredService<IDuplexClientTransport>();
var listener = provider.GetRequiredService<IListener<IMultiplexedConnection>>();
var acceptTask = listener.AcceptAsync(default);
using var duplexClientConnection = duplexClientTransport.CreateConnection(
listener.ServerAddress,
new DuplexConnectionOptions(),
clientAuthenticationOptions: null);
await duplexClientConnection.ConnectAsync(default);
(var multiplexedServerConnection, var transportConnectionInformation) = await acceptTask;
await using var _ = multiplexedServerConnection;
using var reader = new DuplexConnectionReader(duplexClientConnection, MemoryPool<byte>.Shared, 4096);
// Write the initialize frame.
await WriteInitializeFrameAsync(duplexClientConnection, version: 2);
// Connect the server connection to read the initialize frame. It will send the version frame since the version
// 2 is not supported.
var connectTask = multiplexedServerConnection.ConnectAsync(default);
// Read the version frame.
await ReadFrameAsync(reader);
// Act
// Shutdown the client connection because it doesn't support any of the versions returned by the server.
await duplexClientConnection.ShutdownWriteAsync(default);
// Assert
Assert.That(
() => connectTask,
Throws.InstanceOf<IceRpcException>().With.Property("IceRpcError").EqualTo(IceRpcError.ConnectionRefused));
}
[Test]
public async Task Connect_with_server_that_returns_unsupported_slic_version()
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var multiplexedClientTransport = provider.GetRequiredService<IMultiplexedClientTransport>();
var duplexServerTransport = provider.GetRequiredService<IDuplexServerTransport>();
await using var listener = duplexServerTransport.Listen(
new ServerAddress(new Uri("icerpc://[::1]")),
options: new(),
serverAuthenticationOptions: null);
var acceptTask = listener.AcceptAsync(default);
await using var multiplexedClientConnection = multiplexedClientTransport.CreateConnection(
listener.ServerAddress,
new MultiplexedConnectionOptions(),
clientAuthenticationOptions: null);
var connectTask = multiplexedClientConnection.ConnectAsync(default);
(var duplexServerConnection, var transportConnectionInformation) = await acceptTask;
using var _ = duplexServerConnection;
using var reader = new DuplexConnectionReader(duplexServerConnection, MemoryPool<byte>.Shared, 4096);
// Read the initialize frame
await ReadFrameAsync(reader);
// Act
// Write the version frame with versions unsupported by the client.
await WriteFrameAsync(duplexServerConnection, FrameType.Version, new VersionBody(new ulong[] { 3 }).Encode);
// Assert
Assert.That(
() => connectTask,
Throws.InstanceOf<IceRpcException>().With.Property("IceRpcError").EqualTo(IceRpcError.ConnectionRefused));
}
[Test]
public async Task Connect_with_server_that_returns_invalid_slic_version()
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var multiplexedClientTransport = provider.GetRequiredService<IMultiplexedClientTransport>();
var duplexServerTransport = provider.GetRequiredService<IDuplexServerTransport>();
await using var listener = duplexServerTransport.Listen(
new ServerAddress(new Uri("icerpc://[::1]")),
options: new(),
serverAuthenticationOptions: null);
var acceptTask = listener.AcceptAsync(default);
await using var multiplexedClientConnection = multiplexedClientTransport.CreateConnection(
listener.ServerAddress,
new MultiplexedConnectionOptions(),
clientAuthenticationOptions: null);
var connectTask = multiplexedClientConnection.ConnectAsync(default);
(var duplexServerConnection, var transportConnectionInformation) = await acceptTask;
using var _ = duplexServerConnection;
using var reader = new DuplexConnectionReader(duplexServerConnection, MemoryPool<byte>.Shared, 4096);
// Read the initialize frame
await ReadFrameAsync(reader);
// Act
// Write the version frame with the version requested by the client in the initialize frame.
await WriteFrameAsync(duplexServerConnection, FrameType.Version, new VersionBody(new ulong[] { 3, 1 }).Encode);
// Assert
IceRpcException? exception = Assert.ThrowsAsync<IceRpcException>(async () => await connectTask);
Assert.That(exception!.IceRpcError, Is.EqualTo(IceRpcError.IceRpcError));
Assert.That(exception.Message, Is.EqualTo("The connection was aborted by a Slic protocol error."));
}
[Test]
public async Task Connect_version_negotiation()
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var duplexClientTransport = provider.GetRequiredService<IDuplexClientTransport>();
var listener = provider.GetRequiredService<IListener<IMultiplexedConnection>>();
var acceptTask = listener.AcceptAsync(default);
using var duplexClientConnection = duplexClientTransport.CreateConnection(
listener.ServerAddress,
new DuplexConnectionOptions(),
clientAuthenticationOptions: null);
await duplexClientConnection.ConnectAsync(default);
(var multiplexedServerConnection, var transportConnectionInformation) = await acceptTask;
await using var _ = multiplexedServerConnection;
using var reader = new DuplexConnectionReader(duplexClientConnection, MemoryPool<byte>.Shared, 4096);
// Act
// Write initialize frame
await WriteInitializeFrameAsync(duplexClientConnection, version: 2);
// Connect server connection, it doesn't support the client version so should return a version frame.
var connectTask = multiplexedServerConnection.ConnectAsync(default);
(FrameType versionFrameType, ReadOnlySequence<byte> versionBuffer) = await ReadFrameAsync(reader);
// Write back an initialize version with a supported version.
await WriteInitializeFrameAsync(duplexClientConnection, version: 1);
// Wait and read the initialize ack frame from the server.
(FrameType initializeAckFrameType, ReadOnlySequence<byte> _) = await ReadFrameAsync(reader);
// Assert
Assert.That(versionFrameType, Is.EqualTo(FrameType.Version));
Assert.That(DecodeVersionBody(versionBuffer).Versions, Is.EqualTo(new ulong[] { 1 }));
Assert.That(initializeAckFrameType, Is.EqualTo(FrameType.InitializeAck));
Assert.That(() => connectTask, Throws.Nothing);
static VersionBody DecodeVersionBody(ReadOnlySequence<byte> buffer)
{
var decoder = new SliceDecoder(buffer, SliceEncoding.Slice2);
var versionBody = new VersionBody(ref decoder);
decoder.CheckEndOfBuffer();
return versionBody;
}
}
/// <summary>Verifies that disabling the idle timeout doesn't abort the connection if it's idle.</summary>
[Test]
public async Task Connection_with_no_idle_timeout_is_not_aborted_when_idle()
{
// Arrange
var services = new ServiceCollection().AddSlicTest();
services.AddOptions<SlicTransportOptions>("server").Configure(
options => options.IdleTimeout = Timeout.InfiniteTimeSpan);
services.AddOptions<SlicTransportOptions>("client").Configure(
options => options.IdleTimeout = Timeout.InfiniteTimeSpan);
await using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
ValueTask<IMultiplexedStream> acceptStreamTask = sut.Server.AcceptStreamAsync(default);
// Act
await Task.Delay(TimeSpan.FromSeconds(1));
// Assert
Assert.That(acceptStreamTask.IsCompleted, Is.False);
await sut.Client.CloseAsync(MultiplexedConnectionCloseError.NoError, default);
Assert.That(async () => await acceptStreamTask, Throws.InstanceOf<IceRpcException>());
}
/// <summary>Verifies that setting the idle timeout doesn't abort the connection if it's idle.</summary>
[Test]
public async Task Connection_with_idle_timeout_is_not_aborted_when_idle([Values] bool serverIdleTimeout)
{
// Arrange
var services = new ServiceCollection().AddSlicTest();
var idleTimeout = TimeSpan.FromSeconds(1);
if (serverIdleTimeout)
{
services.AddOptions<SlicTransportOptions>("server").Configure(options => options.IdleTimeout = idleTimeout);
}
else
{
services.AddOptions<SlicTransportOptions>("client").Configure(options => options.IdleTimeout = idleTimeout);
}
await using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
ValueTask<IMultiplexedStream> acceptStreamTask = sut.Server.AcceptStreamAsync(default);
// Act
await Task.Delay(TimeSpan.FromSeconds(2));
// Assert
Assert.That(acceptStreamTask.IsCompleted, Is.False);
await sut.Client.CloseAsync(MultiplexedConnectionCloseError.NoError, default);
Assert.That(async () => await acceptStreamTask, Throws.InstanceOf<IceRpcException>());
}
/// <summary>Verifies that setting the idle timeout doesn't abort the connection when there is slow write activity
/// from client to server.</summary>
[Test]
public async Task Connection_with_idle_timeout_and_slow_write_is_not_aborted([Values] bool serverIdleTimeout)
{
// Arrange
var services = new ServiceCollection().AddSlicTest();
var idleTimeout = TimeSpan.FromSeconds(1);
if (serverIdleTimeout)
{
services.AddOptions<SlicTransportOptions>("server").Configure(options => options.IdleTimeout = idleTimeout);
}
else
{
services.AddOptions<SlicTransportOptions>("client").Configure(options => options.IdleTimeout = idleTimeout);
}
await using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
ValueTask<IMultiplexedStream> acceptStreamTask = sut.Server.AcceptStreamAsync(default);
IMultiplexedStream stream = await sut.Client.CreateStreamAsync(bidirectional: false, default);
// Act
for (int i = 0; i < 4; ++i)
{
// Slow writes to the server (the server doesn't even read them).
_ = await stream.Output.WriteAsync(new byte[1], default);
await Task.Delay(TimeSpan.FromMilliseconds(500));
}
stream.Output.Complete();
ValueTask<IMultiplexedStream> nextAcceptStreamTask = sut.Server.AcceptStreamAsync(default);
// Assert
Assert.That(acceptStreamTask.IsCompleted, Is.True);
Assert.That(nextAcceptStreamTask.IsCompleted, Is.False);
await sut.Client.CloseAsync(MultiplexedConnectionCloseError.NoError, default);
Assert.That(async () => await nextAcceptStreamTask, Throws.InstanceOf<IceRpcException>());
}
/// <summary>Verifies the cancellation token of CloseAsync works when the ShutdownAsync of the underlying server
/// duplex connection hangs.</summary>
[Test]
public async Task Close_canceled_when_duplex_server_connection_shutdown_hangs()
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.AddTestDuplexTransportDecorator(
serverOperationsOptions: new()
{
Hold = DuplexTransportOperations.ShutdownWrite
})
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50));
// Act
Task closeTask = sut.Client.CloseAsync(MultiplexedConnectionCloseError.NoError, cts.Token);
// Assert
Assert.That(async () => await closeTask, Throws.InstanceOf<OperationCanceledException>());
}
/// <summary>Verifies that close fails if called before connect.</summary>
[Test]
public async Task Closing_connection_before_calling_connect_fails()
{
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
// Act/Assert
Assert.That(async () => await sut.Client.CloseAsync(0ul, default), Throws.TypeOf<InvalidOperationException>());
}
[Test, TestCaseSource(nameof(ConnectionProtocolErrors))]
public async Task Connection_protocol_errors(
Func<IDuplexConnection, Task> protocolAction,
string expectedErrorMessage)
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var duplexClientTransport = provider.GetRequiredService<IDuplexClientTransport>();
var listener = provider.GetRequiredService<IListener<IMultiplexedConnection>>();
var acceptTask = listener.AcceptAsync(default);
using var duplexClientConnection = duplexClientTransport.CreateConnection(
listener.ServerAddress,
new DuplexConnectionOptions(),
clientAuthenticationOptions: null);
Task connectTask = duplexClientConnection.ConnectAsync(default);
(var multiplexedServerConnection, var transportConnectionInformation) = await acceptTask;
await using var _ = multiplexedServerConnection;
await connectTask;
using var reader = new DuplexConnectionReader(duplexClientConnection, MemoryPool<byte>.Shared, 4096);
// Connect the multiplexed connection.
await WriteInitializeFrameAsync(duplexClientConnection, version: 1);
await multiplexedServerConnection.ConnectAsync(default);
await ReadFrameAsync(reader);
ValueTask<IMultiplexedStream> acceptStreamTask = multiplexedServerConnection.AcceptStreamAsync(default);
// Act
await protocolAction(duplexClientConnection);
// Assert
IceRpcException? exception = Assert.ThrowsAsync<IceRpcException>(async () => await acceptStreamTask);
Assert.That(exception!.IceRpcError, Is.EqualTo(IceRpcError.IceRpcError));
Assert.That(exception.Message, Is.EqualTo("The connection was aborted by a Slic protocol error."));
Assert.That(exception.InnerException?.Message, Is.EqualTo(expectedErrorMessage));
}
[Test]
public async Task ReadFrames_exception_handling_on_protocol_error()
{
// Arrange
bool invalidRead = false;
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.AddTestDuplexTransportDecorator(
serverOperationsOptions: new DuplexTransportOperationsOptions()
{
ReadDecorator = async (decoratee, buffer, cancellationToken) =>
{
int count = await decoratee.ReadAsync(buffer, cancellationToken);
if (invalidRead)
{
buffer.Span[0] = 0xFF; // Bogus frame type.
}
return count;
}
})
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
invalidRead = true;
IMultiplexedStream stream = await sut.Client.CreateStreamAsync(bidirectional: false, default);
// Act
_ = await stream.Output.WriteAsync(new byte[1], default);
// Assert
IceRpcException? exception = Assert.ThrowsAsync<IceRpcException>(
async () => await sut.Server.AcceptStreamAsync(default));
Assert.That(
exception?.IceRpcError,
Is.EqualTo(IceRpcError.IceRpcError),
$"The test failed with an unexpected IceRpcError {exception}");
}
[Test]
public async Task Stream_peer_options_are_set_after_connect()
{
// Arrange
IServiceCollection services = new ServiceCollection().AddSlicTest();
services.AddOptions<SlicTransportOptions>("server").Configure(options =>
{
options.InitialStreamWindowSize = 6893;
options.MaxStreamFrameSize = 2098;
});
services.AddOptions<SlicTransportOptions>("client").Configure(options =>
{
options.InitialStreamWindowSize = 2405;
options.MaxStreamFrameSize = 4567;
});
await using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
// Act
await sut.AcceptAndConnectAsync();
// Assert
var serverConnection = (SlicConnection)sut.Server;
var clientConnection = (SlicConnection)sut.Client;
Assert.That(serverConnection.PeerInitialStreamWindowSize, Is.EqualTo(2405));
Assert.That(clientConnection.PeerInitialStreamWindowSize, Is.EqualTo(6893));
Assert.That(serverConnection.PeerMaxStreamFrameSize, Is.EqualTo(4567));
Assert.That(clientConnection.PeerMaxStreamFrameSize, Is.EqualTo(2098));
}
[TestCase(1024 * 32)]
[TestCase(1024 * 512)]
[TestCase(1024 * 1024)]
public async Task Stream_write_blocks_after_consuming_the_send_credit(int windowSize)
{
// Arrange
IServiceCollection services = new ServiceCollection().AddSlicTest();
services.AddOptions<SlicTransportOptions>("server").Configure(
options => options.InitialStreamWindowSize = windowSize);
await using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);
byte[] payload = new byte[windowSize - 1];
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
using var streams = await sut.CreateAndAcceptStreamAsync();
_ = await streams.Local.Output.WriteAsync(payload, default);
// Act
ValueTask<FlushResult> writeTask = streams.Local.Output.WriteAsync(payload, default);
// Assert
await Task.Delay(TimeSpan.FromMilliseconds(50));
Assert.That(writeTask.IsCompleted, Is.False);
// Make sure the writeTask completes before completing the stream output.
ReadResult readResult = await streams.Remote.Input.ReadAtLeastAsync(windowSize - 1);
Assert.That(readResult.IsCanceled, Is.False);
streams.Remote.Input.AdvanceTo(readResult.Buffer.End);
await writeTask;
}
[TestCase(32 * 1024)]
[TestCase(512 * 1024)]
[TestCase(1024 * 1024)]
public async Task Stream_write_blocking_does_not_affect_concurrent_streams(int windowSize)
{
// Arrange
byte[] payload = new byte[windowSize - 1];
IServiceCollection services = new ServiceCollection().AddSlicTest();
services.AddOptions<SlicTransportOptions>("server").Configure(
options => options.InitialStreamWindowSize = windowSize);
await using ServiceProvider provider = services.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
using var streams1 = await sut.CreateAndAcceptStreamAsync();
using var streams2 = await sut.CreateAndAcceptStreamAsync();
_ = await streams1.Local.Output.WriteAsync(payload, default);
ValueTask<FlushResult> writeTask = streams1.Local.Output.WriteAsync(payload, default);
// Act
// stream1 consumed all its send credit, this shouldn't affect stream2
_ = await streams2.Local.Output.WriteAsync(payload, default);
// Assert
Assert.That(streams2.Local.Id, Is.EqualTo(streams2.Remote.Id));
ReadResult readResult = await streams2.Remote.Input.ReadAtLeastAsync(windowSize - 1);
Assert.That(readResult.IsCanceled, Is.False);
streams2.Remote.Input.AdvanceTo(readResult.Buffer.End);
await Task.Delay(TimeSpan.FromMilliseconds(50));
Assert.That(writeTask.IsCompleted, Is.False);
// Make sure the writeTask completes before completing the stream output.
readResult = await streams1.Remote.Input.ReadAtLeastAsync(windowSize - 1);
Assert.That(readResult.IsCanceled, Is.False);
streams1.Remote.Input.AdvanceTo(readResult.Buffer.End);
await writeTask;
}
/// <summary>Verifies that a pending write operation on the stream fails with <see cref="OperationCanceledException"
/// /> when canceled.</summary>
[Test]
public async Task Stream_write_cancellation()
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.AddTestDuplexTransportDecorator()
.BuildServiceProvider(validateScopes: true);
var sut = provider.GetRequiredService<ClientServerMultiplexedConnection>();
await sut.AcceptAndConnectAsync();
var duplexClientConnection =
provider.GetRequiredService<TestDuplexClientTransportDecorator>().LastCreatedConnection;
using var streams = await sut.CreateAndAcceptStreamAsync();
using var writeCts = new CancellationTokenSource();
// Act
duplexClientConnection.Operations.Hold = DuplexTransportOperations.Write;
ValueTask<FlushResult> writeTask = streams.Local.Output.WriteAsync(new byte[128 * 1024], writeCts.Token);
writeCts.Cancel();
// Assert
Assert.That(
async () => await writeTask,
Throws.InstanceOf<OperationCanceledException>().With.Property("CancellationToken").EqualTo(writeCts.Token));
duplexClientConnection.Operations.Hold = DuplexTransportOperations.None;
}
[Test]
public async Task Write_initialize_frame_with_empty_body()
{
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var duplexClientTransport = provider.GetRequiredService<IDuplexClientTransport>();
var listener = provider.GetRequiredService<IListener<IMultiplexedConnection>>();
var acceptTask = listener.AcceptAsync(default);
using var duplexClientConnection = duplexClientTransport.CreateConnection(
listener.ServerAddress,
new DuplexConnectionOptions(),
clientAuthenticationOptions: null);
Task connectTask = duplexClientConnection.ConnectAsync(default);
(var multiplexedServerConnection, var transportConnectionInformation) = await acceptTask;
await using var _ = multiplexedServerConnection;
await connectTask;
using var reader = new DuplexConnectionReader(duplexClientConnection, MemoryPool<byte>.Shared, 4096);
// Act
await WriteFrameAsync(duplexClientConnection, FrameType.Initialize, (ref SliceEncoder encoder) => { });
// Assert
Assert.That(
async () => await multiplexedServerConnection.ConnectAsync(default),
Throws.InstanceOf<IceRpcException>().With.Property("IceRpcError").EqualTo(IceRpcError.IceRpcError));
}
[TestCase(nameof(FrameType.InitializeAck))]
[TestCase(nameof(FrameType.Version))]
public async Task Write_initialize_ack_or_version_frame_with_empty_body(string frameTypeStr)
{
FrameType frameType = Enum.Parse<FrameType>(frameTypeStr);
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var multiplexedClientTransport = provider.GetRequiredService<IMultiplexedClientTransport>();
var duplexServerTransport = provider.GetRequiredService<IDuplexServerTransport>();
await using var listener = duplexServerTransport.Listen(
new ServerAddress(new Uri("icerpc://[::1]")),
options: new(),
serverAuthenticationOptions: null);
var acceptTask = listener.AcceptAsync(default);
await using var multiplexedClientConnection = multiplexedClientTransport.CreateConnection(
listener.ServerAddress,
new MultiplexedConnectionOptions(),
clientAuthenticationOptions: null);
var connectTask = multiplexedClientConnection.ConnectAsync(default);
(var duplexServerConnection, var transportConnectionInformation) = await acceptTask;
using var _ = duplexServerConnection;
using var reader = new DuplexConnectionReader(duplexServerConnection, MemoryPool<byte>.Shared, 4096);
// Act
await WriteFrameAsync(duplexServerConnection, frameType, (ref SliceEncoder encoder) => { });
// Assert
Assert.That(
async () => await connectTask,
Throws.InstanceOf<IceRpcException>().With.Property("IceRpcError").EqualTo(IceRpcError.IceRpcError));
}
[Test, TestCaseSource(nameof(InvalidConnectionFrames))]
public async Task Write_connection_frame_with_invalid_body(string frameTypeStr, bool emptyBody)
{
FrameType frameType = Enum.Parse<FrameType>(frameTypeStr);
// Arrange
await using ServiceProvider provider = new ServiceCollection()
.AddSlicTest()
.BuildServiceProvider(validateScopes: true);
var duplexClientTransport = provider.GetRequiredService<IDuplexClientTransport>();
var listener = provider.GetRequiredService<IListener<IMultiplexedConnection>>();
var acceptTask = listener.AcceptAsync(default);
using var duplexClientConnection = duplexClientTransport.CreateConnection(
listener.ServerAddress,
new DuplexConnectionOptions(),
clientAuthenticationOptions: null);
Task connectTask = duplexClientConnection.ConnectAsync(default);
(var multiplexedServerConnection, var transportConnectionInformation) = await acceptTask;
await using var _ = multiplexedServerConnection;
await connectTask;
using var reader = new DuplexConnectionReader(duplexClientConnection, MemoryPool<byte>.Shared, 4096);
// Connect the multiplexed connection.
await WriteInitializeFrameAsync(duplexClientConnection, version: 1);
await multiplexedServerConnection.ConnectAsync(default);
(FrameType initializeAckFrameType, ReadOnlySequence<byte> _) = await ReadFrameAsync(reader);
var body = new ReadOnlyMemory<byte>(new byte[256]);
// Act
await WriteFrameAsync(
duplexClientConnection,
frameType,
(ref SliceEncoder encoder) => encoder.WriteByteSpan(emptyBody ? ReadOnlySpan<byte>.Empty : body.Span));
// Assert
Assert.That(
async () => await multiplexedServerConnection.AcceptStreamAsync(default),
Throws.InstanceOf<IceRpcException>().With.Property("IceRpcError").EqualTo(IceRpcError.IceRpcError));
}
[TestCase(nameof(FrameType.Stream))]
[TestCase(nameof(FrameType.StreamWritesClosed))]
[TestCase(nameof(FrameType.StreamReadsClosed))]
public async Task Write_stream_frame_with_invalid_body(string frameTypeStr)
{
FrameType frameType = Enum.Parse<FrameType>(frameTypeStr);
bool emptyBody = frameType == FrameType.Stream;