Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
235 changes: 235 additions & 0 deletions clients/aws-sdk-dynamodb/tests/functional/test_throttle_retries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

"""The integration tests' retry strategy, against DynamoDB wire responses."""

import logging
from typing import Any

import pytest
from aws_sdk_dynamodb.aio.client import AsyncDynamoDBClient
from aws_sdk_dynamodb.aio.config import AsyncDynamoDBConfig
from aws_sdk_dynamodb.client import DynamoDBClient
from aws_sdk_dynamodb.config import DynamoDBConfig
from aws_sdk_dynamodb.models import (
AttributeValueS,
DeleteTableInput,
DescribeTableInput,
GetItemInput,
ListTablesInput,
ResourceInUseException,
)
from retries import (
ThrottleRetryStrategy,
dynamodb_retry_strategy,
is_dynamodb_control_plane_throttle,
)
from smithy_core.aio.client import AsyncRequestPipeline
from smithy_core.client import RequestPipeline
from smithy_core.exceptions import CallError
from smithy_test import mock
from smithy_test.aio import mock_async

from ..integration import create_async_client, create_sync_client

JSON_HEADERS = {"content-type": "application/x-amz-json-1.0"}
OK = "{}"
THROTTLE = (
'{"__type": "com.amazon.coral.availability#ThrottlingException",'
' "message": "The rate of control plane requests made by this account is too high"}'
)
VALIDATION = (
'{"__type": "com.amazon.coral.validate#ValidationException", "message": "bad key"}'
)
IN_USE = (
'{"__type": "com.amazonaws.dynamodb#ResourceInUseException", "message": "busy"}'
)
TIMEOUT = '{"__type": "com.amazonaws.dynamodb#RequestTimeout", "message": "slow"}'


@pytest.fixture
def sleeps(monkeypatch: pytest.MonkeyPatch) -> list[float]:
"""Records the pipeline's waits instead of waiting, in both modes."""
recorded: list[float] = []

def sleep(self: RequestPipeline[Any, Any], delay: float) -> None:
recorded.append(delay)

async def sleep_async(self: AsyncRequestPipeline[Any, Any], delay: float) -> None:
recorded.append(delay)

monkeypatch.setattr(RequestPipeline, "_sleep", sleep)
monkeypatch.setattr(AsyncRequestPipeline, "_sleep", sleep_async)
return recorded


def _client() -> DynamoDBClient:
# The random value is fixed, so each wait is the top of its jitter range.
strategy = dynamodb_retry_strategy(random=lambda: 1.0)
return DynamoDBClient(
DynamoDBConfig.resolve(region="us-west-2", retry_strategy=strategy)
)


def test_retries_a_control_plane_throttle_with_the_throttle_backoff(
sleeps: list[float],
) -> None:
"""Two ThrottlingException 400s on DeleteTable and then a success make 3 requests."""
client = _client()
controller = mock(client)
controller.expect_request().respond_with(400, JSON_HEADERS, THROTTLE).respond_with(
400, JSON_HEADERS, THROTTLE
).respond_with(200, JSON_HEADERS, OK)

client.delete_table(DeleteTableInput(table_name="t"))

assert len(controller.requests) == 3
assert sleeps == [1.0, 2.0]


async def test_retries_a_control_plane_throttle_with_the_async_client(
sleeps: list[float],
) -> None:
"""The async client, which the session table fixture uses, retries the same way."""
strategy = dynamodb_retry_strategy(random=lambda: 1.0)
client = AsyncDynamoDBClient(
await AsyncDynamoDBConfig.resolve(region="us-west-2", retry_strategy=strategy)
)
controller = await mock_async(client)
controller.expect_request().respond_with(400, JSON_HEADERS, THROTTLE).respond_with(
400, JSON_HEADERS, THROTTLE
).respond_with(200, JSON_HEADERS, OK)

await client.describe_table(DescribeTableInput(table_name="t"))

assert len(controller.requests) == 3
assert sleeps == [1.0, 2.0]


def test_gives_up_after_6_attempts_with_a_note(sleeps: list[float]) -> None:
"""A throttle that never ends raises the original error after 6 attempts, 31 s of waits."""
client = _client()
controller = mock(client)
controller.expect_request().respond_with(400, JSON_HEADERS, THROTTLE)

with pytest.raises(CallError) as caught:
client.delete_table(DeleteTableInput(table_name="t"))

assert "#DeleteTable - status: 400" in caught.value.message
assert "gave up after 6 attempts" in "".join(caught.value.__notes__)
assert len(controller.requests) == 6
assert sleeps == [1.0, 2.0, 4.0, 8.0, 16.0]


def test_makes_one_request_and_no_wait_without_a_throttle(
sleeps: list[float], caplog: pytest.LogCaptureFixture
) -> None:
"""A call that succeeds makes 1 request, waits for nothing and logs nothing."""
client = _client()
controller = mock(client)
controller.expect_request().respond_with(200, JSON_HEADERS, OK)

with caplog.at_level(logging.WARNING, logger="retries"):
client.delete_table(DeleteTableInput(table_name="t"))

assert len(controller.requests) == 1
assert sleeps == []
assert [r for r in caplog.records if r.name == "retries"] == []


def test_does_not_retry_an_unmodeled_400_on_a_data_plane_operation(
sleeps: list[float],
) -> None:
"""An unmodeled 400 on GetItem, which is not a control plane operation, gets 1 request."""
client = _client()
controller = mock(client)
controller.expect_request().respond_with(400, JSON_HEADERS, VALIDATION)

with pytest.raises(CallError, match="#GetItem - status: 400"):
client.get_item(GetItemInput(table_name="t", key={"pk": AttributeValueS("x")}))

assert len(controller.requests) == 1
assert sleeps == []


def test_does_not_retry_a_modeled_error_on_a_control_plane_operation(
sleeps: list[float],
) -> None:
"""A modeled ResourceInUseException 400 on DeleteTable gets 1 request."""
client = _client()
controller = mock(client)
controller.expect_request().respond_with(400, JSON_HEADERS, IN_USE)

with pytest.raises(ResourceInUseException):
client.delete_table(DeleteTableInput(table_name="t"))

assert len(controller.requests) == 1
assert sleeps == []


def test_keeps_4_attempts_and_25ms_base_for_other_retryable_errors(
sleeps: list[float], caplog: pytest.LogCaptureFixture
) -> None:
"""A timeout keeps DynamoDB's defaults: 4 attempts and a 25 ms backoff base, unlogged."""
client = _client()
controller = mock(client)
controller.expect_request().respond_with(408, JSON_HEADERS, TIMEOUT)

with caplog.at_level(logging.WARNING, logger="retries"):
with pytest.raises(CallError):
client.list_tables(ListTablesInput())

assert len(controller.requests) == 4
assert sleeps == [0.025, 0.05, 0.1]
assert [r for r in caplog.records if r.name == "retries"] == []


@pytest.mark.parametrize(
"message",
[
# The message of the failed builds of 4 December 2026, which carries a reason.
"Unknown error for operation com.amazonaws.dynamodb#DeleteTable - status: 400 - reason: Bad Request",
"Unknown error for operation com.amazonaws.dynamodb#CreateTable - status: 400",
# The tag calls of the integration tests are control plane calls too.
"Unknown error for operation com.amazonaws.dynamodb#TagResource - status: 400",
"Unknown error for operation com.amazonaws.dynamodb#ListTagsOfResource - status: 400",
],
)
def test_matches_the_logged_throttle_messages(message: str) -> None:
"""The matcher accepts the throttle message with and without an HTTP reason."""
assert is_dynamodb_control_plane_throttle(CallError(message))


@pytest.mark.parametrize(
"message",
[
"Unknown error for operation com.amazonaws.dynamodb#DeleteTable - status: 400 - id: com.amazonaws.dynamodb#Other",
"Unknown error for operation com.amazonaws.dynamodb#DeleteTable - status: 500",
"Unknown error for operation com.amazonaws.dynamodb#PutItem - status: 400",
"Unknown error for operation com.amazonaws.dynamodb#deletetable - status: 400",
],
)
def test_rejects_other_messages(message: str) -> None:
"""The matcher rejects an identified error, another status and a data plane operation."""
assert not is_dynamodb_control_plane_throttle(CallError(message))


def test_each_integration_client_gets_its_own_strategy() -> None:
"""The integration tests' clients use the strategy, one instance per client."""
first = create_sync_client()._config.retry_strategy
second = create_sync_client()._config.retry_strategy

assert isinstance(first, ThrottleRetryStrategy)
assert isinstance(second, ThrottleRetryStrategy)
assert first is not second


async def test_each_async_integration_client_gets_its_own_strategy() -> None:
"""The async factory, which the session table fixture uses, also gives each its own."""
async with (
await create_async_client() as first,
await create_async_client() as second,
):
assert isinstance(first._config.retry_strategy, ThrottleRetryStrategy)
assert isinstance(second._config.retry_strategy, ThrottleRetryStrategy)
assert first._config.retry_strategy is not second._config.retry_strategy
9 changes: 7 additions & 2 deletions clients/aws-sdk-dynamodb/tests/integration/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
TableStatus,
Tag,
)
from retries import dynamodb_retry_strategy
from waiters import wait_until, wait_until_gone

REGION = "us-west-2"
Expand Down Expand Up @@ -61,12 +62,16 @@ def table_input(name: str) -> CreateTableInput:


async def create_async_client() -> AsyncDynamoDBClient:
config = await AsyncDynamoDBConfig.resolve(region=REGION)
config = await AsyncDynamoDBConfig.resolve(
region=REGION, retry_strategy=dynamodb_retry_strategy()
)
return AsyncDynamoDBClient(config=config)


def create_sync_client() -> DynamoDBClient:
config = DynamoDBConfig.resolve(region=REGION)
config = DynamoDBConfig.resolve(
region=REGION, retry_strategy=dynamodb_retry_strategy()
)
return DynamoDBClient(config=config)


Expand Down
2 changes: 2 additions & 0 deletions clients/aws-sdk-iam/tests/functional/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
Loading