/
BulkAllObservable.cs
282 lines (242 loc) · 10.4 KB
/
BulkAllObservable.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
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using OpenSearch.Net;
namespace OpenSearch.Client
{
public class BulkAllObservable<T> : IDisposable, IObservable<BulkAllResponse> where T : class
{
private readonly int _backOffRetries;
private readonly TimeSpan _backOffTime;
private readonly int _bulkSize;
private readonly IOpenSearchClient _client;
private readonly CancellationToken _compositeCancelToken;
private readonly CancellationTokenSource _compositeCancelTokenSource;
private readonly Action<BulkResponseItemBase, T> _droppedDocumentCallBack;
private readonly int _maxDegreeOfParallelism;
private readonly IBulkAllRequest<T> _partitionedBulkRequest;
private readonly Func<BulkResponseItemBase, T, bool> _retryPredicate;
private Action _incrementFailed = () => { };
private Action _incrementRetries = () => { };
private readonly Action<BulkResponse> _bulkResponseCallback;
public BulkAllObservable(
IOpenSearchClient client,
IBulkAllRequest<T> partitionedBulkRequest,
CancellationToken cancellationToken = default
)
{
_client = client;
_partitionedBulkRequest = partitionedBulkRequest;
_backOffRetries = _partitionedBulkRequest.BackOffRetries.GetValueOrDefault(CoordinatedRequestDefaults.BulkAllBackOffRetriesDefault);
_backOffTime = _partitionedBulkRequest?.BackOffTime?.ToTimeSpan() ?? CoordinatedRequestDefaults.BulkAllBackOffTimeDefault;
_bulkSize = _partitionedBulkRequest.Size ?? CoordinatedRequestDefaults.BulkAllSizeDefault;
_retryPredicate = _partitionedBulkRequest.RetryDocumentPredicate ?? RetryBulkActionPredicate;
_droppedDocumentCallBack = _partitionedBulkRequest.DroppedDocumentCallback ?? DroppedDocumentCallbackDefault;
_bulkResponseCallback = _partitionedBulkRequest.BulkResponseCallback;
_maxDegreeOfParallelism =
_partitionedBulkRequest.MaxDegreeOfParallelism ?? CoordinatedRequestDefaults.BulkAllMaxDegreeOfParallelismDefault;
_compositeCancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_compositeCancelToken = _compositeCancelTokenSource.Token;
}
public void Dispose()
{
_compositeCancelTokenSource?.Cancel();
_compositeCancelTokenSource?.Dispose();
}
public IDisposable Subscribe(IObserver<BulkAllResponse> observer)
{
observer.ThrowIfNull(nameof(observer));
BulkAll(observer);
return this;
}
public IDisposable Subscribe(BulkAllObserver observer)
{
_incrementFailed = observer.IncrementTotalNumberOfFailedBuffers;
_incrementRetries = observer.IncrementTotalNumberOfRetries;
return Subscribe((IObserver<BulkAllResponse>)observer);
}
private void BulkAll(IObserver<BulkAllResponse> observer)
{
var documents = _partitionedBulkRequest.Documents;
var partitioned = new PartitionHelper<T>(documents, _bulkSize);
#pragma warning disable 4014
partitioned.ForEachAsync(
#pragma warning restore 4014
(buffer, page) => BulkAsync(buffer, page, 0),
(buffer, response) => observer.OnNext(response),
ex => OnCompleted(ex, observer),
_maxDegreeOfParallelism
);
}
private void OnCompleted(Exception exception, IObserver<BulkAllResponse> observer)
{
if (exception != null)
observer.OnError(exception);
else
{
try
{
RefreshOnCompleted();
observer.OnCompleted();
}
catch (Exception e)
{
observer.OnError(e);
}
}
}
private void RefreshOnCompleted()
{
if (!_partitionedBulkRequest.RefreshOnCompleted) return;
var indices = _partitionedBulkRequest.RefreshIndices ?? _partitionedBulkRequest.Index;
if (indices == null) return;
var refresh = _client.Indices.Refresh(indices, r => r.RequestConfiguration(rc =>
{
switch (_partitionedBulkRequest)
{
case IHelperCallable helperCallable when helperCallable.ParentMetaData is object:
rc.RequestMetaData(helperCallable.ParentMetaData);
break;
default:
rc.RequestMetaData(RequestMetaDataFactory.BulkHelperRequestMetaData());
break;
}
return rc;
}));
if (!refresh.IsValid) throw Throw($"Refreshing after all documents have indexed failed", refresh.ApiCall);
}
private async Task<BulkAllResponse> BulkAsync(IList<T> buffer, long page, int backOffRetries)
{
_compositeCancelToken.ThrowIfCancellationRequested();
var request = _partitionedBulkRequest;
var response = await _client.BulkAsync(s =>
{
s.Index(request.Index);
s.Timeout(request.Timeout);
if (request.BufferToBulk != null) request.BufferToBulk(s, buffer);
else s.IndexMany(buffer);
if (!string.IsNullOrEmpty(request.Pipeline)) s.Pipeline(request.Pipeline);
if (request.Routing != null) s.Routing(request.Routing);
if (request.WaitForActiveShards.HasValue) s.WaitForActiveShards(request.WaitForActiveShards.ToString());
switch (_partitionedBulkRequest)
{
case IHelperCallable helperCallable when helperCallable.ParentMetaData is object:
s.RequestConfiguration(rc => rc.RequestMetaData(helperCallable.ParentMetaData));
break;
default:
s.RequestConfiguration(rc => rc.RequestMetaData(RequestMetaDataFactory.BulkHelperRequestMetaData()));
break;
}
return s;
}, _compositeCancelToken)
.ConfigureAwait(false);
_compositeCancelToken.ThrowIfCancellationRequested();
_bulkResponseCallback?.Invoke(response);
if (!response.ApiCall.Success)
return await HandleBulkRequest(buffer, page, backOffRetries, response).ConfigureAwait(false);
var retryableDocuments = new List<T>();
var droppedDocuments = new List<Tuple<BulkResponseItemBase, T>>();
foreach (var documentWithResponse in response.Items.Zip(buffer, Tuple.Create))
{
if (documentWithResponse.Item1.IsValid) continue;
if (_retryPredicate(documentWithResponse.Item1, documentWithResponse.Item2))
retryableDocuments.Add(documentWithResponse.Item2);
else
droppedDocuments.Add(documentWithResponse);
}
HandleDroppedDocuments(droppedDocuments, response);
if (retryableDocuments.Count > 0 && backOffRetries < _backOffRetries)
return await RetryDocuments(page, ++backOffRetries, retryableDocuments).ConfigureAwait(false);
if (retryableDocuments.Count > 0)
throw ThrowOnBadBulk(response, $"Bulk indexing failed and after retrying {backOffRetries} times");
request.BackPressure?.Release();
return new BulkAllResponse { Retries = backOffRetries, Page = page, Items = response.Items };
}
private void HandleDroppedDocuments(List<Tuple<BulkResponseItemBase, T>> droppedDocuments, BulkResponse response)
{
if (droppedDocuments.Count <= 0) return;
foreach (var dropped in droppedDocuments) _droppedDocumentCallBack(dropped.Item1, dropped.Item2);
if (!_partitionedBulkRequest.ContinueAfterDroppedDocuments)
throw ThrowOnBadBulk(response, $"{nameof(BulkAll)} halted after receiving failures that can not be retried from _bulk");
}
private async Task<BulkAllResponse> HandleBulkRequest(IList<T> buffer, long page, int backOffRetries, BulkResponse response)
{
var clientException = response.ApiCall.OriginalException as OpenSearchClientException;
var failureReason = clientException?.FailureReason;
var reason = failureReason?.GetStringValue() ?? nameof(PipelineFailure.BadRequest);
switch (failureReason)
{
case PipelineFailure.MaxRetriesReached:
if (response.ApiCall.AuditTrail.Last().Event == AuditEvent.FailedOverAllNodes)
throw ThrowOnBadBulk(response, $"{nameof(BulkAll)} halted after attempted bulk failed over all the active nodes");
ThrowOnExhaustedRetries();
return await RetryDocuments(page, ++backOffRetries, buffer).ConfigureAwait(false);
case PipelineFailure.CouldNotStartSniffOnStartup:
case PipelineFailure.BadAuthentication:
case PipelineFailure.NoNodesAttempted:
case PipelineFailure.SniffFailure:
case PipelineFailure.Unexpected:
throw ThrowOnBadBulk(response, $"{nameof(BulkAll)} halted after {nameof(PipelineFailure)}.{reason} from _bulk");
case PipelineFailure.BadResponse:
case PipelineFailure.PingFailure:
case PipelineFailure.MaxTimeoutReached:
case PipelineFailure.BadRequest:
default:
ThrowOnExhaustedRetries();
return await RetryDocuments(page, ++backOffRetries, buffer).ConfigureAwait(false);
}
void ThrowOnExhaustedRetries()
{
if (backOffRetries < _backOffRetries) return;
throw ThrowOnBadBulk(response,
$"{nameof(BulkAll)} halted after {nameof(PipelineFailure)}.{reason} from _bulk and exhausting retries ({backOffRetries})"
);
}
}
private async Task<BulkAllResponse> RetryDocuments(long page, int backOffRetries, IList<T> retryDocuments)
{
_incrementRetries();
await Task.Delay(_backOffTime, _compositeCancelToken).ConfigureAwait(false);
return await BulkAsync(retryDocuments, page, backOffRetries).ConfigureAwait(false);
}
private Exception ThrowOnBadBulk(IOpenSearchResponse response, string message)
{
_incrementFailed();
_partitionedBulkRequest.BackPressure?.Release();
return Throw(message, response.ApiCall);
}
private static OpenSearchClientException Throw(string message, IApiCallDetails details) =>
new OpenSearchClientException(PipelineFailure.BadResponse, message, details);
private static bool RetryBulkActionPredicate(BulkResponseItemBase bulkResponseItem, T d) => bulkResponseItem.Status == 429;
private static void DroppedDocumentCallbackDefault(BulkResponseItemBase bulkResponseItem, T d) { }
}
}