-
Notifications
You must be signed in to change notification settings - Fork 543
Expand file tree
/
Copy pathClientContextCore.cs
More file actions
626 lines (556 loc) · 26 KB
/
Copy pathClientContextCore.cs
File metadata and controls
626 lines (556 loc) · 26 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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Handlers;
using Microsoft.Azure.Cosmos.Resource.CosmosExceptions;
using Microsoft.Azure.Cosmos.Routing;
using Microsoft.Azure.Cosmos.Telemetry;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Documents;
internal class ClientContextCore : CosmosClientContext
{
private readonly BatchAsyncContainerExecutorCache batchExecutorCache;
private readonly CosmosClient client;
private readonly DocumentClient documentClient;
private readonly CosmosSerializerCore serializerCore;
private readonly CosmosResponseFactoryInternal responseFactory;
private readonly RequestInvokerHandler requestHandler;
private readonly CosmosClientOptions clientOptions;
private readonly string userAgent;
private bool isDisposed = false;
private ClientContextCore(
CosmosClient client,
CosmosClientOptions clientOptions,
CosmosSerializerCore serializerCore,
CosmosResponseFactoryInternal cosmosResponseFactory,
RequestInvokerHandler requestHandler,
DocumentClient documentClient,
string userAgent,
BatchAsyncContainerExecutorCache batchExecutorCache)
{
this.client = client;
this.clientOptions = clientOptions;
this.serializerCore = serializerCore;
this.responseFactory = cosmosResponseFactory;
this.requestHandler = requestHandler;
this.documentClient = documentClient;
this.userAgent = userAgent;
this.batchExecutorCache = batchExecutorCache;
}
internal static CosmosClientContext Create(
CosmosClient cosmosClient,
CosmosClientOptions clientOptions)
{
if (cosmosClient == null)
{
throw new ArgumentNullException(nameof(cosmosClient));
}
clientOptions = ClientContextCore.CreateOrCloneClientOptions(clientOptions);
HttpMessageHandler httpMessageHandler = CosmosHttpClientCore.CreateHttpClientHandler(
clientOptions.GatewayModeMaxConnectionLimit,
clientOptions.WebProxy,
clientOptions.ServerCertificateCustomValidationCallback);
DocumentClient documentClient = new DocumentClient(
cosmosClient.Endpoint,
cosmosClient.AuthorizationTokenProvider,
apitype: clientOptions.ApiType,
sendingRequestEventArgs: clientOptions.SendingRequestEventArgs,
transportClientHandlerFactory: clientOptions.TransportClientHandlerFactory,
connectionPolicy: clientOptions.GetConnectionPolicy(cosmosClient.ClientId),
enableCpuMonitor: clientOptions.EnableCpuMonitor,
storeClientFactory: clientOptions.StoreClientFactory,
desiredConsistencyLevel: clientOptions.GetDocumentsConsistencyLevel(),
handler: httpMessageHandler,
sessionContainer: clientOptions.SessionContainer,
cosmosClientId: cosmosClient.Id,
remoteCertificateValidationCallback: ClientContextCore.SslCustomValidationCallBack(clientOptions.ServerCertificateCustomValidationCallback),
cosmosClientTelemetryOptions: clientOptions.CosmosClientTelemetryOptions,
chaosInterceptorFactory: clientOptions.ChaosInterceptorFactory);
return ClientContextCore.Create(
cosmosClient,
documentClient,
clientOptions);
}
private static RemoteCertificateValidationCallback SslCustomValidationCallBack(Func<X509Certificate2, X509Chain, SslPolicyErrors, bool> serverCertificateCustomValidationCallback)
{
return serverCertificateCustomValidationCallback == null ? null : (_, cert, chain, policy) => serverCertificateCustomValidationCallback((X509Certificate2)cert, chain, policy);
}
internal static CosmosClientContext Create(
CosmosClient cosmosClient,
DocumentClient documentClient,
CosmosClientOptions clientOptions,
RequestInvokerHandler requestInvokerHandler = null)
{
if (cosmosClient == null)
{
throw new ArgumentNullException(nameof(cosmosClient));
}
if (documentClient == null)
{
throw new ArgumentNullException(nameof(documentClient));
}
clientOptions = ClientContextCore.CreateOrCloneClientOptions(clientOptions);
if (requestInvokerHandler == null)
{
//Request pipeline
ClientPipelineBuilder clientPipelineBuilder = new ClientPipelineBuilder(
cosmosClient,
clientOptions.ConsistencyLevel,
clientOptions.PriorityLevel,
clientOptions.CustomHandlers,
telemetryToServiceHelper: documentClient.telemetryToServiceHelper);
requestInvokerHandler = clientPipelineBuilder.Build();
}
CosmosSerializerCore serializerCore = CosmosSerializerCore.Create(
clientOptions.Serializer,
clientOptions.SerializerOptions);
// This sets the serializer on client options which gives users access to it if a custom one is not configured.
clientOptions.SetSerializerIfNotConfigured(serializerCore.GetCustomOrDefaultSerializer());
CosmosResponseFactoryInternal responseFactory = new CosmosResponseFactoryCore(serializerCore);
return new ClientContextCore(
client: cosmosClient,
clientOptions: clientOptions,
serializerCore: serializerCore,
cosmosResponseFactory: responseFactory,
requestHandler: requestInvokerHandler,
documentClient: documentClient,
userAgent: documentClient.ConnectionPolicy.UserAgentContainer.UserAgent,
batchExecutorCache: new BatchAsyncContainerExecutorCache());
}
/// <summary>
/// The Cosmos client that is used for the request
/// </summary>
internal override CosmosClient Client => this.ThrowIfDisposed(this.client);
internal override DocumentClient DocumentClient => this.ThrowIfDisposed(this.documentClient);
internal override CosmosSerializerCore SerializerCore => this.ThrowIfDisposed(this.serializerCore);
internal override CosmosResponseFactoryInternal ResponseFactory => this.ThrowIfDisposed(this.responseFactory);
internal override RequestInvokerHandler RequestHandler => this.ThrowIfDisposed(this.requestHandler);
internal override CosmosClientOptions ClientOptions => this.ThrowIfDisposed(this.clientOptions);
internal override string UserAgent => this.ThrowIfDisposed(this.userAgent);
/// <summary>
/// Generates the URI link for the resource
/// </summary>
/// <param name="parentLink">The parent link URI (/dbs/mydbId) </param>
/// <param name="uriPathSegment">The URI path segment</param>
/// <param name="id">The id of the resource</param>
/// <returns>A resource link in the format of {parentLink}/this.UriPathSegment/this.Name with this.Name being a Uri escaped version</returns>
internal override string CreateLink(
string parentLink,
string uriPathSegment,
string id)
{
this.ThrowIfDisposed();
int parentLinkLength = parentLink?.Length ?? 0;
string idUriEscaped = Uri.EscapeUriString(id);
Debug.Assert(parentLinkLength == 0 || !parentLink.EndsWith("/"));
StringBuilder stringBuilder = new StringBuilder(parentLinkLength + 2 + uriPathSegment.Length + idUriEscaped.Length);
if (parentLinkLength > 0)
{
stringBuilder.Append(parentLink);
stringBuilder.Append("/");
}
stringBuilder.Append(uriPathSegment);
stringBuilder.Append("/");
stringBuilder.Append(idUriEscaped);
return stringBuilder.ToString();
}
internal override void ValidateResource(string resourceId)
{
this.ThrowIfDisposed();
this.DocumentClient.ValidateResource(resourceId);
}
internal override Task<TResult>
OperationHelperAsync<TResult>(
string operationName,
string containerName,
string databaseName,
OperationType operationType,
RequestOptions requestOptions,
Func<ITrace, Task<TResult>> task,
Func<TResult, OpenTelemetryAttributes> openTelemetry,
TraceComponent traceComponent = TraceComponent.Transport,
Tracing.TraceLevel traceLevel = Tracing.TraceLevel.Info)
{
return SynchronizationContext.Current == null ?
this.OperationHelperWithRootTraceAsync(operationName,
containerName,
databaseName,
operationType,
requestOptions,
task,
openTelemetry,
traceComponent,
traceLevel) :
this.OperationHelperWithRootTraceWithSynchronizationContextAsync(
operationName,
containerName,
databaseName,
operationType,
requestOptions,
task,
openTelemetry,
traceComponent,
traceLevel);
}
private async Task<TResult> OperationHelperWithRootTraceAsync<TResult>(
string operationName,
string containerName,
string databaseName,
OperationType operationType,
RequestOptions requestOptions,
Func<ITrace, Task<TResult>> task,
Func<TResult, OpenTelemetryAttributes> openTelemetry,
TraceComponent traceComponent,
Tracing.TraceLevel traceLevel)
{
bool disableDiagnostics = requestOptions != null && requestOptions.DisablePointOperationDiagnostics;
using (ITrace trace = disableDiagnostics ? NoOpTrace.Singleton : (ITrace)Tracing.Trace.GetRootTrace(operationName, traceComponent, traceLevel))
{
trace.AddDatum("Client Configuration", this.client.ClientConfigurationTraceDatum);
return await this.RunWithDiagnosticsHelperAsync(
containerName,
databaseName,
operationType,
trace,
task,
openTelemetry,
operationName,
requestOptions);
}
}
private Task<TResult> OperationHelperWithRootTraceWithSynchronizationContextAsync<TResult>(
string operationName,
string containerName,
string databaseName,
OperationType operationType,
RequestOptions requestOptions,
Func<ITrace, Task<TResult>> task,
Func<TResult, OpenTelemetryAttributes> openTelemetry,
TraceComponent traceComponent,
Tracing.TraceLevel traceLevel)
{
Debug.Assert(SynchronizationContext.Current != null, "This should only be used when a SynchronizationContext is specified");
string syncContextVirtualAddress = SynchronizationContext.Current.ToString();
// Used on NETFX applications with SynchronizationContext when doing locking calls
return Task.Run(async () =>
{
bool disableDiagnostics = requestOptions != null && requestOptions.DisablePointOperationDiagnostics;
using (ITrace trace = disableDiagnostics ? NoOpTrace.Singleton : (ITrace)Tracing.Trace.GetRootTrace(operationName, traceComponent, traceLevel))
{
trace.AddDatum("Synchronization Context", syncContextVirtualAddress);
return await this.RunWithDiagnosticsHelperAsync(
containerName,
databaseName,
operationType,
trace,
task,
openTelemetry,
operationName,
requestOptions);
}
});
}
internal override Task<ResponseMessage> ProcessResourceOperationStreamAsync(
string resourceUri,
ResourceType resourceType,
OperationType operationType,
RequestOptions requestOptions,
ContainerInternal cosmosContainerCore,
PartitionKey? partitionKey,
string itemId,
Stream streamPayload,
Action<RequestMessage> requestEnricher,
ITrace trace,
CancellationToken cancellationToken)
{
this.ThrowIfDisposed();
if (this.IsBulkOperationSupported(resourceType, operationType))
{
if (!partitionKey.HasValue)
{
throw new ArgumentOutOfRangeException(nameof(partitionKey));
}
if (requestEnricher != null)
{
throw new ArgumentException($"Bulk does not support {nameof(requestEnricher)}");
}
return this.ProcessResourceOperationAsBulkStreamAsync(
operationType: operationType,
requestOptions: requestOptions,
cosmosContainerCore: cosmosContainerCore,
partitionKey: partitionKey.Value,
itemId: itemId,
streamPayload: streamPayload,
trace: trace,
cancellationToken: cancellationToken);
}
return this.ProcessResourceOperationStreamAsync(
resourceUri: resourceUri,
resourceType: resourceType,
operationType: operationType,
requestOptions: requestOptions,
cosmosContainerCore: cosmosContainerCore,
feedRange: partitionKey.HasValue ? new FeedRangePartitionKey(partitionKey.Value) : null,
streamPayload: streamPayload,
requestEnricher: requestEnricher,
trace: trace,
cancellationToken: cancellationToken);
}
internal override Task<ResponseMessage> ProcessResourceOperationStreamAsync(
string resourceUri,
ResourceType resourceType,
OperationType operationType,
RequestOptions requestOptions,
ContainerInternal cosmosContainerCore,
FeedRange feedRange,
Stream streamPayload,
Action<RequestMessage> requestEnricher,
ITrace trace,
CancellationToken cancellationToken)
{
this.ThrowIfDisposed();
return this.RequestHandler.SendAsync(
resourceUriString: resourceUri,
resourceType: resourceType,
operationType: operationType,
requestOptions: requestOptions,
cosmosContainerCore: cosmosContainerCore,
feedRange: feedRange,
streamPayload: streamPayload,
requestEnricher: requestEnricher,
trace: trace,
cancellationToken: cancellationToken);
}
internal override Task<T> ProcessResourceOperationAsync<T>(
string resourceUri,
ResourceType resourceType,
OperationType operationType,
RequestOptions requestOptions,
ContainerInternal cosmosContainerCore,
FeedRange feedRange,
Stream streamPayload,
Action<RequestMessage> requestEnricher,
Func<ResponseMessage, T> responseCreator,
ITrace trace,
CancellationToken cancellationToken)
{
this.ThrowIfDisposed();
return this.RequestHandler.SendAsync<T>(
resourceUri: resourceUri,
resourceType: resourceType,
operationType: operationType,
requestOptions: requestOptions,
cosmosContainerCore: cosmosContainerCore,
feedRange: feedRange,
streamPayload: streamPayload,
requestEnricher: requestEnricher,
responseCreator: responseCreator,
trace: trace,
cancellationToken: cancellationToken);
}
internal override async Task<ContainerProperties> GetCachedContainerPropertiesAsync(
string containerUri,
ITrace trace,
CancellationToken cancellationToken)
{
using (ITrace childTrace = trace.StartChild("Get Container Properties", TraceComponent.Transport, Tracing.TraceLevel.Info))
{
this.ThrowIfDisposed();
ClientCollectionCache collectionCache = await this.DocumentClient.GetCollectionCacheAsync(childTrace);
try
{
return await collectionCache.ResolveByNameAsync(
HttpConstants.Versions.CurrentVersion,
containerUri,
forceRefesh: false,
trace: childTrace,
clientSideRequestStatistics: null,
cancellationToken: cancellationToken);
}
catch (DocumentClientException ex)
{
throw CosmosExceptionFactory.Create(ex, childTrace);
}
}
}
internal override BatchAsyncContainerExecutor GetExecutorForContainer(ContainerInternal container)
{
this.ThrowIfDisposed();
if (!this.ClientOptions.AllowBulkExecution)
{
return null;
}
return this.batchExecutorCache.GetExecutorForContainer(container, this);
}
/// <inheritdoc/>
internal override async Task InitializeContainerUsingRntbdAsync(
string databaseId,
string containerLinkUri,
CancellationToken cancellationToken)
{
await this.DocumentClient.EnsureValidClientAsync(NoOpTrace.Singleton);
await this.DocumentClient.OpenConnectionsToAllReplicasAsync(
databaseId,
containerLinkUri,
cancellationToken);
}
public override void Dispose()
{
this.Dispose(true);
}
/// <summary>
/// Dispose of cosmos client
/// </summary>
/// <param name="disposing">True if disposing</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
this.batchExecutorCache.Dispose();
this.DocumentClient.Dispose();
}
this.isDisposed = true;
}
}
private async Task<TResult> RunWithDiagnosticsHelperAsync<TResult>(
string containerName,
string databaseName,
OperationType operationType,
ITrace trace,
Func<ITrace, Task<TResult>> task,
Func<TResult, OpenTelemetryAttributes> openTelemetry,
string operationName,
RequestOptions requestOptions)
{
using (OpenTelemetryCoreRecorder recorder =
OpenTelemetryRecorderFactory.CreateRecorder(
operationName: operationName,
containerName: containerName,
databaseName: databaseName,
operationType: operationType,
requestOptions: requestOptions,
trace: trace,
clientContext: this.isDisposed ? null : this))
using (new ActivityScope(Guid.NewGuid()))
{
try
{
TResult result = await task(trace).ConfigureAwait(false);
if (openTelemetry != null && recorder.IsEnabled)
{
// Record request response information
OpenTelemetryAttributes response = openTelemetry(result);
recorder.Record(response);
}
return result;
}
catch (OperationCanceledException oe) when (!(oe is CosmosOperationCanceledException))
{
CosmosOperationCanceledException operationCancelledException = new CosmosOperationCanceledException(oe, trace);
recorder.MarkFailed(operationCancelledException);
throw operationCancelledException;
}
catch (ObjectDisposedException objectDisposed) when (!(objectDisposed is CosmosObjectDisposedException))
{
CosmosObjectDisposedException objectDisposedException = new CosmosObjectDisposedException(
objectDisposed,
this.client,
trace);
recorder.MarkFailed(objectDisposedException);
throw objectDisposedException;
}
catch (NullReferenceException nullRefException) when (!(nullRefException is CosmosNullReferenceException))
{
CosmosNullReferenceException nullException = new CosmosNullReferenceException(
nullRefException,
trace);
recorder.MarkFailed(nullException);
throw nullException;
}
catch (Exception ex)
{
recorder.MarkFailed(ex);
throw;
}
}
}
private async Task<ResponseMessage> ProcessResourceOperationAsBulkStreamAsync(
OperationType operationType,
RequestOptions requestOptions,
ContainerInternal cosmosContainerCore,
PartitionKey partitionKey,
string itemId,
Stream streamPayload,
ITrace trace,
CancellationToken cancellationToken)
{
this.ThrowIfDisposed();
ItemRequestOptions itemRequestOptions = requestOptions as ItemRequestOptions;
TransactionalBatchItemRequestOptions batchItemRequestOptions = TransactionalBatchItemRequestOptions.FromItemRequestOptions(itemRequestOptions);
ItemBatchOperation itemBatchOperation = new ItemBatchOperation(
operationType: operationType,
operationIndex: 0,
partitionKey: partitionKey,
id: itemId,
resourceStream: streamPayload,
requestOptions: batchItemRequestOptions,
cosmosClientContext: this);
TransactionalBatchOperationResult batchOperationResult = await cosmosContainerCore.BatchExecutor.AddAsync(
itemBatchOperation,
trace,
itemRequestOptions,
cancellationToken);
return batchOperationResult.ToResponseMessage(cosmosContainerCore);
}
private bool IsBulkOperationSupported(
ResourceType resourceType,
OperationType operationType)
{
this.ThrowIfDisposed();
if (!this.ClientOptions.AllowBulkExecution)
{
return false;
}
return resourceType == ResourceType.Document
&& (operationType == OperationType.Create
|| operationType == OperationType.Upsert
|| operationType == OperationType.Read
|| operationType == OperationType.Delete
|| operationType == OperationType.Replace
|| operationType == OperationType.Patch);
}
private static CosmosClientOptions CreateOrCloneClientOptions(CosmosClientOptions clientOptions)
{
if (clientOptions == null)
{
return new CosmosClientOptions();
}
return clientOptions.Clone();
}
internal T ThrowIfDisposed<T>(T input)
{
this.ThrowIfDisposed();
return input;
}
private void ThrowIfDisposed()
{
if (this.isDisposed)
{
throw new ObjectDisposedException($"Accessing {nameof(CosmosClient)} after it is disposed is invalid.");
}
}
}
}