Skip to content

Commit 09ba8cc

Browse files
committed
Generate DynamoDB retry defaults like Java
DynamoDB and DynamoDB Streams clients apply a plugin that gives the standard and adaptive retry modes DynamoDB's defaults, 4 attempts and a 25 ms backoff scale, unless the config sets them. This mirrors AwsDynamoDbRetryIntegration in the Java generator.
1 parent 2249fa7 commit 09ba8cc

6 files changed

Lines changed: 227 additions & 2 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"type": "feature",
3+
"description": "DynamoDB and DynamoDB Streams clients use DynamoDB's retry defaults in the standard and adaptive retry modes, as the Java generator does: 4 attempts and a 25 ms backoff scale, unless set in config."
4+
}

‎packages/smithy-python/src/smithy_python/aws/__init__.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
gets bearer auth and the default AWS token provider chain. AWS services, and
1010
services whose rules use AWS functions or built-ins, resolve endpoints with the
1111
AWS rules extension. S3 and S3 Control clients name and resolve their client
12-
context fields as botocore does.
12+
context fields as botocore does. DynamoDB and DynamoDB Streams
13+
clients use DynamoDB's retry defaults.
1314
Clients may also use the AWS protocols ``aws.protocols#restJson1``,
1415
``awsJson1_0``, ``awsJson1_1``, ``restXml``, ``awsQuery`` and ``ec2Query``.
1516
"""
@@ -21,6 +22,7 @@
2122
from ._checksums import AwsChecksumsIntegration
2223
from ._config import AwsConfigIntegration
2324
from ._dependencies import SMITHY_AWS_CORE
25+
from ._dynamodb import DynamoDbRetryIntegration
2426
from ._endpoints import AwsEndpointsIntegration
2527
from ._identity import AwsIdentityIntegration
2628
from ._protocols import (
@@ -48,6 +50,7 @@
4850
"AwsConfigIntegration",
4951
"AwsEndpointsIntegration",
5052
"AwsIdentityIntegration",
53+
"DynamoDbRetryIntegration",
5154
"S3ConfigIntegration",
5255
]
5356

@@ -57,5 +60,6 @@
5760
AwsEndpointsIntegration(),
5861
AwsChecksumsIntegration(),
5962
S3ConfigIntegration(),
63+
DynamoDbRetryIntegration(),
6064
)
6165
"""The integrations AWS services get, in order."""
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
"""DynamoDB's retry defaults, for DynamoDB and DynamoDB Streams clients.
4+
5+
As in the Java generator's ``AwsDynamoDbRetryIntegration``, clients apply a
6+
plugin that gives the standard and adaptive retry modes DynamoDB's defaults: 4
7+
attempts and a 25 ms backoff scale. A retry strategy or attempt count the user
8+
sets is kept.
9+
"""
10+
11+
from __future__ import annotations
12+
13+
from collections.abc import Mapping
14+
from typing import TYPE_CHECKING, Final
15+
16+
from .. import model as _model
17+
from ..dependencies import SMITHY_CORE
18+
from ..integrations import ClientIntegration, ClientMode
19+
from ..symbols import TypeReference
20+
from ._dependencies import SMITHY_AWS_CORE
21+
22+
if TYPE_CHECKING:
23+
from ..clients import ClientPlan
24+
from ..generation import ClientSettings, GenerationContext
25+
26+
__all__ = ["DynamoDbRetryIntegration"]
27+
28+
29+
class DynamoDbRetryIntegration(ClientIntegration):
30+
"""DynamoDB's retry defaults, for the DynamoDB and DynamoDB Streams SDK IDs."""
31+
32+
def matches(self, service: _model.ServiceShape) -> bool:
33+
trait = service.get_trait(_SERVICE)
34+
return isinstance(trait, Mapping) and trait.get("sdkId") in _SDK_IDS
35+
36+
def client_plugins(
37+
self, plan: ClientPlan, mode: ClientMode, package: str
38+
) -> tuple[TypeReference, ...]:
39+
del plan
40+
return (TypeReference(_PLUGIN, _module(package, mode)),)
41+
42+
def write_files(
43+
self,
44+
context: GenerationContext[ClientSettings],
45+
plan: ClientPlan,
46+
modes: tuple[ClientMode, ClientMode],
47+
) -> None:
48+
del plan
49+
package = context.settings.import_name
50+
for mode in modes:
51+
module = _module(package, mode)
52+
writer = context.files.python_module(
53+
f"src/{module.replace('.', '/')}.py", module
54+
)
55+
config = TypeReference(
56+
mode.config, f"{package}.{mode.directory.replace('/', '.')}config"
57+
)
58+
writer.line("_DYNAMODB_DEFAULT_MAX_ATTEMPTS = 4")
59+
writer.line("_DYNAMODB_DEFAULT_BACKOFF_SCALE = 0.025")
60+
writer.line("_DYNAMODB_DEFAULT_MAX_BACKOFF = 20")
61+
writer.line()
62+
writer.line()
63+
writer.line("def ", _PLUGIN, "(config: ", config, ") -> None:")
64+
with writer.indent():
65+
writer.line(
66+
'"""Apply DynamoDB\'s standard and adaptive mode retry defaults '
67+
'for any option left unset."""'
68+
)
69+
writer.line("retry_strategy = config.retry_strategy")
70+
writer.line(
71+
"if retry_strategy is not None and not isinstance(retry_strategy, ",
72+
_OPTIONS,
73+
"):",
74+
)
75+
with writer.indent():
76+
writer.line("return")
77+
writer.line()
78+
writer.line("if isinstance(retry_strategy, ", _OPTIONS, "):")
79+
with writer.indent():
80+
writer.line(
81+
"# Explicit options take precedence over separately "
82+
"resolved fields."
83+
)
84+
writer.line("retry_mode = retry_strategy.retry_mode")
85+
writer.line("max_attempts = retry_strategy.max_attempts")
86+
writer.line("else:")
87+
with writer.indent():
88+
writer.line(
89+
"# Fall back to the config's independently resolved retry "
90+
"fields."
91+
)
92+
writer.line('retry_mode = config.retry_mode or "standard"')
93+
writer.line("max_attempts = config.max_attempts")
94+
writer.line(
95+
'if config.source_of("max_attempts") == ',
96+
_CONFIG_SOURCE,
97+
".DEFAULT:",
98+
)
99+
with writer.indent():
100+
writer.line("max_attempts = None")
101+
writer.line()
102+
writer.line('if retry_mode not in ("standard", "adaptive"):')
103+
with writer.indent():
104+
writer.line("return")
105+
writer.line()
106+
writer.line(
107+
"strategy_cls = ",
108+
_ADAPTIVE,
109+
' if retry_mode == "adaptive" else ',
110+
_STANDARD,
111+
)
112+
writer.line("config.retry_strategy = strategy_cls(")
113+
with writer.indent():
114+
writer.line("max_attempts=(")
115+
with writer.indent():
116+
writer.line("max_attempts")
117+
writer.line("if max_attempts is not None")
118+
writer.line("else _DYNAMODB_DEFAULT_MAX_ATTEMPTS")
119+
writer.line("),")
120+
writer.line("backoff_strategy=", _BACKOFF, "(")
121+
with writer.indent():
122+
writer.line(
123+
"backoff_scale_value=_DYNAMODB_DEFAULT_BACKOFF_SCALE,"
124+
)
125+
writer.line("max_backoff=_DYNAMODB_DEFAULT_MAX_BACKOFF,")
126+
writer.line("jitter_type=", _JITTER, ".FULL,")
127+
writer.line("),")
128+
writer.line(")")
129+
130+
131+
def _module(package: str, mode: ClientMode) -> str:
132+
return f"{package}.{mode.directory.replace('/', '.')}retries"
133+
134+
135+
def _retries(name: str) -> TypeReference:
136+
return TypeReference(name, "smithy_core.retries", dependencies=(SMITHY_CORE,))
137+
138+
139+
_SERVICE: Final = _model.ShapeId("aws.api", "service")
140+
_SDK_IDS: Final = frozenset({"DynamoDB", "DynamoDB Streams"})
141+
_PLUGIN: Final = "dynamodb_retry_plugin"
142+
_OPTIONS: Final = _retries("RetryStrategyOptions")
143+
_STANDARD: Final = _retries("StandardRetryStrategy")
144+
_ADAPTIVE: Final = _retries("AdaptiveRetryStrategy")
145+
_BACKOFF: Final = _retries("ExponentialRetryBackoffStrategy")
146+
_JITTER: Final = _retries("ExponentialBackoffJitterType")
147+
_CONFIG_SOURCE: Final = TypeReference(
148+
"ConfigSource", "smithy_aws_core.config.types", dependencies=(SMITHY_AWS_CORE,)
149+
)

‎packages/smithy-python/tests/unit/test_client_generation.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1701,6 +1701,73 @@ def test_s3_client_context_fields_must_be_booleans(tmp_path: Path) -> None:
17011701
_aws_generate(tmp_path, "greeter_s3_bad", shapes)
17021702

17031703

1704+
@pytest.mark.parametrize("sdk_id", ["DynamoDB", "DynamoDB Streams"])
1705+
def test_dynamodb_clients_apply_dynamodb_retry_defaults(
1706+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, sdk_id: str
1707+
) -> None:
1708+
from smithy_core.retries import (
1709+
AdaptiveRetryStrategy,
1710+
RetryStrategyOptions,
1711+
StandardRetryStrategy,
1712+
)
1713+
1714+
shapes = _shapes()
1715+
shapes["example#Greeter"]["traits"]["aws.api#service"] = {"sdkId": sdk_id}
1716+
package = "greeter_" + sdk_id.replace(" ", "_").lower()
1717+
_aws_generate(tmp_path, package, shapes)
1718+
source = tmp_path / "src" / package
1719+
for mode in ("", "aio/"):
1720+
client = (source / mode / "client.py").read_text()
1721+
assert "dynamodb_retry_plugin" in client
1722+
for name in ("AWS_MAX_ATTEMPTS", "AWS_RETRY_MODE", "AWS_PROFILE"):
1723+
monkeypatch.delenv(name, raising=False)
1724+
monkeypatch.syspath_prepend( # pyright: ignore[reportUnknownMemberType]
1725+
str(tmp_path / "src")
1726+
)
1727+
config_class = getattr(
1728+
importlib.import_module(f"{package}.config"),
1729+
sdk_id.replace(" ", "") + "Config",
1730+
)
1731+
plugin = importlib.import_module(f"{package}.retries").dynamodb_retry_plugin
1732+
1733+
def resolve(**overrides: Any) -> Any:
1734+
return config_class.resolve(
1735+
config_file_path=str(tmp_path / "config"),
1736+
credentials_file_path=str(tmp_path / "credentials"),
1737+
region="us-east-1",
1738+
**overrides,
1739+
)
1740+
1741+
config = resolve()
1742+
plugin(config)
1743+
assert isinstance(config.retry_strategy, StandardRetryStrategy)
1744+
assert config.retry_strategy.max_attempts == 4
1745+
1746+
config = resolve(max_attempts=7, retry_mode="adaptive")
1747+
plugin(config)
1748+
assert isinstance(config.retry_strategy, AdaptiveRetryStrategy)
1749+
assert config.retry_strategy.max_attempts == 7
1750+
1751+
config = resolve(retry_strategy=RetryStrategyOptions(max_attempts=2))
1752+
plugin(config)
1753+
assert config.retry_strategy.max_attempts == 2
1754+
1755+
# A strategy the user built is kept as it is.
1756+
strategy = StandardRetryStrategy(max_attempts=9)
1757+
config = resolve(retry_strategy=strategy)
1758+
plugin(config)
1759+
assert config.retry_strategy is strategy
1760+
1761+
1762+
def test_other_aws_clients_keep_the_default_retries(tmp_path: Path) -> None:
1763+
shapes = _shapes()
1764+
shapes["example#Greeter"]["traits"]["aws.api#service"] = {"sdkId": "Greeter"}
1765+
_aws_generate(tmp_path, "greeter_no_ddb", shapes)
1766+
source = tmp_path / "src/greeter_no_ddb"
1767+
assert not (source / "retries.py").exists()
1768+
assert "dynamodb_retry_plugin" not in (source / "client.py").read_text()
1769+
1770+
17041771
def _add_sigv4(shapes: dict[str, Any]) -> None:
17051772
traits = shapes["example#Greeter"]["traits"]
17061773
traits["aws.api#service"] = {"sdkId": "Greeter"}

‎scripts/api-snapshot/api-rex.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1393,6 +1393,7 @@
13931393
"AwsConfigIntegration": "rex-class",
13941394
"AwsEndpointsIntegration": "rex-class",
13951395
"AwsIdentityIntegration": "rex-class",
1396+
"DynamoDbRetryIntegration": "rex-class",
13961397
"EC2_QUERY": "rex-ProtocolContribution",
13971398
"REST_JSON": "rex-ProtocolContribution",
13981399
"REST_XML": "rex-ProtocolContribution",

‎scripts/verifications/import-cost.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"smithy_json": 21,
1717
"smithy_json (all public modules)": 21,
1818
"smithy_python": 1,
19-
"smithy_python (all public modules)": 39,
19+
"smithy_python (all public modules)": 40,
2020
"smithy_test": 50,
2121
"smithy_test (all public modules)": 70,
2222
"smithy_xml": 20,

0 commit comments

Comments
 (0)