:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement dynamodb source (#73799)
Tom Owers1f50c81311d2
diff --git a/frontend/public/services/dynamodb.png b/frontend/public/services/dynamodb.pngindex 1c1a0813ea03..9bb1e1e26974 100644Binary files a/frontend/public/services/dynamodb.png and b/frontend/public/services/dynamodb.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 9b56f982bb4b..5816a3735c03 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -215,6 +215,7 @@ the row lists both.| dropbox_sign | HTTP | requests | ✅ || drip | HTTP | requests | ✅ || dub | HTTP | requests + `rest_source.RESTClient` | ✅ |+| dynamodb | HTTP | requests | ✅ || dynatrace | HTTP | requests | ✅ || e2b | HTTP | requests | ✅ || e_conomic | HTTP | requests | ✅ |@@ -901,7 +902,6 @@ doesn't conflict with concurrent PRs.- dwolla- dynamics365- dynamics_365_business_central-- dynamodb- e2b- easybill- ebaydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/dynamodb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/dynamodb.pynew file mode 100644index 000000000000..60908ee8791c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/dynamodb.py@@ -0,0 +1,380 @@+import json+import dataclasses+from collections.abc import Iterator, Mapping+from typing import Any, Optional++import requests+from botocore.auth import SigV4Auth+from botocore.awsrequest import AWSRequest+from botocore.credentials import Credentials+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.settings import (+ CONTENT_TYPE,+ DYNAMODB_API_VERSION,+ ENDPOINT_TEMPLATE,+ LIST_TABLES_PAGE_LIMIT,+ MAX_RETRY_ATTEMPTS,+ NON_RETRYABLE_ERROR_MESSAGES,+ REGION_PATTERN,+ REQUEST_TIMEOUT_SECONDS,+ RETRY_INITIAL_WAIT_SECONDS,+ RETRY_MAX_WAIT_SECONDS,+ RETRYABLE_ERROR_CODES,+ SCAN_PAGE_LIMIT,+ SIGV4_SERVICE_NAME,+)++# Numbers wider than a signed 64-bit integer can't land in an Arrow int column, so they degrade+# to float rather than overflowing the write.+_INT64_MIN = -(2**63)+_INT64_MAX = 2**63 - 1+++class DynamoDBAPIError(Exception):+ """A DynamoDB error response. `code` is the AWS error code (e.g. `AccessDeniedException`)."""++ def __init__(self, code: str, message: str, status_code: int) -> None:+ self.code = code+ self.message = message+ self.status_code = status_code+ super().__init__(f"DynamoDB API error: {code}: {message} (HTTP {status_code})")+++class DynamoDBRetryableError(DynamoDBAPIError):+ """Throttling, capacity, and transient server errors — retried in-source."""+++class DynamoDBResumeConfig:+ # Scan's `LastEvaluatedKey`, kept in DynamoDB's own attribute-value encoding so it can go+ # straight back out as `ExclusiveStartKey`.+ table_name: str+ exclusive_start_key: dict[str, Any]+++def validate_region(region: str) -> str:+ """Return the region if it is a well-formed AWS region code, else raise.++ The region is interpolated into the request host, so anything outside the region alphabet+ could point the signed request (and the customer's key) at a host we don't control.+ """+ normalized = (region or "").strip()+ if not REGION_PATTERN.match(normalized):+ raise ValueError(f"Invalid AWS region: {region!r}")+ return normalized+++def target_prefix(api_version: str | None = None) -> str:+ """`X-Amz-Target` prefix for the pinned API version (`2012-08-10` -> `DynamoDB_20120810`)."""+ version = api_version or DYNAMODB_API_VERSION+ return f"DynamoDB_{version.replace('-', '')}"+++def _deserialize_number(raw: str) -> int | float:+ try:+ parsed = int(raw)+ except ValueError:+ return float(raw)+ if _INT64_MIN <= parsed <= _INT64_MAX:+ return parsed+ return float(parsed)+++def deserialize_value(value: Mapping[str, Any]) -> Any:+ """Convert one DynamoDB attribute value (`{"S": "x"}`) into a plain Python value.++ Binary (`B`/`BS`) values stay as the base64 strings the wire format uses — decoding them+ would produce bytes the Delta write has no column type for.+ """+ if len(value) != 1:+ raise ValueError(f"Malformed DynamoDB attribute value: {value!r}")++ tag, raw = next(iter(value.items()))++ if tag == "S":+ return raw+ if tag == "N":+ return _deserialize_number(raw)+ if tag == "BOOL":+ return bool(raw)+ if tag == "NULL":+ return None+ if tag == "B":+ return raw+ if tag == "SS":+ return list(raw)+ if tag == "NS":+ return [_deserialize_number(item) for item in raw]+ if tag == "BS":+ return list(raw)+ if tag == "L":+ return [deserialize_value(item) for item in raw]+ if tag == "M":+ return {key: deserialize_value(item) for key, item in raw.items()}++ raise ValueError(f"Unknown DynamoDB attribute type: {tag!r}")+++def deserialize_item(item: Mapping[str, Any]) -> dict[str, Any]:+ return {key: deserialize_value(value) for key, value in item.items()}+++def _error_code(body: Mapping[str, Any]) -> str:+ # AWS returns `{"__type": "com.amazonaws.dynamodb.v20120810#ResourceNotFoundException"}`;+ # some fronting errors use a bare `code` instead.+ raw = body.get("__type") or body.get("code") or ""+ return str(raw).rsplit("#", 1)[-1] or "UnknownError"+++def _error_message(body: Mapping[str, Any]) -> str:+ for key in ("message", "Message", "errorMessage"):+ value = body.get(key)+ if value:+ return str(value)+ return "No error message returned"+++class DynamoDBClient:+ """SigV4-signed JSON client for the DynamoDB data plane.++ DynamoDB has no REST surface the declarative framework can drive: every operation is a POST+ to the regional endpoint discriminated by `X-Amz-Target`, with an SigV4 `Authorization`+ header. Signing rides botocore (already a repo dependency), but the request itself goes out+ over the tracked session so it stays in our HTTP logs and metrics.+ """++ def __init__(+ self,+ access_key_id: str,+ secret_access_key: str,+ region: str,+ session_token: str | None = None,+ api_version: str | None = None,+ ) -> None:+ self.region = validate_region(region)+ self.endpoint = ENDPOINT_TEMPLATE.format(region=self.region)+ self.target_prefix = target_prefix(api_version)+ self._credentials = Credentials(access_key_id, secret_access_key, session_token or None)+ self._signer = SigV4Auth(self._credentials, SIGV4_SERVICE_NAME, self.region)+ self._session = make_tracked_session(+ redact_values=tuple(value for value in (secret_access_key, session_token) if value),+ # DynamoDB items carry arbitrary customer fields (PII, secrets under generic attribute+ # names) the name-based scrubber can't catch, so keep responses out of HTTP samples.+ capture=False,+ )++ def _signed_headers(self, operation: str, body: str) -> dict[str, str]:+ request = AWSRequest(+ method="POST",+ url=self.endpoint,+ data=body.encode("utf-8"),+ headers={+ "Content-Type": CONTENT_TYPE,+ "X-Amz-Target": f"{self.target_prefix}.{operation}",+ },+ )+ self._signer.add_auth(request)+ return dict(request.headers)++ def send(self, operation: str, payload: Mapping[str, Any]) -> dict[str, Any]:+ """Issue one signed operation. Raises `DynamoDBAPIError` on any error response."""+ body = json.dumps(payload)+ response = self._session.post(+ self.endpoint,+ data=body.encode("utf-8"),+ headers=self._signed_headers(operation, body),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code >= 400:+ try:+ error_body = response.json()+ except ValueError:+ error_body = {}+ code = _error_code(error_body)+ message = _error_message(error_body)+ if code in RETRYABLE_ERROR_CODES or response.status_code >= 500:+ raise DynamoDBRetryableError(code, message, response.status_code)+ raise DynamoDBAPIError(code, message, response.status_code)++ return response.json()++ # Throttling arrives as HTTP 400, which the tracked transport's status-code retries can't+ # see, and it never retries POSTs anyway — so there is no compounding here.+ @retry(+ retry=retry_if_exception_type((DynamoDBRetryableError, requests.ConnectionError, requests.Timeout)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=RETRY_INITIAL_WAIT_SECONDS, max=RETRY_MAX_WAIT_SECONDS),+ reraise=True,+ )+ def request(self, operation: str, payload: Mapping[str, Any]) -> dict[str, Any]:+ return self.send(operation, payload)+++def list_tables(client: DynamoDBClient) -> list[str]:+ tables: list[str] = []+ start_table: str | None = None++ while True:+ payload: dict[str, Any] = {"Limit": LIST_TABLES_PAGE_LIMIT}+ if start_table:+ payload["ExclusiveStartTableName"] = start_table++ response = client.request("ListTables", payload)+ tables.extend(response.get("TableNames") or [])++ start_table = response.get("LastEvaluatedTableName")+ if not start_table:+ return tables+++def describe_table(client: DynamoDBClient, table_name: str) -> dict[str, Any]:+ return client.request("DescribeTable", {"TableName": table_name}).get("Table") or {}+++def primary_keys_from_description(description: Mapping[str, Any]) -> list[str]:+ """Partition key first, then the sort key — the order DynamoDB itself uses for the item key."""+ key_schema = description.get("KeySchema") or []+ ordered = sorted(key_schema, key=lambda entry: 0 if entry.get("KeyType") == "HASH" else 1)+ return [entry["AttributeName"] for entry in ordered if entry.get("AttributeName")]+++def get_table_schemas(+ client: DynamoDBClient,+ with_counts: bool = False,+ names: list[str] | None = None,+) -> list[SourceSchema]:+ table_names = list_tables(client)+ if names is not None:+ wanted = set(names)+ table_names = [name for name in table_names if name in wanted]++ schemas: list[SourceSchema] = []+ for table_name in table_names:+ description = describe_table(client, table_name)+ schemas.append(+ SourceSchema(+ name=table_name,+ # Scan has no server-side timestamp filter, and a FilterExpression still reads+ # the whole table, so incremental sync would cost the same as a full refresh.+ supports_incremental=False,+ supports_append=False,+ detected_primary_keys=primary_keys_from_description(description) or None,+ # `ItemCount` is only refreshed by DynamoDB roughly every six hours.+ row_count=description.get("ItemCount") if with_counts else None,+ )+ )++ return schemas+++def validate_credentials(+ access_key_id: str,+ secret_access_key: str,+ region: str,+ session_token: str | None = None,+ api_version: str | None = None,+) -> tuple[bool, str | None]:+ try:+ client = DynamoDBClient(+ access_key_id=access_key_id,+ secret_access_key=secret_access_key,+ region=region,+ session_token=session_token,+ api_version=api_version,+ )+ except ValueError:+ return False, f"'{region}' isn't a valid AWS region. Use a region code like us-east-1."++ try:+ client.request("ListTables", {"Limit": 1})+ except DynamoDBAPIError as error:+ return False, NON_RETRYABLE_ERROR_MESSAGES.get(error.code) or f"AWS rejected the request: {error.code}."+ except Exception:+ return False, "Could not reach DynamoDB. Check the region and your network settings, then try again."++ return True, None+++def get_rows(+ client: DynamoDBClient,+ table_name: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DynamoDBResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ exclusive_start_key: dict[str, Any] | None = None+ if resume_config is not None:+ if resume_config.table_name == table_name:+ exclusive_start_key = resume_config.exclusive_start_key+ logger.debug(f"DynamoDB: resuming scan of {table_name}")+ else:+ # A key from another table can't be used as this table's ExclusiveStartKey — AWS+ # would reject it with a ValidationException and fail the whole job.+ logger.warning(+ f"DynamoDB: discarding resume state for {resume_config.table_name} while scanning {table_name}"+ )++ while True:+ payload: dict[str, Any] = {"TableName": table_name, "Limit": SCAN_PAGE_LIMIT}+ if exclusive_start_key:+ payload["ExclusiveStartKey"] = exclusive_start_key++ response = client.request("Scan", payload)++ items = [deserialize_item(item) for item in response.get("Items") or []]+ if items:+ yield items++ last_evaluated_key = response.get("LastEvaluatedKey")+ if not last_evaluated_key:+ break++ exclusive_start_key = last_evaluated_key+ # Saved after yielding, so a crash re-yields the last page (merge dedupes on the item+ # key) instead of skipping it.+ resumable_source_manager.save_state(+ DynamoDBResumeConfig(table_name=table_name, exclusive_start_key=last_evaluated_key)+ )++ resumable_source_manager.clear_state()+++def dynamodb_source(+ access_key_id: str,+ secret_access_key: str,+ region: str,+ table_name: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DynamoDBResumeConfig],+ session_token: Optional[str] = None,+ api_version: Optional[str] = None,+) -> SourceResponse:+ client = DynamoDBClient(+ access_key_id=access_key_id,+ secret_access_key=secret_access_key,+ region=region,+ session_token=session_token,+ api_version=api_version,+ )+ primary_keys = primary_keys_from_description(describe_table(client, table_name))++ return SourceResponse(+ name=table_name,+ items=lambda: get_rows(+ client=client,+ table_name=table_name,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=primary_keys or None,+ # Scan walks the table in partition-hash order, which carries no time ordering.+ sort_mode=None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/settings.pynew file mode 100644index 000000000000..0c35f9b38ea2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/settings.py@@ -0,0 +1,57 @@+import re++# DynamoDB's only API version. It is carried in the `X-Amz-Target` header of every request+# (`DynamoDB_20120810.<Operation>`), so this is a real pin rather than a cosmetic label.+DYNAMODB_API_VERSION = "2012-08-10"++# SigV4 service name and the regional endpoint template. The host is always AWS-owned, which+# is why `aws_region` can be a free-text field without becoming an SSRF vector.+SIGV4_SERVICE_NAME = "dynamodb"+ENDPOINT_TEMPLATE = "https://dynamodb.{region}.amazonaws.com/"++# AWS region codes are lowercase alphanumerics and hyphens (`us-east-1`, `ap-southeast-3`,+# `us-gov-west-1`). Anything else could smuggle a host or path into the endpoint.+REGION_PATTERN = re.compile(r"^[a-z0-9-]+$")++CONTENT_TYPE = "application/x-amz-json-1.0"++REQUEST_TIMEOUT_SECONDS = 60++# Scan returns at most 1 MB per call regardless of `Limit`; the cap just bounds how many items+# a single page can hold so wide rows don't build an oversized batch.+SCAN_PAGE_LIMIT = 1000+LIST_TABLES_PAGE_LIMIT = 100++MAX_RETRY_ATTEMPTS = 6+RETRY_INITIAL_WAIT_SECONDS = 1.0+RETRY_MAX_WAIT_SECONDS = 60.0++# Throttling and capacity errors come back as HTTP 400 with an error code in the body, so the+# transport's status-code retries never see them. These are retried in-source instead.+RETRYABLE_ERROR_CODES = frozenset(+ {+ "InternalServerError",+ "ProvisionedThroughputExceededException",+ "RequestLimitExceeded",+ "ServiceUnavailable",+ "ThrottlingException",+ "TransactionInProgressException",+ }+)++_INVALID_KEY_MESSAGE = "AWS rejected your access key. Check the access key ID and secret access key, then reconnect."++# Error codes that never recover on retry, mapped to the message the user sees.+NON_RETRYABLE_ERROR_MESSAGES: dict[str, str | None] = {+ "UnrecognizedClientException": _INVALID_KEY_MESSAGE,+ "InvalidClientTokenId": _INVALID_KEY_MESSAGE,+ "InvalidSignatureException": "AWS could not verify the request signature. Check your secret access key, then reconnect.",+ "SignatureDoesNotMatch": "AWS could not verify the request signature. Check your secret access key, then reconnect.",+ "ExpiredTokenException": "Your AWS session token has expired. Enter a new one and reconnect.",+ "ExpiredToken": "Your AWS session token has expired. Enter a new one and reconnect.",+ "AccessDeniedException": "This AWS key can't read DynamoDB. Grant it dynamodb:ListTables, dynamodb:DescribeTable and dynamodb:Scan, then try again.",+ "ResourceNotFoundException": "This DynamoDB table no longer exists in the selected region. Check the table and region, then try again.",+ "ValidationException": "AWS rejected the request as invalid. Check that the region matches where your tables live.",+ "IncompleteSignature": "AWS could not verify the request signature. Check your access key ID and secret access key, then reconnect.",+ "MissingAuthenticationToken": _INVALID_KEY_MESSAGE,+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/source.pyindex a3a9f80c31cd..729524377a6b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/source.py@@ -1,13 +1,31 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.dynamodb import (+ DynamoDBClient,+ DynamoDBResumeConfig,+ dynamodb_source,+ get_table_schemas,+ validate_credentials as validate_dynamodb_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.settings import (+ DYNAMODB_API_VERSION,+ NON_RETRYABLE_ERROR_MESSAGES,+ RETRYABLE_ERROR_CODES,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dynamodb import (DynamoDBSourceConfig,)@@ -15,18 +33,130 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DynamoDBSource(SimpleSource[DynamoDBSourceConfig]):+class DynamoDBSource(ResumableSource[DynamoDBSourceConfig, DynamoDBResumeConfig]):+ supported_versions = (DYNAMODB_API_VERSION,)+ default_version = DYNAMODB_API_VERSION+ api_docs_url = "https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/Welcome.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DYNAMODB+ @property+ def connection_host_fields(self) -> list[str]:+ # The region picks the endpoint the signed request — and so the customer's key — is sent to.+ return ["aws_region"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return dict(NON_RETRYABLE_ERROR_MESSAGES)++ def get_retryable_errors(self) -> set[str]:+ return set(RETRYABLE_ERROR_CODES)+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DYNAMO_DB,category=DataWarehouseSourceCategory.DATABASES,label="DynamoDB",+ caption="""Enter an AWS access key with read access to DynamoDB to import your tables into the PostHog Data warehouse.++Create an IAM user whose policy allows `dynamodb:ListTables`, `dynamodb:DescribeTable` and `dynamodb:Scan`, then paste its access key below. Tables are read with a full table scan, so every sync uses read capacity on the table.""",iconPath="/static/services/dynamodb.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/dynamodb",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["aws", "nosql"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="aws_access_key_id",+ label="AWS access key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="AKIA...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="aws_secret_access_key",+ label="AWS secret access key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="aws_region",+ label="AWS region",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="us-east-1",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="aws_session_token",+ label="AWS session token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="Only needed for temporary credentials",+ caption="Only for temporary credentials. Session tokens expire after a few hours, so scheduled syncs will fail once the token expires. Use a permanent access key (starts with AKIA) for recurring imports.",+ secret=True,+ ),+ ],+ ),+ )++ def _client(self, config: DynamoDBSourceConfig, api_version: str | None = None) -> DynamoDBClient:+ return DynamoDBClient(+ access_key_id=config.aws_access_key_id,+ secret_access_key=config.aws_secret_access_key,+ region=config.aws_region,+ session_token=config.aws_session_token or None,+ api_version=self.resolve_api_version(api_version),+ )++ def get_schemas(+ self,+ config: DynamoDBSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return get_table_schemas(self._client(config, api_version), with_counts=with_counts, names=names)++ def validate_credentials(+ self,+ config: DynamoDBSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_dynamodb_credentials(+ access_key_id=config.aws_access_key_id,+ secret_access_key=config.aws_secret_access_key,+ region=config.aws_region,+ session_token=config.aws_session_token or None,+ api_version=self.resolve_api_version(api_version),+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DynamoDBResumeConfig]:+ return ResumableSourceManager[DynamoDBResumeConfig](inputs, DynamoDBResumeConfig)++ def source_for_pipeline(+ self,+ config: DynamoDBSourceConfig,+ resumable_source_manager: ResumableSourceManager[DynamoDBResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return dynamodb_source(+ access_key_id=config.aws_access_key_id,+ secret_access_key=config.aws_secret_access_key,+ region=config.aws_region,+ session_token=config.aws_session_token or None,+ table_name=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ api_version=self.resolve_api_version(inputs.api_version),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/tests/test_dynamodb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/tests/test_dynamodb.pynew file mode 100644index 000000000000..9a39ea862ca9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/tests/test_dynamodb.py@@ -0,0 +1,584 @@+import json+import dataclasses+from collections.abc import Iterable, Iterator+from typing import Any, cast++import pytest+from unittest import mock++import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.dynamodb import (+ DynamoDBAPIError,+ DynamoDBClient,+ DynamoDBResumeConfig,+ DynamoDBRetryableError,+ deserialize_item,+ deserialize_value,+ dynamodb_source,+ get_rows,+ get_table_schemas,+ list_tables,+ primary_keys_from_description,+ target_prefix,+ validate_credentials,+ validate_region,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.settings import MAX_RETRY_ATTEMPTS++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.dynamodb"+++class FakeResponse:+ status_code: int = 200+ body: dict[str, Any] = dataclasses.field(default_factory=dict)+ json_decodable: bool = True++ def json(self) -> dict[str, Any]:+ if not self.json_decodable:+ raise ValueError("not json")+ return self.body+++class FakeSession:+ def __init__(self, responses: list[FakeResponse]) -> None:+ self.responses = list(responses)+ self.calls: list[dict[str, Any]] = []++ def post(+ self,+ url: str,+ data: bytes | None = None,+ headers: dict[str, str] | None = None,+ timeout: int | None = None,+ ) -> FakeResponse:+ self.calls.append({"url": url, "data": data, "headers": headers or {}, "timeout": timeout})+ if not self.responses:+ raise AssertionError("FakeSession ran out of queued responses")+ return self.responses.pop(0)++ def payload(self, index: int) -> dict[str, Any]:+ raw = self.calls[index]["data"]+ assert isinstance(raw, bytes)+ return cast(dict[str, Any], json.loads(raw.decode()))++ def target(self, index: int) -> str:+ return self.calls[index]["headers"]["X-Amz-Target"]+++class FakeResumeManager(ResumableSourceManager[DynamoDBResumeConfig]):+ def __init__(self, state: DynamoDBResumeConfig | None = None) -> None:+ self.state = state+ self.saved: list[DynamoDBResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> DynamoDBResumeConfig | None:+ return self.state++ def save_state(self, data: DynamoDBResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def _logger() -> FilteringBoundLogger:+ return cast(FilteringBoundLogger, mock.MagicMock())+++def _make_client(+ responses: list[FakeResponse],+ region: str = "us-east-1",+ session_token: str | None = None,+ api_version: str | None = None,+) -> tuple[DynamoDBClient, FakeSession]:+ session = FakeSession(responses)+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ client = DynamoDBClient(+ access_key_id="AKIATEST",+ secret_access_key="secret",+ region=region,+ session_token=session_token,+ api_version=api_version,+ )+ return client, session+++def _error(code: str, status: int = 400, message: str = "boom") -> FakeResponse:+ return FakeResponse(+ status_code=status,+ body={"__type": f"com.amazonaws.dynamodb.v20120810#{code}", "message": message},+ )++[email protected](autouse=True)+def _no_sleep() -> Iterator[None]:+ with mock.patch("time.sleep"):+ yield+++class TestValidateRegion:+ @pytest.mark.parametrize("region", ["us-east-1", "eu-west-2", "ap-southeast-3", "us-gov-west-1", "cn-north-1"])+ def test_accepts_region_codes(self, region: str) -> None:+ assert validate_region(region) == region++ def test_strips_surrounding_whitespace(self) -> None:+ assert validate_region(" us-east-1 ") == "us-east-1"++ @pytest.mark.parametrize(+ "region",+ [+ "",+ "US-EAST-1",+ "us-east-1.evil.com",+ "us-east-1/../",+ "evil.com",+ "us east 1",+ "us-east-1:443",+ ],+ )+ def test_rejects_anything_that_could_move_the_host(self, region: str) -> None:+ with pytest.raises(ValueError):+ validate_region(region)+++class TestTargetPrefix:+ @pytest.mark.parametrize(+ "api_version, expected",+ [("2012-08-10", "DynamoDB_20120810"), (None, "DynamoDB_20120810")],+ )+ def test_prefix_for_version(self, api_version: str | None, expected: str) -> None:+ assert target_prefix(api_version) == expected+++class TestDeserializeValue:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ({"S": "hello"}, "hello"),+ ({"N": "42"}, 42),+ ({"N": "-7"}, -7),+ ({"N": "4.25"}, 4.25),+ ({"BOOL": True}, True),+ ({"BOOL": False}, False),+ ({"NULL": True}, None),+ ({"B": "aGVsbG8="}, "aGVsbG8="),+ ({"SS": ["a", "b"]}, ["a", "b"]),+ ({"NS": ["1", "2.5"]}, [1, 2.5]),+ ({"BS": ["aGk="]}, ["aGk="]),+ ({"L": [{"S": "a"}, {"N": "1"}]}, ["a", 1]),+ ({"M": {"k": {"S": "v"}}}, {"k": "v"}),+ ({"M": {"outer": {"L": [{"M": {"x": {"N": "1"}}}]}}}, {"outer": [{"x": 1}]}),+ ],+ )+ def test_converts_attribute_values(self, value: dict[str, Any], expected: Any) -> None:+ assert deserialize_value(value) == expected++ def test_number_wider_than_int64_degrades_to_float(self) -> None:+ result = deserialize_value({"N": "170141183460469231731687303715884105727"})+ assert isinstance(result, float)++ @pytest.mark.parametrize("value", [{}, {"S": "a", "N": "1"}, {"ZZ": "1"}])+ def test_rejects_malformed_values(self, value: dict[str, Any]) -> None:+ with pytest.raises(ValueError):+ deserialize_value(value)+++class TestDeserializeItem:+ def test_flattens_every_attribute(self) -> None:+ item = {"pk": {"S": "user#1"}, "age": {"N": "30"}, "tags": {"SS": ["a"]}, "deleted": {"NULL": True}}+ assert deserialize_item(item) == {"pk": "user#1", "age": 30, "tags": ["a"], "deleted": None}+++class TestSigning:+ def test_request_is_sigv4_signed_for_the_target_operation(self) -> None:+ client, session = _make_client([FakeResponse(body={"Items": []})])+ client.send("Scan", {"TableName": "users"})++ headers = session.calls[0]["headers"]+ assert session.calls[0]["url"] == "https://dynamodb.us-east-1.amazonaws.com/"+ assert headers["X-Amz-Target"] == "DynamoDB_20120810.Scan"+ assert headers["Content-Type"] == "application/x-amz-json-1.0"+ assert "X-Amz-Date" in headers+ assert headers["Authorization"].startswith("AWS4-HMAC-SHA256 ")+ assert "Credential=AKIATEST/" in headers["Authorization"]+ assert "/us-east-1/dynamodb/aws4_request" in headers["Authorization"]+ assert "Signature=" in headers["Authorization"]++ def test_signature_covers_the_body_so_two_payloads_differ(self) -> None:+ client, session = _make_client([FakeResponse(), FakeResponse()])+ client.send("Scan", {"TableName": "users"})+ client.send("Scan", {"TableName": "orders"})++ assert session.calls[0]["headers"]["Authorization"] != session.calls[1]["headers"]["Authorization"]++ def test_session_token_is_sent_when_supplied(self) -> None:+ client, session = _make_client([FakeResponse()], session_token="temp-token")+ client.send("ListTables", {})++ assert session.calls[0]["headers"]["X-Amz-Security-Token"] == "temp-token"++ def test_no_session_token_header_without_temporary_credentials(self) -> None:+ client, session = _make_client([FakeResponse()])+ client.send("ListTables", {})++ assert "X-Amz-Security-Token" not in session.calls[0]["headers"]++ def test_region_selects_the_endpoint(self) -> None:+ client, session = _make_client([FakeResponse()], region="eu-west-2")+ client.send("ListTables", {})++ assert session.calls[0]["url"] == "https://dynamodb.eu-west-2.amazonaws.com/"++ def test_invalid_region_is_rejected_before_any_request(self) -> None:+ with mock.patch(f"{_MODULE}.make_tracked_session") as make_session:+ with pytest.raises(ValueError):+ DynamoDBClient(access_key_id="AKIA", secret_access_key="s", region="evil.com")+ make_session.assert_not_called()++ def test_responses_are_excluded_from_http_sample_capture(self) -> None:+ # DynamoDB items carry arbitrary customer fields the name-based scrubber can't catch,+ # so the session must never stream response bodies into shared HTTP samples.+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=FakeSession([])) as make_session:+ DynamoDBClient(access_key_id="AKIA", secret_access_key="s", region="us-east-1")++ assert make_session.call_args.kwargs["capture"] is False+++class TestErrorClassification:+ @pytest.mark.parametrize(+ "code, status, expected_retryable",+ [+ ("ThrottlingException", 400, True),+ ("ProvisionedThroughputExceededException", 400, True),+ ("RequestLimitExceeded", 400, True),+ ("InternalServerError", 500, True),+ ("ServiceUnavailable", 503, True),+ ("AccessDeniedException", 400, False),+ ("UnrecognizedClientException", 400, False),+ ("ValidationException", 400, False),+ ("ResourceNotFoundException", 400, False),+ ],+ )+ def test_error_codes_are_split_into_retryable_and_permanent(+ self, code: str, status: int, expected_retryable: bool+ ) -> None:+ client, _ = _make_client([_error(code, status=status)])++ with pytest.raises(DynamoDBAPIError) as exc_info:+ client.send("Scan", {"TableName": "users"})++ assert exc_info.value.code == code+ assert exc_info.value.status_code == status+ assert isinstance(exc_info.value, DynamoDBRetryableError) is expected_retryable++ def test_unknown_5xx_is_retryable_even_without_a_known_code(self) -> None:+ client, _ = _make_client([_error("SomethingNew", status=502)])++ with pytest.raises(DynamoDBRetryableError):+ client.send("Scan", {"TableName": "users"})++ def test_non_json_error_body_still_raises_a_typed_error(self) -> None:+ client, _ = _make_client([FakeResponse(status_code=400, json_decodable=False)])++ with pytest.raises(DynamoDBAPIError) as exc_info:+ client.send("Scan", {"TableName": "users"})++ assert exc_info.value.code == "UnknownError"++ def test_error_message_includes_the_code_so_non_retryable_matching_works(self) -> None:+ client, _ = _make_client([_error("AccessDeniedException", message="no perms")])++ with pytest.raises(DynamoDBAPIError) as exc_info:+ client.send("Scan", {"TableName": "users"})++ assert "AccessDeniedException" in str(exc_info.value)+ assert "no perms" in str(exc_info.value)+++class TestRequestRetries:+ def test_retryable_error_is_retried_until_it_succeeds(self) -> None:+ client, session = _make_client(+ [_error("ThrottlingException"), _error("ThrottlingException"), FakeResponse(body={"TableNames": ["a"]})]+ )++ assert client.request("ListTables", {}) == {"TableNames": ["a"]}+ assert len(session.calls) == 3++ def test_retries_are_bounded(self) -> None:+ client, session = _make_client([_error("ThrottlingException") for _ in range(MAX_RETRY_ATTEMPTS)])++ with pytest.raises(DynamoDBRetryableError):+ client.request("ListTables", {})++ assert len(session.calls) == MAX_RETRY_ATTEMPTS++ def test_permanent_error_is_not_retried(self) -> None:+ client, session = _make_client([_error("AccessDeniedException")])++ with pytest.raises(DynamoDBAPIError):+ client.request("ListTables", {})++ assert len(session.calls) == 1++ def test_connection_errors_are_retried(self) -> None:+ client, session = _make_client([FakeResponse(body={"TableNames": []})])+ original_post = session.post+ calls: list[int] = []++ def flaky_post(*args: Any, **kwargs: Any) -> FakeResponse:+ calls.append(1)+ if len(calls) == 1:+ raise requests.ConnectionError("reset by peer")+ return original_post(*args, **kwargs)++ with mock.patch.object(session, "post", side_effect=flaky_post):+ assert client.request("ListTables", {}) == {"TableNames": []}++ assert len(calls) == 2+++class TestListTables:+ def test_pagination_follows_last_evaluated_table_name_and_terminates(self) -> None:+ client, session = _make_client(+ [+ FakeResponse(body={"TableNames": ["a", "b"], "LastEvaluatedTableName": "b"}),+ FakeResponse(body={"TableNames": ["c"]}),+ ]+ )++ assert list_tables(client) == ["a", "b", "c"]+ assert "ExclusiveStartTableName" not in session.payload(0)+ assert session.payload(1)["ExclusiveStartTableName"] == "b"++ def test_empty_account_returns_no_tables(self) -> None:+ client, _ = _make_client([FakeResponse(body={})])++ assert list_tables(client) == []+++class TestPrimaryKeys:+ @pytest.mark.parametrize(+ "key_schema, expected",+ [+ ([{"AttributeName": "pk", "KeyType": "HASH"}], ["pk"]),+ (+ [{"AttributeName": "sk", "KeyType": "RANGE"}, {"AttributeName": "pk", "KeyType": "HASH"}],+ ["pk", "sk"],+ ),+ ([], []),+ ],+ )+ def test_partition_key_comes_before_sort_key(self, key_schema: list[dict[str, str]], expected: list[str]) -> None:+ assert primary_keys_from_description({"KeySchema": key_schema}) == expected+++class TestGetTableSchemas:+ def _responses(self) -> list[FakeResponse]:+ return [+ FakeResponse(body={"TableNames": ["users", "orders"]}),+ FakeResponse(+ body={+ "Table": {+ "KeySchema": [+ {"AttributeName": "sk", "KeyType": "RANGE"},+ {"AttributeName": "pk", "KeyType": "HASH"},+ ],+ "ItemCount": 12,+ }+ }+ ),+ FakeResponse(body={"Table": {"KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], "ItemCount": 3}}),+ ]++ def test_each_table_becomes_a_full_refresh_schema_with_detected_keys(self) -> None:+ client, _ = _make_client(self._responses())++ schemas = get_table_schemas(client)++ assert [schema.name for schema in schemas] == ["users", "orders"]+ assert schemas[0].detected_primary_keys == ["pk", "sk"]+ assert schemas[1].detected_primary_keys == ["id"]+ # Scan has no server-side timestamp filter, so nothing here may claim incremental sync.+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)+ assert all(schema.row_count is None for schema in schemas)++ def test_row_counts_are_only_fetched_when_asked_for(self) -> None:+ client, _ = _make_client(self._responses())++ schemas = get_table_schemas(client, with_counts=True)++ assert [schema.row_count for schema in schemas] == [12, 3]++ def test_names_filter_skips_describing_unwanted_tables(self) -> None:+ client, session = _make_client(+ [+ FakeResponse(body={"TableNames": ["users", "orders"]}),+ FakeResponse(body={"Table": {"KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}]}}),+ ]+ )++ schemas = get_table_schemas(client, names=["orders"])++ assert [schema.name for schema in schemas] == ["orders"]+ assert [session.target(index) for index in range(len(session.calls))] == [+ "DynamoDB_20120810.ListTables",+ "DynamoDB_20120810.DescribeTable",+ ]+ assert session.payload(1)["TableName"] == "orders"+++class TestGetRows:+ def test_scan_pages_are_yielded_deserialized_and_checkpointed(self) -> None:+ last_key = {"pk": {"S": "user#1"}}+ client, session = _make_client(+ [+ FakeResponse(+ body={"Items": [{"pk": {"S": "user#1"}, "age": {"N": "30"}}], "LastEvaluatedKey": last_key}+ ),+ FakeResponse(body={"Items": [{"pk": {"S": "user#2"}, "age": {"N": "31"}}]}),+ ]+ )+ manager = FakeResumeManager()++ batches = list(get_rows(client, "users", _logger(), manager))++ assert batches == [[{"pk": "user#1", "age": 30}], [{"pk": "user#2", "age": 31}]]+ assert "ExclusiveStartKey" not in session.payload(0)+ assert session.payload(1)["ExclusiveStartKey"] == last_key+ # State is saved once, after the page that produced the cursor was already yielded.+ assert manager.saved == [DynamoDBResumeConfig(table_name="users", exclusive_start_key=last_key)]+ assert manager.cleared is True++ def test_resumes_from_the_saved_cursor(self) -> None:+ saved_key = {"pk": {"S": "user#7"}}+ client, session = _make_client([FakeResponse(body={"Items": [{"pk": {"S": "user#8"}}]})])+ manager = FakeResumeManager(DynamoDBResumeConfig(table_name="users", exclusive_start_key=saved_key))++ batches = list(get_rows(client, "users", _logger(), manager))++ assert batches == [[{"pk": "user#8"}]]+ assert session.payload(0)["ExclusiveStartKey"] == saved_key++ def test_cursor_saved_for_another_table_is_discarded(self) -> None:+ client, session = _make_client([FakeResponse(body={"Items": []})])+ manager = FakeResumeManager(+ DynamoDBResumeConfig(table_name="orders", exclusive_start_key={"order_id": {"S": "1"}})+ )++ assert list(get_rows(client, "users", _logger(), manager)) == []+ assert "ExclusiveStartKey" not in session.payload(0)++ def test_empty_page_with_a_cursor_keeps_scanning(self) -> None:+ client, _ = _make_client(+ [+ FakeResponse(body={"Items": [], "LastEvaluatedKey": {"pk": {"S": "a"}}}),+ FakeResponse(body={"Items": [{"pk": {"S": "b"}}]}),+ ]+ )++ assert list(get_rows(client, "users", _logger(), FakeResumeManager())) == [[{"pk": "b"}]]+++class TestValidateCredentials:+ def test_valid_credentials_probe_list_tables(self) -> None:+ session = FakeSession([FakeResponse(body={"TableNames": []})])+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ assert validate_credentials("AKIA", "secret", "us-east-1") == (True, None)++ assert session.target(0) == "DynamoDB_20120810.ListTables"++ @pytest.mark.parametrize(+ "code, expected_fragment",+ [+ ("UnrecognizedClientException", "access key"),+ ("AccessDeniedException", "dynamodb:ListTables"),+ ("ExpiredTokenException", "session token"),+ ],+ )+ def test_known_failures_map_to_an_actionable_message(self, code: str, expected_fragment: str) -> None:+ session = FakeSession([_error(code)])+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials("AKIA", "secret", "us-east-1")++ assert valid is False+ assert message is not None and expected_fragment in message++ def test_unknown_error_code_is_reported_verbatim(self) -> None:+ session = FakeSession([_error("SomeNewException")])+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials("AKIA", "secret", "us-east-1")++ assert valid is False+ assert message is not None and "SomeNewException" in message++ def test_bad_region_fails_without_a_request(self) -> None:+ with mock.patch(f"{_MODULE}.make_tracked_session") as make_session:+ valid, message = validate_credentials("AKIA", "secret", "not a region")++ assert valid is False+ assert message is not None and "valid AWS region" in message+ make_session.assert_not_called()++ def test_network_failure_reports_a_connectivity_message(self) -> None:+ session = FakeSession([])+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ with mock.patch.object(session, "post", side_effect=requests.ConnectionError("nope")):+ valid, message = validate_credentials("AKIA", "secret", "us-east-1")++ assert valid is False+ assert message is not None and "Could not reach DynamoDB" in message+++class TestDynamoDBSourceResponse:+ def test_response_carries_the_table_key_and_streams_rows(self) -> None:+ session = FakeSession(+ [+ FakeResponse(+ body={+ "Table": {+ "KeySchema": [+ {"AttributeName": "sk", "KeyType": "RANGE"},+ {"AttributeName": "pk", "KeyType": "HASH"},+ ]+ }+ }+ ),+ FakeResponse(body={"Items": [{"pk": {"S": "a"}, "sk": {"N": "1"}}]}),+ ]+ )+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ response = dynamodb_source(+ access_key_id="AKIA",+ secret_access_key="secret",+ region="us-east-1",+ table_name="users",+ logger=_logger(),+ resumable_source_manager=FakeResumeManager(),+ )++ assert response.name == "users"+ assert response.primary_keys == ["pk", "sk"]+ # Scan walks partition-hash order, so no sort mode may be claimed.+ assert response.sort_mode is None+ assert list(cast("Iterable[Any]", response.items())) == [[{"pk": "a", "sk": 1}]]++ def test_table_without_a_key_schema_yields_no_primary_keys(self) -> None:+ session = FakeSession([FakeResponse(body={"Table": {}}), FakeResponse(body={"Items": []})])+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ response = dynamodb_source(+ access_key_id="AKIA",+ secret_access_key="secret",+ region="us-east-1",+ table_name="users",+ logger=_logger(),+ resumable_source_manager=FakeResumeManager(),+ )++ assert response.primary_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/tests/test_dynamodb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/tests/test_dynamodb_source.pynew file mode 100644index 000000000000..e10aa4b16ec7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/tests/test_dynamodb_source.py@@ -0,0 +1,187 @@+from typing import Any, cast++import pytest+from unittest import mock++from structlog.types import FilteringBoundLogger++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.dynamodb import DynamoDBResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.source import DynamoDBSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dynamodb import (+ DynamoDBSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dynamodb.source"+++def _inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "users",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": cast(FilteringBoundLogger, mock.MagicMock()),+ "reset_pipeline": False,+ }+ return SourceInputs(**{**defaults, **overrides})+++class TestDynamoDBSource:+ def setup_method(self) -> None:+ self.source = DynamoDBSource()+ self.config = DynamoDBSourceConfig(+ aws_access_key_id="AKIA",+ aws_secret_access_key="secret",+ aws_region="us-east-1",+ aws_session_token=None,+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.DYNAMODB++ def test_source_is_released_in_alpha(self) -> None:+ config = self.source.get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.DATABASES+ assert config.iconPath == "/static/services/dynamodb.png"++ def test_credential_fields(self) -> None:+ fields = self.source.get_source_config.fields++ assert [field.name for field in fields] == [+ "aws_access_key_id",+ "aws_secret_access_key",+ "aws_region",+ "aws_session_token",+ ]++ @pytest.mark.parametrize(+ "field_name, expected_secret, expected_required",+ [+ ("aws_access_key_id", False, True),+ ("aws_secret_access_key", True, True),+ ("aws_region", False, True),+ ("aws_session_token", True, False),+ ],+ )+ def test_secrets_are_password_fields(self, field_name: str, expected_secret: bool, expected_required: bool) -> None:+ field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == field_name+ )++ assert field.secret is expected_secret+ assert field.required is expected_required+ assert (field.type == SourceFieldInputConfigType.PASSWORD) is expected_secret++ def test_region_change_forces_credential_re_entry(self) -> None:+ # The region decides which host the stored key is signed for and sent to.+ assert self.source.connection_host_fields == ["aws_region"]++ def test_api_version_is_the_one_the_requests_actually_target(self) -> None:+ assert self.source.supported_versions == ("2012-08-10",)+ assert self.source.default_version == "2012-08-10"+ assert self.source.api_docs_url is not None and self.source.api_docs_url.startswith("https://")++ def test_tables_are_discovered_over_the_connection_not_from_a_static_catalog(self) -> None:+ # Table names are per-account, so the public docs must not try to list them.+ assert self.source.lists_tables_without_credentials is False+ assert self.source.get_documented_tables() == []++ @pytest.mark.parametrize(+ "error_code",+ ["UnrecognizedClientException", "AccessDeniedException", "ExpiredTokenException", "ValidationException"],+ )+ def test_permanent_aws_errors_stop_the_job(self, error_code: str) -> None:+ assert error_code in self.source.get_non_retryable_errors()++ @pytest.mark.parametrize(+ "error_code", ["ThrottlingException", "ProvisionedThroughputExceededException", "InternalServerError"]+ )+ def test_throttling_is_treated_as_self_recovering(self, error_code: str) -> None:+ assert error_code in self.source.get_retryable_errors()+ assert error_code not in self.source.get_non_retryable_errors()++ def test_get_schemas_lists_the_accounts_tables(self) -> None:+ schemas = [SourceSchema(name="users", supports_incremental=False, supports_append=False)]++ with mock.patch(f"{_SOURCE_MODULE}.DynamoDBClient") as client_cls:+ with mock.patch(f"{_SOURCE_MODULE}.get_table_schemas", return_value=schemas) as get_schemas:+ assert self.source.get_schemas(self.config, team_id=1, with_counts=True, names=["users"]) == schemas++ client_cls.assert_called_once_with(+ access_key_id="AKIA",+ secret_access_key="secret",+ region="us-east-1",+ session_token=None,+ api_version="2012-08-10",+ )+ get_schemas.assert_called_once_with(client_cls.return_value, with_counts=True, names=["users"])++ def test_session_token_is_forwarded_when_set(self) -> None:+ config = DynamoDBSourceConfig(+ aws_access_key_id="AKIA",+ aws_secret_access_key="secret",+ aws_region="us-east-1",+ aws_session_token="temp",+ )++ with mock.patch(f"{_SOURCE_MODULE}.DynamoDBClient") as client_cls:+ with mock.patch(f"{_SOURCE_MODULE}.get_table_schemas", return_value=[]):+ self.source.get_schemas(config, team_id=1)++ assert client_cls.call_args.kwargs["session_token"] == "temp"++ @pytest.mark.parametrize(+ "result", [(True, None), (False, "AWS rejected your access key. Check the access key ID and secret.")]+ )+ def test_validate_credentials_passes_the_transport_result_through(self, result: tuple[bool, str | None]) -> None:+ with mock.patch(f"{_SOURCE_MODULE}.validate_dynamodb_credentials", return_value=result) as validate:+ assert self.source.validate_credentials(self.config, team_id=1) == result++ assert validate.call_args.kwargs["region"] == "us-east-1"+ assert validate.call_args.kwargs["api_version"] == "2012-08-10"++ def test_resumable_manager_is_bound_to_the_scan_cursor(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DynamoDBResumeConfig++ def test_source_for_pipeline_syncs_the_selected_table(self) -> None:+ manager: ResumableSourceManager[DynamoDBResumeConfig] = mock.MagicMock()+ inputs = _inputs(schema_name="orders")++ with mock.patch(f"{_SOURCE_MODULE}.dynamodb_source") as source_fn:+ assert self.source.source_for_pipeline(self.config, manager, inputs) == source_fn.return_value++ source_fn.assert_called_once_with(+ access_key_id="AKIA",+ secret_access_key="secret",+ region="us-east-1",+ session_token=None,+ table_name="orders",+ logger=inputs.logger,+ resumable_source_manager=manager,+ api_version="2012-08-10",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamodb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamodb.pyindex 3a48ca661c31..b5f119201df1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamodb.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynamodb.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass DynamoDBSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ aws_region: str+ aws_session_token: str | None = None