-
Notifications
You must be signed in to change notification settings - Fork 491
/
CrossPartitionRangePageAsyncEnumerator.cs
363 lines (307 loc) · 16 KB
/
CrossPartitionRangePageAsyncEnumerator.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
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Pagination
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Query.Core;
using Microsoft.Azure.Cosmos.Query.Core.Collections;
using Microsoft.Azure.Cosmos.Query.Core.Monads;
using Microsoft.Azure.Cosmos.Tracing;
/// <summary>
/// Coordinates draining pages from multiple <see cref="PartitionRangePageAsyncEnumerator{TPage, TState}"/>, while maintaining a global sort order and handling repartitioning (splits, merge).
/// </summary>
internal sealed class CrossPartitionRangePageAsyncEnumerator<TPage, TState> : ITracingAsyncEnumerator<TryCatch<CrossFeedRangePage<TPage, TState>>>
where TPage : Page<TState>
where TState : State
{
private readonly IFeedRangeProvider feedRangeProvider;
private readonly CreatePartitionRangePageAsyncEnumerator<TPage, TState> createPartitionRangeEnumerator;
private readonly AsyncLazy<IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>>> lazyEnumerators;
private FeedRangeState<TState>? nextState;
public CrossPartitionRangePageAsyncEnumerator(
IFeedRangeProvider feedRangeProvider,
CreatePartitionRangePageAsyncEnumerator<TPage, TState> createPartitionRangeEnumerator,
IComparer<PartitionRangePageAsyncEnumerator<TPage, TState>> comparer,
int? maxConcurrency,
PrefetchPolicy prefetchPolicy,
CrossFeedRangeState<TState> state = default)
{
this.feedRangeProvider = feedRangeProvider ?? throw new ArgumentNullException(nameof(feedRangeProvider));
this.createPartitionRangeEnumerator = createPartitionRangeEnumerator ?? throw new ArgumentNullException(nameof(createPartitionRangeEnumerator));
this.lazyEnumerators = new AsyncLazy<IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>>>((ITrace trace, CancellationToken token) =>
InitializeEnumeratorsAsync(
feedRangeProvider,
createPartitionRangeEnumerator,
comparer,
maxConcurrency,
prefetchPolicy,
state,
trace,
token));
}
public TryCatch<CrossFeedRangePage<TPage, TState>> Current { get; private set; }
public FeedRangeInternal CurrentRange { get; private set; }
public async ValueTask<bool> MoveNextAsync(ITrace trace, CancellationToken cancellationToken)
{
if (trace == null)
{
throw new ArgumentNullException(nameof(trace));
}
using (ITrace childTrace = trace.StartChild(name: nameof(MoveNextAsync), component: TraceComponent.Pagination, level: TraceLevel.Info))
{
IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>> enumerators = await this.lazyEnumerators.GetValueAsync(
childTrace,
cancellationToken);
if (enumerators.Count == 0)
{
this.Current = default;
this.CurrentRange = default;
this.nextState = default;
return false;
}
PartitionRangePageAsyncEnumerator<TPage, TState> currentPaginator = enumerators.Dequeue();
bool moveNextResult = false;
try
{
moveNextResult = await currentPaginator.MoveNextAsync(childTrace, cancellationToken);
}
catch
{
// Re-queue the enumerator to avoid emptying the queue
enumerators.Enqueue(currentPaginator);
throw;
}
if (!moveNextResult)
{
// Current enumerator is empty,
// so recursively retry on the next enumerator.
return await this.MoveNextAsync(childTrace, cancellationToken);
}
if (currentPaginator.Current.Failed)
{
// Check if it's a retryable exception.
Exception exception = currentPaginator.Current.Exception;
while (exception.InnerException != null)
{
exception = exception.InnerException;
}
if (IsSplitException(exception))
{
// Handle split
List<FeedRangeEpk> childRanges = await this.feedRangeProvider.GetChildRangeAsync(
currentPaginator.FeedRangeState.FeedRange,
childTrace,
cancellationToken);
if (childRanges.Count <= 1)
{
// We optimistically assumed that the cache is not stale.
// In the event that it is (where we only get back one child / the partition that we think got split)
// Then we need to refresh the cache
await this.feedRangeProvider.RefreshProviderAsync(childTrace, cancellationToken);
childRanges = await this.feedRangeProvider.GetChildRangeAsync(
currentPaginator.FeedRangeState.FeedRange,
childTrace,
cancellationToken);
}
if (childRanges.Count < 1)
{
string errorMessage = "SDK invariant violated 4795CC37: Must have at least one EPK range in a cross partition enumerator";
throw Resource.CosmosExceptions.CosmosExceptionFactory.CreateInternalServerErrorException(
message: errorMessage,
headers: null,
stackTrace: null,
trace: childTrace,
error: new Microsoft.Azure.Documents.Error { Code = "SDK_invariant_violated_4795CC37", Message = errorMessage });
}
if (childRanges.Count == 1)
{
// On a merge, the 410/1002 results in a single parent
// We maintain the current enumerator's range and let the RequestInvokerHandler logic kick in
enumerators.Enqueue(currentPaginator);
}
else
{
// Split
foreach (FeedRangeInternal childRange in childRanges)
{
PartitionRangePageAsyncEnumerator<TPage, TState> childPaginator = this.createPartitionRangeEnumerator(
new FeedRangeState<TState>(childRange, currentPaginator.FeedRangeState.State));
enumerators.Enqueue(childPaginator);
}
}
// Recursively retry
return await this.MoveNextAsync(childTrace, cancellationToken);
}
// Just enqueue the paginator and the user can decide if they want to retry.
enumerators.Enqueue(currentPaginator);
this.Current = TryCatch<CrossFeedRangePage<TPage, TState>>.FromException(currentPaginator.Current.Exception);
this.CurrentRange = currentPaginator.FeedRangeState.FeedRange;
this.nextState = CrossPartitionRangePageAsyncEnumerator<TPage, TState>.GetNextRange(enumerators);
return true;
}
if (currentPaginator.FeedRangeState.State != default)
{
// Don't enqueue the paginator otherwise it's an infinite loop.
enumerators.Enqueue(currentPaginator);
}
CrossFeedRangeState<TState> crossPartitionState;
if (enumerators.Count == 0)
{
crossPartitionState = null;
}
else
{
FeedRangeState<TState>[] feedRangeAndStates = new FeedRangeState<TState>[enumerators.Count];
int i = 0;
foreach (PartitionRangePageAsyncEnumerator<TPage, TState> enumerator in enumerators)
{
feedRangeAndStates[i++] = enumerator.FeedRangeState;
}
crossPartitionState = new CrossFeedRangeState<TState>(feedRangeAndStates);
}
this.Current = TryCatch<CrossFeedRangePage<TPage, TState>>.FromResult(
new CrossFeedRangePage<TPage, TState>(currentPaginator.Current.Result, crossPartitionState));
this.CurrentRange = currentPaginator.FeedRangeState.FeedRange;
this.nextState = CrossPartitionRangePageAsyncEnumerator<TPage, TState>.GetNextRange(enumerators);
return true;
}
}
public ValueTask DisposeAsync()
{
// Do Nothing.
return default;
}
public bool TryPeekNext(out FeedRangeState<TState> nextState)
{
if (this.nextState.HasValue)
{
nextState = this.nextState.Value;
return true;
}
nextState = default;
return false;
}
private static bool IsSplitException(Exception exeception)
{
return exeception is CosmosException cosmosException
&& (cosmosException.StatusCode == HttpStatusCode.Gone)
&& (cosmosException.SubStatusCode == (int)Documents.SubStatusCodes.PartitionKeyRangeGone);
}
private static FeedRangeState<TState>? GetNextRange(IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>> enumerators)
{
if (enumerators == null
|| enumerators.Count == 0)
{
return default;
}
return enumerators.Peek()?.FeedRangeState;
}
private static async Task<IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>>> InitializeEnumeratorsAsync(
IFeedRangeProvider feedRangeProvider,
CreatePartitionRangePageAsyncEnumerator<TPage, TState> createPartitionRangeEnumerator,
IComparer<PartitionRangePageAsyncEnumerator<TPage, TState>> comparer,
int? maxConcurrency,
PrefetchPolicy prefetchPolicy,
CrossFeedRangeState<TState> state,
ITrace trace,
CancellationToken token)
{
ReadOnlyMemory<FeedRangeState<TState>> rangeAndStates;
if (state != default)
{
rangeAndStates = state.Value;
}
else
{
// Fan out to all partitions with default state
List<FeedRangeEpk> ranges = await feedRangeProvider.GetFeedRangesAsync(trace, token);
List<FeedRangeState<TState>> rangesAndStatesBuilder = new List<FeedRangeState<TState>>(ranges.Count);
foreach (FeedRangeInternal range in ranges)
{
rangesAndStatesBuilder.Add(new FeedRangeState<TState>(range, default));
}
rangeAndStates = rangesAndStatesBuilder.ToArray();
}
IReadOnlyList<BufferedPartitionRangePageAsyncEnumeratorBase<TPage, TState>> bufferedEnumerators = CreateBufferedEnumerators(
prefetchPolicy,
createPartitionRangeEnumerator,
rangeAndStates,
token);
if (maxConcurrency.HasValue)
{
await ParallelPrefetch.PrefetchInParallelAsync(bufferedEnumerators, maxConcurrency.Value, trace, token);
}
IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>> queue = comparer == null
? new QueueWrapper<PartitionRangePageAsyncEnumerator<TPage, TState>>(
new Queue<PartitionRangePageAsyncEnumerator<TPage, TState>>(bufferedEnumerators))
: new PriorityQueueWrapper<PartitionRangePageAsyncEnumerator<TPage, TState>>(
new PriorityQueue<PartitionRangePageAsyncEnumerator<TPage, TState>>(
bufferedEnumerators,
comparer));
return queue;
}
private static IReadOnlyList<BufferedPartitionRangePageAsyncEnumeratorBase<TPage, TState>> CreateBufferedEnumerators(
PrefetchPolicy policy,
CreatePartitionRangePageAsyncEnumerator<TPage, TState> createPartitionRangeEnumerator,
ReadOnlyMemory<FeedRangeState<TState>> rangeAndStates,
CancellationToken cancellationToken)
{
List<BufferedPartitionRangePageAsyncEnumeratorBase<TPage, TState>> bufferedEnumerators = new (rangeAndStates.Length);
for (int i = 0; i < rangeAndStates.Length; i++)
{
FeedRangeState<TState> feedRangeState = rangeAndStates.Span[i];
PartitionRangePageAsyncEnumerator<TPage, TState> enumerator = createPartitionRangeEnumerator(feedRangeState);
BufferedPartitionRangePageAsyncEnumeratorBase<TPage, TState> bufferedEnumerator = policy switch
{
PrefetchPolicy.PrefetchSinglePage => new BufferedPartitionRangePageAsyncEnumerator<TPage, TState>(enumerator),
PrefetchPolicy.PrefetchAll => new FullyBufferedPartitionRangeAsyncEnumerator<TPage, TState>(enumerator),
_ => throw new ArgumentOutOfRangeException(nameof(policy)),
};
bufferedEnumerators.Add(bufferedEnumerator);
}
return bufferedEnumerators;
}
private interface IQueue<T> : IEnumerable<T>
{
T Peek();
void Enqueue(T item);
T Dequeue();
public int Count { get; }
}
private sealed class PriorityQueueWrapper<T> : IQueue<T>
{
private readonly PriorityQueue<T> implementation;
public PriorityQueueWrapper(PriorityQueue<T> implementation)
{
this.implementation = implementation ?? throw new ArgumentNullException(nameof(implementation));
}
public int Count => this.implementation.Count;
public T Dequeue() => this.implementation.Dequeue();
public void Enqueue(T item) => this.implementation.Enqueue(item);
public T Peek() => this.implementation.Peek();
public IEnumerator<T> GetEnumerator() => this.implementation.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.implementation.GetEnumerator();
}
private sealed class QueueWrapper<T> : IQueue<T>
{
private readonly Queue<T> implementation;
public QueueWrapper(Queue<T> implementation)
{
this.implementation = implementation ?? throw new ArgumentNullException(nameof(implementation));
}
public int Count => this.implementation.Count;
public T Dequeue() => this.implementation.Dequeue();
public void Enqueue(T item) => this.implementation.Enqueue(item);
public T Peek() => this.implementation.Peek();
public IEnumerator<T> GetEnumerator() => this.implementation.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.implementation.GetEnumerator();
}
}
}