Skip to content

Commit

Permalink
chore: backoff logic now handles retryAfterSeconds.
Browse files Browse the repository at this point in the history
  • Loading branch information
kahirokunn committed Jun 21, 2024
1 parent 90c1401 commit f85e2df
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
2 changes: 1 addition & 1 deletion packages/kubekit-client/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kubekit/client",
"version": "0.2.20",
"version": "0.2.21",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"author": "kahirokunn",
Expand Down
11 changes: 8 additions & 3 deletions packages/kubekit-client/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ReadableStream, TransformStream } from 'node:stream/web';
import { type ObjectReference } from '../lib/types';
import { KubeConfig } from '../lib/config';
import { KubernetesError, isKubernetesError, isTooLargeResourceVersion } from '../lib/error';
import { sleep } from '../lib/sleep';
export { sleep } from '../lib/sleep';
export { TaskManager } from '../lib/task_manager';

Expand Down Expand Up @@ -44,11 +45,15 @@ function removeNullableProperties<T extends Record<string, unknown | undefined>
* @param attempt - Current attempt
* @param maxRetries - Maximum number of retries
*/
async function defaultBackoff(attempt: number, maxRetries: number) {
async function defaultBackoff(attempt: number, maxRetries: number, error: unknown | KubernetesError) {
if (isKubernetesError(error) && 'retryAfterSeconds' in error.details) {
await sleep(error.details.retryAfterSeconds * 1000);
return;
}
const attempts = Math.min(attempt, maxRetries);

const timeout = Math.trunc((Math.random() + 0.4) * (300 << attempts));
await new Promise((resolve) => setTimeout((response: any) => resolve(response), timeout));
await sleep(timeout);
}

const isPlainObject = (value: any) => value?.constructor === Object;
Expand Down Expand Up @@ -434,7 +439,7 @@ $ k3d cluster create kubekit --k3s-arg '--kube-apiserver-arg=feature-gates=Watch
throw error;
}

await options.backoff(retry, options.maxRetries);
await options.backoff(retry, options.maxRetries, error);
}
}
}
Expand Down
12 changes: 9 additions & 3 deletions packages/kubekit-client/src/lib/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,20 @@ export type KubernetesError = {
message: string;
reason: string;
details: {
group: string;
kind: string;
causes: {
reason: string;
message: string;
field: string;
}[];
};
} & (
| {
group: string;
kind: string;
}
| {
retryAfterSeconds: number;
}
);
code: number;
};

Expand Down

0 comments on commit f85e2df

Please sign in to comment.