-
Notifications
You must be signed in to change notification settings - Fork 497
/
Copy pathBatchAsyncBatcher.cs
257 lines (224 loc) · 11.2 KB
/
BatchAsyncBatcher.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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Core.Trace;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Documents;
/// <summary>
/// Maintains a batch of operations and dispatches it as a unit of work.
/// </summary>
/// <remarks>
/// The dispatch process consists of:
/// 1. Creating a <see cref="PartitionKeyRangeServerBatchRequest"/>.
/// 2. Verifying overflow that might happen due to HybridRow serialization. Any operations that did not fit, get sent to the <see cref="BatchAsyncBatcherRetryDelegate"/>.
/// 3. Execution of the request gets delegated to <see cref="BatchAsyncBatcherExecuteDelegate"/>.
/// 4. If there was a split detected, all operations in the request, are sent to the <see cref="BatchAsyncBatcherRetryDelegate"/> for re-queueing.
/// 5. The result of the request is used to wire up all responses with the original Tasks for each operation.
/// </remarks>
/// <seealso cref="ItemBatchOperation"/>
internal class BatchAsyncBatcher
{
private readonly CosmosSerializerCore serializerCore;
private readonly List<ItemBatchOperation> batchOperations;
private readonly BatchAsyncBatcherExecuteDelegate executor;
private readonly BatchAsyncBatcherRetryDelegate retrier;
private readonly int maxBatchByteSize;
private readonly int maxBatchOperationCount;
private readonly InterlockIncrementCheck interlockIncrementCheck = new InterlockIncrementCheck();
private readonly CosmosClientContext clientContext;
private long currentSize = 0;
private bool dispatched = false;
private bool isClientEncrypted = false;
private string intendedCollectionRidValue;
public bool IsEmpty => this.batchOperations.Count == 0;
public BatchAsyncBatcher(
int maxBatchOperationCount,
int maxBatchByteSize,
CosmosSerializerCore serializerCore,
BatchAsyncBatcherExecuteDelegate executor,
BatchAsyncBatcherRetryDelegate retrier,
CosmosClientContext clientContext)
{
if (maxBatchOperationCount < 1)
{
throw new ArgumentOutOfRangeException(nameof(maxBatchOperationCount));
}
if (maxBatchByteSize < 1)
{
throw new ArgumentOutOfRangeException(nameof(maxBatchByteSize));
}
this.batchOperations = new List<ItemBatchOperation>(maxBatchOperationCount);
this.executor = executor ?? throw new ArgumentNullException(nameof(executor));
this.retrier = retrier ?? throw new ArgumentNullException(nameof(retrier));
this.maxBatchByteSize = maxBatchByteSize;
this.maxBatchOperationCount = maxBatchOperationCount;
this.serializerCore = serializerCore ?? throw new ArgumentNullException(nameof(serializerCore));
this.clientContext = clientContext;
}
public virtual bool TryAdd(ItemBatchOperation operation)
{
if (this.dispatched)
{
DefaultTrace.TraceCritical($"Add operation attempted on dispatched batch.");
return false;
}
if (operation == null)
{
throw new ArgumentNullException(nameof(operation));
}
if (operation.Context == null)
{
throw new ArgumentNullException(nameof(operation.Context));
}
if (operation.Context.IsClientEncrypted && !this.isClientEncrypted)
{
this.isClientEncrypted = true;
this.intendedCollectionRidValue = operation.Context.IntendedCollectionRidValue;
}
if (this.batchOperations.Count == this.maxBatchOperationCount)
{
DefaultTrace.TraceInformation($"Batch is full - Max operation count {this.maxBatchOperationCount} reached.");
return false;
}
int itemByteSize = operation.GetApproximateSerializedLength();
if (this.batchOperations.Count > 0 && itemByteSize + this.currentSize > this.maxBatchByteSize)
{
DefaultTrace.TraceInformation($"Batch is full - Max byte size {this.maxBatchByteSize} reached.");
return false;
}
this.currentSize += itemByteSize;
// Operation index is in the scope of the current batch
operation.OperationIndex = this.batchOperations.Count;
operation.Context.CurrentBatcher = this;
this.batchOperations.Add(operation);
return true;
}
public virtual async Task DispatchAsync(
BatchPartitionMetric partitionMetric,
CancellationToken cancellationToken = default)
{
using (ITrace trace = Tracing.Trace.GetRootTrace("Batch Dispatch Async", TraceComponent.Batch, Tracing.TraceLevel.Info))
{
await this.DispatchHelperAsync(trace, partitionMetric, cancellationToken);
}
}
private async Task<object> DispatchHelperAsync(
ITrace trace,
BatchPartitionMetric partitionMetric,
CancellationToken cancellationToken = default)
{
this.interlockIncrementCheck.EnterLockCheck();
PartitionKeyRangeServerBatchRequest serverRequest = null;
ArraySegment<ItemBatchOperation> pendingOperations;
try
{
try
{
// HybridRow serialization might leave some pending operations out of the batch
Tuple<PartitionKeyRangeServerBatchRequest, ArraySegment<ItemBatchOperation>> createRequestResponse = await this.CreateServerRequestAsync(cancellationToken);
serverRequest = createRequestResponse.Item1;
pendingOperations = createRequestResponse.Item2;
// Any overflow goes to a new batch
foreach (ItemBatchOperation operation in pendingOperations)
{
await this.retrier(operation, cancellationToken);
}
}
catch (Exception ex)
{
// Exceptions happening during request creation, fail the entire list
foreach (ItemBatchOperation itemBatchOperation in this.batchOperations)
{
itemBatchOperation.Context.Fail(this, ex);
}
throw;
}
try
{
ValueStopwatch stopwatch = ValueStopwatch.StartNew();
PartitionKeyRangeBatchExecutionResult result = await this.executor(serverRequest, trace, cancellationToken);
int numThrottle = result.ServerResponse.Any(r => r.StatusCode == (System.Net.HttpStatusCode)StatusCodes.TooManyRequests) ? 1 : 0;
partitionMetric.Add(
numberOfDocumentsOperatedOn: result.ServerResponse.Count,
timeTakenInMilliseconds: stopwatch.ElapsedMilliseconds,
numberOfThrottles: numThrottle);
using (PartitionKeyRangeBatchResponse batchResponse = new PartitionKeyRangeBatchResponse(serverRequest.Operations.Count, result.ServerResponse, this.serializerCore))
{
foreach (ItemBatchOperation itemBatchOperation in batchResponse.Operations)
{
TransactionalBatchOperationResult response = batchResponse[itemBatchOperation.OperationIndex];
if (!response.IsSuccessStatusCode)
{
ShouldRetryResult shouldRetry = await itemBatchOperation.Context.ShouldRetryAsync(response, cancellationToken);
if (shouldRetry.ShouldRetry)
{
await this.retrier(itemBatchOperation, cancellationToken);
continue;
}
}
itemBatchOperation.Context.Complete(this, response);
}
}
}
catch (Exception ex)
{
// Exceptions happening during execution fail all the Tasks part of the request (excluding overflow)
foreach (ItemBatchOperation itemBatchOperation in serverRequest.Operations)
{
itemBatchOperation.Context.Fail(this, ex);
}
throw;
}
}
catch (Exception ex)
{
DefaultTrace.TraceError("Exception during BatchAsyncBatcher: {0}", ex);
}
finally
{
this.batchOperations.Clear();
this.dispatched = true;
}
return null;
}
internal virtual async Task<Tuple<PartitionKeyRangeServerBatchRequest, ArraySegment<ItemBatchOperation>>> CreateServerRequestAsync(CancellationToken cancellationToken)
{
// All operations should be for the same PKRange
string partitionKeyRangeId = this.batchOperations[0].Context.PartitionKeyRangeId;
ArraySegment<ItemBatchOperation> operationsArraySegment = new ArraySegment<ItemBatchOperation>(this.batchOperations.ToArray());
return await PartitionKeyRangeServerBatchRequest.CreateAsync(
partitionKeyRangeId,
operationsArraySegment,
this.maxBatchByteSize,
this.maxBatchOperationCount,
ensureContinuousOperationIndexes: false,
serializerCore: this.serializerCore,
isClientEncrypted: this.isClientEncrypted,
intendedCollectionRidValue: this.intendedCollectionRidValue,
cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Executor implementation that processes a list of operations.
/// </summary>
/// <returns>An instance of <see cref="PartitionKeyRangeBatchResponse"/>.</returns>
internal delegate Task<PartitionKeyRangeBatchExecutionResult> BatchAsyncBatcherExecuteDelegate(
PartitionKeyRangeServerBatchRequest request,
ITrace trace,
CancellationToken cancellationToken);
/// <summary>
/// Delegate to process a request for retry an operation
/// </summary>
/// <returns>An instance of <see cref="PartitionKeyRangeBatchResponse"/>.</returns>
internal delegate Task BatchAsyncBatcherRetryDelegate(
ItemBatchOperation operation,
CancellationToken cancellationToken);
}