-
Notifications
You must be signed in to change notification settings - Fork 533
Expand file tree
/
Copy pathDispatcher.cs
More file actions
1285 lines (1157 loc) · 54.5 KB
/
Dispatcher.cs
File metadata and controls
1285 lines (1157 loc) · 54.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Documents.Rntbd
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure.Cosmos.Core.Trace;
using Microsoft.Azure.Documents.FaultInjection;
#if COSMOSCLIENT
using Microsoft.Azure.Cosmos.Rntbd;
#endif
#if NETSTANDARD15 || NETSTANDARD16
using Trace = Microsoft.Azure.Documents.Trace;
#endif
// Dispatcher encapsulates the state and logic needed to dispatch multiple requests through
// a single connection.
internal sealed class Dispatcher : IDisposable
{
// Connection is thread-safe for sending.
// Receiving is done only from the receive loop.
// Initialization and disposal are not thread safe. Guard these
// operations with connectionLock.
private readonly IConnection connection;
private readonly UserAgentContainer userAgent;
private readonly Uri serverUri;
private readonly IConnectionStateListener connectionStateListener;
// All individual operations on CancellationTokenSource are thread safe.
// When examining IsCancellationRequested in order to decide whether to cancel,
// guard the operation with connectionLock.
private readonly CancellationTokenSource cancellation = new CancellationTokenSource();
private readonly TimerPool idleTimerPool;
private readonly bool enableChannelMultiplexing;
private readonly Action<string, Exception> clientCertificateFailureHandler;
private bool disposed = false;
private ServerProperties serverProperties = null;
private int nextRequestId = 0;
// Acquire after connectionLock.
private readonly object callLock = new object();
private Task receiveTask = null; // Guarded by callLock.
// Guarded by callLock.
private readonly Dictionary<uint, CallInfo> calls = new Dictionary<uint, CallInfo>();
private readonly bool shouldRequestMutualTls = false;
// Guarded by callLock.
// The call map can become frozen if the underlying connection becomes
// unusable. This can happen if initialization fails, either the send
// stream or the receive stream are broken, the receive loop fails etc.
private bool callsAllowed = true;
// lock used to guard underlying tcp connection state, which is a state level higher than callLock
// Acquire before callLock
private readonly object connectionLock = new object();
private PooledTimer idleTimer; // Guarded by connectionLock
private Task idleTimerTask; // Guarded by connectionLock
private readonly IChaosInterceptor chaosInterceptor;
private TransportException faultInjectionTransportException;
private bool isFaultInjectionedConnectionError;
public Guid ConnectionCorrelationId { get => this.connection.ConnectionCorrelationId; }
public Dispatcher(
Uri serverUri,
UserAgentContainer userAgent,
IConnectionStateListener connectionStateListener,
string hostNameCertificateOverride,
TimeSpan receiveHangDetectionTime,
TimeSpan sendHangDetectionTime,
TimerPool idleTimerPool,
TimeSpan idleTimeout,
bool enableChannelMultiplexing,
MemoryStreamPool memoryStreamPool,
RemoteCertificateValidationCallback remoteCertificateValidationCallback,
Func<string, X509Certificate2> clientCertificateFunction,
Action<string, Exception> clientCertificateFailureHandler,
Func<string, Task<IPAddress>> dnsResolutionFunction,
IChaosInterceptor chaosInterceptor)
{
this.connection = new Connection(
serverUri, hostNameCertificateOverride,
receiveHangDetectionTime, sendHangDetectionTime,
idleTimeout,
memoryStreamPool,
remoteCertificateValidationCallback,
clientCertificateFunction,
dnsResolutionFunction);
this.userAgent = userAgent;
this.connectionStateListener = connectionStateListener;
this.serverUri = serverUri;
this.idleTimerPool = idleTimerPool;
this.enableChannelMultiplexing = enableChannelMultiplexing;
this.chaosInterceptor = chaosInterceptor;
this.clientCertificateFailureHandler = clientCertificateFailureHandler;
this.shouldRequestMutualTls = clientCertificateFunction != null;
}
internal Dispatcher(
Uri serverUri,
UserAgentContainer userAgent,
IConnectionStateListener connectionStateListener,
TimerPool idleTimerPool,
bool enableChannelMultiplexing,
IChaosInterceptor chaosInterceptor,
IConnection connection)
{
this.connection = connection ?? throw new ArgumentNullException(nameof(connection));
this.userAgent = userAgent;
this.connectionStateListener = connectionStateListener;
this.serverUri = serverUri;
this.idleTimerPool = idleTimerPool;
this.enableChannelMultiplexing = enableChannelMultiplexing;
this.chaosInterceptor = chaosInterceptor;
}
#region Test hook.
internal event Action TestOnConnectionClosed;
internal bool TestIsIdle
{
get
{
lock (this.connectionLock)
{
if (this.connection.Disposed)
{
return true;
}
TimeSpan ignoredTimeToIdle;
return !this.connection.IsActive(out ignoredTimeToIdle);
}
}
}
#endregion
public bool Healthy
{
get
{
this.ThrowIfDisposed();
if (this.cancellation.IsCancellationRequested)
{
return false;
}
Debug.Assert(!Monitor.IsEntered(this.callLock));
lock (this.callLock)
{
if (!this.callsAllowed)
{
return false;
}
}
bool healthy;
try
{
healthy = this.connection.Healthy;
}
catch (ObjectDisposedException)
{
// Connection.Healthy shouldn't be called while the connection is being disposed, or after.
// To avoid additional locking, handle the exception here and store the outcome.
DefaultTrace.TraceWarning(
"[RNTBD Dispatcher {0}] {1} ObjectDisposedException from Connection.Healthy",
this.ConnectionCorrelationId, this);
healthy = false;
}
if (healthy)
{
return true;
}
Debug.Assert(!Monitor.IsEntered(this.callLock));
lock (this.callLock)
{
this.callsAllowed = false;
}
return false;
}
}
public async Task OpenAsync(ChannelOpenArguments args)
{
this.ThrowIfDisposed();
try
{
Debug.Assert(this.connection != null);
await this.connection.OpenAsync(args);
await this.NegotiateRntbdContextAsync(args);
Debug.Assert(!Monitor.IsEntered(this.callLock));
lock (this.callLock)
{
Debug.Assert(this.receiveTask == null);
// The background receive loop and its failure continuation
// task should use a task scheduler internal to the Cosmos DB
// client. In any case, they should avoid using the current
// task scheduler, because some components use task schedulers
// for accounting, others to control and suspend task execution.
// In these cases, it does not make sense for the current
// accounting entity to get charged for the background receive
// loop in perpetuity, and there's a risk the task might get
// suspended and never resumed.
this.receiveTask = Task.Factory.StartNew(
async delegate
{
await this.ReceiveLoopAsync();
},
this.cancellation.Token,
TaskCreationOptions.LongRunning |
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default).Unwrap();
_ = this.receiveTask.ContinueWith(completedTask =>
{
Debug.Assert(completedTask.IsFaulted);
Debug.Assert(this.serverUri != null);
Debug.Assert(completedTask.Exception != null);
DefaultTrace.TraceWarning(
"[RNTBD Dispatcher {0}] Dispatcher.ReceiveLoopAsync failed. Consuming the task " +
"exception asynchronously. Dispatcher: {1}. Exception: {2}",
this.ConnectionCorrelationId, this, completedTask.Exception?.InnerException?.Message);
},
default(CancellationToken),
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.Default);
}
if (this.idleTimerPool != null)
{
// idle timeout is enabled
this.StartIdleTimer();
}
}
catch (DocumentClientException)
{
this.DisallowInitialCalls();
throw;
}
catch (TransportException)
{
this.DisallowInitialCalls();
throw;
}
}
public void InjectFaultInjectionConnectionError(TransportException transportException)
{
if (!this.disposed)
{
this.isFaultInjectionedConnectionError = true;
this.faultInjectionTransportException = transportException;
}
}
public sealed class PrepareCallResult : IDisposable
{
private bool disposed = false;
public PrepareCallResult(uint requestId, Uri uri, TransportSerialization.SerializedRequest serializedRequest)
{
this.RequestId = requestId;
this.Uri = uri;
this.SerializedRequest = serializedRequest;
}
public uint RequestId { get; private set; }
public TransportSerialization.SerializedRequest SerializedRequest { get; }
public Uri Uri { get; private set; }
/// <inheritdoc />
public void Dispose()
{
if (!this.disposed)
{
this.SerializedRequest.Dispose();
this.disposed = true;
}
}
}
// PrepareCall assigns a request ID to the request, serializes it, and
// returns the result. The caller must treat PrepareCallResult as an
// opaque handle.
public PrepareCallResult PrepareCall(DocumentServiceRequest request,
TransportAddressUri physicalAddress,
ResourceOperation resourceOperation,
Guid activityId,
TransportRequestStats transportRequestStats)
{
uint requestId = unchecked((uint) Interlocked.Increment(ref this.nextRequestId));
string requestIdString = requestId.ToString(CultureInfo.InvariantCulture);
int headerSize;
int? bodySize;
TransportSerialization.SerializedRequest serializedRequest = TransportSerialization.BuildRequest(
request,
physicalAddress.PathAndQuery,
resourceOperation,
activityId,
this.connection.BufferProvider,
requestIdString,
out headerSize,
out bodySize);
transportRequestStats.RequestBodySizeInBytes = bodySize;
transportRequestStats.RequestSizeInBytes = serializedRequest.RequestSize;
return new PrepareCallResult(requestId, physicalAddress.Uri, serializedRequest);
}
public async Task<StoreResponse> CallAsync(ChannelCallArguments args, TransportRequestStats transportRequestStats)
{
this.ThrowIfDisposed();
// The current task scheduler must be used for correctness and to
// track per tenant physical charges for the compute gateway.
using (CallInfo callInfo = new CallInfo(
this.ConnectionCorrelationId,
args.CommonArguments.ActivityId,
args.PreparedCall.Uri,
TaskScheduler.Current,
transportRequestStats))
{
uint requestId = args.PreparedCall.RequestId;
Debug.Assert(!Monitor.IsEntered(this.callLock));
lock (this.callLock)
{
transportRequestStats.NumberOfInflightRequestsInConnection = this.calls.Count;
if (!this.callsAllowed)
{
Debug.Assert(args.CommonArguments.UserPayload);
throw new TransportException(
TransportErrorCode.ChannelMultiplexerClosed, null,
args.CommonArguments.ActivityId, args.PreparedCall.Uri,
this.ToString(), args.CommonArguments.UserPayload,
args.CommonArguments.PayloadSent);
}
this.calls.Add(requestId, callInfo);
}
try
{
try
{
if (this.chaosInterceptor != null)
{
await this.chaosInterceptor.OnBeforeConnectionWriteAsync(args);
(bool isFaulted, StoreResponse faultyResponse) = await this.chaosInterceptor.OnRequestCallAsync(args);
if (isFaulted)
{
transportRequestStats.RecordState(TransportRequestStats.RequestStage.Sent);
return faultyResponse;
}
}
await this.connection.WriteRequestAsync(
args.CommonArguments,
args.PreparedCall.SerializedRequest,
transportRequestStats);
transportRequestStats.RecordState(TransportRequestStats.RequestStage.Sent);
if (this.chaosInterceptor != null)
{
await this.chaosInterceptor.OnAfterConnectionWriteAsync(args);
}
}
catch (Exception e)
{
callInfo.SendFailed();
throw new TransportException(
TransportErrorCode.SendFailed, e,
args.CommonArguments.ActivityId, args.PreparedCall.Uri,
this.ToString(), args.CommonArguments.UserPayload,
args.CommonArguments.PayloadSent);
}
// Do not add any code after the end of the previous block.
// Anything that needs to execute before ReadResponseAsync must
// be in the try block, so that no exceptions are missed.
return await callInfo.ReadResponseAsync(args);
}
catch (DocumentClientException)
{
this.DisallowRuntimeCalls();
throw;
}
catch (TransportException)
{
this.DisallowRuntimeCalls();
throw;
}
finally
{
this.RemoveCall(requestId);
}
}
}
/// <summary>
/// Cancels a Rntbd call and notifies the connection by incrementing the transit timeout counters.
/// </summary>
/// <param name="preparedCall">An instance of <see cref="PrepareCallResult"/> containing the call result.</param>
/// <param name="isReadOnly">A boolean flag indicating if the request is read only.</param>
public void CancelCallAndNotifyConnectionOnTimeoutEvent(
PrepareCallResult preparedCall,
bool isReadOnly)
{
this.ThrowIfDisposed();
this.connection.NotifyConnectionStatus(
isCompleted: false,
isReadRequest: isReadOnly);
CallInfo call = this.RemoveCall(preparedCall.RequestId);
if (call != null)
{
call.Cancel();
}
}
/// <summary>
/// Notifies the connection on a successful event, by resetting the transit timeout counters.
/// </summary>
public void NotifyConnectionOnSuccessEvent()
{
this.ThrowIfDisposed();
this.connection.NotifyConnectionStatus(
isCompleted: true);
}
public override string ToString()
{
return this.connection.ToString();
}
public void Dispose()
{
this.ThrowIfDisposed();
this.disposed = true;
DefaultTrace.TraceInformation("[RNTBD Dispatcher {0}] Disposing RNTBD Dispatcher {1}", this.ConnectionCorrelationId, this);
Task idleTimerTaskCopy = null;
Debug.Assert(!Monitor.IsEntered(this.connectionLock));
lock (this.connectionLock)
{
this.StartConnectionShutdown();
idleTimerTaskCopy = this.StopIdleTimer();
}
this.WaitTask(idleTimerTaskCopy, "idle timer");
Task receiveTaskCopy = null;
Debug.Assert(!Monitor.IsEntered(this.connectionLock));
lock (this.connectionLock)
{
Debug.Assert(this.idleTimer == null);
Debug.Assert(this.idleTimerTask == null);
receiveTaskCopy = this.CloseConnection();
}
this.WaitTask(receiveTaskCopy, "receive loop");
DefaultTrace.TraceInformation("[RNTBD Dispatcher {0}] RNTBD Dispatcher {1} is disposed", this.ConnectionCorrelationId, this);
}
private void StartIdleTimer()
{
DefaultTrace.TraceInformation("[RNTBD Dispatcher {0}] RNTBD idle connection monitor: Timer is starting...", this.ConnectionCorrelationId);
TimeSpan timeToIdle = TimeSpan.MinValue;
bool scheduled = false;
try
{
Debug.Assert(!Monitor.IsEntered(this.connectionLock));
lock (this.connectionLock)
{
bool active = this.connection.IsActive(out timeToIdle);
Debug.Assert(active);
if (!active)
{
// This would be rather unexpected.
DefaultTrace.TraceCritical("[RNTBD Dispatcher {0}][{1}] New connection already idle.", this.ConnectionCorrelationId, this);
return;
}
this.ScheduleIdleTimer(timeToIdle);
scheduled = true;
}
}
finally
{
if (scheduled)
{
DefaultTrace.TraceInformation(
"[RNTBD Dispatcher {0}] RNTBD idle connection monitor {1}: Timer is scheduled to fire {2} seconds later at {3}.",
this.ConnectionCorrelationId, this, timeToIdle.TotalSeconds, DateTime.UtcNow + timeToIdle);
}
else
{
DefaultTrace.TraceInformation("[RNTBD Dispatcher {0}] RNTBD idle connection monitor {1}: Timer is not scheduled.", this.ConnectionCorrelationId, this);
}
}
}
private async Task OnIdleTimerAsync(Task precedentTask)
{
DefaultTrace.TraceInformation(
"[RNTBD Dispatcher {0}][{1}] Idle timer fired.",
this.ConnectionCorrelationId, this);
Task receiveTaskCopy = null;
Debug.Assert(!Monitor.IsEntered(this.connectionLock));
lock (this.connectionLock)
{
if (this.cancellation.IsCancellationRequested)
{
return;
}
Debug.Assert(!this.connection.Disposed);
TimeSpan timeToIdle;
bool active = this.connection.IsActive(out timeToIdle);
if (active)
{
this.ScheduleIdleTimer(timeToIdle);
return;
}
Debug.Assert(!Monitor.IsEntered(this.callLock));
lock (this.callLock)
{
if (this.calls.Count > 0)
{
DefaultTrace.TraceCritical(
"[RNTBD Dispatcher {0}][{1}] Looks idle but still has {2} pending requests",
this.ConnectionCorrelationId, this, this.calls.Count);
active = true;
}
else
{
this.callsAllowed = false;
}
}
if (active)
{
this.ScheduleIdleTimer(timeToIdle);
return;
}
this.idleTimer = null;
this.idleTimerTask = null;
this.StartConnectionShutdown();
receiveTaskCopy = this.CloseConnection();
}
await this.WaitTaskAsync(receiveTaskCopy, "receive loop")
.ConfigureAwait(false);
}
// this.connectionLock must be held.
private void ScheduleIdleTimer(TimeSpan timeToIdle)
{
Debug.Assert(Monitor.IsEntered(this.connectionLock));
this.idleTimer = this.idleTimerPool.GetPooledTimer((int)timeToIdle.TotalSeconds);
// IMPORTANT: .Unwrap() is essential here. Without it, idleTimerTask
// would be Task<Task> and would complete when OnIdleTimerAsync
// returns its inner Task (at the first await), not when it
// finishes. StopIdleTimer() waits on idleTimerTask during
// shutdown; if idleTimerTask completes early, shutdown proceeds
// while OnIdleTimerAsync is still running, causing
// use-after-dispose on the connection. Do not remove .Unwrap().
this.idleTimerTask = this.idleTimer.StartTimerAsync()
.ContinueWith(this.OnIdleTimerAsync, TaskContinuationOptions.OnlyOnRanToCompletion)
.Unwrap();
this.idleTimerTask.ContinueWith(
failedTask =>
{
DefaultTrace.TraceWarning(
"[RNTBD Dispatcher {0}][{1}] Idle timer callback failed: {2}",
this.ConnectionCorrelationId, this, failedTask.Exception?.InnerException?.Message);
},
TaskContinuationOptions.OnlyOnFaulted);
}
// this.connectionLock must be held.
private void StartConnectionShutdown()
{
Debug.Assert(Monitor.IsEntered(this.connectionLock));
if (this.cancellation.IsCancellationRequested)
{
return;
}
try
{
Debug.Assert(!Monitor.IsEntered(this.callLock));
lock (this.callLock)
{
this.callsAllowed = false;
}
this.cancellation.Cancel();
}
catch (AggregateException e)
{
DefaultTrace.TraceWarning(
"[RNTBD Dispatcher {0}][{1}] Registered cancellation callbacks failed: {2}",
this.ConnectionCorrelationId, this, e.Message);
// Deliberately ignoring the exception.
}
}
// this.connectionLock must be held.
private Task StopIdleTimer()
{
Task idleTimerTaskCopy = null;
Debug.Assert(Monitor.IsEntered(this.connectionLock));
if (this.idleTimer != null)
{
if (this.idleTimer.CancelTimer())
{
// Dispose() won the race and the timer was cancelled.
this.idleTimer = null;
this.idleTimerTask = null;
}
else
{
idleTimerTaskCopy = this.idleTimerTask;
}
}
return idleTimerTaskCopy;
}
// this.connectionLock must be held.
private Task CloseConnection()
{
Task receiveTaskCopy = null;
Debug.Assert(Monitor.IsEntered(this.connectionLock));
if (!this.connection.Disposed)
{
Debug.Assert(!Monitor.IsEntered(this.callLock));
lock (this.callLock)
{
receiveTaskCopy = this.receiveTask;
}
this.connection.Dispose();
this.TestOnConnectionClosed?.Invoke();
}
return receiveTaskCopy;
}
private void WaitTask(Task t, string description)
{
if (t == null)
{
return;
}
try
{
// Don't hold locks while blocking this thread
Debug.Assert(!Monitor.IsEntered(this.callLock));
Debug.Assert(!Monitor.IsEntered(this.connectionLock));
t.Wait();
}
catch (Exception e)
{
DefaultTrace.TraceWarning(
"[RNTBD Dispatcher {0}][{1}] Parallel task failed: {2}. Exception: {3}",
this.ConnectionCorrelationId, this, description, e.Message);
// Intentionally swallowing the exception. The caller can't
// do anything useful with it.
}
}
private async Task WaitTaskAsync(Task t, string description)
{
if (t == null)
{
return;
}
try
{
Debug.Assert(!Monitor.IsEntered(this.callLock));
Debug.Assert(!Monitor.IsEntered(this.connectionLock));
await t.ConfigureAwait(false);
}
catch (Exception e)
{
DefaultTrace.TraceWarning(
"[RNTBD Dispatcher {0}][{1}] Parallel task failed: {2}. " +
"Exception: {3}: {4}",
this.ConnectionCorrelationId, this, description,
e.GetType().Name, e.Message);
// Intentionally swallowing the exception. The caller can't
// do anything useful with it.
}
}
private void ThrowIfDisposed()
{
if (this.disposed)
{
Debug.Assert(this.serverUri != null);
throw new ObjectDisposedException(
string.Format("{0}:{1}", nameof(Dispatcher), this.serverUri));
}
}
private async Task NegotiateRntbdContextAsync(ChannelOpenArguments args)
{
byte[] contextMessage = TransportSerialization.BuildContextRequest(
args.CommonArguments.ActivityId,
this.userAgent,
args.CallerId,
this.enableChannelMultiplexing,
mutualTlsAuthMode: this.shouldRequestMutualTls ? RntbdConstants.RntbdMutualTlsAuthMode.System : null);
await this.connection.WriteRequestAsync(
args.CommonArguments,
new TransportSerialization.SerializedRequest(new BufferProvider.DisposableBuffer(contextMessage), requestBody: null),
transportRequestStats: null);
// Read the response.
using Connection.ResponseMetadata responseMd =
await this.connection.ReadResponseMetadataAsync(args.CommonArguments);
// Full header and metadata are read now. Parse out more fields and handle them.
StatusCodes status = (StatusCodes) BitConverter.ToUInt32(responseMd.Header.Array, 4);
byte[] responseActivityIdBytes = new byte[16];
Buffer.BlockCopy(responseMd.Header.Array, 8, responseActivityIdBytes, 0, 16);
// Server should just be echoing back the ActivityId from the connection request, but retrieve it
// from the wire and use it from here on, to be absolutely certain we have the same ActivityId
// the server is using
Guid activityId = new Guid(responseActivityIdBytes);
Trace.CorrelationManager.ActivityId = activityId;
BytesDeserializer deserializer = new BytesDeserializer(responseMd.Metadata.Array, responseMd.Metadata.Count);
RntbdConstants.ConnectionContextResponse response = new RntbdConstants.ConnectionContextResponse();
response.ParseFrom(ref deserializer);
string serverAgent = BytesSerializer.GetStringFromBytes(response.serverAgent.value.valueBytes);
string serverVersion = BytesSerializer.GetStringFromBytes(response.serverVersion.value.valueBytes);
Debug.Assert(this.serverProperties == null);
this.serverProperties = new ServerProperties(serverAgent, serverVersion);
if ((UInt32)status < 200 || (UInt32)status >= 400)
{
Debug.Assert(args.CommonArguments.UserPayload == false);
using (MemoryStream errorResponseStream = await this.connection.ReadResponseBodyAsync(
new ChannelCommonArguments(activityId,
TransportErrorCode.TransportNegotiationTimeout,
args.CommonArguments.UserPayload)))
{
Error error = Resource.LoadFrom<Error>(errorResponseStream);
// DEVNOTE: This exception can be sent to the user via the clientCertificateFailureHandler callback.
DocumentClientException exception = new DocumentClientException(
string.Format(CultureInfo.CurrentUICulture,
RMResources.ExceptionMessage,
error.ToString()),
null,
(HttpStatusCode)status,
this.connection.ServerUri);
if (response.clientVersion.isPresent)
{
exception.Headers.Add("RequiredClientVersion",
BytesSerializer.GetStringFromBytes(response.clientVersion.value.valueBytes));
}
if (response.protocolVersion.isPresent)
{
exception.Headers.Add("RequiredProtocolVersion",
response.protocolVersion.value.valueULong.ToString());
}
if (response.serverAgent.isPresent)
{
exception.Headers.Add("ServerAgent",
BytesSerializer.GetStringFromBytes(response.serverAgent.value.valueBytes));
}
if (response.serverVersion.isPresent)
{
exception.Headers.Add(
HttpConstants.HttpHeaders.ServerVersion,
BytesSerializer.GetStringFromBytes(response.serverVersion.value.valueBytes));
}
bool isMutualTlsAuthFailure = false;
if (response.mutualTlsAuthThumbprint.isPresent)
{
exception.Headers.Add(HttpConstants.HttpHeaders.MutualTlsThumbprint,
BytesSerializer.GetStringFromBytes(response.mutualTlsAuthThumbprint.value.valueBytes));
exception.Headers.Add(HttpConstants.HttpHeaders.MutualTlsStatus,
HttpConstants.HttpHeaderValues.MutualTlsAuthFailed);
isMutualTlsAuthFailure = true;
}
// DEVNOTE: Do not modify the exception after this point, as it may affect the mutual TLS auth failure handler.
if (isMutualTlsAuthFailure)
{
this.clientCertificateFailureHandler?.Invoke(
exception.Headers.Get(HttpConstants.HttpHeaders.MutualTlsThumbprint),
exception);
}
throw exception;
}
}
// Even on successful requests, we want to handle Mutual TLS auth failures.
// This is because while we are in dual mode (certificate + token as fallback),
// the server may indicate that the certificate auth failed, but requests can still succeed with the auth token.
// In the future, once Mutual TLS auth is the only auth method, this can be removed as a cert failure will be a 401.
if (response.mutualTlsAuthThumbprint.isPresent)
{
this.clientCertificateFailureHandler?.Invoke(
BytesSerializer.GetStringFromBytes(response.mutualTlsAuthThumbprint.value.valueBytes),
null);
}
this.NotifyConnectionOnSuccessEvent();
args.OpenTimeline.RecordRntbdHandshakeFinishTime();
}
private async Task ReceiveLoopAsync()
{
CancellationToken cancellationToken = this.cancellation.Token;
ChannelCommonArguments args = new ChannelCommonArguments(
Guid.Empty, TransportErrorCode.ReceiveTimeout, true);
Connection.ResponseMetadata responseMd = null;
try
{
bool hasTransportErrors = false;
while (!hasTransportErrors && !cancellationToken.IsCancellationRequested)
{
if (this.isFaultInjectionedConnectionError)
{
hasTransportErrors = true;
throw this.faultInjectionTransportException;
}
args.ActivityId = Guid.Empty;
responseMd = await this.connection.ReadResponseMetadataAsync(args);
ArraySegment<byte> metadata = responseMd.Metadata;
TransportSerialization.RntbdHeader header =
TransportSerialization.DecodeRntbdHeader(responseMd.Header.Array);
args.ActivityId = header.ActivityId;
BytesDeserializer deserializer = new BytesDeserializer(metadata.Array, metadata.Count);
MemoryStream bodyStream = null;
if (HeadersTransportSerialization.TryParseMandatoryResponseHeaders(ref deserializer, out bool payloadPresent, out uint transportRequestId))
{
if (payloadPresent)
{
bodyStream = await this.connection.ReadResponseBodyAsync(args);
}
this.DispatchRntbdResponse(responseMd, header, bodyStream, metadata.Array, metadata.Count, transportRequestId);
}
else
{
hasTransportErrors = true;
this.DispatchChannelFailureException(TransportExceptions.GetInternalServerErrorException(this.serverUri, RMResources.MissingRequiredHeader));
}
responseMd = null;
}
this.DispatchCancellation();
}
catch (OperationCanceledException)
{
responseMd?.Dispose();
this.DispatchCancellation();
}
catch (ObjectDisposedException)
{
responseMd?.Dispose();
this.DispatchCancellation();
}
catch (Exception e)
{
responseMd?.Dispose();
this.DispatchChannelFailureException(e);
}
#if DEBUG
lock (this.callLock)
{
Debug.Assert(!this.callsAllowed);
Debug.Assert(this.calls.Count == 0);
}
#endif
}
private Dictionary<uint, CallInfo> StopCalls()
{
Dictionary<uint, CallInfo> clonedCalls;
Debug.Assert(!Monitor.IsEntered(this.callLock));
lock (this.callLock)
{
clonedCalls = new Dictionary<uint, CallInfo>(this.calls);
this.calls.Clear();
this.callsAllowed = false;
}
return clonedCalls;
}
private void DispatchRntbdResponse(
Connection.ResponseMetadata responseMd,
TransportSerialization.RntbdHeader responseHeader,
MemoryStream responseBody,
byte[] metadata,
int metadataLength,
uint transportRequestId)
{
CallInfo call = this.RemoveCall(transportRequestId);
if (call != null)
{
Debug.Assert(this.serverProperties != null);
Debug.Assert(this.serverProperties.Version != null);
call.TransportRequestStats.RecordState(TransportRequestStats.RequestStage.Received);
call.TransportRequestStats.ResponseMetadataSizeInBytes = responseMd.Metadata.Count;
call.TransportRequestStats.ResponseBodySizeInBytes = responseBody?.Length;
call.SetResponse(responseMd, responseHeader, responseBody, this.serverProperties.Version, metadata, metadataLength);
}
else
{
responseBody?.Dispose();
responseMd.Dispose();
}
}
private void DispatchChannelFailureException(Exception ex)
{
Dictionary<uint, CallInfo> clonedCalls = this.StopCalls();
foreach (KeyValuePair<uint, CallInfo> entry in clonedCalls)
{
CallInfo call = entry.Value;
Debug.Assert(call != null);
call.SetConnectionBrokenException(ex, this.ToString());
}
// If there are no pending calls on this channel and a subscriber is interested
// in connection events, examine the exception and raise the event appropriately.
if ((clonedCalls.Count > 0) || (this.connectionStateListener == null))
{
// If any calls are pending, the event is unnecessary because callers will get
// TransportException. If this.connectionStateListener is null, the point is moot.
return;
}
TransportException transportException = ex as TransportException;
if (transportException == null)
{
// The client transport stack catches SocketException and IOException and wraps them
// in TransportException as appropriate. Other exception types may also be thrown.
// In some cases, it may be reasonable to catch those exceptions and wrap them in
// TransportException.
// In other cases, it may be reasonable to handle additional exception types here.
DefaultTrace.TraceWarning(
"[RNTBD Dispatcher {0}] Not a TransportException. Will not raise the connection state change event: {1}",
this.ConnectionCorrelationId, ex?.Message);
return;
}
// Copy a bunch of values locally to avoid capturing the this pointer.
ConnectionEvent connectionEvent;
switch (transportException.ErrorCode)
{
case TransportErrorCode.ReceiveStreamClosed:
connectionEvent = ConnectionEvent.ReadEof;
break;
case TransportErrorCode.ReceiveFailed:
connectionEvent = ConnectionEvent.ReadFailure;