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 batch import source (#110791)

Tom Owers404955984b53
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 f0134539c223..b274456b72e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -102,6 +102,7 @@ the row lists both.
| aviationstack | HTTP | requests | ✅ |
| aviator | HTTP | requests | ✅ |
| awin | HTTP | requests | ✅ |
+| aws_batch | HTTP | requests | ✅ |
| aws_budgets | HTTP | requests | ✅ |
| aws_cloudtrail | HTTP | requests | ✅ |
| aws_cost_anomaly_detection | HTTP | requests | ✅ |
@@ -916,7 +917,6 @@ doesn't conflict with concurrent PRs.
- autodesk_construction_cloud
- automox
- aws_athena
-- aws_batch
- aws_cloudformation
- aws_compute_optimizer
- aws_config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/aws_batch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/aws_batch.py
new file mode 100644
index 000000000000..3655d2433045
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/aws_batch.py
@@ -0,0 +1,281 @@
+import re
+import json
+import datetime as dt
+from collections.abc import Iterator
+from dataclasses import replace
+from typing import Any
+
+import requests
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.credentials import Credentials
+from botocore.session import Session
+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_batch.settings import (
+ AWS_BATCH_ENDPOINTS,
+ BATCH_API_VERSION,
+ NON_RETRYABLE_ERRORS,
+ PAGE_SIZE,
+)
+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.awsbatch import (
+ AwsBatchSourceConfig,
+)
+
+_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+_REGION = re.compile(r"(?:af|ap|ca|cn|eu|il|me|mx|sa|us)-(?:gov-)?[a-z]+-\d+")
+
+TRANSPORT_RETRY = BoundedRetry(
+ total=3,
+ backoff_factor=1,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset({"POST"}),
+ raise_on_status=False,
+)
+
+
+@frozen
+class AwsBatchResumeConfig:
+ next_token: str | None = None
+ queue_arns: list[str] | None = None
+ queue_index: int = 0
+ complete: bool = False
+
+
+class AwsBatchError(Exception):
+ def __init__(self, code: str, message: str) -> None:
+ super().__init__(f"AWS Batch request failed: {code} - {message}")
+ self.code = code
+ self.message = message
+
+ @property
+ def access_denied(self) -> bool:
+ return "AccessDenied" in self.code or (
+ self.code == "ClientException" and "not authorized to perform" in self.message
+ )
+
+
+class AwsBatchThrottleError(AwsBatchError):
+ pass
+
+
+def error_for_response(response: requests.Response) -> AwsBatchError:
+ try:
+ body = response.json()
+ except ValueError:
+ body = {}
+ if not isinstance(body, dict):
+ body = {}
+ code = str(
+ response.headers.get("x-amzn-ErrorType")
+ or body.get("__type")
+ or body.get("code")
+ or f"HTTP {response.status_code}"
+ )
+ code = code.split(":")[0].split("#")[-1]
+ message = str(body.get("message") or body.get("Message") or response.text)[:500]
+ # The transport retries HTTP 429 and 5xx. Only body-level throttles need another retry policy.
+ if response.status_code == 400 and code in {"ThrottlingException", "TooManyRequestsException", "Throttling"}:
+ return AwsBatchThrottleError(code, message)
+ return AwsBatchError(code, message)
+
+
+class AwsBatchClient:
+ def __init__(self, config: AwsBatchSourceConfig, api_version: str = BATCH_API_VERSION) -> None:
+ if api_version != BATCH_API_VERSION:
+ raise ValueError(f"Unsupported AWS Batch API version: {api_version}")
+ if not _REGION.fullmatch(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://batch.{config.region}.{suffix}"
+ # REST-JSON has no version header. The pinned service model selects its request paths.
+ self.model = Session().get_service_model("batch", api_version=api_version)
+ self.signer = SigV4Auth(
+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),
+ "batch",
+ config.region,
+ )
+ self.session = make_tracked_session(
+ retry=TRANSPORT_RETRY,
+ redact_values=tuple(
+ value
+ for value in (config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token)
+ if value
+ ),
+ )
+
+ @retry(
+ retry=retry_if_exception_type(AwsBatchThrottleError),
+ stop=stop_after_attempt(4),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ url = self.url + self.model.operation_model(operation).http["requestUri"]
+ body = json.dumps(payload).encode("utf-8")
+ request = AWSRequest(method="POST", url=url, data=body, headers={"Content-Type": "application/json"})
+ self.signer.add_auth(request)
+ response = self.session.post(url, data=body, headers=dict(request.headers), timeout=60)
+ if response.status_code >= 400:
+ raise error_for_response(response)
+ parsed = response.json()
+ if not isinstance(parsed, dict):
+ raise ValueError("AWS Batch returned an invalid response.")
+ return parsed
+
+ def close(self) -> None:
+ self.session.close()
+
+
+def normalize_row(item: dict[str, Any], region: str) -> dict[str, Any]:
+ row = {_CAMEL_BOUNDARY.sub("_", name).lower(): value for name, value in item.items()}
+ row["region"] = region
+ for column in ("created_at", "started_at", "stopped_at", "scheduled_at"):
+ if column in row and isinstance(row[column], int | float) and not isinstance(row[column], bool):
+ row[column] = dt.datetime.fromtimestamp(row[column] / 1000, tz=dt.UTC) if row[column] else None
+ return row
+
+
+def next_page_token(body: dict[str, Any], previous_token: str | None) -> str | None:
+ token = body.get("nextToken") or None
+ if token is not None and (not isinstance(token, str) or token == previous_token):
+ raise ValueError("AWS Batch returned an invalid or repeated page token.")
+ return token
+
+
+def discover_queues(client: AwsBatchClient, manager: ResumableSourceManager[AwsBatchResumeConfig]) -> list[str]:
+ queues: list[str] = []
+ token = None
+ while True:
+ payload: dict[str, Any] = {"maxResults": PAGE_SIZE}
+ if token:
+ payload["nextToken"] = token
+ body = client.request("DescribeJobQueues", payload)
+ queues.extend(queue["jobQueueArn"] for queue in body.get("jobQueues", []))
+ token = next_page_token(body, token)
+ manager.safe_point()
+ if token is None:
+ return list(dict.fromkeys(queues))
+
+
+def get_rows(
+ config: AwsBatchSourceConfig,
+ endpoint: str,
+ manager: ResumableSourceManager[AwsBatchResumeConfig],
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint_config = AWS_BATCH_ENDPOINTS[endpoint]
+ state = manager.load_state() if manager.can_resume() else None
+ state = state or AwsBatchResumeConfig()
+ if state.complete:
+ return
+ client = AwsBatchClient(config, api_version)
+ try:
+ if endpoint == "jobs" and state.queue_arns is None:
+ state = replace(state, queue_arns=discover_queues(client, manager))
+ while not state.complete:
+ payload: dict[str, Any] = {"maxResults": PAGE_SIZE}
+ if endpoint == "jobs":
+ queues = state.queue_arns or []
+ if state.queue_index >= len(queues):
+ manager.save_state(replace(state, complete=True))
+ manager.safe_point()
+ return
+ payload["jobQueue"] = queues[state.queue_index]
+ # A name wildcard includes every status without seven separate status walks.
+ payload["filters"] = [{"name": "JOB_NAME", "values": ["*"]}]
+ if state.next_token:
+ payload["nextToken"] = state.next_token
+ body = client.request(endpoint_config.operation, payload)
+ items = body.get(endpoint_config.result_key, [])
+ token = next_page_token(body, state.next_token)
+ if endpoint == "jobs":
+ job_ids = [item["jobId"] for item in items]
+ items = []
+ for offset in range(0, len(job_ids), PAGE_SIZE):
+ items.extend(
+ client.request("DescribeJobs", {"jobs": job_ids[offset : offset + PAGE_SIZE]}).get("jobs", [])
+ )
+ queue_index = state.queue_index + (token is None)
+ state = replace(state, next_token=token, queue_index=queue_index, complete=queue_index >= len(queues))
+ else:
+ state = replace(state, next_token=token, complete=token is None)
+ rows = [normalize_row(item, config.region) for item in items]
+ manager.save_state(state)
+ if rows:
+ yield rows
+ manager.safe_point()
+ finally:
+ client.close()
+
+
+def credential_error_message(error: AwsBatchError) -> str:
+ for pattern, message in NON_RETRYABLE_ERRORS.items():
+ if pattern in str(error):
+ return message
+ return "Could not read AWS Batch data. Check the region and IAM permissions, then try again."
+
+
+def validate_credentials(
+ config: AwsBatchSourceConfig,
+ schema_name: str | None = None,
+ api_version: str = BATCH_API_VERSION,
+) -> tuple[bool, str | None]:
+ if not config.aws_access_key_id or not config.aws_secret_access_key:
+ return False, "Enter both an AWS access key ID and a secret access key."
+ if schema_name is not None and schema_name not in AWS_BATCH_ENDPOINTS:
+ return False, f"Unknown AWS Batch table: {schema_name}"
+ try:
+ client = AwsBatchClient(config, api_version)
+ except ValueError as error:
+ return False, str(error)
+ try:
+ operation = AWS_BATCH_ENDPOINTS[schema_name].operation if schema_name else "DescribeJobQueues"
+ if schema_name == "jobs":
+ queues = client.request("DescribeJobQueues", {"maxResults": 1}).get("jobQueues", [])
+ if queues:
+ jobs = client.request(
+ "ListJobs",
+ {
+ "jobQueue": queues[0]["jobQueueArn"],
+ "maxResults": 1,
+ "filters": [{"name": "JOB_NAME", "values": ["*"]}],
+ },
+ ).get("jobSummaryList", [])
+ if jobs:
+ client.request("DescribeJobs", {"jobs": [jobs[0]["jobId"]]})
+ else:
+ client.request(operation, {"maxResults": 1})
+ except AwsBatchError as error:
+ if schema_name is None and error.access_denied:
+ return True, None
+ return False, credential_error_message(error)
+ except requests.RequestException:
+ return False, "Could not reach AWS Batch. Check the region and try again."
+ finally:
+ client.close()
+ return True, None
+
+
+def aws_batch_source(
+ config: AwsBatchSourceConfig,
+ endpoint: str,
+ manager: ResumableSourceManager[AwsBatchResumeConfig],
+ api_version: str = BATCH_API_VERSION,
+) -> SourceResponse:
+ endpoint_config = AWS_BATCH_ENDPOINTS.get(endpoint)
+ if endpoint_config is None:
+ raise ValueError(f"Unknown AWS Batch table: {endpoint}")
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(config, endpoint, manager, api_version),
+ primary_keys=[endpoint_config.primary_key],
+ sort_mode=None,
+ on_complete=manager.clear_state,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/canonical_descriptions.py
new file mode 100644
index 000000000000..84a634748ee1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/canonical_descriptions.py
@@ -0,0 +1,67 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "jobs": {
+ "description": "AWS Batch jobs in the selected region, with execution details and attempts.",
+ "docs_url": "https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html",
+ "columns": {
+ "job_arn": "ARN that identifies the job across accounts and regions.",
+ "job_id": "Identifier assigned to the job by AWS Batch.",
+ "job_name": "Name supplied when the job was submitted.",
+ "job_queue": "ARN of the queue to which the job was submitted.",
+ "job_definition": "Job definition revision used to start the job.",
+ "status": "Current state of the job, such as RUNNING, SUCCEEDED, or FAILED.",
+ "status_reason": "Reason for the current job state.",
+ "created_at": "Time when the job was created, converted from milliseconds to a UTC timestamp.",
+ "started_at": "Time when the job started, converted to UTC. Null if the job has not started.",
+ "stopped_at": "Time when the job stopped, converted to UTC. Null if the job has not stopped.",
+ "attempts": "Execution attempts, including timing, container details, and failure reasons.",
+ "container": "Container configuration and execution details returned for the job.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "job_queues": {
+ "description": "Queues that accept AWS Batch jobs and assign them to compute environments.",
+ "docs_url": "https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobQueues.html",
+ "columns": {
+ "job_queue_arn": "ARN that identifies the queue across accounts and regions.",
+ "job_queue_name": "Name of the job queue.",
+ "state": "Whether the queue accepts new jobs.",
+ "status": "Current status of the queue.",
+ "priority": "Scheduling priority relative to queues that share a compute environment.",
+ "compute_environment_order": "Compute environments associated with the queue and their selection order.",
+ "scheduling_policy_arn": "ARN of the scheduling policy associated with the queue.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "compute_environments": {
+ "description": "AWS Batch compute environments and their capacity configuration.",
+ "docs_url": "https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeComputeEnvironments.html",
+ "columns": {
+ "compute_environment_arn": "ARN that identifies the compute environment across accounts and regions.",
+ "compute_environment_name": "Name of the compute environment.",
+ "type": "Whether AWS Batch manages the compute environment.",
+ "state": "Whether the compute environment accepts jobs.",
+ "status": "Current status of the compute environment.",
+ "compute_resources": "Capacity, instance, and network settings for managed compute resources.",
+ "ecs_cluster_arn": "ARN of the associated Amazon ECS cluster.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "job_definitions": {
+ "description": "AWS Batch job definition revisions and their execution configuration.",
+ "docs_url": "https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobDefinitions.html",
+ "columns": {
+ "job_definition_arn": "ARN that identifies a specific job definition revision.",
+ "job_definition_name": "Name shared by revisions of this job definition.",
+ "revision": "Revision number of the job definition.",
+ "status": "Whether the revision is ACTIVE or INACTIVE.",
+ "type": "Job definition type, such as container or multinode.",
+ "container_properties": "Container settings, including the image, command, and resource requirements.",
+ "retry_strategy": "Rules that control retries after a job fails.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/settings.py
new file mode 100644
index 000000000000..ab211483d487
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/settings.py
@@ -0,0 +1,65 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+BATCH_API_VERSION = "2016-08-10"
+PAGE_SIZE = 100
+
+
+@frozen
+class AwsBatchEndpoint:
+ operation: str
+ result_key: str
+ primary_key: str
+ description: str
+
+
+AWS_BATCH_ENDPOINTS: dict[str, AwsBatchEndpoint] = {
+ "jobs": AwsBatchEndpoint(
+ operation="ListJobs",
+ result_key="jobSummaryList",
+ primary_key="job_arn",
+ description="Jobs in each queue, with their status, attempts, and execution details. Array children are not expanded.",
+ ),
+ "job_queues": AwsBatchEndpoint(
+ operation="DescribeJobQueues",
+ result_key="jobQueues",
+ primary_key="job_queue_arn",
+ description="Job queues, their priorities, and their associated compute environments.",
+ ),
+ "compute_environments": AwsBatchEndpoint(
+ operation="DescribeComputeEnvironments",
+ result_key="computeEnvironments",
+ primary_key="compute_environment_arn",
+ description="Compute environments, their capacity settings, and their state.",
+ ),
+ "job_definitions": AwsBatchEndpoint(
+ operation="DescribeJobDefinitions",
+ result_key="jobDefinitions",
+ primary_key="job_definition_arn",
+ description="Job definition revisions, including their resource requirements and container settings.",
+ ),
+}
+ENDPOINTS = tuple(AWS_BATCH_ENDPOINTS)
+ENDPOINT_DESCRIPTIONS = {name: endpoint.description for name, endpoint in AWS_BATCH_ENDPOINTS.items()}
+
+# A creation filter misses later job status changes. Full refresh keeps those changes visible.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
+
+PERMISSION_MESSAGE = (
+ "AWS denied access to Batch. Grant batch:DescribeJobQueues, batch:ListJobs, batch:DescribeJobs, "
+ "batch:DescribeComputeEnvironments, and batch:DescribeJobDefinitions for the tables you select."
+)
+CREDENTIAL_MESSAGE = "AWS rejected the credentials. Check the access key ID, secret access key, and session token."
+NON_RETRYABLE_ERRORS: dict[str, str] = {
+ **dict.fromkeys(
+ ("UnrecognizedClientException", "InvalidClientTokenId", "SignatureDoesNotMatch", "InvalidSignatureException"),
+ CREDENTIAL_MESSAGE,
+ ),
+ "ExpiredToken": "The AWS session token has expired. Enter new credentials.",
+ "AccessDenied": PERMISSION_MESSAGE,
+ "not authorized to perform": PERMISSION_MESSAGE,
+ "SubscriptionRequiredException": "Enable AWS Batch for this account before you connect it.",
+ "OptInRequired": "Enable AWS Batch in the selected region before you connect it.",
+ "not subscribed": "Enable AWS Batch for this account before you connect it.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/source.py
index e023e15c1bb1..8d0d24541ef4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/source.py
@@ -1,8 +1,38 @@
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_batch.aws_batch import (
+ AwsBatchResumeConfig,
+ aws_batch_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_batch.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_batch.settings import (
+ BATCH_API_VERSION,
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ NON_RETRYABLE_ERRORS,
+)
+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.awsbatch import (
AwsBatchSourceConfig,
)
@@ -10,18 +40,109 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AwsBatchSource(SimpleSource[AwsBatchSourceConfig]):
+class AwsBatchSource(ResumableSource[AwsBatchSourceConfig, AwsBatchResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (BATCH_API_VERSION,)
+ default_version = BATCH_API_VERSION
+ api_docs_url = "https://docs.aws.amazon.com/batch/latest/APIReference/Welcome.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AWSBATCH
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return dict(NON_RETRYABLE_ERRORS)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AwsBatchSourceConfig,
+ 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, INCREMENTAL_FIELDS, names, descriptions=ENDPOINT_DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: AwsBatchSourceConfig,
+ 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[AwsBatchResumeConfig]:
+ return ResumableSourceManager(inputs, AwsBatchResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AwsBatchSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AwsBatchResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aws_batch_source(
+ config, inputs.schema_name, resumable_source_manager, self.resolve_api_version(inputs.api_version)
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.AWSBATCH,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Amazon Web Services (AWS Batch)",
+ label="AWS Batch",
+ caption=(
+ "Sync AWS Batch jobs and resources from one region. "
+ "Grant `batch:DescribeJobQueues`, `batch:ListJobs`, and `batch:DescribeJobs` to read jobs. "
+ "Grant `batch:DescribeComputeEnvironments` and `batch:DescribeJobDefinitions` to read those tables. "
+ "Enter an access key ID and secret access key. Add a session token for temporary credentials. "
+ "All tables use full refresh so later job status changes remain visible. "
+ "The jobs table includes jobs that AWS still retains in existing queues. "
+ "Array children and individual nodes are not expanded."
+ ),
iconPath="/static/services/aws_batch.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["aws", "batch", "jobs", "compute"],
+ 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="",
+ secret=True,
+ caption="Required for temporary credentials. Replace these credentials when the session token expires.",
+ ),
+ 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_batch/tests/test_aws_batch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/tests/test_aws_batch.py
new file mode 100644
index 000000000000..cf848bde3fab
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/tests/test_aws_batch.py
@@ -0,0 +1,423 @@
+import json
+import datetime as dt
+from collections.abc import Iterable, Iterator
+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_batch import (
+ aws_batch as transport,
+ source as source_module,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_batch.aws_batch import (
+ AwsBatchClient,
+ AwsBatchError,
+ AwsBatchResumeConfig,
+ AwsBatchThrottleError,
+ aws_batch_source,
+ error_for_response,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_batch.settings import BATCH_API_VERSION
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_batch.source import AwsBatchSource
+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 SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsbatch import (
+ AwsBatchSourceConfig,
+)
+
+
+def config() -> AwsBatchSourceConfig:
+ return AwsBatchSourceConfig(
+ aws_access_key_id="AKIAEXAMPLE",
+ aws_secret_access_key="example-secret",
+ aws_session_token="example-session",
+ region="eu-west-1",
+ )
+
+
+def manager() -> MagicMock:
+ result = MagicMock(spec=ResumableSourceManager)
+ result.can_resume.return_value = False
+ return result
+
+
+def session() -> Iterator[MagicMock]:
+ with patch.object(transport, "make_tracked_session") as factory:
+ yield factory.return_value
+
+
+def response(payload: Any, status: int = 200, headers: dict[str, str] | None = None) -> requests.Response:
+ result = requests.Response()
+ result.status_code = status
+ result._content = json.dumps(payload).encode()
+ result.headers.update(headers or {})
+ return result
+
+
+def test_source_adapter_delegates_validation_and_manager_creation(config: AwsBatchSourceConfig) -> None:
+ source = AwsBatchSource()
+ inputs = MagicMock(spec=SourceInputs)
+ manager = MagicMock(spec=ResumableSourceManager)
+ with (
+ patch.object(source_module, "validate_credentials", return_value=(True, None)) as validate,
+ patch.object(source_module, "ResumableSourceManager", return_value=manager) as manager_factory,
+ ):
+ assert source.validate_credentials(config, team_id=1, schema_name="jobs") == (True, None)
+ assert source.get_resumable_source_manager(inputs) is manager
+ validate.assert_called_once_with(config, "jobs", BATCH_API_VERSION)
+ manager_factory.assert_called_once_with(inputs, AwsBatchResumeConfig)
+
+
+ "operation,path",
+ [
+ ("ListJobs", "/v1/listjobs"),
+ ("DescribeJobs", "/v1/describejobs"),
+ ("DescribeJobQueues", "/v1/describejobqueues"),
+ ("DescribeComputeEnvironments", "/v1/describecomputeenvironments"),
+ ("DescribeJobDefinitions", "/v1/describejobdefinitions"),
+ ],
+)
+def test_signed_rest_json_request(config: AwsBatchSourceConfig, session: MagicMock, operation: str, path: str) -> None:
+ session.post.return_value = response({"nextToken": "next"})
+ client = AwsBatchClient(config)
+ assert client.request(operation, {"maxResults": 100}) == {"nextToken": "next"}
+ args, kwargs = session.post.call_args
+ assert args == (f"https://batch.eu-west-1.amazonaws.com{path}",)
+ assert json.loads(kwargs["data"]) == {"maxResults": 100}
+ assert kwargs["headers"]["Content-Type"] == "application/json"
+ assert kwargs["headers"]["X-Amz-Security-Token"] == "example-session"
+ assert "/eu-west-1/batch/aws4_request" in kwargs["headers"]["Authorization"]
+ assert "X-Amz-Date" in kwargs["headers"]
+ assert "X-Amz-Target" not in kwargs["headers"]
+ assert client.model.api_version == "2016-08-10"
+ assert kwargs["timeout"] == 60
+ factory = cast(MagicMock, transport.make_tracked_session)
+ assert set(factory.call_args.kwargs["redact_values"]) == {"AKIAEXAMPLE", "example-secret", "example-session"}
+
+
[email protected]("region,suffix", [("cn-north-1", "amazonaws.com.cn"), ("us-gov-west-1", "amazonaws.com")])
+def test_region_selects_endpoint_and_signature(
+ config: AwsBatchSourceConfig, session: MagicMock, region: str, suffix: str
+) -> None:
+ config.region = region
+ config.aws_session_token = None
+ session.post.return_value = response({})
+ AwsBatchClient(config).request("DescribeJobQueues", {"maxResults": 1})
+ args, kwargs = session.post.call_args
+ assert args[0] == f"https://batch.{region}.{suffix}/v1/describejobqueues"
+ assert f"/{region}/batch/aws4_request" in kwargs["headers"]["Authorization"]
+ assert "X-Amz-Security-Token" not in kwargs["headers"]
+
+
[email protected]("region", ["", "https://example.com", "us-east-1.example.com/", "us-east-1@localhost"])
+def test_invalid_region_never_sends_credentials(config: AwsBatchSourceConfig, session: MagicMock, region: str) -> None:
+ config.region = region
+ valid, reason = validate_credentials(config)
+ assert not valid
+ assert reason == "Enter an AWS region, such as us-east-1."
+ session.post.assert_not_called()
+
+
+ "endpoint,result_key,arn_key",
+ [
+ ("job_queues", "jobQueues", "jobQueueArn"),
+ ("compute_environments", "computeEnvironments", "computeEnvironmentArn"),
+ ("job_definitions", "jobDefinitions", "jobDefinitionArn"),
+ ],
+)
[email protected]("terminal_token", [None, ""])
+def test_full_refresh_pages_through_empty_results_and_checkpoints_terminal_page(
+ config: AwsBatchSourceConfig,
+ session: MagicMock,
+ manager: MagicMock,
+ endpoint: str,
+ result_key: str,
+ arn_key: str,
+ terminal_token: str | None,
+) -> None:
+ session.post.side_effect = [
+ response({result_key: [{arn_key: "arn:first"}], "nextToken": "one"}),
+ response({result_key: [], "nextToken": "two"}),
+ response({result_key: [{arn_key: "arn:last"}], "nextToken": terminal_token}),
+ ]
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.schema_name = endpoint
+ inputs.api_version = None
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ result = AwsBatchSource().source_for_pipeline(config, manager, inputs)
+ rows = [row for batch in cast(Iterable[list[dict[str, Any]]], result.items()) for row in batch]
+ assert result.primary_keys is not None
+ assert [row[result.primary_keys[0]] for row in rows] == ["arn:first", "arn:last"]
+ assert all(row["region"] == "eu-west-1" for row in rows)
+ assert [json.loads(call.kwargs["data"]) for call in session.post.call_args_list] == [
+ {"maxResults": 100},
+ {"maxResults": 100, "nextToken": "one"},
+ {"maxResults": 100, "nextToken": "two"},
+ ]
+ assert manager.save_state.call_args.args[0].complete
+ assert manager.safe_point.call_count == 3
+ manager.clear_state.assert_not_called()
+ assert result.on_complete is not None
+ result.on_complete()
+ manager.clear_state.assert_called_once()
+ session.close.assert_called_once()
+
+
+def test_jobs_discover_queues_and_hydrate_all_statuses(
+ config: AwsBatchSourceConfig, session: MagicMock, manager: MagicMock
+) -> None:
+ calls: list[tuple[str, dict[str, Any]]] = []
+
+ def send(url: str, **kwargs: Any) -> requests.Response:
+ payload = json.loads(kwargs["data"])
+ calls.append((url.rsplit("/", 1)[-1], payload))
+ if url.endswith("describejobqueues"):
+ if "nextToken" not in payload:
+ return response({"jobQueues": [], "nextToken": "queues-next"})
+ return response({"jobQueues": [{"jobQueueArn": "arn:queue:one"}, {"jobQueueArn": "arn:queue:two"}]})
+ if url.endswith("listjobs"):
+ assert payload["filters"] == [{"name": "JOB_NAME", "values": ["*"]}]
+ assert "jobStatus" not in payload
+ assert payload["maxResults"] == 100
+ if payload["jobQueue"] == "arn:queue:one" and "nextToken" not in payload:
+ return response({"jobSummaryList": [], "nextToken": "jobs-next"})
+ return response({"jobSummaryList": [{"jobId": payload["jobQueue"] + ":job"}]})
+ return response(
+ {
+ "jobs": [
+ {
+ "jobArn": payload["jobs"][0],
+ "status": "SUCCEEDED",
+ "createdAt": 1735689600000,
+ "startedAt": 0,
+ "stoppedAt": 1735689605000,
+ "attempts": [{"container": {"exitCode": 0}}],
+ }
+ ]
+ }
+ )
+
+ session.post.side_effect = send
+ result = aws_batch_source(config, "jobs", manager)
+ rows = [row for batch in cast(Iterable[list[dict[str, Any]]], result.items()) for row in batch]
+ assert [row["job_arn"] for row in rows] == ["arn:queue:one:job", "arn:queue:two:job"]
+ assert rows[0]["created_at"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ assert rows[0]["started_at"] is None
+ assert rows[0]["stopped_at"] == dt.datetime(2025, 1, 1, 0, 0, 5, tzinfo=dt.UTC)
+ assert rows[0]["attempts"] == [{"container": {"exitCode": 0}}]
+ assert [payload.get("nextToken") for operation, payload in calls if operation == "listjobs"] == [
+ None,
+ "jobs-next",
+ None,
+ ]
+ assert manager.save_state.call_args.args[0].complete
+ assert result.sort_mode is None
+
+
[email protected]("job_count", [0, 100, 101])
+def test_job_descriptions_respect_batch_limit(
+ config: AwsBatchSourceConfig, session: MagicMock, manager: MagicMock, job_count: int
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AwsBatchResumeConfig(queue_arns=["arn:queue"])
+ session.post.side_effect = [
+ response({"jobSummaryList": [{"jobId": f"job-{i}"} for i in range(job_count)]}),
+ *[response({"jobs": []}) for _ in range(0, job_count, 100)],
+ ]
+ assert list(cast(Iterable[Any], aws_batch_source(config, "jobs", manager).items())) == []
+ described = [json.loads(call.kwargs["data"])["jobs"] for call in session.post.call_args_list[1:]]
+ assert all(0 < len(ids) <= 100 for ids in described)
+ assert [job for ids in described for job in ids] == [f"job-{i}" for i in range(job_count)]
+
+
[email protected]("endpoint", ["job_queues", "jobs"])
+def test_resume_continues_the_saved_page_and_parent(
+ config: AwsBatchSourceConfig, session: MagicMock, manager: MagicMock, endpoint: str
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AwsBatchResumeConfig(
+ next_token="saved-page", queue_arns=["arn:completed", "arn:remaining"], queue_index=1
+ )
+ session.post.return_value = response({"jobQueues": [], "jobSummaryList": []})
+ assert list(cast(Iterable[Any], aws_batch_source(config, endpoint, manager).items())) == []
+ assert session.post.call_count == 1
+ payload = json.loads(session.post.call_args.kwargs["data"])
+ assert payload["nextToken"] == "saved-page"
+ if endpoint == "jobs":
+ assert payload["jobQueue"] == "arn:remaining"
+ assert manager.save_state.call_args.args[0].complete
+
+
[email protected]("complete", [False, True])
+def test_empty_queue_catalog_and_completed_resume(
+ config: AwsBatchSourceConfig, session: MagicMock, manager: MagicMock, complete: bool
+) -> None:
+ manager.can_resume.return_value = complete
+ manager.load_state.return_value = AwsBatchResumeConfig(complete=True)
+ session.post.return_value = response({"jobQueues": []})
+ assert list(cast(Iterable[Any], aws_batch_source(config, "jobs", manager).items())) == []
+ assert session.post.call_count == (0 if complete else 1)
+
+
+def test_failed_hydration_does_not_checkpoint_missing_rows(
+ config: AwsBatchSourceConfig, session: MagicMock, manager: MagicMock
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AwsBatchResumeConfig(queue_arns=["arn:queue"])
+ session.post.side_effect = [
+ response({"jobSummaryList": [{"jobId": "job-one"}], "nextToken": "unsafe"}),
+ response({"message": "AccessDeniedException"}, 403, {"x-amzn-ErrorType": "AccessDeniedException"}),
+ ]
+ with pytest.raises(AwsBatchError):
+ list(cast(Iterable[Any], aws_batch_source(config, "jobs", manager).items()))
+ manager.save_state.assert_not_called()
+ session.close.assert_called_once()
+
+
[email protected]("token", ["same", 123])
+def test_invalid_page_token_fails_without_checkpoint(
+ config: AwsBatchSourceConfig, session: MagicMock, manager: MagicMock, token: str | int
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AwsBatchResumeConfig(next_token="same")
+ session.post.return_value = response({"jobQueues": [], "nextToken": token})
+ with pytest.raises(ValueError, match="page token"):
+ list(cast(Iterable[Any], aws_batch_source(config, "job_queues", manager).items()))
+ manager.save_state.assert_not_called()
+
+
+ "status,payload,headers,code,retryable",
+ [
+ (400, {"__type": "com.amazonaws.batch#ThrottlingException"}, {}, "ThrottlingException", True),
+ (429, {"code": "ThrottlingException"}, {}, "ThrottlingException", False),
+ (500, {"message": "Unavailable"}, {}, "HTTP 500", False),
+ (
+ 403,
+ {"Message": "Denied"},
+ {"x-amzn-ErrorType": "AccessDeniedException:detail"},
+ "AccessDeniedException",
+ False,
+ ),
+ (400, {"code": "ClientException", "message": "Invalid input"}, {}, "ClientException", False),
+ (502, ["Unexpected response"], {}, "HTTP 502", False),
+ ],
+)
+def test_error_parsing_and_disjoint_retry_policies(
+ status: int, payload: Any, headers: dict[str, str], code: str, retryable: bool
+) -> None:
+ error = error_for_response(response(payload, status, headers))
+ assert error.code == code
+ assert isinstance(error, AwsBatchThrottleError) == retryable
+ if status in (429, 500, 502):
+ assert transport.TRANSPORT_RETRY.is_retry("POST", status)
+
+
+def test_body_throttle_retries_and_non_json_errors(config: AwsBatchSourceConfig, session: MagicMock) -> None:
+ session.post.side_effect = [response({"code": "ThrottlingException"}, 400), response({"jobQueues": []})]
+ with patch.object(cast(Any, AwsBatchClient.request).retry, "wait", wait_none()):
+ assert AwsBatchClient(config).request("DescribeJobQueues", {"maxResults": 1}) == {"jobQueues": []}
+ assert session.post.call_count == 2
+ invalid = response({}, 503)
+ invalid._content = b"temporarily unavailable"
+ assert error_for_response(invalid).message == "temporarily unavailable"
+
+
[email protected]("schema_name", [None, "jobs", "job_queues", "compute_environments", "job_definitions"])
+ "code,message,reason_fragment,allow_create",
+ [
+ ("AccessDeniedException", "Access denied", "Grant batch:", True),
+ ("ClientException", "User is not authorized to perform: batch:DescribeJobQueues", "Grant batch:", True),
+ (
+ "UnrecognizedClientException",
+ "The security token included in the request is invalid.",
+ "rejected the credentials",
+ False,
+ ),
+ (
+ "InvalidSignatureException",
+ "The request signature we calculated does not match the signature you provided.",
+ "rejected the credentials",
+ False,
+ ),
+ ("ExpiredTokenException", "The security token included in the request is expired", "expired", False),
+ ("SubscriptionRequiredException", "Subscription required", "Enable AWS Batch", False),
+ ("OptInRequired", "Service not enabled", "selected region", False),
+ ("ClientException", "Invalid parameter", "Check the region", False),
+ ],
+)
+def test_credential_error_mapping(
+ config: AwsBatchSourceConfig,
+ session: MagicMock,
+ schema_name: str | None,
+ code: str,
+ message: str,
+ reason_fragment: str,
+ allow_create: bool,
+) -> None:
+ session.post.return_value = response({"__type": code, "message": message}, 400)
+ valid, reason = validate_credentials(config, schema_name)
+ assert valid == (allow_create and schema_name is None)
+ if valid:
+ assert reason is None
+ else:
+ assert reason is not None and reason_fragment in reason
+ session.close.assert_called_once()
+
+
[email protected]("exception", [requests.Timeout(), requests.ConnectionError()])
+def test_connection_error_is_actionable(config: AwsBatchSourceConfig, session: MagicMock, exception: Exception) -> None:
+ session.post.side_effect = exception
+ assert validate_credentials(config) == (False, "Could not reach AWS Batch. Check the region and try again.")
+
+
[email protected]("schema_name", [None, "job_queues", "compute_environments", "job_definitions", "jobs"])
+def test_validation_probes_only_required_operations(
+ config: AwsBatchSourceConfig, session: MagicMock, schema_name: str | None
+) -> None:
+ session.post.side_effect = [
+ response({"jobQueues": [{"jobQueueArn": "arn:queue"}]}),
+ response({"jobSummaryList": [{"jobId": "job-one"}]}),
+ response({"jobs": []}),
+ ]
+ assert validate_credentials(config, schema_name) == (True, None)
+ assert session.post.call_count == (3 if schema_name == "jobs" else 1)
+ assert json.loads(session.post.call_args_list[0].kwargs["data"]) == {"maxResults": 1}
+ if schema_name == "jobs":
+ assert json.loads(session.post.call_args_list[-1].kwargs["data"]) == {"jobs": ["job-one"]}
+
+
[email protected]("field", ["aws_access_key_id", "aws_secret_access_key"])
+def test_missing_credentials_do_not_call_aws(config: AwsBatchSourceConfig, session: MagicMock, field: str) -> None:
+ setattr(config, field, "")
+ assert validate_credentials(config) == (False, "Enter both an AWS access key ID and a secret access key.")
+ session.post.assert_not_called()
+
+
+def test_unknown_endpoint_and_version_fail_before_request(
+ config: AwsBatchSourceConfig, session: MagicMock, manager: MagicMock
+) -> None:
+ with pytest.raises(ValueError, match="Unknown AWS Batch table"):
+ aws_batch_source(config, "unknown", manager)
+ assert validate_credentials(config, "unknown") == (False, "Unknown AWS Batch table: unknown")
+ with pytest.raises(ValueError, match="Unsupported AWS Batch API version"):
+ AwsBatchClient(config, api_version="1900-01-01")
+ session.post.assert_not_called()
+
+
+def test_invalid_success_body_is_not_silently_empty(config: AwsBatchSourceConfig, session: MagicMock) -> None:
+ session.post.return_value = response([])
+ with pytest.raises(ValueError, match="invalid response"):
+ AwsBatchClient(config, BATCH_API_VERSION).request("DescribeJobQueues", {"maxResults": 1})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsbatch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsbatch.py
index a6e851f30777..9f950ba1bb7a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsbatch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsbatch.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AwsBatchSourceConfig(config.Config):
- pass
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ region: str
+ aws_session_token: str | None = None