-
Notifications
You must be signed in to change notification settings - Fork 473
/
TransactionalBatchResponse.cs
415 lines (366 loc) · 17 KB
/
TransactionalBatchResponse.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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Diagnostics;
using Microsoft.Azure.Cosmos.Serialization.HybridRow;
using Microsoft.Azure.Cosmos.Serialization.HybridRow.RecordIO;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Documents;
/// <summary>
/// Response of a <see cref="TransactionalBatch"/> request.
/// </summary>
#pragma warning disable CA1710 // Identifiers should have correct suffix
public class TransactionalBatchResponse : IReadOnlyList<TransactionalBatchOperationResult>, IDisposable
#pragma warning restore CA1710 // Identifiers should have correct suffix
{
private List<TransactionalBatchOperationResult> results;
/// <summary>
/// Initializes a new instance of the <see cref="TransactionalBatchResponse"/> class.
/// This method is intended to be used only when a response from the server is not available.
/// </summary>
/// <param name="statusCode">Indicates why the batch was not processed.</param>
/// <param name="subStatusCode">Provides further details about why the batch was not processed.</param>
/// <param name="errorMessage">The reason for failure.</param>
/// <param name="operations">Operations that were to be executed.</param>
/// <param name="trace">Diagnostics for the operation</param>
internal TransactionalBatchResponse(
HttpStatusCode statusCode,
SubStatusCodes subStatusCode,
string errorMessage,
IReadOnlyList<ItemBatchOperation> operations,
ITrace trace)
: this(statusCode,
subStatusCode,
errorMessage,
new Headers(),
trace: trace,
operations: operations,
serializer: null)
{
this.CreateAndPopulateResults(operations, trace);
}
/// <summary>
/// Initializes a new instance of the <see cref="TransactionalBatchResponse"/> class.
/// </summary>
protected TransactionalBatchResponse()
{
}
private TransactionalBatchResponse(
HttpStatusCode statusCode,
SubStatusCodes subStatusCode,
string errorMessage,
Headers headers,
ITrace trace,
IReadOnlyList<ItemBatchOperation> operations,
CosmosSerializerCore serializer)
{
this.StatusCode = statusCode;
this.SubStatusCode = subStatusCode;
this.ErrorMessage = errorMessage;
this.Operations = operations;
this.SerializerCore = serializer;
this.Headers = headers;
this.Diagnostics = new CosmosTraceDiagnostics(trace ?? NoOpTrace.Singleton);
}
/// <summary>
/// Gets the current HTTP headers.
/// </summary>
public virtual Headers Headers { get; internal set; }
/// <summary>
/// Gets the ActivityId that identifies the server request made to execute the batch.
/// </summary>
public virtual string ActivityId => this.Headers?.ActivityId;
/// <summary>
/// Gets the request charge for the batch request.
/// </summary>
/// <value>
/// The request charge measured in request units.
/// </value>
public virtual double RequestCharge => this.Headers?.RequestCharge ?? 0;
/// <summary>
/// Gets the amount of time to wait before retrying this or any other request within Cosmos container or collection due to throttling.
/// </summary>
public virtual TimeSpan? RetryAfter => this.Headers?.RetryAfter;
/// <summary>
/// Gets the completion status code of the batch request.
/// </summary>
/// <value>The request completion status code.</value>
public virtual HttpStatusCode StatusCode { get; internal set; }
/// <summary>
/// Gets the reason for failure of the batch request.
/// </summary>
/// <value>The reason for failure, if any.</value>
public virtual string ErrorMessage { get; internal set; }
/// <summary>
/// Gets a value indicating whether the batch was processed.
/// </summary>
public virtual bool IsSuccessStatusCode
{
get
{
int statusCodeInt = (int)this.StatusCode;
return statusCodeInt >= 200 && statusCodeInt <= 299;
}
}
/// <summary>
/// Gets the number of operation results.
/// </summary>
public virtual int Count => this.results?.Count ?? 0;
/// <summary>
/// Gets the cosmos diagnostic information for the current request to Azure Cosmos DB service
/// </summary>
public virtual CosmosDiagnostics Diagnostics { get; }
internal virtual SubStatusCodes SubStatusCode { get; }
internal virtual CosmosSerializerCore SerializerCore { get; }
internal IReadOnlyList<ItemBatchOperation> Operations { get; set; }
/// <summary>
/// Gets the result of the operation at the provided index in the batch.
/// </summary>
/// <param name="index">0-based index of the operation in the batch whose result needs to be returned.</param>
/// <returns>Result of operation at the provided index in the batch.</returns>
public virtual TransactionalBatchOperationResult this[int index] => this.results[index];
/// <summary>
/// Gets the result of the operation at the provided index in the batch - the returned result has a Resource of provided type.
/// </summary>
/// <typeparam name="T">Type to which the Resource in the operation result needs to be deserialized to, when present.</typeparam>
/// <param name="index">0-based index of the operation in the batch whose result needs to be returned.</param>
/// <returns>Result of batch operation that contains a Resource deserialized to specified type.</returns>
public virtual TransactionalBatchOperationResult<T> GetOperationResultAtIndex<T>(int index)
{
TransactionalBatchOperationResult result = this.results[index];
T resource = default;
if (result.ResourceStream != null)
{
resource = this.SerializerCore.FromStream<T>(result.ResourceStream);
}
return new TransactionalBatchOperationResult<T>(result, resource);
}
/// <summary>
/// Gets an enumerator over the operation results.
/// </summary>
/// <returns>Enumerator over the operation results.</returns>
public virtual IEnumerator<TransactionalBatchOperationResult> GetEnumerator()
{
return this.results.GetEnumerator();
}
/// <summary>
/// Gets all the Activity IDs associated with the response.
/// </summary>
/// <returns>An enumerable that contains the Activity IDs.</returns>
#if INTERNAL
public
#else
internal
#endif
virtual IEnumerable<string> GetActivityIds()
{
yield return this.ActivityId;
}
/// <summary>
/// Disposes the current <see cref="TransactionalBatchResponse"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
internal static async Task<TransactionalBatchResponse> FromResponseMessageAsync(
ResponseMessage responseMessage,
ServerBatchRequest serverRequest,
CosmosSerializerCore serializer,
bool shouldPromoteOperationStatus,
ITrace trace,
CancellationToken cancellationToken)
{
using (ITrace createResponseTrace = trace.StartChild("Create Trace", TraceComponent.Batch, TraceLevel.Info))
{
using (responseMessage)
{
TransactionalBatchResponse response = null;
if (responseMessage.Content != null)
{
Stream content = responseMessage.Content;
// Shouldn't be the case practically, but handle it for safety.
if (!responseMessage.Content.CanSeek)
{
content = new MemoryStream();
await responseMessage.Content.CopyToAsync(content);
}
if (content.ReadByte() == (int)HybridRowVersion.V1)
{
content.Position = 0;
response = await TransactionalBatchResponse.PopulateFromContentAsync(
content,
responseMessage,
serverRequest,
serializer,
trace,
shouldPromoteOperationStatus);
if (response == null)
{
// Convert any payload read failures as InternalServerError
response = new TransactionalBatchResponse(
HttpStatusCode.InternalServerError,
SubStatusCodes.Unknown,
ClientResources.ServerResponseDeserializationFailure,
responseMessage.Headers,
trace,
serverRequest.Operations,
serializer);
}
}
}
if (response == null)
{
response = new TransactionalBatchResponse(
responseMessage.StatusCode,
responseMessage.Headers.SubStatusCode,
responseMessage.ErrorMessage,
responseMessage.Headers,
trace,
serverRequest.Operations,
serializer);
}
if (response.results == null || response.results.Count != serverRequest.Operations.Count)
{
if (responseMessage.IsSuccessStatusCode)
{
// Server should be guaranteeing number of results equal to operations when
// batch request is successful - so fail as InternalServerError if this is not the case.
response = new TransactionalBatchResponse(
HttpStatusCode.InternalServerError,
SubStatusCodes.Unknown,
ClientResources.InvalidServerResponse,
responseMessage.Headers,
trace,
serverRequest.Operations,
serializer);
}
// When the overall response status code is TooManyRequests, propagate the RetryAfter into the individual operations.
int retryAfterMilliseconds = 0;
if ((int)responseMessage.StatusCode == (int)StatusCodes.TooManyRequests)
{
if (!responseMessage.Headers.TryGetValue(HttpConstants.HttpHeaders.RetryAfterInMilliseconds, out string retryAfter) ||
retryAfter == null ||
!int.TryParse(retryAfter, out retryAfterMilliseconds))
{
retryAfterMilliseconds = 0;
}
}
response.CreateAndPopulateResults(serverRequest.Operations, trace, retryAfterMilliseconds);
}
return response;
}
}
}
private void CreateAndPopulateResults(IReadOnlyList<ItemBatchOperation> operations, ITrace trace, int retryAfterMilliseconds = 0)
{
this.results = new List<TransactionalBatchOperationResult>();
for (int i = 0; i < operations.Count; i++)
{
TransactionalBatchOperationResult result = new TransactionalBatchOperationResult(this.StatusCode)
{
SubStatusCode = this.SubStatusCode,
RetryAfter = TimeSpan.FromMilliseconds(retryAfterMilliseconds),
SessionToken = this.Headers.Session,
PartitionKeyRangeId = this.Headers.PartitionKeyRangeId,
ActivityId = this.ActivityId,
};
result.Trace = trace;
this.results.Add(result);
}
}
private static async Task<TransactionalBatchResponse> PopulateFromContentAsync(
Stream content,
ResponseMessage responseMessage,
ServerBatchRequest serverRequest,
CosmosSerializerCore serializer,
ITrace trace,
bool shouldPromoteOperationStatus)
{
List<TransactionalBatchOperationResult> results = new List<TransactionalBatchOperationResult>();
// content is ensured to be seekable in caller.
int resizerInitialCapacity = (int)content.Length;
Result res = await content.ReadRecordIOAsync(
(Func<ReadOnlyMemory<byte>, Result>)(record =>
{
Result r = TransactionalBatchOperationResult.ReadOperationResult(record, out TransactionalBatchOperationResult operationResult);
if (r != Result.Success)
{
return r;
}
operationResult.Trace = trace;
operationResult.SessionToken = responseMessage.Headers.Session;
operationResult.PartitionKeyRangeId = responseMessage.Headers.PartitionKeyRangeId;
operationResult.ActivityId = responseMessage.Headers.ActivityId;
results.Add(operationResult);
return r;
}),
resizer: new MemorySpanResizer<byte>(resizerInitialCapacity));
if (res != Result.Success)
{
return null;
}
HttpStatusCode responseStatusCode = responseMessage.StatusCode;
SubStatusCodes responseSubStatusCode = responseMessage.Headers.SubStatusCode;
// Promote the operation error status as the Batch response error status if we have a MultiStatus response
// to provide users with status codes they are used to.
if ((int)responseMessage.StatusCode == (int)StatusCodes.MultiStatus
&& shouldPromoteOperationStatus)
{
foreach (TransactionalBatchOperationResult result in results)
{
if ((int)result.StatusCode != (int)StatusCodes.FailedDependency && (int)result.StatusCode >= (int)StatusCodes.StartingErrorCode)
{
responseStatusCode = result.StatusCode;
responseSubStatusCode = result.SubStatusCode;
break;
}
}
}
TransactionalBatchResponse response = new TransactionalBatchResponse(
responseStatusCode,
responseSubStatusCode,
responseMessage.ErrorMessage,
responseMessage.Headers,
trace,
serverRequest.Operations,
serializer)
{
results = results
};
return response;
}
/// <summary>
/// Disposes the disposable members held by this class.
/// </summary>
/// <param name="disposing">Indicates whether to dispose managed resources or not.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.Operations != null)
{
foreach (ItemBatchOperation operation in this.Operations)
{
operation.Dispose();
}
this.Operations = null;
}
}
}
}
}