-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
MsQuicStream.cs
1517 lines (1257 loc) · 56.5 KB
/
MsQuicStream.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Quic.Implementations.MsQuic.Internal;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.Quic.Implementations.MsQuic.Internal.MsQuicNativeMethods;
namespace System.Net.Quic.Implementations.MsQuic
{
internal sealed class MsQuicStream : QuicStreamProvider
{
// Delegate that wraps the static function that will be called when receiving an event.
internal static readonly StreamCallbackDelegate s_streamDelegate = new StreamCallbackDelegate(NativeCallbackHandler);
// The state is passed to msquic and then it's passed back by msquic to the callback handler.
private readonly State _state = new State();
private readonly bool _canRead;
private readonly bool _canWrite;
// Backing for StreamId
private long _streamId = -1;
private int _disposed;
private sealed class State
{
public SafeMsQuicStreamHandle Handle = null!; // set in ctor.
// Roots the state in GC and it won't get collected while this exist.
// It must be kept alive until we receive SHUTDOWN_COMPLETE event
public GCHandle StateGCHandle;
public MsQuicStream? Stream; // roots the stream in the pinned state to prevent GC during an async read I/O.
public MsQuicConnection.State ConnectionState = null!; // set in ctor.
public string TraceId = null!; // set in ctor.
public ReadState ReadState;
// set when ReadState.Aborted:
public long ReadErrorCode = -1;
// filled when ReadState.BuffersAvailable:
public QuicBuffer[] ReceiveQuicBuffers = Array.Empty<QuicBuffer>();
public int ReceiveQuicBuffersCount;
public int ReceiveQuicBuffersTotalBytes;
// set when ReadState.PendingRead:
public Memory<byte> ReceiveUserBuffer;
public CancellationTokenRegistration ReceiveCancellationRegistration;
// Resettable completions to be used for multiple calls to receive.
public readonly ResettableCompletionSource<int> ReceiveResettableCompletionSource = new ResettableCompletionSource<int>();
public SendState SendState;
public long SendErrorCode = -1;
// Buffers to hold during a call to send.
public MemoryHandle[] BufferArrays = new MemoryHandle[1];
public IntPtr SendQuicBuffers;
public int SendBufferMaxCount;
public int SendBufferCount;
// Resettable completions to be used for multiple calls to send.
public readonly ResettableCompletionSource<uint> SendResettableCompletionSource = new ResettableCompletionSource<uint>();
public ShutdownWriteState ShutdownWriteState;
// Set once writes have been shutdown.
public readonly TaskCompletionSource ShutdownWriteCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
public ShutdownState ShutdownState;
// The value makes sure that we release the handles only once.
public int ShutdownDone;
// Set once stream have been shutdown.
public readonly TaskCompletionSource ShutdownCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
public void Cleanup()
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"{TraceId} releasing handles.");
ShutdownState = ShutdownState.Finished;
CleanupSendState(this);
Handle?.Dispose();
Marshal.FreeHGlobal(SendQuicBuffers);
SendQuicBuffers = IntPtr.Zero;
if (StateGCHandle.IsAllocated) StateGCHandle.Free();
ConnectionState?.RemoveStream(null);
}
}
internal string TraceId() => _state.TraceId;
// inbound.
internal MsQuicStream(MsQuicConnection.State connectionState, SafeMsQuicStreamHandle streamHandle, QUIC_STREAM_OPEN_FLAGS flags)
{
_state.Handle = streamHandle;
_canRead = true;
_canWrite = !flags.HasFlag(QUIC_STREAM_OPEN_FLAGS.UNIDIRECTIONAL);
if (!_canWrite)
{
_state.SendState = SendState.Closed;
}
_state.StateGCHandle = GCHandle.Alloc(_state);
try
{
MsQuicApi.Api.SetCallbackHandlerDelegate(
_state.Handle,
s_streamDelegate,
GCHandle.ToIntPtr(_state.StateGCHandle));
}
catch
{
_state.StateGCHandle.Free();
throw;
}
if (!connectionState.TryAddStream(this))
{
_state.StateGCHandle.Free();
throw new ObjectDisposedException(nameof(QuicConnection));
}
_state.ConnectionState = connectionState;
_state.TraceId = MsQuicTraceHelper.GetTraceId(_state.Handle);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(
_state,
$"{TraceId()} Inbound {(flags.HasFlag(QUIC_STREAM_OPEN_FLAGS.UNIDIRECTIONAL) ? "uni" : "bi")}directional stream created " +
$"in connection {_state.ConnectionState.TraceId}.");
}
}
// outbound.
internal MsQuicStream(MsQuicConnection.State connectionState, QUIC_STREAM_OPEN_FLAGS flags)
{
Debug.Assert(connectionState.Handle != null);
_canRead = !flags.HasFlag(QUIC_STREAM_OPEN_FLAGS.UNIDIRECTIONAL);
_canWrite = true;
_state.StateGCHandle = GCHandle.Alloc(_state);
if (!_canRead)
{
_state.ReadState = ReadState.Closed;
}
try
{
uint status = MsQuicApi.Api.StreamOpenDelegate(
connectionState.Handle,
flags,
s_streamDelegate,
GCHandle.ToIntPtr(_state.StateGCHandle),
out _state.Handle);
QuicExceptionHelpers.ThrowIfFailed(status, "Failed to open stream to peer.");
status = MsQuicApi.Api.StreamStartDelegate(_state.Handle, QUIC_STREAM_START_FLAGS.FAIL_BLOCKED);
QuicExceptionHelpers.ThrowIfFailed(status, "Could not start stream.");
}
catch
{
_state.Handle?.Dispose();
_state.StateGCHandle.Free();
throw;
}
if (!connectionState.TryAddStream(this))
{
_state.Handle?.Dispose();
_state.StateGCHandle.Free();
throw new ObjectDisposedException(nameof(QuicConnection));
}
_state.ConnectionState = connectionState;
_state.TraceId = MsQuicTraceHelper.GetTraceId(_state.Handle);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(
_state,
$"{_state.TraceId} Outbound {(flags.HasFlag(QUIC_STREAM_OPEN_FLAGS.UNIDIRECTIONAL) ? "uni" : "bi")}directional stream created " +
$"in connection {_state.ConnectionState.TraceId}.");
}
}
internal override bool CanRead => _disposed == 0 && _canRead;
internal override bool CanWrite => _disposed == 0 && _canWrite;
internal override long StreamId
{
get
{
ThrowIfDisposed();
if (_streamId == -1)
{
_streamId = GetStreamId();
}
return _streamId;
}
}
internal override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
return WriteAsync(buffer, endStream: false, cancellationToken);
}
internal override ValueTask WriteAsync(ReadOnlySequence<byte> buffers, CancellationToken cancellationToken = default)
{
return WriteAsync(buffers, endStream: false, cancellationToken);
}
internal override async ValueTask WriteAsync(ReadOnlySequence<byte> buffers, bool endStream, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using CancellationTokenRegistration registration = HandleWriteStartState(cancellationToken);
await SendReadOnlySequenceAsync(buffers, endStream ? QUIC_SEND_FLAGS.FIN : QUIC_SEND_FLAGS.NONE).ConfigureAwait(false);
HandleWriteCompletedState();
}
internal override ValueTask WriteAsync(ReadOnlyMemory<ReadOnlyMemory<byte>> buffers, CancellationToken cancellationToken = default)
{
return WriteAsync(buffers, endStream: false, cancellationToken);
}
internal override async ValueTask WriteAsync(ReadOnlyMemory<ReadOnlyMemory<byte>> buffers, bool endStream, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using CancellationTokenRegistration registration = HandleWriteStartState(cancellationToken);
await SendReadOnlyMemoryListAsync(buffers, endStream ? QUIC_SEND_FLAGS.FIN : QUIC_SEND_FLAGS.NONE).ConfigureAwait(false);
HandleWriteCompletedState();
}
internal override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, bool endStream, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
using CancellationTokenRegistration registration = HandleWriteStartState(cancellationToken);
await SendReadOnlyMemoryAsync(buffer, endStream ? QUIC_SEND_FLAGS.FIN : QUIC_SEND_FLAGS.NONE).ConfigureAwait(false);
HandleWriteCompletedState();
}
private CancellationTokenRegistration HandleWriteStartState(CancellationToken cancellationToken)
{
if (_state.SendState == SendState.Closed)
{
throw new InvalidOperationException(SR.net_quic_writing_notallowed);
}
else if ( _state.SendState == SendState.Aborted)
{
if (_state.SendErrorCode != -1)
{
throw new QuicStreamAbortedException(_state.SendErrorCode);
}
throw new OperationCanceledException(cancellationToken);
}
if (cancellationToken.IsCancellationRequested)
{
lock (_state)
{
if (_state.SendState == SendState.None || _state.SendState == SendState.Pending)
{
_state.SendState = SendState.Aborted;
}
}
throw new OperationCanceledException(cancellationToken);
}
// if token was already cancelled, this would execute synchronously
CancellationTokenRegistration registration = cancellationToken.UnsafeRegister(static (s, token) =>
{
var state = (State)s!;
bool shouldComplete = false;
lock (state)
{
if (state.SendState == SendState.None || state.SendState == SendState.Pending)
{
state.SendState = SendState.Aborted;
shouldComplete = true;
}
}
if (shouldComplete)
{
state.SendResettableCompletionSource.CompleteException(
ExceptionDispatchInfo.SetCurrentStackTrace(new OperationCanceledException("Write was canceled", token)));
}
}, _state);
lock (_state)
{
if (_state.SendState == SendState.Aborted)
{
cancellationToken.ThrowIfCancellationRequested();
if (_state.SendErrorCode != -1)
{
throw new QuicStreamAbortedException(_state.SendErrorCode);
}
throw new OperationCanceledException(SR.net_quic_sending_aborted);
}
else if (_state.SendState == SendState.ConnectionClosed)
{
throw GetConnectionAbortedException(_state);
}
}
return registration;
}
private void HandleWriteCompletedState()
{
lock (_state)
{
if (_state.SendState == SendState.Finished)
{
_state.SendState = SendState.None;
}
}
}
private void HandleWriteFailedState()
{
lock (_state)
{
if (_state.SendState == SendState.Pending)
{
_state.SendState = SendState.Finished;
}
}
}
internal override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
if (_state.ReadState == ReadState.Closed)
{
throw new InvalidOperationException(SR.net_quic_reading_notallowed);
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(_state, $"{TraceId()} Stream reading into Memory of '{destination.Length}' bytes.");
}
ReadState initialReadState; // value before transitions
long abortError;
bool preCanceled = false;
lock (_state)
{
initialReadState = _state.ReadState;
abortError = _state.ReadErrorCode;
// Failure scenario: pre-canceled token. Transition: any -> Aborted
// PendingRead state indicates there is another concurrent read operation in flight
// which is forbidden, so it is handled separately
if (initialReadState != ReadState.PendingRead && cancellationToken.IsCancellationRequested)
{
initialReadState = ReadState.Aborted;
_state.ReadState = ReadState.Aborted;
preCanceled = true;
}
// Success scenario: EOS already reached, completing synchronously. No transition (final state)
if (initialReadState == ReadState.ReadsCompleted)
{
return new ValueTask<int>(0);
}
// Success scenario: no data available yet, will return a task to wait on. Transition None->PendingRead
if (initialReadState == ReadState.None)
{
Debug.Assert(_state.Stream is null);
_state.ReceiveUserBuffer = destination;
_state.Stream = this;
_state.ReadState = ReadState.PendingRead;
if (cancellationToken.CanBeCanceled)
{
_state.ReceiveCancellationRegistration = cancellationToken.UnsafeRegister(static (obj, token) =>
{
var state = (State)obj!;
bool completePendingRead;
lock (state)
{
completePendingRead = state.ReadState == ReadState.PendingRead;
state.Stream = null;
state.ReceiveUserBuffer = null;
state.ReadState = ReadState.Aborted;
}
if (completePendingRead)
{
state.ReceiveResettableCompletionSource.CompleteException(ExceptionDispatchInfo.SetCurrentStackTrace(new OperationCanceledException(token)));
}
}, _state);
}
else
{
_state.ReceiveCancellationRegistration = default;
}
return _state.ReceiveResettableCompletionSource.GetValueTask();
}
// Success scenario: data already available, completing synchronously. Transition IndividualReadComplete->None
if (initialReadState == ReadState.IndividualReadComplete)
{
_state.ReadState = ReadState.None;
int taken = CopyMsQuicBuffersToUserBuffer(_state.ReceiveQuicBuffers.AsSpan(0, _state.ReceiveQuicBuffersCount), destination.Span);
ReceiveComplete(taken);
if (taken != _state.ReceiveQuicBuffersTotalBytes)
{
// Need to re-enable receives because MsQuic will pause them when we don't consume the entire buffer.
EnableReceive();
}
return new ValueTask<int>(taken);
}
}
// All success scenarios returned at this point. Failure scenarios below:
Exception? ex = null;
switch (initialReadState)
{
case ReadState.PendingRead:
ex = new InvalidOperationException("Only one read is supported at a time.");
break;
case ReadState.Aborted:
ex = preCanceled ? new OperationCanceledException(cancellationToken) :
ThrowHelper.GetStreamAbortedException(abortError);
break;
case ReadState.ConnectionClosed:
default:
Debug.Assert(initialReadState == ReadState.ConnectionClosed, $"{nameof(ReadState)} of '{initialReadState}' is unaccounted for in {nameof(ReadAsync)}.");
ex = GetConnectionAbortedException(_state);
break;
}
return ValueTask.FromException<int>(ExceptionDispatchInfo.SetCurrentStackTrace(ex!));
}
/// <returns>The number of bytes copied.</returns>
private static unsafe int CopyMsQuicBuffersToUserBuffer(ReadOnlySpan<QuicBuffer> sourceBuffers, Span<byte> destinationBuffer)
{
Debug.Assert(sourceBuffers.Length != 0);
int originalDestinationLength = destinationBuffer.Length;
QuicBuffer nativeBuffer;
int takeLength = 0;
int i = 0;
do
{
nativeBuffer = sourceBuffers[i];
takeLength = Math.Min((int)nativeBuffer.Length, destinationBuffer.Length);
new Span<byte>(nativeBuffer.Buffer, takeLength).CopyTo(destinationBuffer);
destinationBuffer = destinationBuffer.Slice(takeLength);
}
while (destinationBuffer.Length != 0 && ++i < sourceBuffers.Length);
return originalDestinationLength - destinationBuffer.Length;
}
internal override void AbortRead(long errorCode)
{
ThrowIfDisposed();
bool shouldComplete = false;
lock (_state)
{
if (_state.ReadState == ReadState.PendingRead)
{
shouldComplete = true;
_state.Stream = null;
_state.ReceiveUserBuffer = null;
}
if (_state.ReadState < ReadState.ReadsCompleted)
{
_state.ReadState = ReadState.Aborted;
}
}
if (shouldComplete)
{
_state.ReceiveResettableCompletionSource.CompleteException(
ExceptionDispatchInfo.SetCurrentStackTrace(new QuicOperationAbortedException("Read was aborted")));
}
StartShutdown(QUIC_STREAM_SHUTDOWN_FLAGS.ABORT_RECEIVE, errorCode);
}
internal override void AbortWrite(long errorCode)
{
ThrowIfDisposed();
bool shouldComplete = false;
lock (_state)
{
if (_state.SendState < SendState.Aborted)
{
_state.SendState = SendState.Aborted;
}
if (_state.ShutdownWriteState == ShutdownWriteState.None)
{
_state.ShutdownWriteState = ShutdownWriteState.Canceled;
shouldComplete = true;
}
}
if (shouldComplete)
{
_state.ShutdownWriteCompletionSource.SetException(
ExceptionDispatchInfo.SetCurrentStackTrace(new QuicStreamAbortedException("Shutdown was aborted.", errorCode)));
}
StartShutdown(QUIC_STREAM_SHUTDOWN_FLAGS.ABORT_SEND, errorCode);
}
private void StartShutdown(QUIC_STREAM_SHUTDOWN_FLAGS flags, long errorCode)
{
uint status = MsQuicApi.Api.StreamShutdownDelegate(_state.Handle, flags, errorCode);
QuicExceptionHelpers.ThrowIfFailed(status, "StreamShutdown failed.");
}
internal override async ValueTask ShutdownWriteCompleted(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
lock (_state)
{
if (_state.ShutdownWriteState == ShutdownWriteState.ConnectionClosed)
{
throw GetConnectionAbortedException(_state);
}
}
// TODO do anything to stop writes?
using CancellationTokenRegistration registration = cancellationToken.UnsafeRegister(static (s, token) =>
{
var state = (State)s!;
bool shouldComplete = false;
lock (state)
{
if (state.ShutdownWriteState == ShutdownWriteState.None)
{
state.ShutdownWriteState = ShutdownWriteState.Canceled; // TODO: should we separate states for cancelling here vs calling Abort?
shouldComplete = true;
}
}
if (shouldComplete)
{
state.ShutdownWriteCompletionSource.SetException(
ExceptionDispatchInfo.SetCurrentStackTrace(new OperationCanceledException("Wait for shutdown write was canceled", token)));
}
}, _state);
await _state.ShutdownWriteCompletionSource.Task.ConfigureAwait(false);
}
internal override async ValueTask ShutdownCompleted(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
lock (_state)
{
if (_state.ShutdownState == ShutdownState.ConnectionClosed)
{
throw GetConnectionAbortedException(_state);
}
}
// TODO do anything to stop writes?
using CancellationTokenRegistration registration = cancellationToken.UnsafeRegister(static (s, token) =>
{
var state = (State)s!;
bool shouldComplete = false;
lock (state)
{
if (state.ShutdownState == ShutdownState.None)
{
state.ShutdownState = ShutdownState.Canceled;
shouldComplete = true;
}
}
if (shouldComplete)
{
state.ShutdownWriteCompletionSource.SetException(
ExceptionDispatchInfo.SetCurrentStackTrace(new OperationCanceledException("Wait for shutdown was canceled", token)));
}
}, _state);
await _state.ShutdownCompletionSource.Task.ConfigureAwait(false);
}
internal override void Shutdown()
{
ThrowIfDisposed();
lock (_state)
{
_state.SendState = SendState.Finished;
}
// it is ok to send shutdown several times, MsQuic will ignore it
StartShutdown(QUIC_STREAM_SHUTDOWN_FLAGS.GRACEFUL, errorCode: 0);
}
// TODO consider removing sync-over-async with blocking calls.
internal override int Read(Span<byte> buffer)
{
ThrowIfDisposed();
byte[] rentedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
int readLength = ReadAsync(new Memory<byte>(rentedBuffer, 0, buffer.Length)).AsTask().GetAwaiter().GetResult();
rentedBuffer.AsSpan(0, readLength).CopyTo(buffer);
return readLength;
}
finally
{
ArrayPool<byte>.Shared.Return(rentedBuffer);
}
}
internal override void Write(ReadOnlySpan<byte> buffer)
{
ThrowIfDisposed();
// TODO: optimize this.
WriteAsync(buffer.ToArray()).AsTask().GetAwaiter().GetResult();
}
// MsQuic doesn't support explicit flushing
internal override void Flush()
{
ThrowIfDisposed();
}
// MsQuic doesn't support explicit flushing
internal override Task FlushAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
return Task.CompletedTask;
}
public override ValueTask DisposeAsync()
{
// TODO: perform a graceful shutdown and wait for completion?
Dispose(true);
return default;
}
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MsQuicStream()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
int disposed = Interlocked.Exchange(ref _disposed, 1);
if (disposed != 0)
{
return;
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(_state, $"{TraceId()} Stream disposing {disposing}");
bool callShutdown = false;
bool abortRead = false;
bool releaseHandles = false;
lock (_state)
{
if (_state.SendState < SendState.Aborted)
{
callShutdown = true;
}
if (_state.ReadState < ReadState.ReadsCompleted)
{
abortRead = true;
_state.ReadState = ReadState.Aborted;
}
if (_state.ShutdownState == ShutdownState.None)
{
_state.ShutdownState = ShutdownState.Pending;
}
// Check if we already got final event.
releaseHandles = Interlocked.Exchange(ref _state.ShutdownDone, 1) == 2;
if (releaseHandles)
{
_state.ShutdownState = ShutdownState.Finished;
}
}
if (callShutdown)
{
try
{
// Handle race condition when stream can be closed handling SHUTDOWN_COMPLETE.
StartShutdown(QUIC_STREAM_SHUTDOWN_FLAGS.GRACEFUL, errorCode: 0);
} catch (ObjectDisposedException) { };
}
if (abortRead)
{
try
{
StartShutdown(QUIC_STREAM_SHUTDOWN_FLAGS.ABORT_RECEIVE, 0xffffffff);
} catch (ObjectDisposedException) { };
}
if (releaseHandles)
{
_state.Cleanup();
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(_state, $"{TraceId()} Stream disposed");
}
private void EnableReceive()
{
uint status = MsQuicApi.Api.StreamReceiveSetEnabledDelegate(_state.Handle, enabled: true);
QuicExceptionHelpers.ThrowIfFailed(status, "StreamReceiveSetEnabled failed.");
}
/// <summary>
/// Callback calls for a single instance of a stream are serialized by msquic.
/// They happen on a msquic thread and shouldn't take too long to not to block msquic.
/// </summary>
private static uint NativeCallbackHandler(
IntPtr stream,
IntPtr context,
ref StreamEvent streamEvent)
{
GCHandle gcHandle = GCHandle.FromIntPtr(context);
Debug.Assert(gcHandle.IsAllocated);
Debug.Assert(gcHandle.Target is not null);
var state = (State)gcHandle.Target;
return HandleEvent(state, ref streamEvent);
}
private static uint HandleEvent(State state, ref StreamEvent evt)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Info(state, $"{state.TraceId} Stream received event {evt.Type}");
}
try
{
switch (evt.Type)
{
// Stream has started.
// Will only be done for outbound streams (inbound streams have already started)
case QUIC_STREAM_EVENT_TYPE.START_COMPLETE:
return HandleEventStartComplete(state, ref evt);
// Received data on the stream
case QUIC_STREAM_EVENT_TYPE.RECEIVE:
return HandleEventRecv(state, ref evt);
// Send has completed.
// Contains a canceled bool to indicate if the send was canceled.
case QUIC_STREAM_EVENT_TYPE.SEND_COMPLETE:
return HandleEventSendComplete(state, ref evt);
// Peer has told us to shutdown the reading side of the stream.
case QUIC_STREAM_EVENT_TYPE.PEER_SEND_SHUTDOWN:
return HandleEventPeerSendShutdown(state);
// Peer has told us to abort the reading side of the stream.
case QUIC_STREAM_EVENT_TYPE.PEER_SEND_ABORTED:
return HandleEventPeerSendAborted(state, ref evt);
// Peer has stopped receiving data, don't send anymore.
case QUIC_STREAM_EVENT_TYPE.PEER_RECEIVE_ABORTED:
return HandleEventPeerRecvAborted(state, ref evt);
// Occurs when shutdown is completed for the send side.
// This only happens for shutdown on sending, not receiving
// Receive shutdown can only be abortive.
case QUIC_STREAM_EVENT_TYPE.SEND_SHUTDOWN_COMPLETE:
return HandleEventSendShutdownComplete(state, ref evt);
// Shutdown for both sending and receiving is completed.
case QUIC_STREAM_EVENT_TYPE.SHUTDOWN_COMPLETE:
return HandleEventShutdownComplete(state, ref evt);
default:
return MsQuicStatusCodes.Success;
}
}
catch (Exception ex)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Error(state, $"{state.TraceId} Exception occurred during handling Stream {evt.Type} event: {ex}");
}
Debug.Fail($"{state.TraceId} Exception occurred during handling Stream {evt.Type} event: {ex}");
return MsQuicStatusCodes.InternalError;
}
}
private static unsafe uint HandleEventRecv(State state, ref StreamEvent evt)
{
ref StreamEventDataReceive receiveEvent = ref evt.Data.Receive;
if (receiveEvent.BufferCount == 0)
{
// This is a 0-length receive that happens once reads are finished (via abort or otherwise).
// State changes for this are handled in PEER_SEND_SHUTDOWN / PEER_SEND_ABORT / SHUTDOWN_COMPLETE event handlers.
return MsQuicStatusCodes.Success;
}
int readLength;
bool shouldComplete = false;
lock (state)
{
switch (state.ReadState)
{
case ReadState.None:
// ReadAsync() hasn't been called yet. Stash the buffer so the next ReadAsync call completes synchronously.
// We are overwriting state.ReceiveQuicBuffers here even if we only partially consumed them
// and it is intended, because unconsumed data will arrive again from the point we've stopped.
// New RECEIVE event wouldn't come until we call EnableReceive(), and we call it only after we've consumed
// as much as we could and said so to msquic in ReceiveComplete(taken), so new event will have all the
// remaining data.
if ((uint)state.ReceiveQuicBuffers.Length < receiveEvent.BufferCount)
{
QuicBuffer[] oldReceiveBuffers = state.ReceiveQuicBuffers;
state.ReceiveQuicBuffers = ArrayPool<QuicBuffer>.Shared.Rent((int)receiveEvent.BufferCount);
if (oldReceiveBuffers.Length != 0) // don't return Array.Empty.
{
ArrayPool<QuicBuffer>.Shared.Return(oldReceiveBuffers);
}
}
for (uint i = 0; i < receiveEvent.BufferCount; ++i)
{
state.ReceiveQuicBuffers[i] = receiveEvent.Buffers[i];
}
state.ReceiveQuicBuffersCount = (int)receiveEvent.BufferCount;
state.ReceiveQuicBuffersTotalBytes = checked((int)receiveEvent.TotalBufferLength);
state.ReadState = ReadState.IndividualReadComplete;
return MsQuicStatusCodes.Pending;
case ReadState.PendingRead:
// There is a pending ReadAsync().
state.ReceiveCancellationRegistration.Unregister();
shouldComplete = true;
state.Stream = null;
state.ReadState = ReadState.None;
readLength = CopyMsQuicBuffersToUserBuffer(new ReadOnlySpan<QuicBuffer>(receiveEvent.Buffers, (int)receiveEvent.BufferCount), state.ReceiveUserBuffer.Span);
state.ReceiveUserBuffer = null;
break;
default:
Debug.Assert(state.ReadState is ReadState.Aborted or ReadState.ConnectionClosed, $"Unexpected {nameof(ReadState)} '{state.ReadState}' in {nameof(HandleEventRecv)}.");
// There was a race between a user aborting the read stream and the callback being ran.
// This will eat any received data.
return MsQuicStatusCodes.Success;
}
}
// We're completing a pending read.
if (shouldComplete)
{
state.ReceiveResettableCompletionSource.Complete(readLength);
}
// Returning Success when the entire buffer hasn't been consumed will cause MsQuic to disable further receive events until EnableReceive() is called.
// Returning Continue will cause a second receive event to fire immediately after this returns, but allows MsQuic to clean up its buffers.
uint ret = (uint)readLength == receiveEvent.TotalBufferLength
? MsQuicStatusCodes.Success
: MsQuicStatusCodes.Continue;
receiveEvent.TotalBufferLength = (uint)readLength;
return ret;
}
private static uint HandleEventPeerRecvAborted(State state, ref StreamEvent evt)
{
bool shouldComplete = false;
lock (state)
{
if (state.SendState == SendState.None || state.SendState == SendState.Pending)
{
shouldComplete = true;
}
state.SendState = SendState.Aborted;
state.SendErrorCode = (long)evt.Data.PeerSendAborted.ErrorCode;
}
if (shouldComplete)
{
state.SendResettableCompletionSource.CompleteException(
ExceptionDispatchInfo.SetCurrentStackTrace(new QuicStreamAbortedException(state.SendErrorCode)));
}
return MsQuicStatusCodes.Success;
}
private static uint HandleEventStartComplete(State state, ref StreamEvent evt)
{
// TODO: We should probably check for a failure as indicated by the event data (or at least assert no failure if we aren't expecting it).
// However, since there is no definition for START_COMPLETE event data currently, we can't do this right now.
return MsQuicStatusCodes.Success;
}
private static uint HandleEventSendShutdownComplete(State state, ref StreamEvent evt)
{
bool shouldComplete = false;
lock (state)
{
if (state.ShutdownWriteState == ShutdownWriteState.None)
{
state.ShutdownWriteState = ShutdownWriteState.Finished;
shouldComplete = true;
}
}
if (shouldComplete)
{
state.ShutdownWriteCompletionSource.SetResult();
}
return MsQuicStatusCodes.Success;
}
private static uint HandleEventShutdownComplete(State state, ref StreamEvent evt)
{
StreamEventDataShutdownComplete shutdownCompleteEvent = evt.Data.ShutdownComplete;
if (shutdownCompleteEvent.ConnectionShutdown != 0)
{
return HandleEventConnectionClose(state);
}
bool shouldReadComplete = false;
bool shouldShutdownWriteComplete = false;
bool shouldShutdownComplete = false;
lock (state)
{
// This event won't occur within the middle of a receive.
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(state, $"{state.TraceId} Stream completing resettable event source.");