forked from ydb-platform/ydb-java-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSessionRetryContext.java
More file actions
443 lines (384 loc) · 16.4 KB
/
SessionRetryContext.java
File metadata and controls
443 lines (384 loc) · 16.4 KB
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package tech.ydb.table;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.MoreExecutors;
import tech.ydb.core.Result;
import tech.ydb.core.Status;
import tech.ydb.core.StatusCode;
import tech.ydb.core.UnexpectedResultException;
import tech.ydb.core.tracing.Scope;
import tech.ydb.core.tracing.Span;
import tech.ydb.core.tracing.SpanKind;
import tech.ydb.core.tracing.Tracer;
import tech.ydb.core.utils.FutureTools;
/**
* @author Sergey Polovko
*/
@ParametersAreNonnullByDefault
public class SessionRetryContext {
private static final String EXECUTE_SPAN_NAME = "ydb.Execute";
private static final String EXECUTE_WITH_RETRY_SPAN_NAME = "ydb.Retry";
private static final String RETRY_ATTEMPT_ATTR = "ydb.retry.attempt";
private static final String RETRY_SLEEP_MS_ATTR = "ydb.retry.sleep_ms";
private final SessionSupplier sessionSupplier;
private final Executor executor;
private final Duration sessionCreationTimeout;
private final int maxRetries;
private final long backoffSlotMillis;
private final int backoffCeiling;
private final long fastBackoffSlotMillis;
private final int fastBackoffCeiling;
private final boolean retryNotFound;
private final boolean idempotent;
private SessionRetryContext(Builder b) {
this.sessionSupplier = b.sessionSupplier;
this.executor = b.executor;
this.sessionCreationTimeout = b.sessionCreationTimeout;
this.maxRetries = b.maxRetries;
this.backoffSlotMillis = b.backoffSlotMillis;
this.backoffCeiling = b.backoffCeiling;
this.fastBackoffSlotMillis = b.fastBackoffSlotMillis;
this.fastBackoffCeiling = b.fastBackoffCeiling;
this.retryNotFound = b.retryNotFound;
this.idempotent = b.idempotent;
}
public static Builder create(SessionSupplier sessionSupplier) {
return new Builder(Objects.requireNonNull(sessionSupplier));
}
public <T> CompletableFuture<Result<T>> supplyResult(Function<Session, CompletableFuture<Result<T>>> fn) {
return supplyResult(SessionRetryHandler.DEFAULT, fn);
}
public CompletableFuture<Status> supplyStatus(Function<Session, CompletableFuture<Status>> fn) {
return supplyStatus(SessionRetryHandler.DEFAULT, fn);
}
public <T> CompletableFuture<Result<T>> supplyResult(SessionRetryHandler h,
Function<Session, CompletableFuture<Result<T>>> fn) {
RetryableResultTask<T> task = new RetryableResultTask<>(h, fn);
task.requestSession();
return task.getFuture();
}
public CompletableFuture<Status> supplyStatus(SessionRetryHandler h,
Function<Session, CompletableFuture<Status>> fn) {
RetryableStatusTask task = new RetryableStatusTask(h, fn);
task.requestSession();
return task.getFuture();
}
private boolean canRetry(StatusCode code) {
return code.isRetryable(idempotent) || (retryNotFound && code == StatusCode.NOT_FOUND);
}
private boolean canRetry(Throwable t) {
Throwable cause = FutureTools.unwrapCompletionException(t);
if (cause instanceof UnexpectedResultException) {
StatusCode statusCode = ((UnexpectedResultException) cause).getStatus().getCode();
return canRetry(statusCode);
}
return false;
}
private long backoffTimeMillisInternal(int retryNumber, long backoffSlotMillis, int backoffCeiling) {
int slots = 1 << Math.min(retryNumber, backoffCeiling);
long delay = backoffSlotMillis * slots;
return delay + ThreadLocalRandom.current().nextLong(delay);
}
private long slowBackoffTimeMillis(int retryNumber) {
return backoffTimeMillisInternal(retryNumber, backoffSlotMillis, backoffCeiling);
}
private long fastBackoffTimeMillis(int retryNumber) {
return backoffTimeMillisInternal(retryNumber, fastBackoffSlotMillis, fastBackoffCeiling);
}
private long backoffTimeMillis(StatusCode code, int retryNumber) {
switch (code) {
case BAD_SESSION:
// Instant retry
return 0;
case ABORTED:
case CLIENT_CANCELLED:
case CLIENT_INTERNAL_ERROR:
case SESSION_BUSY:
case TRANSPORT_UNAVAILABLE:
case UNAVAILABLE:
case UNDETERMINED:
// Fast backoff
return fastBackoffTimeMillis(retryNumber);
case NOT_FOUND:
case OVERLOADED:
case CLIENT_RESOURCE_EXHAUSTED:
default:
// Slow backoff
return slowBackoffTimeMillis(retryNumber);
}
}
private long backoffTimeMillis(Throwable t, int retryNumber) {
Throwable cause = FutureTools.unwrapCompletionException(t);
if (cause instanceof UnexpectedResultException) {
StatusCode statusCode = ((UnexpectedResultException) cause).getStatus().getCode();
return backoffTimeMillis(statusCode, retryNumber);
}
return slowBackoffTimeMillis(retryNumber);
}
/**
* BASE RETRYABLE TASK
*/
private abstract class BaseRetryableTask<R> implements Runnable {
private final CompletableFuture<R> promise = new CompletableFuture<>();
private final AtomicInteger retryNumber = new AtomicInteger();
private final Function<Session, CompletableFuture<R>> fn;
private final long createTimestamp = Instant.now().toEpochMilli();
private final SessionRetryHandler handler;
private final Tracer tracer;
private final Span executeSpan;
private Span retrySpan = Span.NOOP;
BaseRetryableTask(SessionRetryHandler h, Function<Session, CompletableFuture<R>> fn) {
this.fn = fn;
this.handler = h;
this.tracer = sessionSupplier.getTracer();
this.executeSpan = tracer.startSpan(EXECUTE_SPAN_NAME, SpanKind.INTERNAL);
this.promise.whenComplete(this::finishExecuteSpan);
}
CompletableFuture<R> getFuture() {
return promise;
}
abstract Status toStatus(R result);
abstract R toFailedResult(Result<Session> sessionResult);
private long ms() {
return Instant.now().toEpochMilli() - createTimestamp;
}
// called on timer expiration
@Override
public void run() {
if (promise.isCancelled()) {
handler.onCancel(SessionRetryContext.this, retryNumber.get(), ms());
finishRetrySpan(null, null);
return;
}
executor.execute(this::requestSession);
}
public void requestSession() {
try (@SuppressWarnings("unused") Scope ignored = executeSpan.makeCurrent()) {
retrySpan = tracer.startSpan(EXECUTE_WITH_RETRY_SPAN_NAME, SpanKind.INTERNAL);
}
CompletableFuture<Result<Session>> sessionFuture = createSessionWithRetrySpanParent();
if (sessionFuture.isDone() && !sessionFuture.isCompletedExceptionally()) {
// faster than subscribing on future
acceptSession(sessionFuture.join());
} else {
sessionFuture.whenCompleteAsync((result, th) -> {
if (result != null) {
acceptSession(result);
}
if (th != null) {
handleException(th);
}
}, executor);
}
}
private void acceptSession(@Nonnull Result<Session> sessionResult) {
if (!sessionResult.isSuccess()) {
handleError(sessionResult.getStatus(), toFailedResult(sessionResult));
return;
}
final Session session = sessionResult.getValue();
try {
try (@SuppressWarnings("unused") Scope ignored = retrySpan.makeCurrent()) {
fn.apply(session).whenComplete((fnResult, fnException) -> {
try {
try (@SuppressWarnings("unused") Scope ignored1 = retrySpan.makeCurrent()) {
session.close();
if (fnException != null) {
handleException(fnException);
return;
}
Status status = toStatus(fnResult);
if (status.isSuccess()) {
handler.onSuccess(SessionRetryContext.this, retryNumber.get(), ms());
finishRetrySpan(status, null);
promise.complete(fnResult);
} else {
handleError(status, fnResult);
}
}
} catch (Throwable unexpected) {
handler.onError(SessionRetryContext.this, unexpected, retryNumber.get(), ms());
finishRetrySpan(null, unexpected);
promise.completeExceptionally(unexpected);
}
});
}
} catch (RuntimeException ex) {
session.close();
handleException(ex);
}
}
private void scheduleNext(long delayMillis) {
if (promise.isCancelled()) {
return;
}
sessionSupplier.getScheduler().schedule(this, delayMillis, TimeUnit.MILLISECONDS);
}
private void handleError(@Nonnull Status status, R result) {
StatusCode code = status.getCode();
if (!canRetry(code)) {
handler.onError(SessionRetryContext.this, code, retryNumber.get(), ms());
finishRetrySpan(status, null);
promise.complete(result);
return;
}
int failedAttempt = retryNumber.get();
int retry = retryNumber.incrementAndGet();
if (retry <= maxRetries) {
long next = backoffTimeMillis(code, retry);
handler.onRetry(SessionRetryContext.this, code, retry, next, ms());
recordRetrySchedule(failedAttempt, next);
finishRetrySpan(status, null);
scheduleNext(next);
} else {
handler.onLimit(SessionRetryContext.this, code, maxRetries, ms());
finishRetrySpan(status, null);
promise.complete(result);
}
}
private void handleException(@Nonnull Throwable ex) {
// Check retrayable execption
if (!canRetry(ex)) {
handler.onError(SessionRetryContext.this, ex, retryNumber.get(), ms());
finishRetrySpan(null, ex);
promise.completeExceptionally(ex);
return;
}
int failedAttempt = retryNumber.get();
int retry = retryNumber.incrementAndGet();
if (retry <= maxRetries) {
long next = backoffTimeMillis(ex, retry);
handler.onRetry(SessionRetryContext.this, ex, retry, next, ms());
recordRetrySchedule(failedAttempt, next);
finishRetrySpan(null, ex);
scheduleNext(next);
} else {
handler.onLimit(SessionRetryContext.this, ex, maxRetries, ms());
finishRetrySpan(null, ex);
promise.completeExceptionally(ex);
}
}
private CompletableFuture<Result<Session>> createSessionWithRetrySpanParent() {
try (@SuppressWarnings("unused") Scope ignored = retrySpan.makeCurrent()) {
return sessionSupplier.createSession(sessionCreationTimeout);
}
}
private void recordRetrySchedule(int failedAttempt, long nextDelayMillis) {
retrySpan.setAttribute(RETRY_ATTEMPT_ATTR, failedAttempt);
retrySpan.setAttribute(RETRY_SLEEP_MS_ATTR, nextDelayMillis);
}
private void finishRetrySpan(Status status, Throwable throwable) {
retrySpan.setStatus(status, throwable);
retrySpan.end();
retrySpan = Span.NOOP;
}
private void finishExecuteSpan(R result, Throwable throwable) {
Throwable unwrapped = FutureTools.unwrapCompletionException(throwable);
Status status = toStatus(result);
executeSpan.setStatus(status, unwrapped);
executeSpan.end();
}
}
/**
* RETRYABLE RESULT TASK
*/
private final class RetryableResultTask<T> extends BaseRetryableTask<Result<T>> {
RetryableResultTask(SessionRetryHandler h, Function<Session, CompletableFuture<Result<T>>> fn) {
super(h, fn);
}
@Override
Status toStatus(Result<T> result) {
return result.getStatus();
}
@Override
Result<T> toFailedResult(Result<Session> sessionResult) {
return sessionResult.map(s -> null);
}
}
/**
* RETRYABLE STATUS TASK
*/
private final class RetryableStatusTask extends BaseRetryableTask<Status> {
RetryableStatusTask(SessionRetryHandler h, Function<Session, CompletableFuture<Status>> fn) {
super(h, fn);
}
@Override
Status toStatus(Status status) {
return status;
}
@Override
Status toFailedResult(Result<Session> sessionResult) {
return sessionResult.getStatus();
}
}
/**
* BUILDER
*/
@ParametersAreNonnullByDefault
public static final class Builder {
private final SessionSupplier sessionSupplier;
private Executor executor = MoreExecutors.directExecutor();
private Duration sessionCreationTimeout = Duration.ofSeconds(5);
private int maxRetries = 10;
private long backoffSlotMillis = 500;
private int backoffCeiling = 6;
private long fastBackoffSlotMillis = 5;
private int fastBackoffCeiling = 10;
private boolean retryNotFound = true;
private boolean idempotent = false;
public Builder(SessionSupplier sessionSupplier) {
this.sessionSupplier = sessionSupplier;
}
public Builder executor(Executor executor) {
this.executor = Objects.requireNonNull(executor);
return this;
}
public Builder sessionCreationTimeout(Duration duration) {
this.sessionCreationTimeout = duration;
return this;
}
public Builder maxRetries(int maxRetries) {
this.maxRetries = maxRetries;
return this;
}
public Builder backoffSlot(Duration duration) {
Preconditions.checkArgument(!duration.isNegative(), "backoffSlot(%s) is negative", duration);
this.backoffSlotMillis = duration.toMillis();
return this;
}
public Builder backoffCeiling(int backoffCeiling) {
this.backoffCeiling = backoffCeiling;
return this;
}
public Builder fastBackoffSlot(Duration duration) {
Preconditions.checkArgument(!duration.isNegative(), "backoffSlot(%s) is negative", duration);
this.fastBackoffSlotMillis = duration.toMillis();
return this;
}
public Builder fastBackoffCeiling(int backoffCeiling) {
this.fastBackoffCeiling = backoffCeiling;
return this;
}
public Builder retryNotFound(boolean retryNotFound) {
this.retryNotFound = retryNotFound;
return this;
}
public Builder idempotent(boolean idempotent) {
this.idempotent = idempotent;
return this;
}
public SessionRetryContext build() {
return new SessionRetryContext(this);
}
}
}