-
Notifications
You must be signed in to change notification settings - Fork 494
/
RequestMessage.cs
417 lines (358 loc) · 15.7 KB
/
RequestMessage.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
//------------------------------------------------------------
// 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.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Common;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Documents;
/// <summary>
/// Represents a request in the processing pipeline of the Azure Cosmos DB SDK.
/// </summary>
/// <remarks>
/// It is expected that direct property access is used for properties that will be read and used within the Azure Cosmos SDK pipeline, for example <see cref="RequestMessage.OperationType"/>.
/// <see cref="RequestMessage.Properties"/> should be used for any other property that needs to be sent to the backend but will not be read nor used within the Azure Cosmos DB SDK pipeline.
/// <see cref="RequestMessage.Headers"/> should be used for HTTP headers that need to be passed down and sent to the backend.
/// </remarks>
public class RequestMessage : IDisposable
{
/// <summary>
/// Create a <see cref="RequestMessage"/>
/// </summary>
public RequestMessage()
{
this.Trace = NoOpTrace.Singleton;
}
/// <summary>
/// Create a <see cref="RequestMessage"/>
/// </summary>
/// <param name="method">The http method</param>
/// <param name="requestUri">The requested URI</param>
public RequestMessage(HttpMethod method, Uri requestUri)
{
this.Method = method;
this.RequestUriString = requestUri?.OriginalString;
this.InternalRequestUri = requestUri;
this.Trace = NoOpTrace.Singleton;
}
/// <summary>
/// Create a <see cref="RequestMessage"/>
/// </summary>
/// <param name="method">The http method</param>
/// <param name="requestUriString">The requested URI</param>
/// /// <param name="trace">The trace node to append traces to.</param>
internal RequestMessage(
HttpMethod method,
string requestUriString,
ITrace trace)
{
this.Method = method;
this.RequestUriString = requestUriString;
this.Trace = trace ?? throw new ArgumentNullException(nameof(trace));
}
/// <summary>
/// Create a <see cref="RequestMessage"/>, used for Clone() method.
/// </summary>
/// <param name="method">The http method</param>
/// <param name="requestUriString">The requested URI</param>
/// <param name="trace">The trace node to append traces to.</param>
/// <param name="headers">The headers to use.</param>
/// <param name="properties">The properties to use.</param>
private RequestMessage(
HttpMethod method,
string requestUriString,
ITrace trace,
Headers headers,
Dictionary<string, object> properties)
{
this.Method = method;
this.RequestUriString = requestUriString;
this.Trace = trace ?? throw new ArgumentNullException(nameof(trace));
this.headers = new Lazy<Headers>(() => headers);
this.properties = new Lazy<Dictionary<string, object>>(() => properties);
}
/// <summary>
/// Gets the <see cref="HttpMethod"/> for the current request.
/// </summary>
public virtual HttpMethod Method { get; private set; }
/// <summary>
/// Gets the <see cref="Uri"/> for the current request.
/// </summary>
public virtual Uri RequestUri
{
get
{
if (this.InternalRequestUri == null)
{
this.InternalRequestUri = new Uri(this.RequestUriString, UriKind.Relative);
}
return this.InternalRequestUri;
}
}
/// <summary>
/// Gets the current <see cref="RequestMessage"/> HTTP headers.
/// </summary>
public virtual Headers Headers => this.headers.Value;
/// <summary>
/// Gets or sets the current <see cref="RequestMessage"/> payload.
/// </summary>
public virtual Stream Content
{
get => this.content;
set
{
this.CheckDisposed();
this.content = value;
}
}
internal string RequestUriString { get; }
internal Uri InternalRequestUri { get; private set; }
internal ITrace Trace { get; set; }
internal RequestOptions RequestOptions { get; set; }
internal ResourceType ResourceType { get; set; }
internal OperationType OperationType { get; set; }
internal PartitionKeyRangeIdentity PartitionKeyRangeId { get; set; }
/// <summary>
/// Used to override the client default. This is used for scenarios
/// in query where the service interop is not present.
/// </summary>
internal bool? UseGatewayMode { get; set; }
internal DocumentServiceRequest DocumentServiceRequest { get; set; }
internal Action<DocumentServiceRequest> OnBeforeSendRequestActions { get; set; }
internal bool IsPropertiesInitialized => this.properties.IsValueCreated;
/// <summary>
/// The partition key range handler is only needed for read feed on partitioned resources
/// where the partition key range needs to be computed.
/// </summary>
internal bool IsPartitionKeyRangeHandlerRequired => this.OperationType == OperationType.ReadFeed &&
this.ResourceType.IsPartitioned() && this.PartitionKeyRangeId == null &&
this.Headers.PartitionKey == null;
internal string ContainerId { get; set; }
internal string DatabaseId { get; set; }
/// <summary>
/// Request properties Per request context available to handlers.
/// These will not be automatically included into the wire.
/// </summary>
public virtual Dictionary<string, object> Properties => this.properties.Value;
private readonly Lazy<Dictionary<string, object>> properties = new Lazy<Dictionary<string, object>>(RequestMessage.CreateDictionary);
private readonly Lazy<Headers> headers = new Lazy<Headers>(RequestMessage.CreateHeaders);
private bool disposed;
private Stream content;
/// <summary>
/// Disposes the current <see cref="RequestMessage"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes of the request message content
/// </summary>
/// <param name="disposing">True to dispose content</param>
protected virtual void Dispose(bool disposing)
{
// The reason for this type to implement IDisposable is that it contains instances of types that implement
// IDisposable (content).
if (disposing && !this.disposed)
{
this.disposed = true;
if (this.Content != null)
{
this.Content.Dispose();
}
}
}
internal void AddThroughputHeader(int? throughputValue)
{
if (throughputValue.HasValue)
{
this.Headers.OfferThroughput = throughputValue.Value.ToString(CultureInfo.InvariantCulture);
}
}
internal void AddThroughputPropertiesHeader(ThroughputProperties throughputProperties)
{
if (throughputProperties == null)
{
return;
}
if (throughputProperties.Throughput.HasValue &&
(throughputProperties.AutoscaleMaxThroughput.HasValue || throughputProperties.AutoUpgradeMaxThroughputIncrementPercentage.HasValue))
{
throw new InvalidOperationException("Autoscale provisioned throughput can not be configured with fixed offer");
}
if (throughputProperties.Throughput.HasValue)
{
this.AddThroughputHeader(throughputProperties.Throughput);
}
else if (throughputProperties?.Content?.OfferAutoscaleSettings != null)
{
this.Headers.Add(HttpConstants.HttpHeaders.OfferAutopilotSettings, throughputProperties.Content.OfferAutoscaleSettings.GetJsonString());
}
}
internal async Task AssertPartitioningDetailsAsync(CosmosClient client, CancellationToken cancellationToken, ITrace trace)
{
if (this.IsMasterOperation())
{
return;
}
#if DEBUG
try
{
CollectionCache collectionCache = await client.DocumentClient.GetCollectionCacheAsync(trace);
ContainerProperties collectionFromCache =
await collectionCache.ResolveCollectionAsync(this.ToDocumentServiceRequest(), cancellationToken, trace);
if (collectionFromCache.PartitionKey?.Paths?.Count > 0)
{
Debug.Assert(this.AssertPartitioningPropertiesAndHeaders());
}
}
catch (DocumentClientException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
// Ignore container non-existence
}
#else
await Task.CompletedTask;
#endif
}
internal DocumentServiceRequest ToDocumentServiceRequest()
{
if (this.DocumentServiceRequest == null)
{
DocumentServiceRequest serviceRequest;
if (this.OperationType == OperationType.ReadFeed && this.ResourceType == ResourceType.Database)
{
serviceRequest = new DocumentServiceRequest(
operationType: this.OperationType,
resourceIdOrFullName: null,
resourceType: this.ResourceType,
body: this.Content,
headers: this.Headers.CosmosMessageHeaders.INameValueCollection,
isNameBased: false,
authorizationTokenType: AuthorizationTokenType.PrimaryMasterKey);
}
else
{
serviceRequest = new DocumentServiceRequest(
this.OperationType,
this.ResourceType,
this.RequestUriString,
this.Content,
AuthorizationTokenType.PrimaryMasterKey,
this.Headers.CosmosMessageHeaders.INameValueCollection);
}
if (this.UseGatewayMode.HasValue)
{
serviceRequest.UseGatewayMode = this.UseGatewayMode.Value;
}
serviceRequest.UseStatusCodeForFailures = true;
serviceRequest.UseStatusCodeFor429 = true;
serviceRequest.Properties = this.Properties;
this.DocumentServiceRequest = serviceRequest;
}
// Routing to a particular PartitionKeyRangeId
if (this.PartitionKeyRangeId != null)
{
this.DocumentServiceRequest.RouteTo(this.PartitionKeyRangeId);
}
this.DocumentServiceRequest.RequestContext.ExcludeRegions = this.RequestOptions?.ExcludeRegions;
this.OnBeforeRequestHandler(this.DocumentServiceRequest);
return this.DocumentServiceRequest;
}
/// <summary>
/// Clone the request message
/// </summary>
/// <returns>a cloned copy of the RequestMessage</returns>
internal RequestMessage Clone(ITrace newTrace, CloneableStream cloneContent)
{
RequestMessage clone = new RequestMessage(
this.Method,
this.RequestUriString,
newTrace,
this.Headers.Clone(),
new Dictionary<string, object>(this.Properties));
if (this.Content != null && cloneContent != null)
{
clone.Content = cloneContent.Clone();
}
if (this.RequestOptions != null)
{
clone.RequestOptions = this.RequestOptions.ShallowCopy();
}
clone.ResourceType = this.ResourceType;
clone.OperationType = this.OperationType;
if (this.PartitionKeyRangeId != null)
{
clone.PartitionKeyRangeId = string.IsNullOrEmpty(this.PartitionKeyRangeId.CollectionRid)
? new PartitionKeyRangeIdentity(this.PartitionKeyRangeId.PartitionKeyRangeId)
: new PartitionKeyRangeIdentity(this.PartitionKeyRangeId.CollectionRid, this.PartitionKeyRangeId.PartitionKeyRangeId);
}
clone.UseGatewayMode = this.UseGatewayMode;
clone.ContainerId = this.ContainerId;
clone.DatabaseId = this.DatabaseId;
return clone;
}
private static Dictionary<string, object> CreateDictionary()
{
return new Dictionary<string, object>();
}
private static Headers CreateHeaders()
{
return new Headers();
}
private void OnBeforeRequestHandler(DocumentServiceRequest serviceRequest)
{
serviceRequest.RequestContext.ExcludeRegions = this.RequestOptions?.ExcludeRegions;
this.OnBeforeSendRequestActions?.Invoke(serviceRequest);
}
private bool AssertPartitioningPropertiesAndHeaders()
{
// Either PK/key-range-id is assumed
bool pkExists = !string.IsNullOrEmpty(this.Headers.PartitionKey);
bool epkExists = this.Properties.ContainsKey(WFConstants.BackendHeaders.EffectivePartitionKeyString);
if (pkExists && epkExists)
{
throw new ArgumentNullException(RMResources.PartitionKeyAndEffectivePartitionKeyBothSpecified);
}
bool isPointOperation = this.OperationType != OperationType.ReadFeed;
if (!pkExists && !epkExists && this.OperationType.IsPointOperation())
{
throw new ArgumentNullException(RMResources.MissingPartitionKeyValue);
}
bool partitionKeyRangeIdExists = !string.IsNullOrEmpty(this.Headers.PartitionKeyRangeId);
if (partitionKeyRangeIdExists)
{
// Assert operation type is not write
if (this.OperationType != OperationType.Query && this.OperationType != OperationType.ReadFeed && this.OperationType != OperationType.Batch)
{
throw new ArgumentOutOfRangeException(RMResources.UnexpectedPartitionKeyRangeId);
}
}
if (pkExists && partitionKeyRangeIdExists)
{
throw new ArgumentOutOfRangeException(RMResources.PartitionKeyAndPartitionKeyRangeRangeIdBothSpecified);
}
return true;
}
private bool IsMasterOperation()
{
return this.ResourceType != ResourceType.Document;
}
private void CheckDisposed()
{
if (this.disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
}
}