Repository navigation
feat(cli): respect standard AWS retry settings #2190
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
a190363
91032f5
12b581c
a1ca591
68f0cc3
2e824fa
eee2248
9b02381
9dc68ff
82d8102
e4476a7
0484f94
e0ba975
5f8457c
afd1d10
6814862
208b3f4
1ccc6a8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; | ||
| import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; | ||
| import type { SdkRetrySettings } from './types'; | ||
| import { ToolkitError } from '../../toolkit/toolkit-error'; | ||
|
|
||
| /** | ||
| * The retry strategies the CLI can hand to an SDK client | ||
| */ | ||
| export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy; | ||
|
|
||
| /** | ||
| * Build the retry strategy for an SDK client | ||
| * | ||
| * Passing an explicit `retryStrategy` to an SDK client makes the SDK ignore the user's retry | ||
| * configuration, so we apply the user's settings here and fall back to `defaultMaxAttempts` | ||
| * when they have not set one. The backoff schedule is not user-configurable: there is no | ||
| * standard setting for it, and we tune it per client. | ||
| * | ||
| * The strategy holds per-client state (the retry quota, and in adaptive mode the client-side | ||
| * rate limiter), so don't share one across services: throttling on one would slow the others. | ||
| * | ||
| * @param defaultMaxAttempts - total number of attempts, including the initial call, if the user has not set one | ||
| * @param backoffMs - delay in milliseconds before the given attempt | ||
| * @param settings - the user's retry settings | ||
| */ | ||
| export function sdkRetryStrategy( | ||
| defaultMaxAttempts: number, | ||
| backoffMs: (attempt: number) => number, | ||
| settings: SdkRetrySettings, | ||
| ): SdkRetryStrategy { | ||
| const maxAttempts = settings.maxAttempts ?? defaultMaxAttempts; | ||
|
|
||
| switch (settings.mode) { | ||
| case undefined: | ||
| case 'standard': | ||
| // Standard mode with our own backoff schedule | ||
| return new ConfiguredRetryStrategy(maxAttempts, backoffMs); | ||
| case 'adaptive': | ||
| return new AdaptiveRetryStrategy(maxAttempts, { | ||
| maxAttempts, | ||
| backoff: { | ||
| // The SDK passes the number of completed attempts; our schedule is keyed on the next one, | ||
| // which matches how `ConfiguredRetryStrategy` calls its backoff function. | ||
| computeNextBackoffDelay: (completedAttempts: number) => backoffMs(completedAttempts + 1), | ||
| // The delay base is baked into our backoff function | ||
| setDelayBase: () => undefined, | ||
| }, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Read the user's retry settings the way the AWS CLI v2 does | ||
| * | ||
| * Each setting is taken from its environment variable, and otherwise from the given profile in | ||
| * the shared config file. Unlike the AWS CLI v2, an empty environment variable counts as unset, | ||
| * like in the JavaScript SDK: CI templates often pass unset variables through that way. | ||
| */ | ||
| export async function retrySettings(profile: string): Promise<SdkRetrySettings> { | ||
| const fromConfig = await retrySettingsFromConfig(profile); | ||
| const maxAttempts = process.env.AWS_MAX_ATTEMPTS || fromConfig.maxAttempts; | ||
| const mode = process.env.AWS_RETRY_MODE || fromConfig.mode; | ||
| validateMaxAttempts(maxAttempts); | ||
| validateMode(mode); | ||
| return { maxAttempts: maxAttempts === undefined ? undefined : Number(maxAttempts), mode }; | ||
| } | ||
|
|
||
| /** | ||
| * Validate max attempts the way the AWS CLI v2 does: a whole number of at least 1 | ||
| * | ||
| * The AWS CLI parses with Python's `int()`, which also rejects numeric formats that `Number` | ||
| * accepts, like '0x10', '1e2' or '3.0'. We accept those: nobody writes them by accident. | ||
| * | ||
| * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/configprovider.py#L145 | ||
| * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/config.py#L400-L403 | ||
| */ | ||
| export function validateMaxAttempts(maxAttempts: string | number | undefined): void { | ||
| if (maxAttempts === undefined) { | ||
| return; | ||
| } | ||
| // `Number('')` and `Number(' ')` are 0, so blanks fail the minimum | ||
| const value = Number(maxAttempts); | ||
| if (!Number.isInteger(value) || value < 1) { | ||
| throw new ToolkitError('InvalidRetryConfiguration', `invalid value provided for max attempts: '${maxAttempts}', must be a whole number of at least 1`); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Validate the retry mode the way the AWS CLI v2 does | ||
| * | ||
| * Stricter than the JavaScript SDK, which silently uses standard mode for anything that isn't | ||
| * exactly 'adaptive', typos included: | ||
| * https://github.com/smithy-lang/smithy-typescript/blob/d6725176da29286396c921bbe52d3bbd6b93a46b/packages/core/src/submodules/retry/middleware-retry/configurations.ts#L102-L114 | ||
| * | ||
| * We reject anything the AWS CLI v2 rejects, which includes 'legacy': it's a documented mode, but | ||
| * neither the JavaScript SDK nor the AWS CLI v2 supports it. | ||
| * | ||
| * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/config.py#L404-L405 | ||
| */ | ||
| export function validateMode(mode: string | undefined): asserts mode is SdkRetrySettings['mode'] { | ||
| if (mode !== undefined && mode !== 'standard' && mode !== 'adaptive') { | ||
| throw new ToolkitError( | ||
| 'InvalidRetryConfiguration', | ||
| `invalid value provided for retry mode: '${mode}', must be one of 'standard' or 'adaptive'`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Read the raw retry settings from the given profile in the shared config file | ||
| * | ||
| * Only `~/.aws/config` is read: the credentials file may only hold credentials, and the | ||
| * retry settings are documented for the config file only. | ||
| * | ||
| * @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html | ||
| */ | ||
| async function retrySettingsFromConfig(profile: string): Promise<{ maxAttempts?: string; mode?: string }> { | ||
| const { configFile } = await loadSharedConfigFiles({ ignoreCache: true }); | ||
| return { | ||
| maxAttempts: configFile?.[profile]?.max_attempts, | ||
| mode: configFile?.[profile]?.retry_mode, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Build a jittered exponential-backoff delay function whose result is capped at a maximum. | ||
| * | ||
| * An uncapped exponential backoff (`base * 2^attempt`) grows without bound as the | ||
| * number of retries increases. For the retry counts we use on the CloudFormation | ||
| * client in particular, that means the SDK can spend *tens of minutes* silently | ||
| * sleeping between retries when the service returns a retryable error such as | ||
| * `InternalFailure`. To the user that looks like the CLI has hung. Capping each | ||
| * individual delay at ~15s bounds the total retry time to a few minutes at worst, | ||
| * while still giving the SDK plenty of opportunity to ride out transient server | ||
| * problems or throttling. | ||
| * | ||
| * The delay is jittered because `ConfiguredRetryStrategy` replaces the SDK's own | ||
| * jittered backoff with whatever function it is handed. Without jitter, requests | ||
| * that were throttled at the same moment retry at the same moments, and a herd of | ||
| * pollers stays a herd instead of dispersing over the retry window. We use equal | ||
| * jitter - a random point in `[floor(delay/2), delay - 1]` - rather than the SDK's | ||
| * full jitter, so that the worst case stays under the capped delay above and the | ||
| * wait before a retry never collapses to nearly zero. | ||
|
iliapolo marked this conversation as resolved.
Resolved
|
||
| * | ||
| * @param baseMs - base delay in milliseconds (used in `baseMs * 2^attempt`) | ||
| * @param capMs - maximum delay in milliseconds; any computed delay larger than this is clamped | ||
| */ | ||
| export function cappedExponentialBackoff(baseMs: number, capMs: number): (attempt: number) => number { | ||
| return (attempt: number) => { | ||
| const delay = Math.min(baseMs * (2 ** attempt), capMs); | ||
| return Math.floor(delay / 2 + Math.random() * (delay / 2)); | ||
| }; | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 Blocking —
retrySettingsnow runs insideSdkProvider.withAwsCliCompatibleDefaults, so a throw here stops the SDK provider from being created, which breaks the CLI. Two setups the CLI accepts today would start failing withInvalidRetryConfiguration, with no feature flag to opt out (AGENTS.md#feature-flags):retry_mode = legacyorAWS_RETRY_MODE=legacy. AWS documents this setting and recommends it for keeping the old retry behaviour in other SDKs and tools that often share~/.aws/configor a CI environment.validateModerejects it, but the JS SDK runs it as standard mode.AWS_MAX_ATTEMPTS=. CI templates often pass an unset variable through like this. The??on line 60 treats''as set, so the profile value is skipped, andNumber('')is 0, which fails validation. The JS SDK treats an empty value as unset.Suggested change: Match the JS SDK for these two inputs and keep strict validation for real typos. Replace lines 60-61 with:
Keep the
validateMaxAttempts(maxAttempts); validateMode(mode);calls.validateModestill narrowsmode, so the return statement type-checks. Update the doc comment on lines 55-56 ("even to an empty string") and thelegacynote onvalidateMode. AddretrySettingstests forlegacyand for an emptyAWS_MAX_ATTEMPTSfalling back to the profile value.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agree that empty values should be treated as unset but will keep rejecting
legacybecause the AWS CLI also rejects it.