Skip to content

: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.

feat(data-warehouse): implement the aws step functions import source (#110809)

Tom Owersff2ef4882817
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index b7f62456de42..42adb8f2e185 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -114,6 +114,7 @@ the row lists both.
| aws_sagemaker | HTTP | requests | ✅ |
| aws_security_hub | HTTP | requests | ✅ |
| aws_ses | HTTP | requests | ✅ |
+| aws_step_functions | HTTP | requests | ✅ |
| aws_systems_manager | HTTP | requests | ✅ |
| aws_waf | HTTP | requests | ✅ |
| azure_cost_management | HTTP | requests | ✅ |
@@ -931,7 +932,6 @@ doesn't conflict with concurrent PRs.
- aws_macie
- aws_rds_performance_insights
- aws_savings_plans
-- aws_step_functions
- aws_support
- aws_trusted_advisor
- aws_xray
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/aws_step_functions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/aws_step_functions.py
new file mode 100644
index 000000000000..e4b8617d6660
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/aws_step_functions.py
@@ -0,0 +1,288 @@
+import re
+import json
+from collections.abc import Iterator
+from dataclasses import field, replace
+from datetime import UTC, datetime
+from typing import Any
+
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.credentials import Credentials
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_step_functions.settings import (
+ CONTENT_TYPE,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ PAGE_SIZE,
+ TARGET_PREFIXES,
+)
+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.http.transport import BoundedRetry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsstepfunctions import (
+ AwsStepFunctionsSourceConfig,
+)
+
+
+class AwsStepFunctionsError(Exception):
+ def __init__(self, code: str, message: str) -> None:
+ self.code = code
+ super().__init__(f"AWS Step Functions request failed: {code} - {message}")
+
+
+class AwsStepFunctionsThrottle(AwsStepFunctionsError):
+ pass
+
+
+@frozen
+class AwsStepFunctionsResumeConfig:
+ machine_token: str | None = None
+ machine_arns: list[str] = field(default_factory=list)
+ machines_done: bool = False
+ execution_token: str | None = None
+ execution_arns: list[str] = field(default_factory=list)
+ executions_done: bool = False
+ history_token: str | None = None
+
+
+class AwsStepFunctionsClient:
+ def __init__(self, config: AwsStepFunctionsSourceConfig, api_version: str) -> None:
+ if api_version not in TARGET_PREFIXES:
+ raise ValueError(f"Unsupported AWS Step Functions API version: {api_version}")
+ if not config.aws_access_key_id or not config.aws_secret_access_key:
+ raise ValueError("Enter both an AWS access key ID and a secret access key.")
+ if not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-\d+", config.region):
+ raise ValueError("Enter an AWS region, such as us-east-1.")
+ suffix = "amazonaws.com.cn" if config.region.startswith("cn-") else "amazonaws.com"
+ self.url = f"https://states.{config.region}.{suffix}/"
+ self.target_prefix = TARGET_PREFIXES[api_version]
+ self.signer = SigV4Auth(
+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),
+ "states",
+ config.region,
+ )
+ self.session = make_tracked_session(
+ retry=BoundedRetry(
+ total=3,
+ backoff_factor=1,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset(["POST"]),
+ raise_on_status=False,
+ ),
+ redact_values=tuple(value for value in (config.aws_secret_access_key, config.aws_session_token) if value),
+ )
+
+ # AWS also reports throttling as HTTP 400, outside the transport's status retries.
+ @retry(
+ retry=retry_if_exception_type(AwsStepFunctionsThrottle),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ stop=stop_after_attempt(5),
+ reraise=True,
+ )
+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ body = json.dumps(payload).encode()
+ request = AWSRequest(
+ method="POST",
+ url=self.url,
+ data=body,
+ headers={"Content-Type": CONTENT_TYPE, "X-Amz-Target": f"{self.target_prefix}.{operation}"},
+ )
+ self.signer.add_auth(request)
+ response = self.session.post(
+ self.url, data=body, headers=dict(request.headers), timeout=60, allow_redirects=False
+ )
+ if response.status_code >= 400:
+ try:
+ error = response.json()
+ except ValueError:
+ error = {}
+ if not isinstance(error, dict):
+ error = {}
+ code = (
+ str(
+ response.headers.get("x-amzn-ErrorType")
+ or error.get("__type")
+ or error.get("code")
+ or f"HTTP {response.status_code}"
+ )
+ .split(":")[0]
+ .rsplit("#", 1)[-1]
+ )
+ message = str(error.get("message") or error.get("Message") or response.reason)[:500]
+ error_class = (
+ AwsStepFunctionsThrottle
+ if response.status_code == 400
+ and code in {"ThrottlingException", "Throttling", "TooManyRequestsException", "KmsThrottlingException"}
+ else AwsStepFunctionsError
+ )
+ raise error_class(code, message)
+ if response.status_code != 200:
+ raise AwsStepFunctionsError(f"HTTP {response.status_code}", "Unexpected AWS response status.")
+ result = response.json()
+ if not isinstance(result, dict):
+ raise ValueError("AWS Step Functions returned an invalid response.")
+ return result
+
+ def page(self, endpoint: str, token: str | None = None, **params: Any) -> dict[str, Any]:
+ payload = {"maxResults": PAGE_SIZE, **params}
+ if token:
+ payload["nextToken"] = token
+ return self.request(ENDPOINTS[endpoint].operation, payload)
+
+ def close(self) -> None:
+ self.session.close()
+
+
+def normalize_row(item: dict[str, Any]) -> dict[str, Any]:
+ row = {re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", key).lower(): value for key, value in item.items()}
+ for key in ("creation_date", "start_date", "stop_date", "redrive_date", "timestamp"):
+ value = row.get(key)
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ row[key] = datetime.fromtimestamp(value, tz=UTC)
+ return row
+
+
+def get_rows(
+ client: AwsStepFunctionsClient,
+ endpoint: str,
+ manager: ResumableSourceManager[AwsStepFunctionsResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ state = manager.load_state() if manager.can_resume() else None
+ state = state or AwsStepFunctionsResumeConfig()
+ while True:
+ rows: list[dict[str, Any]] = []
+ if not state.machine_arns:
+ if state.machines_done:
+ break
+ page = client.page("state_machines", state.machine_token)
+ machines = page["stateMachines"]
+ state = replace(state, machine_token=page.get("nextToken"), machines_done=not page.get("nextToken"))
+ if endpoint == "state_machines":
+ rows = [normalize_row(item) for item in machines]
+ else:
+ state = replace(
+ state, machine_arns=[item["stateMachineArn"] for item in machines if item["type"] == "STANDARD"]
+ )
+ elif state.execution_arns:
+ execution_arn = state.execution_arns[0]
+ page = client.page(
+ "execution_history",
+ state.history_token,
+ executionArn=execution_arn,
+ includeExecutionData=False,
+ reverseOrder=False,
+ )
+ rows = [
+ normalize_row({**item, "executionArn": execution_arn, "stateMachineArn": state.machine_arns[0]})
+ for item in page["events"]
+ ]
+ token = page.get("nextToken")
+ state = replace(
+ state,
+ history_token=token,
+ execution_arns=state.execution_arns if token else state.execution_arns[1:],
+ )
+ elif state.executions_done:
+ state = replace(state, machine_arns=state.machine_arns[1:], execution_token=None, executions_done=False)
+ else:
+ page = client.page("executions", state.execution_token, stateMachineArn=state.machine_arns[0])
+ state = replace(state, execution_token=page.get("nextToken"), executions_done=not page.get("nextToken"))
+ if endpoint == "executions":
+ rows = [normalize_row(item) for item in page["executions"]]
+ else:
+ state = replace(state, execution_arns=[item["executionArn"] for item in page["executions"]])
+ manager.save_state(state)
+ if rows:
+ yield rows
+ manager.safe_point()
+
+
+def aws_step_functions_source(
+ config: AwsStepFunctionsSourceConfig,
+ endpoint: str,
+ api_version: str,
+ manager: ResumableSourceManager[AwsStepFunctionsResumeConfig],
+) -> SourceResponse:
+ if endpoint not in ENDPOINTS:
+ raise ValueError(f"Unknown AWS Step Functions table: {endpoint}")
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ client = AwsStepFunctionsClient(config, api_version)
+ try:
+ yield from get_rows(client, endpoint, manager)
+ finally:
+ client.close()
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=list(ENDPOINTS[endpoint].primary_keys),
+ sort_mode=None,
+ on_complete=manager.clear_state,
+ )
+
+
+def probe(client: AwsStepFunctionsClient, schema_name: str | None) -> None:
+ page = client.request("ListStateMachines", {"maxResults": 1})
+ if schema_name is None or schema_name == "state_machines":
+ return
+ while True:
+ for machine in page["stateMachines"]:
+ if machine["type"] != "STANDARD":
+ continue
+ executions = client.request(
+ "ListExecutions", {"stateMachineArn": machine["stateMachineArn"], "maxResults": 1}
+ )
+ if schema_name == "executions":
+ return
+ while True:
+ if executions["executions"]:
+ client.request(
+ "GetExecutionHistory",
+ {
+ "executionArn": executions["executions"][0]["executionArn"],
+ "maxResults": 1,
+ "includeExecutionData": False,
+ "reverseOrder": False,
+ },
+ )
+ return
+ if not executions.get("nextToken"):
+ break
+ executions = client.request(
+ "ListExecutions",
+ {
+ "stateMachineArn": machine["stateMachineArn"],
+ "maxResults": 1,
+ "nextToken": executions["nextToken"],
+ },
+ )
+ if not page.get("nextToken"):
+ return
+ page = client.request("ListStateMachines", {"maxResults": 1, "nextToken": page["nextToken"]})
+
+
+def validate_credentials(
+ config: AwsStepFunctionsSourceConfig, schema_name: str | None, api_version: str
+) -> tuple[bool, str | None]:
+ if schema_name is not None and schema_name not in ENDPOINTS:
+ return False, f"Unknown AWS Step Functions table: {schema_name}"
+ try:
+ client = AwsStepFunctionsClient(config, api_version)
+ except ValueError as error:
+ return False, str(error)
+ try:
+ probe(client, schema_name)
+ except AwsStepFunctionsError as error:
+ if schema_name is None and error.code in {"AccessDenied", "AccessDeniedException"}:
+ return True, None
+ if error.code in ERROR_MESSAGES:
+ return False, ERROR_MESSAGES[error.code]
+ raise
+ finally:
+ client.close()
+ return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/canonical_descriptions.py
new file mode 100644
index 000000000000..d77d718a22a5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/canonical_descriptions.py
@@ -0,0 +1,42 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "state_machines": {
+ "description": "State machines in the configured AWS region.",
+ "docs_url": "https://docs.aws.amazon.com/step-functions/latest/apireference/API_ListStateMachines.html",
+ "columns": {
+ "state_machine_arn": "The Amazon Resource Name (ARN) that identifies the state machine.",
+ "name": "The state machine name.",
+ "type": "The workflow type: STANDARD or EXPRESS.",
+ "creation_date": "The time AWS created the state machine, in UTC.",
+ },
+ },
+ "executions": {
+ "description": "Executions of Standard state machines, with status and timing data.",
+ "docs_url": "https://docs.aws.amazon.com/step-functions/latest/apireference/API_ListExecutions.html",
+ "columns": {
+ "execution_arn": "The ARN that identifies the execution.",
+ "state_machine_arn": "The ARN of the state machine that ran the execution.",
+ "name": "The execution name.",
+ "status": "The execution status reported by AWS.",
+ "start_date": "The execution start time, in UTC.",
+ "stop_date": "The execution completion time, in UTC, when available.",
+ "redrive_count": "The number of times AWS restarted the execution through redrive.",
+ "redrive_date": "The most recent redrive time, in UTC.",
+ },
+ },
+ "execution_history": {
+ "description": "Events from Standard execution histories. Input and output payloads are excluded.",
+ "docs_url": "https://docs.aws.amazon.com/step-functions/latest/apireference/API_GetExecutionHistory.html",
+ "columns": {
+ "execution_arn": "The parent execution ARN. Combine it with id to identify an event across this table.",
+ "state_machine_arn": "The ARN of the state machine that ran the parent execution.",
+ "id": "The event identifier within its execution.",
+ "previous_event_id": "The identifier of the preceding event.",
+ "type": "The event type reported by AWS.",
+ "timestamp": "The event time, in UTC.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/settings.py
new file mode 100644
index 000000000000..d97048513764
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/settings.py
@@ -0,0 +1,48 @@
+from posthog.dataclasses import frozen
+
+API_VERSION = "2016-11-23"
+TARGET_PREFIXES = {API_VERSION: "AWSStepFunctions"}
+CONTENT_TYPE = "application/x-amz-json-1.0"
+PAGE_SIZE = 100
+
+
+@frozen
+class StepFunctionsEndpoint:
+ operation: str
+ result_key: str
+ primary_keys: tuple[str, ...]
+
+
+ENDPOINTS = {
+ "state_machines": StepFunctionsEndpoint(
+ operation="ListStateMachines", result_key="stateMachines", primary_keys=("state_machine_arn",)
+ ),
+ "executions": StepFunctionsEndpoint(
+ operation="ListExecutions", result_key="executions", primary_keys=("execution_arn",)
+ ),
+ "execution_history": StepFunctionsEndpoint(
+ operation="GetExecutionHistory", result_key="events", primary_keys=("execution_arn", "id")
+ ),
+}
+ENDPOINT_DESCRIPTIONS = {
+ "state_machines": "State machines in the configured AWS region, including Standard and Express workflows.",
+ "executions": "Execution status and times for Standard workflows in the configured AWS region.",
+ "execution_history": "History events for Standard workflow executions, without input or output payloads.",
+}
+PERMISSION_MESSAGE = (
+ "Grant states:ListStateMachines, states:ListExecutions, and states:GetExecutionHistory for the tables you select."
+)
+ERROR_MESSAGES = {
+ "AccessDenied": PERMISSION_MESSAGE,
+ "AccessDeniedException": PERMISSION_MESSAGE,
+ "UnrecognizedClientException": "AWS rejected the credentials. Check the access key ID, secret access key, and session token.",
+ "InvalidClientTokenId": "AWS rejected the access key ID. Check that the key is active.",
+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and session token.",
+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key.",
+ "ExpiredTokenException": "The AWS session token expired. Connect again with current credentials.",
+ "ExpiredToken": "The AWS session token expired. Connect again with current credentials.",
+ "SubscriptionRequiredException": "Enable AWS Step Functions in this account and region, then try again.",
+ "OptInRequired": "Enable AWS Step Functions in this account and region, then try again.",
+ "KmsAccessDeniedException": "Grant access to the AWS KMS key used by this workflow.",
+ "InvalidToken": "The AWS pagination token expired or is invalid. Restart the table sync.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/source.py
index 3a639bb3f502..b57e84a810c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/source.py
@@ -1,8 +1,34 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_step_functions.aws_step_functions import (
+ AwsStepFunctionsResumeConfig,
+ aws_step_functions_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_step_functions.settings import (
+ API_VERSION,
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from 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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsstepfunctions import (
AwsStepFunctionsSourceConfig,
)
@@ -10,18 +36,112 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AwsStepFunctionsSource(SimpleSource[AwsStepFunctionsSourceConfig]):
+class AwsStepFunctionsSource(ResumableSource[AwsStepFunctionsSourceConfig, AwsStepFunctionsResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = "https://docs.aws.amazon.com/step-functions/latest/apireference/Welcome.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AWSSTEPFUNCTIONS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {f"AWS Step Functions request failed: {code}": message for code, message in ERROR_MESSAGES.items()}
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_step_functions.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AwsStepFunctionsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, {}, names, descriptions=ENDPOINT_DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: AwsStepFunctionsSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, schema_name, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[AwsStepFunctionsResumeConfig]:
+ return ResumableSourceManager(inputs, AwsStepFunctionsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AwsStepFunctionsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AwsStepFunctionsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aws_step_functions_source(
+ config, inputs.schema_name, self.resolve_api_version(inputs.api_version), resumable_source_manager
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.AWSSTEPFUNCTIONS,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Amazon Web Services (AWS Step Functions)",
+ label="AWS Step Functions",
+ caption=(
+ "Sync state machines, executions, and execution history from one AWS region. "
+ "Grant `states:ListStateMachines`, `states:ListExecutions`, and `states:GetExecutionHistory` for the tables you select. "
+ "Executions and history cover Standard workflows only. History excludes input and output payloads. "
+ "All tables use full refresh because these APIs have no time filter."
+ ),
iconPath="/static/services/aws_step_functions.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/aws-step-functions",
+ releaseStatus=ReleaseStatus.ALPHA,
+ 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_session_token",
+ label="AWS session token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="Only needed for temporary credentials",
+ secret=True,
+ caption="Temporary credentials expire. Update them before the next scheduled sync.",
+ ),
+ SourceFieldInputConfig(
+ name="region",
+ label="AWS region",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="us-east-1",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/tests/test_aws_step_functions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/tests/test_aws_step_functions.py
new file mode 100644
index 000000000000..1f232f343fba
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_step_functions/tests/test_aws_step_functions.py
@@ -0,0 +1,335 @@
+import json
+from collections.abc import Generator, Iterator
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from tenacity import wait_none
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_step_functions.aws_step_functions import (
+ AwsStepFunctionsClient,
+ AwsStepFunctionsError,
+ AwsStepFunctionsResumeConfig,
+ aws_step_functions_source,
+ normalize_row,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_step_functions.settings import API_VERSION
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_step_functions.source import (
+ AwsStepFunctionsSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsstepfunctions import (
+ AwsStepFunctionsSourceConfig,
+)
+
+SM1 = "arn:aws:states:us-east-1:123456789012:stateMachine:example-one"
+SM2 = "arn:aws:states:us-east-1:123456789012:stateMachine:example-two"
+EXPRESS = "arn:aws:states:us-east-1:123456789012:stateMachine:example-express"
+EXECUTIONS = [f"arn:aws:states:us-east-1:123456789012:execution:example-one:run-{i}" for i in range(4)]
+
+
+def config() -> AwsStepFunctionsSourceConfig:
+ return AwsStepFunctionsSourceConfig(
+ aws_access_key_id="AKIAEXAMPLE", aws_secret_access_key="example-secret", region="us-east-1"
+ )
+
+
+def session() -> Iterator[MagicMock]:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.aws_step_functions.aws_step_functions.make_tracked_session"
+ ) as factory:
+ yield factory.return_value
+
+
+def response(status: int, body: object, headers: dict[str, str] | None = None) -> requests.Response:
+ result = requests.Response()
+ result.status_code = status
+ result._content = json.dumps(body).encode()
+ result.headers.update(headers or {})
+ return result
+
+
+def manager(state: AwsStepFunctionsResumeConfig | None = None) -> MagicMock:
+ result = MagicMock()
+ result.can_resume.return_value = state is not None
+ result.load_state.return_value = state
+ return result
+
+
+def source_items(source: SourceResponse) -> Generator[list[dict[str, Any]]]:
+ return cast(Generator[list[dict[str, Any]]], source.items())
+
+
+ "region,suffix",
+ [("us-east-1", "amazonaws.com"), ("eu-west-1", "amazonaws.com"), ("cn-north-1", "amazonaws.com.cn")],
+)
[email protected]("token", [None, "example-session-token"])
+def test_signed_request(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock, region: str, suffix: str, token: str | None
+) -> None:
+ config.region = region
+ config.aws_session_token = token
+ session.post.return_value = response(200, {"stateMachines": []})
+ client = AwsStepFunctionsClient(config, API_VERSION)
+ client.request("ListStateMachines", {"maxResults": 1})
+ args, kwargs = session.post.call_args
+ assert args == (f"https://states.{region}.{suffix}/",)
+ assert json.loads(kwargs["data"]) == {"maxResults": 1}
+ headers = kwargs["headers"]
+ assert headers["X-Amz-Target"] == "AWSStepFunctions.ListStateMachines"
+ assert headers["Content-Type"] == "application/x-amz-json-1.0"
+ assert f"/{region}/states/aws4_request" in headers["Authorization"]
+ assert "x-amz-target" in headers["Authorization"]
+ assert headers.get("X-Amz-Security-Token") == token
+ assert headers["X-Amz-Date"]
+ assert kwargs["allow_redirects"] is False
+ assert kwargs["timeout"] == 60
+
+
+def install_pages(session: MagicMock) -> None:
+ def post(url: str, **kwargs: Any) -> requests.Response:
+ payload = json.loads(kwargs["data"])
+ operation = kwargs["headers"]["X-Amz-Target"].split(".")[-1]
+ assert payload["maxResults"] <= 1000
+ assert not {"startDate", "startTime", "updatedAt", "statusFilter"}.intersection(payload)
+ token = payload.get("nextToken")
+ if operation == "ListStateMachines":
+ machine_pages: dict[str | None, dict[str, Any]] = {
+ None: {
+ "stateMachines": [
+ {"stateMachineArn": EXPRESS, "type": "EXPRESS"},
+ {"stateMachineArn": SM1, "type": "STANDARD"},
+ ],
+ "nextToken": "m2",
+ },
+ "m2": {"stateMachines": [], "nextToken": "m3"},
+ "m3": {"stateMachines": [{"stateMachineArn": SM2, "type": "STANDARD"}]},
+ }
+ return response(200, machine_pages[token])
+ if operation == "ListExecutions":
+ machine = payload["stateMachineArn"]
+ assert machine != EXPRESS
+ execution_pages: dict[tuple[str, str | None], dict[str, Any]] = {
+ (SM1, None): {
+ "executions": [
+ {"executionArn": arn, "stateMachineArn": SM1, "startDate": 100} for arn in EXECUTIONS[:2]
+ ],
+ "nextToken": "e2",
+ },
+ (SM1, "e2"): {"executions": [{"executionArn": EXECUTIONS[2], "stateMachineArn": SM1, "startDate": 1}]},
+ (SM2, None): {"executions": [], "nextToken": "e-empty"},
+ (SM2, "e-empty"): {
+ "executions": [{"executionArn": EXECUTIONS[3], "stateMachineArn": SM2, "startDate": 200}]
+ },
+ }
+ return response(200, execution_pages[(machine, token)])
+ assert operation == "GetExecutionHistory"
+ assert payload["includeExecutionData"] is False
+ assert payload["reverseOrder"] is False
+ if token is None:
+ return response(200, {"events": [{"id": 1, "timestamp": 1}], "nextToken": "h2"})
+ assert token == "h2"
+ return response(200, {"events": [{"id": 2, "previousEventId": 1, "timestamp": 2}]})
+
+ session.post.side_effect = post
+
+
[email protected]("endpoint,count", [("state_machines", 3), ("executions", 4), ("execution_history", 8)])
+def test_full_refresh_pagination_and_resume_at_every_batch(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock, endpoint: str, count: int
+) -> None:
+ install_pages(session)
+ initial_manager = manager()
+ source = aws_step_functions_source(config, endpoint, API_VERSION, initial_manager)
+ expected = [row for batch in source_items(source) for row in batch]
+ assert len(expected) == count
+ assert source.primary_keys is not None
+ assert len({tuple(row[key] for key in source.primary_keys) for row in expected}) == count
+ assert source.sort_mode is None
+ initial_manager.clear_state.assert_not_called()
+ assert source.on_complete is not None
+ source.on_complete()
+ initial_manager.clear_state.assert_called_once()
+ initial_manager.safe_point.assert_called()
+ if endpoint == "executions":
+ assert {row["start_date"] for row in expected} == {datetime.fromtimestamp(i, UTC) for i in (1, 100, 200)}
+ if endpoint == "execution_history":
+ assert {row["execution_arn"] for row in expected} == set(EXECUTIONS)
+ assert {row["state_machine_arn"] for row in expected} == {SM1, SM2}
+ batch_count = len(list(source_items(aws_step_functions_source(config, endpoint, API_VERSION, manager()))))
+ for stop_after in range(1, batch_count + 1):
+ interrupted_manager = manager()
+ iterator = source_items(aws_step_functions_source(config, endpoint, API_VERSION, interrupted_manager))
+ prefix = [row for _ in range(stop_after) for row in next(iterator)]
+ state = interrupted_manager.save_state.call_args.args[0]
+ iterator.close()
+ resumed = aws_step_functions_source(config, endpoint, API_VERSION, manager(state))
+ assert prefix + [row for batch in source_items(resumed) for row in batch] == expected
+ session.close.assert_called()
+
+
[email protected]("endpoint", ["state_machines", "executions", "execution_history"])
+def test_empty_pages_finish_and_resume_without_requests(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock, endpoint: str
+) -> None:
+ session.post.side_effect = [
+ response(200, {"stateMachines": [], "nextToken": "next"}),
+ response(200, {"stateMachines": []}),
+ ]
+ checkpoint = manager()
+ assert list(source_items(aws_step_functions_source(config, endpoint, API_VERSION, checkpoint))) == []
+ assert checkpoint.safe_point.call_count == 2
+ state = checkpoint.save_state.call_args.args[0]
+ session.post.reset_mock()
+ assert list(source_items(aws_step_functions_source(config, endpoint, API_VERSION, manager(state)))) == []
+ session.post.assert_not_called()
+
+
[email protected]("schema_name", [None, "state_machines", "executions", "execution_history"])
+ "code,valid_at_create",
+ [
+ ("AccessDeniedException", True),
+ ("AccessDenied", True),
+ ("UnrecognizedClientException", False),
+ ("InvalidSignatureException", False),
+ ("ExpiredTokenException", False),
+ ("SubscriptionRequiredException", False),
+ ],
+)
+def test_credentials_error_mapping(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock, schema_name: str | None, code: str, valid_at_create: bool
+) -> None:
+ session.post.return_value = response(
+ 400, {"__type": f"com.amazonaws.states#{code}", "message": "Example AWS error"}
+ )
+ valid, message = validate_credentials(config, schema_name, API_VERSION)
+ assert valid is (schema_name is None and valid_at_create)
+ if valid:
+ assert message is None
+ else:
+ assert message
+ assert "Example AWS error" not in message
+ patterns = AwsStepFunctionsSource().get_non_retryable_errors()
+ assert any(pattern in f"AWS Step Functions request failed: {code} - Example AWS error" for pattern in patterns)
+ session.post.assert_called_once()
+ session.close.assert_called_once()
+
+
+ "status,body,headers,code",
+ [
+ (403, {}, {"x-amzn-ErrorType": "AccessDeniedException:http"}, "AccessDeniedException"),
+ (500, {}, {}, "HTTP 500"),
+ (400, [], {}, "HTTP 400"),
+ (302, {}, {}, "HTTP 302"),
+ ],
+)
+def test_transport_errors(
+ config: AwsStepFunctionsSourceConfig,
+ session: MagicMock,
+ status: int,
+ body: object,
+ headers: dict[str, str],
+ code: str,
+) -> None:
+ session.post.return_value = response(status, body, headers)
+ with pytest.raises(AwsStepFunctionsError) as error:
+ AwsStepFunctionsClient(config, API_VERSION).request("ListStateMachines", {})
+ assert error.value.code == code
+ session.post.assert_called_once()
+
+
+def test_body_throttle_retries_with_a_new_signature(config: AwsStepFunctionsSourceConfig, session: MagicMock) -> None:
+ session.post.side_effect = [response(400, {"__type": "ThrottlingException"}), response(200, {"stateMachines": []})]
+ client = AwsStepFunctionsClient(config, API_VERSION)
+ with patch.object(client.signer, "add_auth", wraps=client.signer.add_auth) as sign:
+ result = client.request.retry_with(wait=wait_none())(client, "ListStateMachines", {}) # type: ignore[attr-defined]
+ assert result == {"stateMachines": []}
+ assert sign.call_count == 2
+
+
[email protected]("code", ["ServiceUnavailable", "UnknownError"])
+def test_validation_propagates_transient_and_unknown_errors(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock, code: str
+) -> None:
+ session.post.return_value = response(500, {"__type": code})
+ with pytest.raises(AwsStepFunctionsError):
+ validate_credentials(config, None, API_VERSION)
+ session.close.assert_called_once()
+
+
+ "field,value,message",
+ [
+ ("region", "us-east-1.example.com", "AWS region"),
+ ("region", "", "AWS region"),
+ ("aws_access_key_id", "", "access key ID"),
+ ("aws_secret_access_key", "", "secret access key"),
+ ],
+)
+def test_invalid_config_does_not_send_credentials(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock, field: str, value: str, message: str
+) -> None:
+ setattr(config, field, value)
+ valid, reason = validate_credentials(config, None, API_VERSION)
+ assert not valid
+ assert reason is not None and message in reason
+ session.post.assert_not_called()
+
+
[email protected]("schema_name", [None, "state_machines", "executions", "execution_history"])
+def test_permission_probe_walks_to_standard_execution(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock, schema_name: str | None
+) -> None:
+ install_pages(session)
+ assert validate_credentials(config, schema_name, API_VERSION) == (True, None)
+ calls = session.post.call_args_list
+ if schema_name in (None, "state_machines"):
+ assert len(calls) == 1
+ elif schema_name == "executions":
+ assert calls[-1].kwargs["headers"]["X-Amz-Target"].endswith(".ListExecutions")
+ else:
+ assert calls[-1].kwargs["headers"]["X-Amz-Target"].endswith(".GetExecutionHistory")
+
+
[email protected]("schema_name", ["executions", "execution_history"])
+def test_probe_handles_empty_and_express_only_accounts(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock, schema_name: str
+) -> None:
+ session.post.side_effect = [
+ response(200, {"stateMachines": [{"stateMachineArn": EXPRESS, "type": "EXPRESS"}], "nextToken": "next"}),
+ response(200, {"stateMachines": []}),
+ ]
+ assert validate_credentials(config, schema_name, API_VERSION) == (True, None)
+ assert len(session.post.call_args_list) == 2
+
+
+def test_unknown_schema_and_version_fail_before_network(
+ config: AwsStepFunctionsSourceConfig, session: MagicMock
+) -> None:
+ assert validate_credentials(config, "missing", API_VERSION) == (False, "Unknown AWS Step Functions table: missing")
+ with pytest.raises(ValueError, match="Unknown AWS Step Functions table"):
+ aws_step_functions_source(config, "missing", API_VERSION, manager())
+ with pytest.raises(ValueError, match="Unsupported AWS Step Functions API version"):
+ AwsStepFunctionsClient(config, "1900-01-01")
+ session.post.assert_not_called()
+
+
+def test_normalization_preserves_nested_details() -> None:
+ details = {"error": "ExampleError", "cause": "Example task failure"}
+ assert normalize_row(
+ {"executionArn": "example", "timestamp": 1.5, "stopDate": None, "taskFailedEventDetails": details}
+ ) == {
+ "execution_arn": "example",
+ "timestamp": datetime.fromtimestamp(1.5, UTC),
+ "stop_date": None,
+ "task_failed_event_details": details,
+ }
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsstepfunctions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsstepfunctions.py
index f3c6ddd77d88..acecc3ea745e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsstepfunctions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsstepfunctions.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AwsStepFunctionsSourceConfig(config.Config):
- pass
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ region: str
+ aws_session_token: str | None = None