-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSlicConnection.cs
1525 lines (1353 loc) · 56.5 KB
/
SlicConnection.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.Slice;
using IceRpc.Slice.Internal;
using IceRpc.Transports.Internal;
using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Security.Authentication;
using System.Threading.Channels;
namespace IceRpc.Transports.Slic.Internal;
/// <summary>The Slic connection implements an <see cref="IMultiplexedConnection" /> on top of a <see
/// cref="IDuplexConnection" />.</summary>
internal class SlicConnection : IMultiplexedConnection
{
internal bool IsServer { get; }
internal int MinSegmentSize { get; }
internal int PauseWriterThreshold { get; }
internal int PeerPacketMaxSize { get; private set; }
internal int PeerPauseWriterThreshold { get; private set; }
internal MemoryPool<byte> Pool { get; }
internal int ResumeWriterThreshold { get; }
private readonly Channel<IMultiplexedStream> _acceptStreamChannel;
private int _bidirectionalStreamCount;
private SemaphoreSlim? _bidirectionalStreamSemaphore;
private readonly CancellationTokenSource _closedCts = new();
private readonly CancellationToken _closedCancellationToken;
private string? _closedMessage;
private Task? _closeTask;
private Task<TransportConnectionInformation>? _connectTask;
private readonly CancellationTokenSource _disposedCts = new();
private Task? _disposeTask;
private readonly IDuplexConnection _duplexConnection;
private readonly DuplexConnectionReader _duplexConnectionReader;
private readonly SlicDuplexConnectionWriter _duplexConnectionWriter;
private readonly Action<TimeSpan, Action?> _enableIdleTimeoutAndKeepAlive;
private bool _isClosed;
private ulong? _lastRemoteBidirectionalStreamId;
private ulong? _lastRemoteUnidirectionalStreamId;
private readonly TimeSpan _localIdleTimeout;
private readonly int _maxBidirectionalStreams;
private readonly int _maxUnidirectionalStreams;
// _mutex ensure the assignment of _lastRemoteXxx members and the addition of the stream to _streams is
// an atomic operation.
private readonly object _mutex = new();
private ulong _nextBidirectionalId;
private ulong _nextUnidirectionalId;
private readonly int _packetMaxSize;
private IceRpcError? _peerCloseError;
private TimeSpan _peerIdleTimeout = Timeout.InfiniteTimeSpan;
private Task _pingTask = Task.CompletedTask;
private Task _pongTask = Task.CompletedTask;
private Task? _readFramesTask;
private readonly ConcurrentDictionary<ulong, SlicStream> _streams = new();
private int _streamSemaphoreWaitCount;
private readonly TaskCompletionSource _streamSemaphoreWaitClosed =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _unidirectionalStreamCount;
private SemaphoreSlim? _unidirectionalStreamSemaphore;
private readonly SemaphoreSlim _writeSemaphore = new(1, 1);
public async ValueTask<IMultiplexedStream> AcceptStreamAsync(CancellationToken cancellationToken)
{
lock (_mutex)
{
ObjectDisposedException.ThrowIf(_disposeTask is not null, this);
if (_connectTask is null || !_connectTask.IsCompletedSuccessfully)
{
throw new InvalidOperationException("Cannot accept stream before connecting the Slic connection.");
}
if (_isClosed)
{
throw new IceRpcException(_peerCloseError ?? IceRpcError.ConnectionAborted, _closedMessage);
}
}
try
{
return await _acceptStreamChannel.Reader.ReadAsync(cancellationToken).ConfigureAwait(false);
}
catch (ChannelClosedException exception)
{
Debug.Assert(exception.InnerException is not null);
// The exception given to ChannelWriter.Complete(Exception? exception) is the InnerException.
throw ExceptionUtil.Throw(exception.InnerException);
}
}
public Task<TransportConnectionInformation> ConnectAsync(CancellationToken cancellationToken)
{
lock (_mutex)
{
ObjectDisposedException.ThrowIf(_disposeTask is not null, this);
if (_connectTask is not null)
{
throw new InvalidOperationException("Cannot connect twice a Slic connection.");
}
if (_isClosed)
{
throw new InvalidOperationException("Cannot connect a closed Slic connection.");
}
_connectTask = PerformConnectAsync();
}
return _connectTask;
async Task<TransportConnectionInformation> PerformConnectAsync()
{
await Task.Yield(); // Exit mutex lock
// Connect the duplex connection.
TransportConnectionInformation transportConnectionInformation;
TimeSpan peerIdleTimeout = TimeSpan.MaxValue;
try
{
transportConnectionInformation = await _duplexConnection.ConnectAsync(cancellationToken)
.ConfigureAwait(false);
// Initialize the Slic connection.
if (IsServer)
{
// Read the Initialize frame.
(ulong version, InitializeBody? initializeBody) = await ReadFrameAsync(
DecodeInitialize,
cancellationToken).ConfigureAwait(false);
if (version != 1)
{
// Unsupported version, try to negotiate another version by sending a Version frame with the
// Slic versions supported by this server.
await SendFrameAsync(
FrameType.Versions,
new VersionBody(new ulong[] { SlicDefinitions.V1 }).Encode,
cancellationToken).ConfigureAwait(false);
(version, initializeBody) = await ReadFrameAsync(
DecodeInitialize,
cancellationToken).ConfigureAwait(false);
}
if (initializeBody is null)
{
throw new IceRpcException(
IceRpcError.ConnectionAborted,
$"The connection was aborted because the peer's Slic version '{version}' is not supported.");
}
// Check the application protocol and set the parameters.
string protocolName = initializeBody.Value.ApplicationProtocolName;
if (!Protocol.TryParse(protocolName, out Protocol? protocol) || protocol != Protocol.IceRpc)
{
throw new IceRpcException(
IceRpcError.ConnectionAborted,
$"The connection was aborted because the peer's application protocol '{protocolName}' is not supported.");
}
DecodeParameters(initializeBody.Value.Parameters);
// Write back an InitializeAck frame.
await SendFrameAsync(
FrameType.InitializeAck,
new InitializeAckBody(EncodeParameters()).Encode,
cancellationToken).ConfigureAwait(false);
}
else
{
// Write the Initialize frame.
await SendFrameAsync(
FrameType.Initialize,
(ref SliceEncoder encoder) =>
{
encoder.EncodeVarUInt62(SlicDefinitions.V1);
new InitializeBody(Protocol.IceRpc.Name, EncodeParameters()).Encode(ref encoder);
},
cancellationToken).ConfigureAwait(false);
// Read the Initialize frame.
InitializeAckBody initializeAckBody = await ReadFrameAsync(
DecodeInitializeAckOrVersion,
cancellationToken).ConfigureAwait(false);
DecodeParameters(initializeAckBody.Parameters);
}
}
catch (InvalidDataException exception)
{
throw new IceRpcException(
IceRpcError.IceRpcError,
"The connection was aborted by a Slic protocol error.",
exception);
}
catch (OperationCanceledException)
{
throw;
}
catch (AuthenticationException)
{
throw;
}
catch (IceRpcException)
{
throw;
}
catch (Exception exception)
{
Debug.Fail($"ConnectAsync failed with an unexpected exception: {exception}");
throw;
}
// Enable the idle timeout checks after the connection establishment. The Ping frames sent by the keep alive
// check are not expected until the Slic connection initialization completes. The idle timeout check uses
// the smallest idle timeout.
TimeSpan idleTimeout = _peerIdleTimeout == Timeout.InfiniteTimeSpan ? _localIdleTimeout :
(_peerIdleTimeout < _localIdleTimeout ? _peerIdleTimeout : _localIdleTimeout);
if (idleTimeout != Timeout.InfiniteTimeSpan)
{
// Only client connections send ping frames when idle to keep the server connection alive. The server
// sends back a Pong frame in turn to keep alive the client connection.
_enableIdleTimeoutAndKeepAlive(idleTimeout, IsServer ? null : KeepAlive);
}
_readFramesTask = ReadFramesAsync(_disposedCts.Token);
return transportConnectionInformation;
}
static (uint, InitializeBody?) DecodeInitialize(FrameType frameType, ReadOnlySequence<byte> buffer)
{
if (frameType != FrameType.Initialize)
{
throw new InvalidDataException($"Received unexpected Slic frame: '{frameType}'.");
}
return SliceEncoding.Slice2.DecodeBuffer<(uint, InitializeBody?)>(
buffer,
(ref SliceDecoder decoder) =>
{
uint version = decoder.DecodeVarUInt32();
if (version == SlicDefinitions.V1)
{
return (version, new InitializeBody(ref decoder));
}
else
{
decoder.Skip((int)(buffer.Length - decoder.Consumed));
return (version, null);
}
});
}
static InitializeAckBody DecodeInitializeAckOrVersion(FrameType frameType, ReadOnlySequence<byte> buffer)
{
switch (frameType)
{
case FrameType.InitializeAck:
return SliceEncoding.Slice2.DecodeBuffer(
buffer,
(ref SliceDecoder decoder) => new InitializeAckBody(ref decoder));
case FrameType.Versions:
// We currently only support V1
VersionBody versionBody = SliceEncoding.Slice2.DecodeBuffer(
buffer,
(ref SliceDecoder decoder) => new VersionBody(ref decoder));
throw new IceRpcException(
IceRpcError.ConnectionAborted,
$"The connection was aborted because the peer's Slic version(s) '{string.Join(", ", versionBody.Versions)}' are not supported.");
default:
throw new InvalidDataException($"Received unexpected Slic frame: '{frameType}'.");
}
}
void KeepAlive()
{
lock (_mutex)
{
// Send a new ping frame if the previous frame was sent and the connection is not closed
// or being close. The check for _isClosed ensures _pingTask is not reassigned once the
// connection is closed.
if (_pingTask.IsCompleted && !_isClosed)
{
_pingTask = SendPingFrameAsync();
}
}
async Task SendPingFrameAsync()
{
await Task.Yield(); // Exit mutex lock
try
{
await SendFrameAsync(FrameType.Ping, encode: null, CancellationToken.None).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Expected if the connection was closed.
}
catch (IceRpcException)
{
// Expected if the connection failed.
}
catch (Exception exception)
{
Debug.Fail($"ping task failed with an unexpected exception: {exception}");
throw;
}
}
}
async ValueTask<T> ReadFrameAsync<T>(
Func<FrameType, ReadOnlySequence<byte>, T> decodeFunc,
CancellationToken cancellationToken)
{
(FrameType FrameType, int FrameSize, ulong?)? header =
await ReadFrameHeaderAsync(cancellationToken).ConfigureAwait(false);
if (header is null || header.Value.FrameSize == 0)
{
throw new InvalidDataException("Received invalid Slic frame.");
}
ReadOnlySequence<byte> buffer = await _duplexConnectionReader.ReadAtLeastAsync(
header.Value.FrameSize,
cancellationToken).ConfigureAwait(false);
if (buffer.Length > header.Value.FrameSize)
{
buffer = buffer.Slice(0, header.Value.FrameSize);
}
T decodedFrame = decodeFunc(header.Value.FrameType, buffer);
_duplexConnectionReader.AdvanceTo(buffer.End);
return decodedFrame;
}
}
public async Task CloseAsync(MultiplexedConnectionCloseError closeError, CancellationToken cancellationToken)
{
lock (_mutex)
{
ObjectDisposedException.ThrowIf(_disposeTask is not null, this);
if (_connectTask is null || !_connectTask.IsCompletedSuccessfully)
{
throw new InvalidOperationException("Cannot close a Slic connection before connecting it.");
}
// The close task might already be set if the peer closed the connection.
_closeTask ??= PerformCloseAsync();
}
// Wait for the sending of the close frame.
await _closeTask.ConfigureAwait(false);
// Now, wait for the peer to send the close frame that will terminate the read frames task.
Debug.Assert(_readFramesTask is not null);
await _readFramesTask.WaitAsync(cancellationToken).ConfigureAwait(false);
async Task PerformCloseAsync()
{
await Task.Yield(); // Exit mutex lock
Close(new IceRpcException(IceRpcError.OperationAborted), "The connection was closed.");
// The semaphore can't be disposed until the close task completes.
using SemaphoreLock _ = await _writeSemaphore.AcquireAsync(cancellationToken).ConfigureAwait(false);
WriteFrame(FrameType.Close, streamId: null, new CloseBody((ulong)closeError).Encode);
await _duplexConnectionWriter.FlushAsync(cancellationToken).ConfigureAwait(false);
if (!IsServer)
{
// The sending of the client-side Close frame is followed by the shutdown of the duplex connection. For
// TCP, it's important to always shutdown the connection on the client-side first to avoid TIME_WAIT
// states on the server-side.
_duplexConnectionWriter.Shutdown();
}
}
}
public async ValueTask<IMultiplexedStream> CreateStreamAsync(
bool bidirectional,
CancellationToken cancellationToken)
{
lock (_mutex)
{
ObjectDisposedException.ThrowIf(_disposeTask is not null, this);
if (_connectTask is null || !_connectTask.IsCompletedSuccessfully)
{
throw new InvalidOperationException("Cannot create stream before connecting the Slic connection.");
}
if (_isClosed)
{
throw new IceRpcException(_peerCloseError ?? IceRpcError.ConnectionAborted, _closedMessage);
}
++_streamSemaphoreWaitCount;
}
try
{
using var createStreamCts = CancellationTokenSource.CreateLinkedTokenSource(
_closedCancellationToken,
cancellationToken);
SemaphoreSlim? streamCountSemaphore = bidirectional ?
_bidirectionalStreamSemaphore :
_unidirectionalStreamSemaphore;
if (streamCountSemaphore is null)
{
// The stream semaphore is null if the peer's max streams configuration is 0. In this case, we let
// CreateStreamAsync hang indefinitely until the connection is closed.
await Task.Delay(-1, createStreamCts.Token).ConfigureAwait(false);
}
else
{
await streamCountSemaphore.WaitAsync(createStreamCts.Token).ConfigureAwait(false);
}
// TODO: Cache SlicStream
return new SlicStream(this, bidirectional, remote: false);
}
catch (OperationCanceledException)
{
cancellationToken.ThrowIfCancellationRequested();
Debug.Assert(_isClosed);
throw new IceRpcException(_peerCloseError ?? IceRpcError.OperationAborted, _closedMessage);
}
finally
{
lock (_mutex)
{
--_streamSemaphoreWaitCount;
if (_isClosed && _streamSemaphoreWaitCount == 0)
{
_streamSemaphoreWaitClosed.SetResult();
}
}
}
}
public ValueTask DisposeAsync()
{
Close(new IceRpcException(IceRpcError.OperationAborted), "The connection was disposed.");
lock (_mutex)
{
_disposeTask ??= PerformDisposeAsync();
}
return new(_disposeTask);
async Task PerformDisposeAsync()
{
// Make sure we execute the code below without holding the mutex lock.
await Task.Yield();
_disposedCts.Cancel();
try
{
await Task.WhenAll(
_connectTask ?? Task.CompletedTask,
_readFramesTask ?? Task.CompletedTask,
_writeSemaphore.WaitAsync(CancellationToken.None),
_streamSemaphoreWaitClosed.Task,
_pingTask,
_pongTask,
_closeTask ?? Task.CompletedTask).ConfigureAwait(false);
}
catch
{
// Expected if any of these tasks failed or was canceled. Each task takes care of handling unexpected
// exceptions so there's no need to handle them here.
}
// Clean-up the streams that might still be queued on the channel.
while (_acceptStreamChannel.Reader.TryRead(out IMultiplexedStream? stream))
{
if (stream.IsBidirectional)
{
stream.Output.Complete();
stream.Input.Complete();
}
else if (stream.IsRemote)
{
stream.Input.Complete();
}
else
{
stream.Output.Complete();
}
}
try
{
await _acceptStreamChannel.Reader.Completion.ConfigureAwait(false);
}
catch
{
}
_duplexConnection.Dispose();
_duplexConnectionReader.Dispose();
await _duplexConnectionWriter.DisposeAsync().ConfigureAwait(false);
_disposedCts.Dispose();
_writeSemaphore.Dispose();
_bidirectionalStreamSemaphore?.Dispose();
_unidirectionalStreamSemaphore?.Dispose();
_closedCts.Dispose();
}
}
internal SlicConnection(
IDuplexConnection duplexConnection,
MultiplexedConnectionOptions options,
SlicTransportOptions slicOptions,
bool isServer)
{
IsServer = isServer;
Pool = options.Pool;
MinSegmentSize = options.MinSegmentSize;
_maxBidirectionalStreams = options.MaxBidirectionalStreams;
_maxUnidirectionalStreams = options.MaxUnidirectionalStreams;
PauseWriterThreshold = slicOptions.PauseWriterThreshold;
ResumeWriterThreshold = slicOptions.ResumeWriterThreshold;
_localIdleTimeout = slicOptions.IdleTimeout;
_packetMaxSize = slicOptions.PacketMaxSize;
_acceptStreamChannel = Channel.CreateUnbounded<IMultiplexedStream>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = true
});
_closedCancellationToken = _closedCts.Token;
var duplexConnectionDecorator = new IdleTimeoutDuplexConnectionDecorator(duplexConnection);
_enableIdleTimeoutAndKeepAlive = duplexConnectionDecorator.Enable;
_duplexConnection = duplexConnectionDecorator;
_duplexConnectionReader = new DuplexConnectionReader(_duplexConnection, options.Pool, options.MinSegmentSize);
_duplexConnectionWriter = new SlicDuplexConnectionWriter(
_duplexConnection,
options.Pool,
options.MinSegmentSize);
// Initially set the peer packet max size to the local max size to ensure we can receive the first initialize
// frame.
PeerPacketMaxSize = _packetMaxSize;
PeerPauseWriterThreshold = PauseWriterThreshold;
// We use the same stream ID numbering scheme as Quic.
if (IsServer)
{
_nextBidirectionalId = 1;
_nextUnidirectionalId = 3;
}
else
{
_nextBidirectionalId = 0;
_nextUnidirectionalId = 2;
}
}
internal ValueTask FillBufferWriterAsync(
IBufferWriter<byte> bufferWriter,
int byteCount,
CancellationToken cancellationToken) =>
_duplexConnectionReader.FillBufferWriterAsync(bufferWriter, byteCount, cancellationToken);
internal void ReleaseStream(SlicStream stream)
{
Debug.Assert(stream.IsStarted);
_streams.Remove(stream.Id, out SlicStream? _);
if (stream.IsRemote)
{
if (stream.IsBidirectional)
{
Interlocked.Decrement(ref _bidirectionalStreamCount);
}
else
{
Interlocked.Decrement(ref _unidirectionalStreamCount);
}
}
else if (!_isClosed)
{
if (stream.IsBidirectional)
{
_bidirectionalStreamSemaphore!.Release();
}
else
{
_unidirectionalStreamSemaphore!.Release();
}
}
}
internal async ValueTask SendFrameAsync(
FrameType frameType,
EncodeAction? encode,
CancellationToken cancellationToken)
{
using var writeCts = CancellationTokenSource.CreateLinkedTokenSource(
_closedCancellationToken,
cancellationToken);
try
{
using SemaphoreLock _ = await AcquireWriteLockAsync(writeCts.Token).ConfigureAwait(false);
WriteFrame(frameType, streamId: null, encode);
await _duplexConnectionWriter.FlushAsync(writeCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
cancellationToken.ThrowIfCancellationRequested();
Debug.Assert(_isClosed);
throw new IceRpcException(_peerCloseError ?? IceRpcError.ConnectionAborted, _closedMessage);
}
}
internal async ValueTask SendStreamFrameAsync(
SlicStream stream,
FrameType frameType,
EncodeAction? encode,
bool sendReadsCompletedFrame)
{
Debug.Assert(frameType >= FrameType.StreamReset);
try
{
using SemaphoreLock _ = await AcquireWriteLockAsync(_closedCancellationToken).ConfigureAwait(false);
if (!stream.IsStarted)
{
StartStream(stream);
}
WriteFrame(frameType, stream.Id, encode);
if (sendReadsCompletedFrame)
{
WriteFrame(FrameType.StreamReadsCompleted, stream.Id, encode: null);
}
await _duplexConnectionWriter.FlushAsync(_closedCancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Debug.Assert(_isClosed);
throw new IceRpcException(_peerCloseError ?? IceRpcError.ConnectionAborted, _closedMessage);
}
}
internal async ValueTask<FlushResult> SendStreamFrameAsync(
SlicStream stream,
ReadOnlySequence<byte> source1,
ReadOnlySequence<byte> source2,
bool endStream,
bool sendReadsCompletedFrame,
CancellationToken cancellationToken)
{
Debug.Assert(!source1.IsEmpty || endStream);
if (_connectTask is null)
{
throw new InvalidOperationException("Cannot send a stream frame before calling ConnectAsync.");
}
using var writeCts = CancellationTokenSource.CreateLinkedTokenSource(
_closedCancellationToken,
cancellationToken);
try
{
do
{
// Next, ensure send credit is available. If not, this will block until the receiver allows sending
// additional data.
int sendCredit = 0;
if (!source1.IsEmpty || !source2.IsEmpty)
{
sendCredit = await stream.AcquireSendCreditAsync(writeCts.Token).ConfigureAwait(false);
Debug.Assert(sendCredit > 0);
}
// Gather data from source1 or source2 up to sendCredit bytes or the Slic packet maximum size.
int sendMaxSize = Math.Min(sendCredit, PeerPacketMaxSize);
ReadOnlySequence<byte> sendSource1;
ReadOnlySequence<byte> sendSource2;
if (!source1.IsEmpty)
{
int length = Math.Min((int)source1.Length, sendMaxSize);
sendSource1 = source1.Slice(0, length);
source1 = source1.Slice(length);
}
else
{
sendSource1 = ReadOnlySequence<byte>.Empty;
}
if (source1.IsEmpty && !source2.IsEmpty)
{
int length = Math.Min((int)source2.Length, sendMaxSize - (int)sendSource1.Length);
sendSource2 = source2.Slice(0, length);
source2 = source2.Slice(length);
}
else
{
sendSource2 = ReadOnlySequence<byte>.Empty;
}
// If there's no data left to send and endStream is true, it's the last stream frame.
bool lastStreamFrame = endStream && source1.IsEmpty && source2.IsEmpty;
// Finally, acquire the write semaphore to ensure only one stream writes to the connection.
using SemaphoreLock semaphoreLock = await AcquireWriteLockAsync(writeCts.Token).ConfigureAwait(false);
if (!stream.IsStarted)
{
StartStream(stream);
}
// Notify the stream that we're consuming sendSize credit. It's important to call this before sending
// the stream frame to avoid race conditions where the StreamConsumed frame could be received before the
// send credit was updated.
if (sendCredit > 0)
{
stream.ConsumedSendCredit((int)(sendSource1.Length + sendSource2.Length));
}
EncodeStreamFrameHeader(stream.Id, sendSource1.Length + sendSource2.Length, lastStreamFrame);
if (lastStreamFrame)
{
// Notify the stream that the last stream frame is considered sent at this point. This will complete
// writes on the stream and allow the stream to be released if reads are also completed.
stream.SentLastStreamFrame();
}
// Write and flush the stream frame.
if (!sendSource1.IsEmpty)
{
_duplexConnectionWriter.Write(sendSource1);
}
if (!sendSource2.IsEmpty)
{
_duplexConnectionWriter.Write(sendSource2);
}
if (sendReadsCompletedFrame)
{
WriteFrame(FrameType.StreamReadsCompleted, stream.Id, encode: null);
}
await _duplexConnectionWriter.FlushAsync(writeCts.Token).ConfigureAwait(false);
}
while (!source1.IsEmpty || !source2.IsEmpty); // Loop until there's no data left to send.
}
catch (OperationCanceledException)
{
cancellationToken.ThrowIfCancellationRequested();
Debug.Assert(_isClosed);
throw new IceRpcException(_peerCloseError ?? IceRpcError.OperationAborted, _closedMessage);
}
return new FlushResult(isCanceled: false, isCompleted: false);
void EncodeStreamFrameHeader(ulong streamId, long size, bool lastStreamFrame)
{
var encoder = new SliceEncoder(_duplexConnectionWriter, SliceEncoding.Slice2);
encoder.EncodeFrameType(
!lastStreamFrame ? FrameType.Stream :
FrameType.StreamLast);
Span<byte> sizePlaceholder = encoder.GetPlaceholderSpan(4);
int startPos = encoder.EncodedByteCount;
encoder.EncodeVarUInt62(streamId);
SliceEncoder.EncodeVarUInt62((ulong)(encoder.EncodedByteCount - startPos + size), sizePlaceholder);
}
}
internal void ThrowIfClosed()
{
lock (_mutex)
{
if (_isClosed)
{
throw new IceRpcException(_peerCloseError ?? IceRpcError.ConnectionAborted, _closedMessage);
}
}
}
private ValueTask<SemaphoreLock> AcquireWriteLockAsync(CancellationToken cancellationToken)
{
lock (_mutex)
{
// Make sure the connection is not being closed or closed when we acquire the semaphore.
if (_isClosed)
{
throw new IceRpcException(_peerCloseError ?? IceRpcError.ConnectionAborted, _closedMessage);
}
return _writeSemaphore.AcquireAsync(cancellationToken);
}
}
private void AddStream(ulong id, SlicStream stream)
{
lock (_mutex)
{
if (_isClosed)
{
throw new IceRpcException(_peerCloseError ?? IceRpcError.ConnectionAborted, _closedMessage);
}
_streams[id] = stream;
// Assign the stream ID within the mutex to ensure that the addition of the stream to the connection and the
// stream ID assignment are atomic.
stream.Id = id;
// Keep track of the last assigned stream ID. This is used to figure out if the stream is known or unknown.
if (stream.IsRemote)
{
if (stream.IsBidirectional)
{
_lastRemoteBidirectionalStreamId = id;
}
else
{
_lastRemoteUnidirectionalStreamId = id;
}
}
}
}
private void Close(Exception exception, string closeMessage, IceRpcError? peerCloseError = null)
{
lock (_mutex)
{
if (_isClosed)
{
return;
}
_isClosed = true;
_closedMessage = closeMessage;
_peerCloseError = peerCloseError;
if (_streamSemaphoreWaitCount == 0)
{
_streamSemaphoreWaitClosed.SetResult();
}
}
// Cancel pending CreateStreamAsync, AcceptStreamAsync and writes on the connection.
_closedCts.Cancel();
_acceptStreamChannel.Writer.TryComplete(exception);
// Close streams.
foreach (SlicStream stream in _streams.Values)
{
stream.Close(exception);
}
}
private void DecodeParameters(IDictionary<ParameterKey, IList<byte>> parameters)
{
int? peerPacketMaxSize = null;
int? peerPauseWriterThreshold = null;
foreach ((ParameterKey key, IList<byte> buffer) in parameters)
{
switch (key)
{
case ParameterKey.MaxBidirectionalStreams:
{
int value = DecodeParamValue(buffer);
if (value > 0)
{
_bidirectionalStreamSemaphore = new SemaphoreSlim(value, value);
}
break;
}
case ParameterKey.MaxUnidirectionalStreams:
{
int value = DecodeParamValue(buffer);
if (value > 0)
{
_unidirectionalStreamSemaphore = new SemaphoreSlim(value, value);
}
break;
}
case ParameterKey.IdleTimeout:
{
_peerIdleTimeout = TimeSpan.FromMilliseconds(DecodeParamValue(buffer));
if (_peerIdleTimeout == TimeSpan.Zero)
{
throw new InvalidDataException(
"The IdleTimeout Slic connection parameter is invalid, it must be greater than 0 s.");
}
break;
}
case ParameterKey.PacketMaxSize:
{
peerPacketMaxSize = DecodeParamValue(buffer);
if (peerPacketMaxSize < 1024)
{
throw new InvalidDataException(
"The PacketMaxSize Slic connection parameter is invalid, it must be greater than 1KB.");
}
break;
}
case ParameterKey.PauseWriterThreshold:
{
peerPauseWriterThreshold = DecodeParamValue(buffer);
if (peerPauseWriterThreshold < 1024)
{
throw new InvalidDataException(
"The PauseWriterThreshold Slic connection parameter is invalid, it must be greater than 1KB.");
}
break;
}
// Ignore unsupported parameter.
}
}
if (peerPacketMaxSize is null)
{
throw new InvalidDataException(
"The peer didn't send the required PacketMaxSize Slic connection parameter.");
}
else
{
PeerPacketMaxSize = peerPacketMaxSize.Value;
}
if (peerPauseWriterThreshold is null)
{
throw new InvalidDataException(
"The peer didn't send the required PauseWriterThreshold Slic connection parameter.");
}
else
{
PeerPauseWriterThreshold = peerPauseWriterThreshold.Value;
}
// all parameter values are currently integers in the range 0..Int32Max encoded as varuint62.
static int DecodeParamValue(IList<byte> buffer)
{
// The IList<byte> decoded by the Slice engine is backed by an array
ulong value = SliceEncoding.Slice2.DecodeBuffer(
new ReadOnlySequence<byte>((byte[])buffer),
(ref SliceDecoder decoder) => decoder.DecodeVarUInt62());
try
{
return checked((int)value);
}
catch (OverflowException exception)
{
throw new InvalidDataException("The value is out of the varuint32 accepted range.", exception);
}
}
}
private Dictionary<ParameterKey, IList<byte>> EncodeParameters()
{
var parameters = new List<KeyValuePair<ParameterKey, IList<byte>>>
{
// Required parameters.
EncodeParameter(ParameterKey.PacketMaxSize, (ulong)_packetMaxSize),
EncodeParameter(ParameterKey.PauseWriterThreshold, (ulong)PauseWriterThreshold)
};
// Optional parameters.
if (_localIdleTimeout != Timeout.InfiniteTimeSpan)
{
parameters.Add(EncodeParameter(ParameterKey.IdleTimeout, (ulong)_localIdleTimeout.TotalMilliseconds));
}
if (_maxBidirectionalStreams > 0)
{
parameters.Add(EncodeParameter(ParameterKey.MaxBidirectionalStreams, (ulong)_maxBidirectionalStreams));
}