Skip to content

Commit f4a72cc

Browse files
author
Arthur Granado
committed
chore: extract the condition for retry request to the new function
Improve code maintainability and make it easier to include new logic to retry request, that now in its own scope.
1 parent a7abade commit f4a72cc

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

src/supervisor/kuberenetes-api-wrappers.ts

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as http from 'http';
22
import * as sleep from 'sleep-promise';
3+
import { IRequestError } from './types';
34

45
export const ATTEMPTS_MAX = 3;
56
export const DEFAULT_SLEEP_SEC = 1;
@@ -13,20 +14,11 @@ export async function retryKubernetesApiRequest<ResponseType>(
1314
try {
1415
return await func();
1516
} catch (err) {
16-
if (!(err.response)) {
17+
if (!shouldRetryRequest(err, attempt)) {
1718
throw err;
1819
}
1920

20-
const response = err.response;
21-
if (response.statusCode !== 429) {
22-
throw err;
23-
}
24-
25-
if (attempt === ATTEMPTS_MAX) {
26-
throw err;
27-
}
28-
29-
const sleepSeconds = calculateSleepSeconds(response);
21+
const sleepSeconds = calculateSleepSeconds(err.response);
3022
await sleep(sleepSeconds * 1000);
3123
}
3224
}
@@ -48,3 +40,19 @@ export function calculateSleepSeconds(httpResponse: http.IncomingMessage): numbe
4840
}
4941
return Math.min(sleepSeconds, MAX_SLEEP_SEC);
5042
}
43+
44+
function shouldRetryRequest(err: IRequestError, attempt: number): boolean {
45+
if (attempt >= ATTEMPTS_MAX) {
46+
return false;
47+
}
48+
49+
if (!(err.response)) {
50+
return false;
51+
}
52+
53+
if (err.response.statusCode === 429) {
54+
return true;
55+
}
56+
57+
return false;
58+
}

src/supervisor/types.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { IncomingMessage } from 'http';
12
import { AppsV1Api, BatchV1Api, BatchV1beta1Api, CoreV1Api, KubeConfig,
23
V1ObjectMeta, V1OwnerReference, V1PodSpec } from '@kubernetes/client-node';
34

@@ -12,6 +13,10 @@ export enum WorkloadKind {
1213
Pod = 'Pod',
1314
}
1415

16+
export interface IRequestError {
17+
response?: IncomingMessage;
18+
}
19+
1520
export interface IKubeObjectMetadata {
1621
kind: string;
1722
objectMeta: V1ObjectMeta;

0 commit comments

Comments
 (0)