-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathRestRequest.java
More file actions
710 lines (645 loc) · 26.8 KB
/
RestRequest.java
File metadata and controls
710 lines (645 loc) · 26.8 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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
/*
* Copyright (c) 2012-2022 Snowflake Computing Inc. All rights reserved.
*/
package net.snowflake.client.jdbc;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLKeyException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLProtocolException;
import net.snowflake.client.core.Event;
import net.snowflake.client.core.EventUtil;
import net.snowflake.client.core.ExecTimeTelemetryData;
import net.snowflake.client.core.HttpUtil;
import net.snowflake.client.core.SFOCSPException;
import net.snowflake.client.core.SessionUtil;
import net.snowflake.client.core.SnowflakeJdbcInternalApi;
import net.snowflake.client.core.URLUtil;
import net.snowflake.client.core.UUIDUtils;
import net.snowflake.client.jdbc.telemetryOOB.TelemetryService;
import net.snowflake.client.log.ArgSupplier;
import net.snowflake.client.log.SFLogger;
import net.snowflake.client.log.SFLoggerFactory;
import net.snowflake.client.util.DecorrelatedJitterBackoff;
import net.snowflake.client.util.SecretDetector;
import net.snowflake.client.util.Stopwatch;
import net.snowflake.common.core.SqlState;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
/**
* This is an abstraction on top of http client.
*
* <p>Currently it only has one method for retrying http request execution so that the same logic
* doesn't have to be replicated at difference places where retry is needed.
*
* @author jhuang
*/
public class RestRequest {
private static final SFLogger logger = SFLoggerFactory.getLogger(RestRequest.class);
// Request guid per HTTP request
private static final String SF_REQUEST_GUID = "request_guid";
// min backoff in milli before we retry due to transient issues
private static final long minBackoffInMilli = 1000;
// max backoff in milli before we retry due to transient issues
// we double the backoff after each retry till we reach the max backoff
private static final long maxBackoffInMilli = 16000;
// retry at least once even if timeout limit has been reached
private static final int MIN_RETRY_COUNT = 1;
public static CloseableHttpResponse execute(
CloseableHttpClient httpClient,
HttpRequestBase httpRequest,
long retryTimeout,
long authTimeout,
int socketTimeout,
int maxRetries,
int injectSocketTimeout,
AtomicBoolean canceling,
boolean withoutCookies,
boolean includeRetryParameters,
boolean includeRequestGuid,
boolean retryHTTP403,
ExecTimeTelemetryData execTimeTelemetryData)
throws SnowflakeSQLException {
return execute(
httpClient,
httpRequest,
retryTimeout,
authTimeout,
socketTimeout,
maxRetries,
injectSocketTimeout,
canceling,
withoutCookies,
includeRetryParameters,
includeRequestGuid,
retryHTTP403,
false, // noRetry
execTimeTelemetryData);
}
/**
* Execute an http request with retry logic.
*
* @param httpClient client object used to communicate with other machine
* @param httpRequest request object contains all the request information
* @param retryTimeout : retry timeout (in seconds)
* @param authTimeout : authenticator specific timeout (in seconds)
* @param socketTimeout : curl timeout (in ms)
* @param maxRetries : max retry count for the request
* @param injectSocketTimeout : simulate socket timeout
* @param canceling canceling flag
* @param withoutCookies whether the cookie spec should be set to IGNORE or not
* @param includeRetryParameters whether to include retry parameters in retried requests. Only
* needs to be true for JDBC statement execution (query requests to Snowflake server).
* @param includeRequestGuid whether to include request_guid parameter
* @param retryHTTP403 whether to retry on HTTP 403 or not
* @param noRetry should we disable retry on non-successful http resp code
* @param execTimeData ExecTimeTelemetryData
* @return HttpResponse Object get from server
* @throws net.snowflake.client.jdbc.SnowflakeSQLException Request timeout Exception or Illegal
* State Exception i.e. connection is already shutdown etc
*/
public static CloseableHttpResponse execute(
CloseableHttpClient httpClient,
HttpRequestBase httpRequest,
long retryTimeout,
long authTimeout,
int socketTimeout,
int maxRetries,
int injectSocketTimeout,
AtomicBoolean canceling,
boolean withoutCookies,
boolean includeRetryParameters,
boolean includeRequestGuid,
boolean retryHTTP403,
boolean noRetry,
ExecTimeTelemetryData execTimeData)
throws SnowflakeSQLException {
Stopwatch stopwatch = null;
if (logger.isDebugEnabled()) {
stopwatch = new Stopwatch();
stopwatch.start();
}
String requestInfoScrubbed = SecretDetector.maskSASToken(httpRequest.toString());
String requestIdStr = URLUtil.getRequestIdLogStr(httpRequest.getURI());
logger.debug(
"{}Executing rest request: {}, retry timeout: {}, socket timeout: {}, max retries: {},"
+ " inject socket timeout: {}, canceling: {}, without cookies: {}, include retry parameters: {},"
+ " include request guid: {}, retry http 403: {}, no retry: {}",
requestIdStr,
requestInfoScrubbed,
retryTimeout,
socketTimeout,
maxRetries,
injectSocketTimeout,
canceling,
withoutCookies,
includeRetryParameters,
includeRequestGuid,
retryHTTP403,
noRetry);
CloseableHttpResponse response = null;
// time the client started attempting to submit request
final long startTime = System.currentTimeMillis();
// start time for each request,
// used for keeping track how much time we have spent
// due to network issues so that we can compare against the user
// specified network timeout to make sure we do not retry infinitely
// when there are transient network/GS issues.
long startTimePerRequest = startTime;
// Used to indicate that this is a login/auth request and will be using the new retry strategy.
boolean isLoginRequest = SessionUtil.isNewRetryStrategyRequest(httpRequest);
if (isLoginRequest) {
logger.debug("{}Request is a login/auth request. Using new retry strategy", requestIdStr);
}
// total elapsed time due to transient issues.
long elapsedMilliForTransientIssues = 0;
// retry timeout (ms)
long retryTimeoutInMilliseconds = retryTimeout * 1000;
// amount of time to wait for backing off before retry
long backoffInMilli = minBackoffInMilli;
// auth timeout (ms)
long authTimeoutInMilli = authTimeout * 1000;
DecorrelatedJitterBackoff backoff =
new DecorrelatedJitterBackoff(backoffInMilli, maxBackoffInMilli);
int origSocketTimeout = 0;
Exception savedEx = null;
// label the reason to break retry
String breakRetryReason = "";
String lastStatusCodeForRetry = "";
int retryCount = 0;
// try request till we get a good response or retry timeout
while (true) {
logger.debug(
"{}Retry count: {}, max retries: {}, retry timeout: {} s, backoff: {} ms. Attempting request: {}",
requestIdStr,
retryCount,
maxRetries,
retryTimeout,
backoffInMilli,
requestInfoScrubbed);
try {
// update start time
startTimePerRequest = System.currentTimeMillis();
if (withoutCookies) {
httpRequest.setConfig(HttpUtil.getRequestConfigWithoutCookies());
}
// for first call, simulate a socket timeout by setting socket timeout
// to the injected socket timeout value
if (injectSocketTimeout != 0 && retryCount == 0) {
// test code path
logger.debug(
"{}Injecting socket timeout by setting socket timeout to {} ms",
requestIdStr,
injectSocketTimeout);
httpRequest.setConfig(
HttpUtil.getDefaultRequestConfigWithSocketTimeout(
injectSocketTimeout, withoutCookies));
}
/*
* Add retryCount if the first request failed
* GS can uses the parameter for optimization. Specifically GS
* will only check metadata database to see if a query has been running
* for a retry request. This way for the majority of query requests
* which are not part of retry we don't have to pay the performance
* overhead of looking up in metadata database.
*/
URIBuilder builder = new URIBuilder(httpRequest.getURI());
// If HTAP
if ("true".equalsIgnoreCase(System.getenv("HTAP_SIMULATION"))
&& builder.getPathSegments().contains("query-request")) {
logger.debug("{}Setting htap simulation", requestIdStr);
builder.setParameter("target", "htap_simulation");
}
if (includeRetryParameters && retryCount > 0) {
updateRetryParameters(builder, retryCount, lastStatusCodeForRetry, startTime);
}
// When the auth timeout is set, set the socket timeout as the authTimeout
// so that it can be renewed in time and pass it to the http request configuration.
if (authTimeout > 0) {
int requestSocketAndConnectTimeout = (int) authTimeout * 1000;
logger.debug(
"{}Setting auth timeout as the socket timeout: {} s", requestIdStr, authTimeout);
httpRequest.setConfig(
HttpUtil.getDefaultRequestConfigWithSocketAndConnectTimeout(
requestSocketAndConnectTimeout, withoutCookies));
}
if (includeRequestGuid) {
UUID guid = UUIDUtils.getUUID();
logger.debug("{}Request {} guid: {}", requestIdStr, requestInfoScrubbed, guid.toString());
// Add request_guid for better tracing
builder.setParameter(SF_REQUEST_GUID, guid.toString());
}
httpRequest.setURI(builder.build());
execTimeData.setHttpClientStart();
response = httpClient.execute(httpRequest);
execTimeData.setHttpClientEnd();
} catch (IllegalStateException ex) {
// if exception is caused by illegal state, e.g shutdown of http client
// because of closing of connection, then fail immediately and stop retrying.
throw new SnowflakeSQLLoggedException(
null, ErrorCode.INVALID_STATE, ex, /* session= */ ex.getMessage());
} catch (SSLHandshakeException
| SSLKeyException
| SSLPeerUnverifiedException
| SSLProtocolException ex) {
// if an SSL issue occurs like an SSLHandshakeException then fail
// immediately and stop retrying the requests
String formattedMsg =
ex.getMessage()
+ "\n"
+ "Verify that the hostnames and portnumbers in SYSTEM$ALLOWLIST are added to your firewall's allowed list.\n"
+ "To troubleshoot your connection further, you can refer to this article:\n"
+ "https://docs.snowflake.com/en/user-guide/client-connectivity-troubleshooting/overview";
throw new SnowflakeSQLLoggedException(null, ErrorCode.NETWORK_ERROR, ex, formattedMsg);
} catch (Exception ex) {
savedEx = ex;
// if the request took more than socket timeout log an error
long currentMillis = System.currentTimeMillis();
if ((currentMillis - startTimePerRequest) > HttpUtil.getSocketTimeout().toMillis()) {
logger.warn(
"{}HTTP request took longer than socket timeout {} ms: {} ms",
requestIdStr,
HttpUtil.getSocketTimeout().toMillis(),
(currentMillis - startTimePerRequest));
}
StringWriter sw = new StringWriter();
savedEx.printStackTrace(new PrintWriter(sw));
logger.debug(
"{}Exception encountered for: {}, {}, {}",
requestIdStr,
requestInfoScrubbed,
ex.getLocalizedMessage(),
(ArgSupplier) sw::toString);
} finally {
// Reset the socket timeout to its original value if it is not the
// very first iteration.
if (injectSocketTimeout != 0 && retryCount == 0) {
// test code path
httpRequest.setConfig(
HttpUtil.getDefaultRequestConfigWithSocketTimeout(origSocketTimeout, withoutCookies));
}
}
/*
* If we got a response and the status code is not one of those
* transient failures, no more retry
*/
if (noRetry
|| isCertificateRevoked(savedEx)
|| isNonRetryableHTTPCode(response, retryHTTP403)) {
String msg = "Unknown cause";
if (response != null) {
logger.debug(
"{}HTTP response code for request {}: {}",
requestIdStr,
requestInfoScrubbed,
response.getStatusLine().getStatusCode());
msg =
"StatusCode: "
+ response.getStatusLine().getStatusCode()
+ ", Reason: "
+ response.getStatusLine().getReasonPhrase();
} else if (savedEx != null) // may be null.
{
Throwable rootCause = getRootCause(savedEx);
msg = rootCause.getMessage();
}
if (response == null || response.getStatusLine().getStatusCode() != 200) {
logger.debug(
"{}Error response not retryable, " + msg + ", request: {}",
requestIdStr,
requestInfoScrubbed);
EventUtil.triggerBasicEvent(
Event.EventType.NETWORK_ERROR, msg + ", Request: " + httpRequest, false);
}
breakRetryReason = "status code does not need retry";
if (noRetry) {
logger.debug(
"{}HTTP retry disabled for this request. noRetry: {}", requestIdStr, noRetry);
breakRetryReason = "retry is disabled";
}
// reset retryCount
retryCount = 0;
break;
} else {
if (response != null) {
logger.debug(
"{}HTTP response not ok: status code: {}, request: {}",
requestIdStr,
response.getStatusLine().getStatusCode(),
requestInfoScrubbed);
} else if (savedEx != null) {
logger.debug(
"{}Null response for cause: {}, request: {}",
requestIdStr,
getRootCause(savedEx).getMessage(),
requestInfoScrubbed);
} else {
logger.debug("{}Null response for request: {}", requestIdStr, requestInfoScrubbed);
}
// get the elapsed time for the last request
// elapsed in millisecond for last call, used for calculating the
// remaining amount of time to sleep:
// (backoffInMilli - elapsedMilliForLastCall)
long elapsedMilliForLastCall = System.currentTimeMillis() - startTimePerRequest;
// check canceling flag
if (canceling != null && canceling.get()) {
logger.debug("{}Stop retrying since canceling is requested", requestIdStr);
breakRetryReason = "canceling is requested";
break;
}
String breakRetryEventName = "";
if (retryTimeoutInMilliseconds > 0) {
// Check for retry time-out.
// increment total elapsed due to transient issues
elapsedMilliForTransientIssues += elapsedMilliForLastCall;
// check if the total elapsed time for transient issues has exceeded
// the retry timeout and we retry at least the min, if so, we will not
// retry
if (elapsedMilliForTransientIssues > retryTimeoutInMilliseconds
&& retryCount >= MIN_RETRY_COUNT) {
logger.error(
"{}Stop retrying since elapsed time due to network "
+ "issues has reached timeout. "
+ "Elapsed: {} ms, timeout: {} ms",
requestIdStr,
elapsedMilliForTransientIssues,
retryTimeoutInMilliseconds);
breakRetryReason = "retry timeout";
breakRetryEventName = "HttpRequestRetryTimeout";
}
}
if (maxRetries > 0 && retryCount > maxRetries) {
// check for max retries.
logger.error(
"{}Stop retrying as max retries have been reached for request: {}! Max retry count: {}",
requestIdStr,
requestInfoScrubbed,
maxRetries);
breakRetryReason = "max retries reached";
breakRetryEventName = "HttpRequestRetryLimitExceeded";
}
if (breakRetryEventName != "" && !breakRetryEventName.isEmpty()) {
// If either of network timeout is exhausted or max retries have been reached, stop
// retrying!
TelemetryService.getInstance()
.logHttpRequestTelemetryEvent(
breakRetryEventName,
httpRequest,
injectSocketTimeout,
canceling,
withoutCookies,
includeRetryParameters,
includeRequestGuid,
response,
savedEx,
breakRetryReason,
retryTimeout,
retryCount,
SqlState.IO_ERROR,
ErrorCode.NETWORK_ERROR.getMessageCode());
// rethrow the timeout exception
if (response == null && savedEx != null) {
throw new SnowflakeSQLException(
savedEx,
ErrorCode.NETWORK_ERROR,
"Exception encountered for HTTP request: " + savedEx.getMessage());
}
// no more retry
// reset state
retryCount = 0;
break;
}
// If this was a request for an Okta one-time token that failed with a retry-able error,
// throw exception to renew the token before trying again.
if (String.valueOf(httpRequest.getURI()).contains("okta.com/api/v1/authn")) {
throw new SnowflakeSQLException(
ErrorCode.AUTHENTICATOR_REQUEST_TIMEOUT,
retryCount,
true,
elapsedMilliForTransientIssues / 1000);
}
// Make sure that any authenticator specific info that needs to be
// updated get's updated before the next retry. Ex - JWT token
// Check to see if customer set socket/connect timeout has been reached,
// if not we don't increase the retry count since JWT renew doesn't count as a retry
// attempt.
if (authTimeout > 0
&& elapsedMilliForTransientIssues > authTimeoutInMilli
&& (socketTimeout == 0
|| elapsedMilliForTransientIssues
< socketTimeout)) /* socket timeout not reached */ {
/* connect timeout not reached */
// check if this is a login-request
if (String.valueOf(httpRequest.getURI()).contains("login-request")) {
throw new SnowflakeSQLException(
ErrorCode.AUTHENTICATOR_REQUEST_TIMEOUT,
retryCount,
true,
elapsedMilliForTransientIssues / 1000);
}
}
// sleep for backoff - elapsed amount of time
if (backoffInMilli > elapsedMilliForLastCall) {
try {
logger.debug(
"{}Retry request {}: sleeping for {} ms",
requestIdStr,
requestInfoScrubbed,
backoffInMilli);
Thread.sleep(backoffInMilli);
} catch (InterruptedException ex1) {
logger.debug("{}Backoff sleep before retrying login got interrupted", requestIdStr);
}
elapsedMilliForTransientIssues += backoffInMilli;
backoffInMilli =
getNewBackoffInMilli(
backoffInMilli,
isLoginRequest,
backoff,
retryCount,
retryTimeoutInMilliseconds,
elapsedMilliForTransientIssues);
}
retryCount++;
lastStatusCodeForRetry =
response == null ? "0" : String.valueOf(response.getStatusLine().getStatusCode());
// If the request failed with any other retry-able error and auth timeout is reached
// increase the retry count and throw special exception to renew the token before retrying.
if (authTimeout > 0) {
if (elapsedMilliForTransientIssues >= authTimeoutInMilli) {
throw new SnowflakeSQLException(
ErrorCode.AUTHENTICATOR_REQUEST_TIMEOUT,
retryCount,
false,
elapsedMilliForTransientIssues / 1000);
}
}
int numOfRetryToTriggerTelemetry =
TelemetryService.getInstance().getNumOfRetryToTriggerTelemetry();
if (retryCount == numOfRetryToTriggerTelemetry) {
TelemetryService.getInstance()
.logHttpRequestTelemetryEvent(
String.format("HttpRequestRetry%dTimes", numOfRetryToTriggerTelemetry),
httpRequest,
injectSocketTimeout,
canceling,
withoutCookies,
includeRetryParameters,
includeRequestGuid,
response,
savedEx,
breakRetryReason,
retryTimeout,
retryCount,
SqlState.IO_ERROR,
ErrorCode.NETWORK_ERROR.getMessageCode());
}
savedEx = null;
// release connection before retry
httpRequest.releaseConnection();
}
}
if (response == null) {
if (savedEx != null) {
logger.error(
"{}Returning null response. Cause: {}, request: {}",
requestIdStr,
getRootCause(savedEx),
requestInfoScrubbed);
} else {
logger.error(
"{}Returning null response for request: {}", requestIdStr, requestInfoScrubbed);
}
} else if (response.getStatusLine().getStatusCode() != 200) {
logger.error(
"{}Error response: HTTP Response code: {}, request: {}",
requestIdStr,
response.getStatusLine().getStatusCode(),
requestInfoScrubbed);
}
if ((response == null || response.getStatusLine().getStatusCode() != 200)) {
String eventName;
if (response == null) {
eventName = "NullResponseHttpError";
} else {
if (response.getStatusLine() == null) {
eventName = "NullResponseStatusLine";
} else {
eventName = String.format("HttpError%d", response.getStatusLine().getStatusCode());
}
}
TelemetryService.getInstance()
.logHttpRequestTelemetryEvent(
eventName,
httpRequest,
injectSocketTimeout,
canceling,
withoutCookies,
includeRetryParameters,
includeRequestGuid,
response,
savedEx,
breakRetryReason,
retryTimeout,
retryCount,
null,
0);
// rethrow the timeout exception
if (response == null && savedEx != null) {
throw new SnowflakeSQLException(
savedEx,
ErrorCode.NETWORK_ERROR,
"Exception encountered for HTTP request: " + savedEx.getMessage());
}
}
if (logger.isDebugEnabled() && stopwatch != null) {
stopwatch.stop();
}
logger.debug(
"{}Execution of request {} took {} ms with total of {} retries",
requestIdStr,
requestInfoScrubbed,
stopwatch == null ? "n/a" : stopwatch.elapsedMillis(),
retryCount);
return response;
}
@SnowflakeJdbcInternalApi
public static void updateRetryParameters(
URIBuilder builder, int retryCount, String lastStatusCodeForRetry, long startTime) {
builder.setParameter("retryCount", String.valueOf(retryCount));
builder.setParameter("retryReason", lastStatusCodeForRetry);
builder.setParameter("clientStartTime", String.valueOf(startTime));
}
static long getNewBackoffInMilli(
long previousBackoffInMilli,
boolean isLoginRequest,
DecorrelatedJitterBackoff decorrelatedJitterBackoff,
int retryCount,
long retryTimeoutInMilliseconds,
long elapsedMilliForTransientIssues) {
long backoffInMilli;
if (isLoginRequest) {
long jitteredBackoffInMilli =
decorrelatedJitterBackoff.getJitterForLogin(previousBackoffInMilli);
backoffInMilli =
(long)
decorrelatedJitterBackoff.chooseRandom(
jitteredBackoffInMilli + previousBackoffInMilli,
Math.pow(2, retryCount) + jitteredBackoffInMilli);
} else {
backoffInMilli = decorrelatedJitterBackoff.nextSleepTime(previousBackoffInMilli);
}
backoffInMilli = Math.min(maxBackoffInMilli, Math.max(previousBackoffInMilli, backoffInMilli));
if (retryTimeoutInMilliseconds > 0
&& (elapsedMilliForTransientIssues + backoffInMilli) > retryTimeoutInMilliseconds) {
// If the timeout will be reached before the next backoff, just use the remaining
// time (but cannot be negative) - this is the only place when backoff is not in range
// min-max.
backoffInMilli =
Math.max(
0,
Math.min(
backoffInMilli, retryTimeoutInMilliseconds - elapsedMilliForTransientIssues));
logger.debug(
"We are approaching retry timeout {}ms, setting backoff to {}ms",
retryTimeoutInMilliseconds,
backoffInMilli);
}
return backoffInMilli;
}
static boolean isNonRetryableHTTPCode(CloseableHttpResponse response, boolean retryHTTP403) {
return response != null
&& (response.getStatusLine().getStatusCode() < 500
|| // service unavailable
response.getStatusLine().getStatusCode() >= 600)
&& // gateway timeout
response.getStatusLine().getStatusCode() != 408
&& // retry
response.getStatusLine().getStatusCode() != 429
&& // request timeout
(!retryHTTP403 || response.getStatusLine().getStatusCode() != 403);
}
private static boolean isCertificateRevoked(Exception ex) {
if (ex == null) {
return false;
}
Throwable ex0 = getRootCause(ex);
if (!(ex0 instanceof SFOCSPException)) {
return false;
}
SFOCSPException cause = (SFOCSPException) ex0;
return cause.getErrorCode() == OCSPErrorCode.CERTIFICATE_STATUS_REVOKED;
}
private static Throwable getRootCause(Throwable ex) {
Throwable ex0 = ex;
while (ex0.getCause() != null) {
ex0 = ex0.getCause();
}
return ex0;
}
}