-
Notifications
You must be signed in to change notification settings - Fork 494
/
DocumentClient.cs
7103 lines (6542 loc) · 392 KB
/
DocumentClient.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) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using global::Azure.Core;
using Microsoft.Azure.Cosmos.Common;
using Microsoft.Azure.Cosmos.Core.Trace;
using Microsoft.Azure.Cosmos.Handler;
using Microsoft.Azure.Cosmos.Query;
using Microsoft.Azure.Cosmos.Query.Core.QueryPlan;
using Microsoft.Azure.Cosmos.Routing;
using Microsoft.Azure.Cosmos.Telemetry;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Cosmos.Tracing.TraceData;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Collections;
using Microsoft.Azure.Documents.Routing;
using Newtonsoft.Json;
/// <summary>
/// Provides a client-side logical representation for the Azure Cosmos DB service.
/// This client is used to configure and execute requests against the service.
/// </summary>
/// <threadSafety>
/// This type is thread safe.
/// </threadSafety>
/// <remarks>
/// The service client that encapsulates the endpoint and credentials and connection policy used to access the Azure Cosmos DB service.
/// It is recommended to cache and reuse this instance within your application rather than creating a new instance for every operation.
///
/// <para>
/// When your app uses DocumentClient, you should call its IDisposable.Dispose implementation when you are finished using it.
/// Depending on your programming technique, you can do this in one of two ways:
/// </para>
///
/// <para>
/// 1. By using a language construct such as the using statement in C#.
/// The using statement is actually a syntactic convenience.
/// At compile time, the language compiler implements the intermediate language (IL) for a try/catch block.
/// <code language="c#">
/// <![CDATA[
/// using (IDocumentClient client = new DocumentClient(new Uri("endpoint"), "authKey"))
/// {
/// ...
/// }
/// ]]>
/// </code>
/// </para>
///
/// <para>
/// 2. By wrapping the call to the IDisposable.Dispose implementation in a try/catch block.
/// The following example replaces the using block in the previous example with a try/catch/finally block.
/// <code language="c#">
/// <![CDATA[
/// IDocumentClient client = new DocumentClient(new Uri("endpoint"), "authKey"))
/// try{
/// ...
/// }
/// finally{
/// if (client != null) client.Dispose();
/// }
/// ]]>
/// </code>
/// </para>
///
/// </remarks>
internal partial class DocumentClient : IDisposable, IAuthorizationTokenProvider, ICosmosAuthorizationTokenProvider, IDocumentClient, IDocumentClientInternal
{
private const string AllowOverrideStrongerConsistency = "AllowOverrideStrongerConsistency";
private const string MaxConcurrentConnectionOpenConfig = "MaxConcurrentConnectionOpenRequests";
private const string IdleConnectionTimeoutInSecondsConfig = "IdleConnectionTimeoutInSecondsConfig";
private const string OpenConnectionTimeoutInSecondsConfig = "OpenConnectionTimeoutInSecondsConfig";
private const string TransportTimerPoolGranularityInSecondsConfig = "TransportTimerPoolGranularityInSecondsConfig";
private const string EnableTcpChannelConfig = "CosmosDbEnableTcpChannel";
private const string MaxRequestsPerChannelConfig = "CosmosDbMaxRequestsPerTcpChannel";
private const string TcpPartitionCount = "CosmosDbTcpPartitionCount";
private const string MaxChannelsPerHostConfig = "CosmosDbMaxTcpChannelsPerHost";
private const string RntbdPortReuseMode = "CosmosDbTcpPortReusePolicy";
private const string RntbdPortPoolReuseThreshold = "CosmosDbTcpPortReuseThreshold";
private const string RntbdPortPoolBindAttempts = "CosmosDbTcpPortReuseBindAttempts";
private const string RntbdReceiveHangDetectionTimeConfig = "CosmosDbTcpReceiveHangDetectionTimeSeconds";
private const string RntbdSendHangDetectionTimeConfig = "CosmosDbTcpSendHangDetectionTimeSeconds";
private const string EnableCpuMonitorConfig = "CosmosDbEnableCpuMonitor";
// Env variable
private const string RntbdMaxConcurrentOpeningConnectionCountConfig = "AZURE_COSMOS_TCP_MAX_CONCURRENT_OPENING_CONNECTION_COUNT";
private const int MaxConcurrentConnectionOpenRequestsPerProcessor = 25;
private const int DefaultMaxRequestsPerRntbdChannel = 30;
private const int DefaultRntbdPartitionCount = 1;
private const int DefaultMaxRntbdChannelsPerHost = ushort.MaxValue;
private const PortReuseMode DefaultRntbdPortReuseMode = PortReuseMode.ReuseUnicastPort;
private const int DefaultRntbdPortPoolReuseThreshold = 256;
private const int DefaultRntbdPortPoolBindAttempts = 5;
private const int DefaultRntbdReceiveHangDetectionTimeSeconds = 65;
private const int DefaultRntbdSendHangDetectionTimeSeconds = 10;
private const bool DefaultEnableCpuMonitor = true;
private const string DefaultInitTaskKey = "InitTaskKey";
private readonly bool IsLocalQuorumConsistency = false;
private readonly bool isReplicaAddressValidationEnabled;
//Auth
internal readonly AuthorizationTokenProvider cosmosAuthorization;
// Gateway has backoff/retry logic to hide transient errors.
private RetryPolicy retryPolicy;
private bool allowOverrideStrongerConsistency = false;
private int maxConcurrentConnectionOpenRequests = Environment.ProcessorCount * MaxConcurrentConnectionOpenRequestsPerProcessor;
private int openConnectionTimeoutInSeconds = 5;
private int idleConnectionTimeoutInSeconds = -1;
private int timerPoolGranularityInSeconds = 1;
private bool enableRntbdChannel = true;
private int maxRequestsPerRntbdChannel = DefaultMaxRequestsPerRntbdChannel;
private int rntbdPartitionCount = DefaultRntbdPartitionCount;
private int maxRntbdChannels = DefaultMaxRntbdChannelsPerHost;
private PortReuseMode rntbdPortReuseMode = DefaultRntbdPortReuseMode;
private int rntbdPortPoolReuseThreshold = DefaultRntbdPortPoolReuseThreshold;
private int rntbdPortPoolBindAttempts = DefaultRntbdPortPoolBindAttempts;
private int rntbdReceiveHangDetectionTimeSeconds = DefaultRntbdReceiveHangDetectionTimeSeconds;
private int rntbdSendHangDetectionTimeSeconds = DefaultRntbdSendHangDetectionTimeSeconds;
private bool enableCpuMonitor = DefaultEnableCpuMonitor;
private int rntbdMaxConcurrentOpeningConnectionCount = 5;
private string clientId;
//Consistency
private Documents.ConsistencyLevel? desiredConsistencyLevel;
internal CosmosAccountServiceConfiguration accountServiceConfiguration { get; private set; }
internal TelemetryToServiceHelper telemetryToServiceHelper { get; set; }
private ClientCollectionCache collectionCache;
private PartitionKeyRangeCache partitionKeyRangeCache;
//Private state.
private bool isSuccessfullyInitialized;
private bool isDisposed;
// creator of TransportClient is responsible for disposing it.
private IStoreClientFactory storeClientFactory;
internal CosmosHttpClient httpClient { get; private set; }
// Flag that indicates whether store client factory must be disposed whenever client is disposed.
// Setting this flag to false will result in store client factory not being disposed when client is disposed.
// This flag is used to allow shared store client factory survive disposition of a document client while other clients continue using it.
private bool isStoreClientFactoryCreatedInternally;
//Id counter.
private static int idCounter;
//Trace Id.
private int traceId;
//RemoteCertificateValidationCallback
internal RemoteCertificateValidationCallback remoteCertificateValidationCallback;
//Distributed Tracing Flag
internal CosmosClientTelemetryOptions cosmosClientTelemetryOptions;
//SessionContainer.
internal ISessionContainer sessionContainer;
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private AsyncLazy<QueryPartitionProvider> queryPartitionProvider;
private DocumentClientEventSource eventSource;
private Func<bool, Task<bool>> initializeTaskFactory;
internal AsyncCacheNonBlocking<string, bool> initTaskCache;
private JsonSerializerSettings serializerSettings;
private event EventHandler<SendingRequestEventArgs> sendingRequest;
private event EventHandler<ReceivedResponseEventArgs> receivedResponse;
private Func<TransportClient, TransportClient> transportClientHandlerFactory;
/// <summary>
/// Initializes a new instance of the <see cref="DocumentClient"/> class using the
/// specified Azure Cosmos DB service endpoint, key, and connection policy for the Azure Cosmos DB service.
/// </summary>
/// <param name="serviceEndpoint">
/// The service endpoint to use to create the client.
/// </param>
/// <param name="authKey">
/// The list of Permission objects to use to create the client.
/// </param>
/// <param name="connectionPolicy">
/// (Optional) The connection policy for the client. If none is passed, the default is used <see cref="ConnectionPolicy"/>
/// </param>
/// <param name="desiredConsistencyLevel">
/// (Optional) This can be used to weaken the database account consistency level for read operations.
/// If this is not set the database account consistency level will be used for all requests.
/// </param>
/// <remarks>
/// The service endpoint and the authorization key can be obtained from the Azure Management Portal.
/// The authKey used here is encrypted for privacy when being used, and deleted from computer memory when no longer needed
/// <para>
/// Using Direct connectivity, wherever possible, is recommended
/// </para>
/// </remarks>
/// <seealso cref="Uri"/>
/// <seealso cref="SecureString"/>
/// <seealso cref="ConnectionPolicy"/>
/// <seealso cref="ConsistencyLevel"/>
public DocumentClient(Uri serviceEndpoint,
SecureString authKey,
ConnectionPolicy connectionPolicy = null,
Documents.ConsistencyLevel? desiredConsistencyLevel = null)
{
if (authKey == null)
{
throw new ArgumentNullException("authKey");
}
if (authKey != null)
{
this.cosmosAuthorization = new AuthorizationTokenProviderMasterKey(authKey);
}
this.Initialize(serviceEndpoint, connectionPolicy, desiredConsistencyLevel);
this.initTaskCache = new AsyncCacheNonBlocking<string, bool>(cancellationToken: this.cancellationTokenSource.Token);
this.isReplicaAddressValidationEnabled = ConfigurationManager.IsReplicaAddressValidationEnabled(connectionPolicy);
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentClient"/> class using the
/// specified Azure Cosmos DB service endpoint, key, connection policy and a custom JsonSerializerSettings
/// for the Azure Cosmos DB service.
/// </summary>
/// <param name="serviceEndpoint">
/// The service endpoint to use to create the client.
/// </param>
/// <param name="authKey">
/// The list of Permission objects to use to create the client.
/// </param>
/// <param name="connectionPolicy">
/// The connection policy for the client.
/// </param>
/// <param name="desiredConsistencyLevel">
/// This can be used to weaken the database account consistency level for read operations.
/// If this is not set the database account consistency level will be used for all requests.
/// </param>
/// <param name="serializerSettings">
/// The custom JsonSerializer settings to be used for serialization/derialization.
/// </param>
/// <remarks>
/// The service endpoint and the authorization key can be obtained from the Azure Management Portal.
/// The authKey used here is encrypted for privacy when being used, and deleted from computer memory when no longer needed
/// <para>
/// Using Direct connectivity, wherever possible, is recommended
/// </para>
/// </remarks>
/// <seealso cref="Uri"/>
/// <seealso cref="SecureString"/>
/// <seealso cref="ConnectionPolicy"/>
/// <seealso cref="ConsistencyLevel"/>
/// <seealso cref="JsonSerializerSettings"/>
[Obsolete("Please use the constructor that takes JsonSerializerSettings as the third parameter.")]
public DocumentClient(Uri serviceEndpoint,
SecureString authKey,
ConnectionPolicy connectionPolicy,
Documents.ConsistencyLevel? desiredConsistencyLevel,
JsonSerializerSettings serializerSettings)
: this(serviceEndpoint, authKey, connectionPolicy, desiredConsistencyLevel)
{
this.serializerSettings = serializerSettings;
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentClient"/> class using the
/// specified Azure Cosmos DB service endpoint, key, connection policy and a custom JsonSerializerSettings
/// for the Azure Cosmos DB service.
/// </summary>
/// <param name="serviceEndpoint">
/// The service endpoint to use to create the client.
/// </param>
/// <param name="authKey">
/// The list of Permission objects to use to create the client.
/// </param>
/// <param name="serializerSettings">
/// The custom JsonSerializer settings to be used for serialization/derialization.
/// </param>
/// <param name="connectionPolicy">
/// (Optional) The connection policy for the client. If none is passed, the default is used <see cref="ConnectionPolicy"/>
/// </param>
/// <param name="desiredConsistencyLevel">
/// (Optional) This can be used to weaken the database account consistency level for read operations.
/// If this is not set the database account consistency level will be used for all requests.
/// </param>
/// <remarks>
/// The service endpoint and the authorization key can be obtained from the Azure Management Portal.
/// The authKey used here is encrypted for privacy when being used, and deleted from computer memory when no longer needed
/// <para>
/// Using Direct connectivity, wherever possible, is recommended
/// </para>
/// </remarks>
/// <seealso cref="Uri"/>
/// <seealso cref="SecureString"/>
/// <seealso cref="JsonSerializerSettings"/>
/// <seealso cref="ConnectionPolicy"/>
/// <seealso cref="ConsistencyLevel"/>
public DocumentClient(Uri serviceEndpoint,
SecureString authKey,
JsonSerializerSettings serializerSettings,
ConnectionPolicy connectionPolicy = null,
Documents.ConsistencyLevel? desiredConsistencyLevel = null)
: this(serviceEndpoint, authKey, connectionPolicy, desiredConsistencyLevel)
{
this.serializerSettings = serializerSettings;
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentClient"/> class using the
/// specified service endpoint, an authorization key (or resource token) and a connection policy
/// for the Azure Cosmos DB service.
/// </summary>
/// <param name="serviceEndpoint">The service endpoint to use to create the client.</param>
/// <param name="authKeyOrResourceToken">The authorization key or resource token to use to create the client.</param>
/// <param name="connectionPolicy">(Optional) The connection policy for the client.</param>
/// <param name="desiredConsistencyLevel">(Optional) The default consistency policy for client operations.</param>
/// <remarks>
/// The service endpoint can be obtained from the Azure Management Portal.
/// If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
/// If however you are connecting as a specific Azure Cosmos DB User, the value passed to <paramref name="authKeyOrResourceToken"/> is the ResourceToken obtained from the permission feed for the user.
/// <para>
/// Using Direct connectivity, wherever possible, is recommended.
/// </para>
/// </remarks>
/// <seealso cref="Uri"/>
/// <seealso cref="ConnectionPolicy"/>
/// <seealso cref="ConsistencyLevel"/>
public DocumentClient(Uri serviceEndpoint,
string authKeyOrResourceToken,
ConnectionPolicy connectionPolicy = null,
Documents.ConsistencyLevel? desiredConsistencyLevel = null)
: this(serviceEndpoint, authKeyOrResourceToken, sendingRequestEventArgs: null, connectionPolicy: connectionPolicy, desiredConsistencyLevel: desiredConsistencyLevel)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentClient"/> class using the
/// specified service endpoint, an authorization key (or resource token) and a connection policy
/// for the Azure Cosmos DB service.
/// </summary>
/// <param name="serviceEndpoint">The service endpoint to use to create the client.</param>
/// <param name="authKeyOrResourceToken">The authorization key or resource token to use to create the client.</param>
/// <param name="handler">The HTTP handler stack to use for sending requests (e.g., HttpClientHandler).</param>
/// <param name="connectionPolicy">(Optional) The connection policy for the client.</param>
/// <param name="desiredConsistencyLevel">(Optional) The default consistency policy for client operations.</param>
/// <remarks>
/// The service endpoint can be obtained from the Azure Management Portal.
/// If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
/// If however you are connecting as a specific Azure Cosmos DB User, the value passed to <paramref name="authKeyOrResourceToken"/> is the ResourceToken obtained from the permission feed for the user.
/// <para>
/// Using Direct connectivity, wherever possible, is recommended.
/// </para>
/// </remarks>
/// <seealso cref="Uri"/>
/// <seealso cref="ConnectionPolicy"/>
/// <seealso cref="ConsistencyLevel"/>
public DocumentClient(Uri serviceEndpoint,
string authKeyOrResourceToken,
HttpMessageHandler handler,
ConnectionPolicy connectionPolicy = null,
Documents.ConsistencyLevel? desiredConsistencyLevel = null)
: this(serviceEndpoint, authKeyOrResourceToken, sendingRequestEventArgs: null, connectionPolicy: connectionPolicy, desiredConsistencyLevel: desiredConsistencyLevel, handler: handler)
{
}
internal DocumentClient(Uri serviceEndpoint,
string authKeyOrResourceToken,
EventHandler<SendingRequestEventArgs> sendingRequestEventArgs,
ConnectionPolicy connectionPolicy = null,
Documents.ConsistencyLevel? desiredConsistencyLevel = null,
JsonSerializerSettings serializerSettings = null,
ApiType apitype = ApiType.None,
EventHandler<ReceivedResponseEventArgs> receivedResponseEventArgs = null,
HttpMessageHandler handler = null,
ISessionContainer sessionContainer = null,
bool? enableCpuMonitor = null,
Func<TransportClient, TransportClient> transportClientHandlerFactory = null,
IStoreClientFactory storeClientFactory = null)
: this(serviceEndpoint,
AuthorizationTokenProvider.CreateWithResourceTokenOrAuthKey(authKeyOrResourceToken),
sendingRequestEventArgs,
connectionPolicy,
desiredConsistencyLevel,
serializerSettings,
apitype,
receivedResponseEventArgs,
handler,
sessionContainer,
enableCpuMonitor,
transportClientHandlerFactory,
storeClientFactory)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentClient"/> class using the
/// specified service endpoint, an authorization key (or resource token) and a connection policy
/// for the Azure Cosmos DB service.
/// </summary>
/// <param name="serviceEndpoint">The service endpoint to use to create the client.</param>
/// <param name="cosmosAuthorization">The cosmos authorization for the client.</param>
/// <param name="sendingRequestEventArgs"> The event handler to be invoked before the request is sent.</param>
/// <param name="receivedResponseEventArgs"> The event handler to be invoked after a response has been received.</param>
/// <param name="connectionPolicy">(Optional) The connection policy for the client.</param>
/// <param name="desiredConsistencyLevel">(Optional) The default consistency policy for client operations.</param>
/// <param name="serializerSettings">The custom JsonSerializer settings to be used for serialization/derialization.</param>
/// <param name="apitype">Api type for the account</param>
/// <param name="handler">The HTTP handler stack to use for sending requests (e.g., HttpClientHandler).</param>
/// <param name="sessionContainer">The default session container with which DocumentClient is created.</param>
/// <param name="enableCpuMonitor">Flag that indicates whether client-side CPU monitoring is enabled for improved troubleshooting.</param>
/// <param name="transportClientHandlerFactory">Transport client handler factory.</param>
/// <param name="storeClientFactory">Factory that creates store clients sharing the same transport client to optimize network resource reuse across multiple document clients in the same process.</param>
/// <param name="isLocalQuorumConsistency">Flag to allow Quorum Read with Eventual Consistency Account</param>
/// <param name="cosmosClientId"></param>
/// <param name="remoteCertificateValidationCallback">This delegate responsible for validating the third party certificate. </param>
/// <param name="cosmosClientTelemetryOptions">This is distributed tracing flag</param>
/// <remarks>
/// The service endpoint can be obtained from the Azure Management Portal.
/// If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
/// If however you are connecting as a specific Azure Cosmos DB User, the value passed to is the ResourceToken obtained from the permission feed for the user.
/// <para>
/// Using Direct connectivity, wherever possible, is recommended.
/// </para>
/// </remarks>
/// <seealso cref="Uri"/>
/// <seealso cref="ConnectionPolicy"/>
/// <seealso cref="ConsistencyLevel"/>
internal DocumentClient(Uri serviceEndpoint,
AuthorizationTokenProvider cosmosAuthorization,
EventHandler<SendingRequestEventArgs> sendingRequestEventArgs,
ConnectionPolicy connectionPolicy = null,
Documents.ConsistencyLevel? desiredConsistencyLevel = null,
JsonSerializerSettings serializerSettings = null,
ApiType apitype = ApiType.None,
EventHandler<ReceivedResponseEventArgs> receivedResponseEventArgs = null,
HttpMessageHandler handler = null,
ISessionContainer sessionContainer = null,
bool? enableCpuMonitor = null,
Func<TransportClient, TransportClient> transportClientHandlerFactory = null,
IStoreClientFactory storeClientFactory = null,
bool isLocalQuorumConsistency = false,
string cosmosClientId = null,
RemoteCertificateValidationCallback remoteCertificateValidationCallback = null,
CosmosClientTelemetryOptions cosmosClientTelemetryOptions = null)
{
if (sendingRequestEventArgs != null)
{
this.sendingRequest += sendingRequestEventArgs;
}
if (serializerSettings != null)
{
this.serializerSettings = serializerSettings;
}
this.ApiType = apitype;
if (receivedResponseEventArgs != null)
{
this.receivedResponse += receivedResponseEventArgs;
}
this.cosmosAuthorization = cosmosAuthorization ?? throw new ArgumentNullException(nameof(cosmosAuthorization));
this.transportClientHandlerFactory = transportClientHandlerFactory;
this.IsLocalQuorumConsistency = isLocalQuorumConsistency;
this.initTaskCache = new AsyncCacheNonBlocking<string, bool>(cancellationToken: this.cancellationTokenSource.Token);
this.Initialize(
serviceEndpoint: serviceEndpoint,
connectionPolicy: connectionPolicy,
desiredConsistencyLevel: desiredConsistencyLevel,
handler: handler,
sessionContainer: sessionContainer,
enableCpuMonitor: enableCpuMonitor,
storeClientFactory: storeClientFactory,
cosmosClientId: cosmosClientId,
remoteCertificateValidationCallback: remoteCertificateValidationCallback,
cosmosClientTelemetryOptions: cosmosClientTelemetryOptions);
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentClient"/> class using the
/// specified service endpoint, an authorization key (or resource token), a connection policy
/// and a custom JsonSerializerSettings for the Azure Cosmos DB service.
/// </summary>
/// <param name="serviceEndpoint">The service endpoint to use to create the client.</param>
/// <param name="authKeyOrResourceToken">The authorization key or resource token to use to create the client.</param>
/// <param name="connectionPolicy">The connection policy for the client.</param>
/// <param name="desiredConsistencyLevel">The default consistency policy for client operations.</param>
/// <param name="serializerSettings">The custom JsonSerializer settings to be used for serialization/derialization.</param>
/// <remarks>
/// The service endpoint can be obtained from the Azure Management Portal.
/// If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
/// If however you are connecting as a specific Azure Cosmos DB User, the value passed to <paramref name="authKeyOrResourceToken"/> is the ResourceToken obtained from the permission feed for the user.
/// <para>
/// Using Direct connectivity, wherever possible, is recommended.
/// </para>
/// </remarks>
/// <seealso cref="Uri"/>
/// <seealso cref="ConnectionPolicy"/>
/// <seealso cref="ConsistencyLevel"/>
/// <seealso cref="JsonSerializerSettings"/>
[Obsolete("Please use the constructor that takes JsonSerializerSettings as the third parameter.")]
public DocumentClient(Uri serviceEndpoint,
string authKeyOrResourceToken,
ConnectionPolicy connectionPolicy,
Documents.ConsistencyLevel? desiredConsistencyLevel,
JsonSerializerSettings serializerSettings)
: this(serviceEndpoint, authKeyOrResourceToken, (HttpMessageHandler)null, connectionPolicy, desiredConsistencyLevel)
{
this.serializerSettings = serializerSettings;
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentClient"/> class using the
/// specified service endpoint, an authorization key (or resource token), a connection policy
/// and a custom JsonSerializerSettings for the Azure Cosmos DB service.
/// </summary>
/// <param name="serviceEndpoint">The service endpoint to use to create the client.</param>
/// <param name="authKeyOrResourceToken">The authorization key or resource token to use to create the client.</param>
/// <param name="serializerSettings">The custom JsonSerializer settings to be used for serialization/derialization.</param>
/// <param name="connectionPolicy">(Optional) The connection policy for the client.</param>
/// <param name="desiredConsistencyLevel">(Optional) The default consistency policy for client operations.</param>
/// <remarks>
/// The service endpoint can be obtained from the Azure Management Portal.
/// If you are connecting using one of the Master Keys, these can be obtained along with the endpoint from the Azure Management Portal
/// If however you are connecting as a specific Azure Cosmos DB User, the value passed to <paramref name="authKeyOrResourceToken"/> is the ResourceToken obtained from the permission feed for the user.
/// <para>
/// Using Direct connectivity, wherever possible, is recommended.
/// </para>
/// </remarks>
/// <seealso cref="Uri"/>
/// <seealso cref="JsonSerializerSettings"/>
/// <seealso cref="ConnectionPolicy"/>
/// <seealso cref="ConsistencyLevel"/>
public DocumentClient(Uri serviceEndpoint,
string authKeyOrResourceToken,
JsonSerializerSettings serializerSettings,
ConnectionPolicy connectionPolicy = null,
Documents.ConsistencyLevel? desiredConsistencyLevel = null)
: this(serviceEndpoint, authKeyOrResourceToken, (HttpMessageHandler)null, connectionPolicy, desiredConsistencyLevel)
{
this.serializerSettings = serializerSettings;
}
/// <summary>
/// Internal constructor purely for unit-testing
/// </summary>
internal DocumentClient(Uri serviceEndpoint, ConnectionPolicy connectionPolicy)
{
// do nothing
this.ServiceEndpoint = serviceEndpoint;
this.ConnectionPolicy = connectionPolicy ?? new ConnectionPolicy();
}
internal virtual async Task<ClientCollectionCache> GetCollectionCacheAsync(ITrace trace)
{
using (ITrace childTrace = trace.StartChild("Get Collection Cache", TraceComponent.Routing, Tracing.TraceLevel.Info))
{
await this.EnsureValidClientAsync(childTrace);
return this.collectionCache;
}
}
internal virtual async Task<PartitionKeyRangeCache> GetPartitionKeyRangeCacheAsync(ITrace trace)
{
using (ITrace childTrace = trace.StartChild("Get Partition Key Range Cache", TraceComponent.Routing, Tracing.TraceLevel.Info))
{
await this.EnsureValidClientAsync(childTrace);
return this.partitionKeyRangeCache;
}
}
internal GlobalAddressResolver AddressResolver { get; private set; }
internal GlobalEndpointManager GlobalEndpointManager { get; private set; }
internal GlobalPartitionEndpointManager PartitionKeyRangeLocation { get; private set; }
/// <summary>
/// Open the connection to validate that the client initialization is successful in the Azure Cosmos DB service.
/// </summary>
/// <returns>
/// A <see cref="System.Threading.Tasks.Task"/> object.
/// </returns>
/// <remarks>
/// This method is recommended to be called, after the constructor, but before calling any other methods on the DocumentClient instance.
/// If there are any initialization exceptions, this method will throw them (set on the task).
/// Alternately, calling any API will throw initialization exception at the first call.
/// </remarks>
/// <example>
/// <code language="c#">
/// <![CDATA[
/// using (IDocumentClient client = new DocumentClient(new Uri("service endpoint"), "auth key"))
/// {
/// await client.OpenAsync();
/// }
/// ]]>
/// </code>
/// </example>
public Task OpenAsync(CancellationToken cancellationToken = default)
{
return TaskHelper.InlineIfPossibleAsync(() => this.OpenPrivateInlineAsync(cancellationToken), null, cancellationToken);
}
private async Task OpenPrivateInlineAsync(CancellationToken cancellationToken)
{
await this.EnsureValidClientAsync(NoOpTrace.Singleton);
await TaskHelper.InlineIfPossibleAsync(() => this.OpenPrivateAsync(cancellationToken), this.ResetSessionTokenRetryPolicy.GetRequestPolicy(), cancellationToken);
}
private async Task OpenPrivateAsync(CancellationToken cancellationToken)
{
// Initialize caches for all databases and collections
ResourceFeedReader<Documents.Database> databaseFeedReader = this.CreateDatabaseFeedReader(
new FeedOptions { MaxItemCount = -1 });
try
{
while (databaseFeedReader.HasMoreResults)
{
foreach (Documents.Database database in await databaseFeedReader.ExecuteNextAsync(cancellationToken))
{
ResourceFeedReader<DocumentCollection> collectionFeedReader = this.CreateDocumentCollectionFeedReader(
database.SelfLink,
new FeedOptions { MaxItemCount = -1 });
List<Task> tasks = new List<Task>();
while (collectionFeedReader.HasMoreResults)
{
tasks.AddRange((await collectionFeedReader.ExecuteNextAsync(cancellationToken)).Select(collection => this.InitializeCachesAsync(database.Id, collection, cancellationToken)));
}
await Task.WhenAll(tasks);
}
}
}
catch (DocumentClientException ex)
{
// Clear the caches to ensure that we don't have partial results
this.collectionCache = new ClientCollectionCache(
sessionContainer: this.sessionContainer,
storeModel: this.GatewayStoreModel,
tokenProvider: this,
retryPolicy: this.retryPolicy,
telemetryToServiceHelper: this.telemetryToServiceHelper);
this.partitionKeyRangeCache = new PartitionKeyRangeCache(this, this.GatewayStoreModel, this.collectionCache);
DefaultTrace.TraceWarning("{0} occurred while OpenAsync. Exception Message: {1}", ex.ToString(), ex.Message);
}
}
internal virtual void Initialize(Uri serviceEndpoint,
ConnectionPolicy connectionPolicy = null,
Documents.ConsistencyLevel? desiredConsistencyLevel = null,
HttpMessageHandler handler = null,
ISessionContainer sessionContainer = null,
bool? enableCpuMonitor = null,
IStoreClientFactory storeClientFactory = null,
TokenCredential tokenCredential = null,
string cosmosClientId = null,
RemoteCertificateValidationCallback remoteCertificateValidationCallback = null,
CosmosClientTelemetryOptions cosmosClientTelemetryOptions = null)
{
if (serviceEndpoint == null)
{
throw new ArgumentNullException("serviceEndpoint");
}
this.clientId = cosmosClientId;
this.remoteCertificateValidationCallback = remoteCertificateValidationCallback;
this.cosmosClientTelemetryOptions = cosmosClientTelemetryOptions ?? new CosmosClientTelemetryOptions();
this.queryPartitionProvider = new AsyncLazy<QueryPartitionProvider>(async () =>
{
await this.EnsureValidClientAsync(NoOpTrace.Singleton);
return new QueryPartitionProvider(this.accountServiceConfiguration.QueryEngineConfiguration);
}, CancellationToken.None);
#if !(NETSTANDARD15 || NETSTANDARD16)
#if NETSTANDARD20
// GetEntryAssembly returns null when loaded from native netstandard2.0
if (System.Reflection.Assembly.GetEntryAssembly() != null)
{
#endif
// For tests we want to allow stronger consistency during construction or per call
string allowOverrideStrongerConsistencyConfig = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.AllowOverrideStrongerConsistency];
if (!string.IsNullOrEmpty(allowOverrideStrongerConsistencyConfig))
{
if (!bool.TryParse(allowOverrideStrongerConsistencyConfig, out this.allowOverrideStrongerConsistency))
{
this.allowOverrideStrongerConsistency = false;
}
}
// We might want to override the defaults sometime
string maxConcurrentConnectionOpenRequestsOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.MaxConcurrentConnectionOpenConfig];
if (!string.IsNullOrEmpty(maxConcurrentConnectionOpenRequestsOverrideString))
{
int maxConcurrentConnectionOpenRequestOverrideInt = 0;
if (Int32.TryParse(maxConcurrentConnectionOpenRequestsOverrideString, out maxConcurrentConnectionOpenRequestOverrideInt))
{
this.maxConcurrentConnectionOpenRequests = maxConcurrentConnectionOpenRequestOverrideInt;
}
}
string openConnectionTimeoutInSecondsOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.OpenConnectionTimeoutInSecondsConfig];
if (!string.IsNullOrEmpty(openConnectionTimeoutInSecondsOverrideString))
{
int openConnectionTimeoutInSecondsOverrideInt = 0;
if (Int32.TryParse(openConnectionTimeoutInSecondsOverrideString, out openConnectionTimeoutInSecondsOverrideInt))
{
this.openConnectionTimeoutInSeconds = openConnectionTimeoutInSecondsOverrideInt;
}
}
string idleConnectionTimeoutInSecondsOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.IdleConnectionTimeoutInSecondsConfig];
if (!string.IsNullOrEmpty(idleConnectionTimeoutInSecondsOverrideString))
{
int idleConnectionTimeoutInSecondsOverrideInt = 0;
if (Int32.TryParse(idleConnectionTimeoutInSecondsOverrideString, out idleConnectionTimeoutInSecondsOverrideInt))
{
this.idleConnectionTimeoutInSeconds = idleConnectionTimeoutInSecondsOverrideInt;
}
}
string transportTimerPoolGranularityInSecondsOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.TransportTimerPoolGranularityInSecondsConfig];
if (!string.IsNullOrEmpty(transportTimerPoolGranularityInSecondsOverrideString))
{
int timerPoolGranularityInSecondsOverrideInt = 0;
if (Int32.TryParse(transportTimerPoolGranularityInSecondsOverrideString, out timerPoolGranularityInSecondsOverrideInt))
{
// timeoutgranularity specified should be greater than min(5 seconds)
if (timerPoolGranularityInSecondsOverrideInt > this.timerPoolGranularityInSeconds)
{
this.timerPoolGranularityInSeconds = timerPoolGranularityInSecondsOverrideInt;
}
}
}
string enableRntbdChannelOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.EnableTcpChannelConfig];
if (!string.IsNullOrEmpty(enableRntbdChannelOverrideString))
{
bool enableRntbdChannel = false;
if (bool.TryParse(enableRntbdChannelOverrideString, out enableRntbdChannel))
{
this.enableRntbdChannel = enableRntbdChannel;
}
}
string maxRequestsPerRntbdChannelOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.MaxRequestsPerChannelConfig];
if (!string.IsNullOrEmpty(maxRequestsPerRntbdChannelOverrideString))
{
int maxRequestsPerChannel = DocumentClient.DefaultMaxRequestsPerRntbdChannel;
if (int.TryParse(maxRequestsPerRntbdChannelOverrideString, out maxRequestsPerChannel))
{
this.maxRequestsPerRntbdChannel = maxRequestsPerChannel;
}
}
string rntbdPartitionCountOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.TcpPartitionCount];
if (!string.IsNullOrEmpty(rntbdPartitionCountOverrideString))
{
int rntbdPartitionCount = DocumentClient.DefaultRntbdPartitionCount;
if (int.TryParse(rntbdPartitionCountOverrideString, out rntbdPartitionCount))
{
this.rntbdPartitionCount = rntbdPartitionCount;
}
}
string maxRntbdChannelsOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.MaxChannelsPerHostConfig];
if (!string.IsNullOrEmpty(maxRntbdChannelsOverrideString))
{
int maxRntbdChannels = DefaultMaxRntbdChannelsPerHost;
if (int.TryParse(maxRntbdChannelsOverrideString, out maxRntbdChannels))
{
this.maxRntbdChannels = maxRntbdChannels;
}
}
string rntbdPortReuseModeOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.RntbdPortReuseMode];
if (!string.IsNullOrEmpty(rntbdPortReuseModeOverrideString))
{
PortReuseMode portReuseMode = DefaultRntbdPortReuseMode;
if (Enum.TryParse<PortReuseMode>(rntbdPortReuseModeOverrideString, out portReuseMode))
{
this.rntbdPortReuseMode = portReuseMode;
}
}
string rntbdPortPoolReuseThresholdOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.RntbdPortPoolReuseThreshold];
if (!string.IsNullOrEmpty(rntbdPortPoolReuseThresholdOverrideString))
{
int rntbdPortPoolReuseThreshold = DocumentClient.DefaultRntbdPortPoolReuseThreshold;
if (int.TryParse(rntbdPortPoolReuseThresholdOverrideString, out rntbdPortPoolReuseThreshold))
{
this.rntbdPortPoolReuseThreshold = rntbdPortPoolReuseThreshold;
}
}
string rntbdPortPoolBindAttemptsOverrideString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.RntbdPortPoolBindAttempts];
if (!string.IsNullOrEmpty(rntbdPortPoolBindAttemptsOverrideString))
{
int rntbdPortPoolBindAttempts = DocumentClient.DefaultRntbdPortPoolBindAttempts;
if (int.TryParse(rntbdPortPoolBindAttemptsOverrideString, out rntbdPortPoolBindAttempts))
{
this.rntbdPortPoolBindAttempts = rntbdPortPoolBindAttempts;
}
}
string rntbdReceiveHangDetectionTimeSecondsString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.RntbdReceiveHangDetectionTimeConfig];
if (!string.IsNullOrEmpty(rntbdReceiveHangDetectionTimeSecondsString))
{
int rntbdReceiveHangDetectionTimeSeconds = DefaultRntbdReceiveHangDetectionTimeSeconds;
if (int.TryParse(rntbdReceiveHangDetectionTimeSecondsString, out rntbdReceiveHangDetectionTimeSeconds))
{
this.rntbdReceiveHangDetectionTimeSeconds = rntbdReceiveHangDetectionTimeSeconds;
}
}
string rntbdSendHangDetectionTimeSecondsString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.RntbdSendHangDetectionTimeConfig];
if (!string.IsNullOrEmpty(rntbdSendHangDetectionTimeSecondsString))
{
int rntbdSendHangDetectionTimeSeconds = DefaultRntbdSendHangDetectionTimeSeconds;
if (int.TryParse(rntbdSendHangDetectionTimeSecondsString, out rntbdSendHangDetectionTimeSeconds))
{
this.rntbdSendHangDetectionTimeSeconds = rntbdSendHangDetectionTimeSeconds;
}
}
if (enableCpuMonitor.HasValue)
{
this.enableCpuMonitor = enableCpuMonitor.Value;
}
else
{
string enableCpuMonitorString = System.Configuration.ConfigurationManager.AppSettings[DocumentClient.EnableCpuMonitorConfig];
if (!string.IsNullOrEmpty(enableCpuMonitorString))
{
bool enableCpuMonitorFlag = DefaultEnableCpuMonitor;
if (bool.TryParse(enableCpuMonitorString, out enableCpuMonitorFlag))
{
this.enableCpuMonitor = enableCpuMonitorFlag;
}
}
}
#if NETSTANDARD20
}
#endif
#endif
string rntbdMaxConcurrentOpeningConnectionCountOverrideString = Environment.GetEnvironmentVariable(RntbdMaxConcurrentOpeningConnectionCountConfig);
if (!string.IsNullOrEmpty(rntbdMaxConcurrentOpeningConnectionCountOverrideString))
{
if (Int32.TryParse(rntbdMaxConcurrentOpeningConnectionCountOverrideString, out int rntbdMaxConcurrentOpeningConnectionCountOverrideInt))
{
if (rntbdMaxConcurrentOpeningConnectionCountOverrideInt <= 0)
{
throw new ArgumentException("RntbdMaxConcurrentOpeningConnectionCountConfig should be larger than 0");
}
this.rntbdMaxConcurrentOpeningConnectionCount = rntbdMaxConcurrentOpeningConnectionCountOverrideInt;
}
}
// ConnectionPolicy always overrides appconfig
if (connectionPolicy != null)
{
if (connectionPolicy.IdleTcpConnectionTimeout.HasValue)
{
this.idleConnectionTimeoutInSeconds = (int)connectionPolicy.IdleTcpConnectionTimeout.Value.TotalSeconds;
}
if (connectionPolicy.OpenTcpConnectionTimeout.HasValue)
{
this.openConnectionTimeoutInSeconds = (int)connectionPolicy.OpenTcpConnectionTimeout.Value.TotalSeconds;
}
if (connectionPolicy.MaxRequestsPerTcpConnection.HasValue)
{
this.maxRequestsPerRntbdChannel = connectionPolicy.MaxRequestsPerTcpConnection.Value;
}
if (connectionPolicy.MaxTcpPartitionCount.HasValue)
{
this.rntbdPartitionCount = connectionPolicy.MaxTcpPartitionCount.Value;
}
if (connectionPolicy.MaxTcpConnectionsPerEndpoint.HasValue)
{
this.maxRntbdChannels = connectionPolicy.MaxTcpConnectionsPerEndpoint.Value;
}
if (connectionPolicy.PortReuseMode.HasValue)
{
this.rntbdPortReuseMode = connectionPolicy.PortReuseMode.Value;
}
}
this.ServiceEndpoint = serviceEndpoint.OriginalString.EndsWith("/", StringComparison.Ordinal) ? serviceEndpoint : new Uri(serviceEndpoint.OriginalString + "/");
this.ConnectionPolicy = connectionPolicy ?? ConnectionPolicy.Default;
#if !NETSTANDARD16
ServicePointAccessor servicePoint = ServicePointAccessor.FindServicePoint(this.ServiceEndpoint);
servicePoint.ConnectionLimit = this.ConnectionPolicy.MaxConnectionLimit;
#endif
this.GlobalEndpointManager = new GlobalEndpointManager(this, this.ConnectionPolicy);
this.PartitionKeyRangeLocation = this.ConnectionPolicy.EnablePartitionLevelFailover
? new GlobalPartitionEndpointManagerCore(this.GlobalEndpointManager)
: GlobalPartitionEndpointManagerNoOp.Instance;
this.httpClient = CosmosHttpClientCore.CreateWithConnectionPolicy(
this.ApiType,
DocumentClientEventSource.Instance,
this.ConnectionPolicy,
handler,
this.sendingRequest,
this.receivedResponse);
// Loading VM Information (non blocking call and initialization won't fail if this call fails)
VmMetadataApiHandler.TryInitialize(this.httpClient);
// Starting ClientTelemetry Job
this.telemetryToServiceHelper = TelemetryToServiceHelper.CreateAndInitializeClientConfigAndTelemetryJob(this.clientId,
this.ConnectionPolicy,
this.cosmosAuthorization,
this.httpClient,
this.ServiceEndpoint,
this.GlobalEndpointManager,
this.cancellationTokenSource);
if (sessionContainer != null)
{
this.sessionContainer = sessionContainer;
}
else
{
this.sessionContainer = new SessionContainer(this.ServiceEndpoint.Host);
}
this.retryPolicy = new RetryPolicy(
globalEndpointManager: this.GlobalEndpointManager,
connectionPolicy: this.ConnectionPolicy,
partitionKeyRangeLocationCache: this.PartitionKeyRangeLocation);
this.ResetSessionTokenRetryPolicy = this.retryPolicy;
this.desiredConsistencyLevel = desiredConsistencyLevel;
// Setup the proxy to be used based on connection mode.
// For gateway: GatewayProxy.
// For direct: WFStoreProxy [set in OpenAsync()].
this.eventSource = DocumentClientEventSource.Instance;
this.initializeTaskFactory = (_) => TaskHelper.InlineIfPossible<bool>(
() => this.GetInitializationTaskAsync(storeClientFactory: storeClientFactory),
new ResourceThrottleRetryPolicy(
this.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests,
this.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds));
// Create the task to start the initialize task
// Task will be awaited on in the EnsureValidClientAsync
Task initTask = this.initTaskCache.GetAsync(
key: DocumentClient.DefaultInitTaskKey,
singleValueInitFunc: this.initializeTaskFactory,
forceRefresh: (_) => false);
// ContinueWith on the initialization task is needed for handling the UnobservedTaskException
// if this task throws for some reason. Awaiting inside a constructor is not supported and
// even if we had to await inside GetInitializationTask to catch the exception, that will
// be a blocking call. In such cases, the recommended approach is to "handle" the
// UnobservedTaskException by using ContinueWith method w/ TaskContinuationOptions.OnlyOnFaulted
// and accessing the Exception property on the target task.
#pragma warning disable VSTHRD110 // Observe result of async calls
initTask.ContinueWith(t => DefaultTrace.TraceWarning("initializeTask failed {0}", t.Exception), TaskContinuationOptions.OnlyOnFaulted);
#pragma warning restore VSTHRD110 // Observe result of async calls
this.traceId = Interlocked.Increment(ref DocumentClient.idCounter);
DefaultTrace.TraceInformation(string.Format(
CultureInfo.InvariantCulture,
"DocumentClient with id {0} initialized at endpoint: {1} with ConnectionMode: {2}, connection Protocol: {3}, and consistency level: {4}",