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 savings plans import source (#110805)

Tom Owers4d63b3c61f84
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 42adb8f2e185..4b717343bce9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -112,6 +112,7 @@ the row lists both.
| aws_inspector | HTTP | requests | ✅ |
| aws_organizations | HTTP | requests | ✅ |
| aws_sagemaker | HTTP | requests | ✅ |
+| aws_savings_plans | HTTP | requests | ✅ |
| aws_security_hub | HTTP | requests | ✅ |
| aws_ses | HTTP | requests | ✅ |
| aws_step_functions | HTTP | requests | ✅ |
@@ -931,7 +932,6 @@ doesn't conflict with concurrent PRs.
- aws_iam_access_analyzer
- aws_macie
- aws_rds_performance_insights
-- aws_savings_plans
- aws_support
- aws_trusted_advisor
- aws_xray
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/aws_savings_plans.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/aws_savings_plans.py
new file mode 100644
index 000000000000..2dc2a3231f43
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/aws_savings_plans.py
@@ -0,0 +1,287 @@
+import re
+import json
+import datetime as dt
+from collections.abc import Iterator
+from decimal import Decimal
+from typing import Any
+
+import requests
+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_savings_plans.settings import (
+ COST_EXPLORER_API_VERSION,
+ DEFAULT_LOOKBACK_DAYS,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ RESTATEMENT_DAYS,
+ SAVINGS_PLANS_API_VERSION,
+ SIGNING_REGION,
+ SavingsPlansEndpoint,
+)
+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.awssavingsplans import (
+ AwsSavingsPlansSourceConfig,
+)
+
+TRANSPORT_RETRY = BoundedRetry(
+ total=3,
+ backoff_factor=1,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset(["POST"]),
+ raise_on_status=False,
+)
+THROTTLE_CODES = {"ThrottlingException", "TooManyRequestsException", "LimitExceededException", "RequestLimitExceeded"}
+CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+
+
+@frozen
+class AwsSavingsPlansResumeConfig:
+ next_token: str | None = None
+ window_start: str | None = None
+ window_end: str | None = None
+ end_date: str | None = None
+ completed: bool = False
+
+
+class AwsSavingsPlansError(Exception):
+ def __init__(self, code: str) -> None:
+ self.code = code
+ super().__init__(f"AWS Savings Plans request failed: {code}")
+
+
+class AwsSavingsPlansThrottledError(AwsSavingsPlansError):
+ pass
+
+
+class AwsSavingsPlansClient:
+ def __init__(self, config: AwsSavingsPlansSourceConfig, api_version: str) -> None:
+ if api_version != SAVINGS_PLANS_API_VERSION:
+ raise ValueError(f"Unsupported AWS Savings Plans API version: {api_version}")
+ self.credentials = Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token)
+ 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(AwsSavingsPlansThrottledError),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ stop=stop_after_attempt(5),
+ reraise=True,
+ )
+ def request(self, endpoint: SavingsPlansEndpoint, payload: dict[str, Any]) -> dict[str, Any]:
+ if endpoint.service == "savingsplans":
+ url = f"https://savingsplans.amazonaws.com/{endpoint.operation}"
+ headers = {"Content-Type": "application/json", "X-Amz-Api-Version": SAVINGS_PLANS_API_VERSION}
+ else:
+ url = "https://ce.us-east-1.amazonaws.com/"
+ headers = {
+ "Content-Type": "application/x-amz-json-1.1",
+ "X-Amz-Target": f"AWSInsightsIndexService.{endpoint.operation}",
+ "X-Amz-Api-Version": COST_EXPLORER_API_VERSION,
+ }
+ body = json.dumps(payload).encode()
+ request = AWSRequest(method="POST", url=url, data=body, headers=headers)
+ SigV4Auth(self.credentials, endpoint.service, SIGNING_REGION).add_auth(request)
+ response = self.session.post(url, data=body, headers=dict(request.headers), timeout=60)
+ if response.status_code >= 400:
+ try:
+ error = response.json()
+ except ValueError:
+ error = {}
+ if not isinstance(error, dict):
+ error = {}
+ raw_code = response.headers.get("x-amzn-ErrorType") or error.get("__type") or error.get("code")
+ code = str(raw_code or f"HTTP {response.status_code}").split(":")[0].rsplit("#", 1)[-1]
+ if response.status_code == 400 and code in THROTTLE_CODES:
+ raise AwsSavingsPlansThrottledError(code)
+ raise AwsSavingsPlansError(code)
+ return response.json()
+
+ def close(self) -> None:
+ self.session.close()
+
+
+def parse_date(value: Any) -> dt.date | None:
+ if value is None or value == "":
+ return None
+ if isinstance(value, dt.datetime):
+ return value.date()
+ if isinstance(value, dt.date):
+ return value
+ return dt.datetime.fromisoformat(str(value).replace("Z", "+00:00")).date()
+
+
+def build_payload(
+ endpoint: SavingsPlansEndpoint, start: dt.date | None = None, end: dt.date | None = None
+) -> dict[str, Any]:
+ if endpoint.service == "savingsplans":
+ return {"maxResults": 100}
+ if start is None or end is None:
+ raise ValueError("Cost Explorer requires a start date and an end date")
+ payload: dict[str, Any] = {"TimePeriod": {"Start": start.isoformat(), "End": end.isoformat()}}
+ if endpoint.granularity:
+ payload["Granularity"] = endpoint.granularity
+ if endpoint.token_key:
+ payload["MaxResults"] = 100
+ if endpoint.operation == "GetSavingsPlansUtilizationDetails":
+ payload["DataType"] = ["ATTRIBUTES", "UTILIZATION", "AMORTIZED_COMMITMENT", "SAVINGS"]
+ return payload
+
+
+def normalize_rows(endpoint: SavingsPlansEndpoint, body: dict[str, Any]) -> list[dict[str, Any]]:
+ rows = []
+ for item in body.get(endpoint.result_key, []):
+ row = {CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in item.items()}
+ if endpoint.service == "savingsplans":
+ for field in ("start", "end", "returnable_until"):
+ if row.get(field):
+ row[field] = dt.datetime.fromisoformat(row[field].replace("Z", "+00:00"))
+ for field in ("commitment", "recurring_payment_amount", "upfront_payment_amount"):
+ if row.get(field) is not None:
+ row[field] = Decimal(row[field])
+ else:
+ period = row.pop("time_period", body.get("TimePeriod"))
+ if not period:
+ raise ValueError("AWS returned metrics without a time period")
+ row["period_start"] = dt.datetime.fromisoformat(period["Start"]).replace(tzinfo=dt.UTC)
+ row["period_end"] = dt.datetime.fromisoformat(period["End"]).replace(tzinfo=dt.UTC)
+ for field in ("utilization", "savings", "amortized_commitment", "coverage"):
+ for key, value in row.pop(field, {}).items():
+ row[f"{field}_{CAMEL_BOUNDARY.sub('_', key).lower()}"] = (
+ Decimal(value) if value not in (None, "") else None
+ )
+ rows.append(row)
+ return rows
+
+
+def validation_error(code: str, endpoint: SavingsPlansEndpoint) -> str:
+ if code.startswith("AccessDenied") or code == "UnauthorizedException":
+ return f"AWS denied access. Grant {endpoint.service}:{endpoint.operation} to the IAM user or role."
+ for pattern, message in ERROR_MESSAGES.items():
+ if pattern in code:
+ return message
+ return "AWS could not complete the request. Check the credentials and try again."
+
+
+def validate_credentials(
+ config: AwsSavingsPlansSourceConfig,
+ schema_name: str | None = None,
+ api_version: str = SAVINGS_PLANS_API_VERSION,
+) -> tuple[bool, str | None]:
+ if not config.aws_access_key_id or not config.aws_secret_access_key:
+ return False, "Enter an AWS access key ID and secret access key."
+ endpoint = ENDPOINTS.get(schema_name or "savings_plans")
+ if endpoint is None:
+ return False, "Unknown AWS Savings Plans table."
+ try:
+ parse_date(config.start_date)
+ except ValueError:
+ return False, "Enter the start date as YYYY-MM-DD."
+ client = AwsSavingsPlansClient(config, api_version)
+ try:
+ end = dt.datetime.now(dt.UTC).date() - dt.timedelta(days=1)
+ payload = build_payload(endpoint, end - dt.timedelta(days=1), end)
+ if endpoint.token_key:
+ payload["maxResults" if endpoint.service == "savingsplans" else "MaxResults"] = 1
+ client.request(endpoint, payload)
+ except AwsSavingsPlansError as error:
+ if schema_name is None and (error.code.startswith("AccessDenied") or error.code == "UnauthorizedException"):
+ return True, None
+ return False, validation_error(error.code, endpoint)
+ except requests.RequestException:
+ return False, "Could not reach AWS. Try again later."
+ finally:
+ client.close()
+ return True, None
+
+
+def get_rows(
+ config: AwsSavingsPlansSourceConfig,
+ endpoint: SavingsPlansEndpoint,
+ manager: ResumableSourceManager[AwsSavingsPlansResumeConfig],
+ incremental: bool,
+ last_value: Any,
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ resume = manager.load_state() if manager.can_resume() else None
+ if resume and resume.completed:
+ return
+ # Freeze request windows across retries because AWS tokens depend on the original parameters.
+ end = parse_date(resume.end_date) if resume else None
+ end = end or (dt.datetime.now(dt.UTC).date() - dt.timedelta(days=1))
+ history_floor = end - dt.timedelta(days=DEFAULT_LOOKBACK_DAYS)
+ floor = max(parse_date(config.start_date) or history_floor, history_floor)
+ watermark = parse_date(last_value) if incremental and endpoint.service == "ce" else None
+ start = max(floor, watermark - dt.timedelta(days=RESTATEMENT_DAYS)) if watermark else floor
+ start = (parse_date(resume.window_start) or start) if resume else start
+ stop = (parse_date(resume.window_end) if resume else None) or min(
+ start + dt.timedelta(days=endpoint.window_days), end
+ )
+ token = resume.next_token if resume else None
+ client = AwsSavingsPlansClient(config, api_version)
+ try:
+ while endpoint.service == "savingsplans" or start < end:
+ payload = build_payload(endpoint, start, stop)
+ if token and endpoint.token_key:
+ payload[endpoint.token_key] = token
+ body = client.request(endpoint, payload)
+ rows = normalize_rows(endpoint, body)
+ next_token = body.get(endpoint.token_key) if endpoint.token_key else None
+ if next_token and next_token == token:
+ raise ValueError("AWS returned a repeated pagination token")
+ completed = not next_token and (endpoint.service == "savingsplans" or stop >= end)
+ next_start = start if next_token else stop
+ next_stop = stop if next_token else min(stop + dt.timedelta(days=endpoint.window_days), end)
+ manager.save_state(
+ AwsSavingsPlansResumeConfig(
+ next_token=next_token,
+ window_start=next_start.isoformat(),
+ window_end=next_stop.isoformat(),
+ end_date=end.isoformat(),
+ completed=completed,
+ )
+ )
+ if rows:
+ yield rows
+ manager.safe_point()
+ if completed:
+ break
+ start, stop, token = next_start, next_stop, next_token
+ finally:
+ client.close()
+
+
+def aws_savings_plans_source(
+ config: AwsSavingsPlansSourceConfig,
+ endpoint_name: str,
+ manager: ResumableSourceManager[AwsSavingsPlansResumeConfig],
+ incremental: bool,
+ last_value: Any,
+ api_version: str,
+) -> SourceResponse:
+ endpoint = ENDPOINTS[endpoint_name]
+ metrics = endpoint.service == "ce"
+ return SourceResponse(
+ name=endpoint_name,
+ items=lambda: get_rows(config, endpoint, manager, incremental, last_value, api_version),
+ primary_keys=list(endpoint.primary_keys),
+ partition_keys=["period_start"] if metrics else None,
+ partition_mode="datetime" if metrics else None,
+ partition_format="month" if metrics else None,
+ # "desc" saves the watermark once at job end, so unordered rows cannot strand older ones.
+ sort_mode="desc",
+ on_complete=manager.clear_state,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/canonical_descriptions.py
new file mode 100644
index 000000000000..22f9c7cafd77
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/canonical_descriptions.py
@@ -0,0 +1,62 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "savings_plans": {
+ "description": "Purchased Savings Plans with their commitment, payment option, term, and state.",
+ "docs_url": "https://docs.aws.amazon.com/savingsplans/latest/APIReference/API_SavingsPlan.html",
+ "columns": {
+ "savings_plan_arn": "Amazon Resource Name that identifies the Savings Plan.",
+ "savings_plan_id": "Identifier of the Savings Plan.",
+ "commitment": "Hourly commitment for the Savings Plan.",
+ "currency": "Currency for the Savings Plan.",
+ "start": "Start time of the Savings Plan.",
+ "end": "End time of the Savings Plan.",
+ "state": "Current state of the Savings Plan.",
+ "payment_option": "Payment option for the Savings Plan.",
+ "term_duration_in_seconds": "Plan duration in seconds.",
+ "tags": "Tags attached to the Savings Plan.",
+ },
+ },
+ "utilization_daily": {
+ "description": "Daily use of Savings Plans commitments and the resulting savings.",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansUtilization.html",
+ "columns": {
+ "period_start": "Inclusive start of the reporting period in UTC.",
+ "period_end": "Exclusive end of the reporting period in UTC.",
+ "utilization_total_commitment": "Total commitment during the period.",
+ "utilization_used_commitment": "Commitment used during the period.",
+ "utilization_unused_commitment": "Commitment that was not used during the period.",
+ "utilization_utilization_percentage": "Percentage of the commitment used during the period.",
+ "savings_net_savings": "Net savings compared with on-demand pricing.",
+ "savings_on_demand_cost_equivalent": "Equivalent cost at on-demand prices.",
+ },
+ },
+ "utilization_details_daily": {
+ "description": "Daily use, savings, and attributes for each Savings Plan.",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansUtilizationDetails.html",
+ "columns": {
+ "savings_plan_arn": "Amazon Resource Name that identifies the Savings Plan.",
+ "period_start": "Inclusive start of the reporting period in UTC.",
+ "period_end": "Exclusive end of the reporting period in UTC.",
+ "attributes": "Attributes associated with the Savings Plan.",
+ "utilization_total_commitment": "Total commitment during the period.",
+ "utilization_used_commitment": "Commitment used during the period.",
+ "utilization_unused_commitment": "Commitment that was not used during the period.",
+ "savings_net_savings": "Net savings compared with on-demand pricing.",
+ },
+ },
+ "coverage_daily": {
+ "description": "Daily spend covered by Savings Plans and the remaining on-demand cost.",
+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansCoverage.html",
+ "columns": {
+ "period_start": "Inclusive start of the reporting period in UTC.",
+ "period_end": "Exclusive end of the reporting period in UTC.",
+ "coverage_coverage_percentage": "Percentage of eligible spend covered by Savings Plans.",
+ "coverage_spend_covered_by_savings_plans": "Spend covered by Savings Plans.",
+ "coverage_on_demand_cost": "Eligible spend that Savings Plans did not cover.",
+ "coverage_total_cost": "Total eligible spend during the period.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/settings.py
new file mode 100644
index 000000000000..3c8fce509fc9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/settings.py
@@ -0,0 +1,79 @@
+from typing import Literal
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+SAVINGS_PLANS_API_VERSION = "2019-06-28"
+COST_EXPLORER_API_VERSION = "2017-10-25"
+SIGNING_REGION = "us-east-1"
+DEFAULT_LOOKBACK_DAYS = 365
+RESTATEMENT_DAYS = 7
+
+
+@frozen
+class SavingsPlansEndpoint:
+ operation: str
+ result_key: str
+ primary_keys: tuple[str, ...]
+ service: Literal["savingsplans", "ce"] = "ce"
+ token_key: str | None = "NextToken"
+ window_days: int = 92
+ granularity: str | None = "DAILY"
+
+
+ENDPOINTS: dict[str, SavingsPlansEndpoint] = {
+ "savings_plans": SavingsPlansEndpoint(
+ operation="DescribeSavingsPlans",
+ result_key="savingsPlans",
+ primary_keys=("savings_plan_arn",),
+ service="savingsplans",
+ token_key="nextToken",
+ granularity=None,
+ ),
+ "utilization_daily": SavingsPlansEndpoint(
+ operation="GetSavingsPlansUtilization",
+ result_key="SavingsPlansUtilizationsByTime",
+ primary_keys=("period_start",),
+ token_key=None,
+ ),
+ "utilization_details_daily": SavingsPlansEndpoint(
+ operation="GetSavingsPlansUtilizationDetails",
+ result_key="SavingsPlansUtilizationDetails",
+ primary_keys=("savings_plan_arn", "period_start"),
+ window_days=1,
+ granularity=None,
+ ),
+ "coverage_daily": SavingsPlansEndpoint(
+ operation="GetSavingsPlansCoverage",
+ result_key="SavingsPlansCoverages",
+ primary_keys=("period_start",),
+ ),
+}
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [incremental_field("period_start")] for name, endpoint in ENDPOINTS.items() if endpoint.service == "ce"
+}
+
+ENDPOINT_DESCRIPTIONS = {
+ "savings_plans": "Savings Plans with their commitment, term, state, and payment details.",
+ "utilization_daily": "Daily commitment use and savings across Savings Plans.",
+ "utilization_details_daily": "Daily commitment use and savings for each Savings Plan.",
+ "coverage_daily": "Daily spend covered by Savings Plans and remaining on-demand spend.",
+}
+
+ERROR_MESSAGES = {
+ "AccessDenied": "AWS denied access. Grant the IAM read permission for the selected table.",
+ "UnauthorizedException": "AWS denied access. Grant the IAM read permission for the selected table.",
+ "UnrecognizedClientException": "AWS rejected the credentials. Check the access key ID and secret access key.",
+ "InvalidClientTokenId": "AWS rejected the credentials. Check the access key ID and session token.",
+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and session token.",
+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key.",
+ "ExpiredToken": "The AWS session token expired. Connect again with valid credentials.",
+ "SubscriptionRequired": "Enable Cost Explorer in your AWS account, then try again.",
+ "OptInRequired": "Enable Cost Explorer in your AWS account, then try again.",
+ "DataUnavailableException": "AWS has no data for these dates. Enable Cost Explorer or select a later start date.",
+ "BillExpirationException": "AWS no longer keeps data for these dates. Select a later start date.",
+ "ValidationException": "AWS rejected the request. Check the source settings and try again.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/source.py
index 4ebf8dadf800..c6fdb177c333 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/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_savings_plans.aws_savings_plans import (
+ AwsSavingsPlansResumeConfig,
+ aws_savings_plans_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_savings_plans.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_savings_plans.settings import (
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ INCREMENTAL_FIELDS,
+ SAVINGS_PLANS_API_VERSION,
+)
+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.awssavingsplans import (
AwsSavingsPlansSourceConfig,
)
@@ -10,18 +40,119 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AwsSavingsPlansSource(SimpleSource[AwsSavingsPlansSourceConfig]):
+class AwsSavingsPlansSource(ResumableSource[AwsSavingsPlansSourceConfig, AwsSavingsPlansResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (SAVINGS_PLANS_API_VERSION,)
+ default_version = SAVINGS_PLANS_API_VERSION
+ api_docs_url = "https://docs.aws.amazon.com/savingsplans/latest/APIReference/Welcome.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AWSSAVINGSPLANS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {f"AWS Savings Plans request failed: {code}": message for code, message in ERROR_MESSAGES.items()}
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AwsSavingsPlansSourceConfig,
+ 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, merge_only=INCREMENTAL_FIELDS
+ )
+
+ def validate_credentials(
+ self,
+ config: AwsSavingsPlansSourceConfig,
+ 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[AwsSavingsPlansResumeConfig]:
+ return ResumableSourceManager(inputs, AwsSavingsPlansResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AwsSavingsPlansSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AwsSavingsPlansResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aws_savings_plans_source(
+ config,
+ inputs.schema_name,
+ resumable_source_manager,
+ inputs.should_use_incremental_field,
+ inputs.db_incremental_field_last_value,
+ self.resolve_api_version(inputs.api_version),
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
- name=ExternalDataSourceType.AWSSAVINGSPLANS,
+ name=self.source_type,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
- label="Amazon Web Services (AWS Savings Plans / Cost Explorer)",
+ label="AWS Savings Plans",
+ caption=(
+ "Sync Savings Plans, commitment use, and coverage into the PostHog Data warehouse. "
+ "Grant `savingsplans:DescribeSavingsPlans` for plan inventory. "
+ "Grant `ce:GetSavingsPlansUtilization` for daily utilization. "
+ "Grant `ce:GetSavingsPlansUtilizationDetails` for utilization details. "
+ "Grant `ce:GetSavingsPlansCoverage` for daily coverage. "
+ "Enable Cost Explorer for the metric tables. AWS charges for Cost Explorer requests. "
+ "Daily utilization details require at least one request per day. "
+ "This source uses the global endpoints in the standard AWS partition. "
+ "Metric imports cover up to 365 days and read the previous seven days again during incremental syncs."
+ ),
iconPath="/static/services/aws_savings_plans.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl=self.api_docs_url,
+ 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 for temporary credentials",
+ secret=True,
+ caption="Temporary credentials expire. Connect again with valid credentials when they expire.",
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="YYYY-MM-DD",
+ secret=False,
+ caption="Optional. Imports up to 365 days of metrics when empty. AWS requires the end date before today.",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans.py
new file mode 100644
index 000000000000..8a45ee52a3bf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans.py
@@ -0,0 +1,360 @@
+import json
+import datetime as dt
+from collections.abc import Iterable
+from decimal import Decimal
+from typing import Any, cast
+
+import pytest
+import time_machine
+from unittest.mock import MagicMock, patch
+
+import requests
+from botocore.session import get_session
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_savings_plans.aws_savings_plans import (
+ AwsSavingsPlansClient,
+ AwsSavingsPlansError,
+ AwsSavingsPlansResumeConfig,
+ AwsSavingsPlansThrottledError,
+ aws_savings_plans_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_savings_plans.settings import (
+ ENDPOINTS,
+ SAVINGS_PLANS_API_VERSION,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awssavingsplans import (
+ AwsSavingsPlansSourceConfig,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.aws_savings_plans.aws_savings_plans"
+
+
+def config(start_date: str | None = "2025-01-01") -> AwsSavingsPlansSourceConfig:
+ return AwsSavingsPlansSourceConfig(
+ aws_access_key_id="AKIAEXAMPLE",
+ aws_secret_access_key="example-secret",
+ aws_session_token="example-session",
+ start_date=start_date,
+ )
+
+
+def response(body: Any, status: int = 200, 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 transport():
+ with patch(f"{MODULE}.make_tracked_session") as factory:
+ factory.return_value.post.return_value = response({})
+ yield factory
+
+
+def manager() -> MagicMock:
+ result = MagicMock(spec=ResumableSourceManager)
+ result.can_resume.return_value = False
+ return result
+
+
[email protected](autouse=True)
+def frozen_time():
+ with time_machine.travel("2025-01-12T12:00:00Z", tick=False):
+ yield
+
+
+def run_source(
+ manager: MagicMock,
+ name: str,
+ incremental: bool = False,
+ last_value: Any = None,
+ start_date: str | None = "2025-01-01",
+) -> list[dict[str, Any]]:
+ source = aws_savings_plans_source(
+ config(start_date), name, manager, incremental, last_value, SAVINGS_PLANS_API_VERSION
+ )
+ return [row for batch in cast(Iterable[Any], source.items()) for row in batch]
+
+
[email protected]("name", list(ENDPOINTS))
+def test_signed_protocol_and_payload_match_service_model(transport: MagicMock, manager: MagicMock, name: str) -> None:
+ run_source(manager, name, start_date="2025-01-10")
+ call = transport.return_value.post.call_args
+ headers = call.kwargs["headers"]
+ payload = json.loads(call.kwargs["data"])
+ endpoint = ENDPOINTS[name]
+ model = get_session().get_service_model(endpoint.service)
+ operation = model.operation_model(endpoint.operation)
+ assert operation.input_shape is not None
+ assert set(payload).issubset(operation.input_shape.members)
+ assert headers["X-Amz-Api-Version"] == model.api_version
+ assert f"/us-east-1/{endpoint.service}/aws4_request" in headers["Authorization"]
+ assert headers["X-Amz-Security-Token"] == "example-session"
+ assert headers["X-Amz-Date"]
+ assert call.kwargs["timeout"] == 60
+ if endpoint.service == "savingsplans":
+ assert call.args[0] == "https://savingsplans.amazonaws.com/DescribeSavingsPlans"
+ assert headers["Content-Type"] == "application/json"
+ assert "X-Amz-Target" not in headers
+ assert payload == {"maxResults": 100}
+ else:
+ assert call.args[0] == "https://ce.us-east-1.amazonaws.com/"
+ assert headers["Content-Type"] == "application/x-amz-json-1.1"
+ assert headers["X-Amz-Target"] == f"AWSInsightsIndexService.{endpoint.operation}"
+ assert payload["TimePeriod"] == {"Start": "2025-01-10", "End": "2025-01-11"}
+ if name == "utilization_details_daily":
+ assert "Granularity" not in payload
+ assert payload["DataType"] == ["ATTRIBUTES", "UTILIZATION", "AMORTIZED_COMMITMENT", "SAVINGS"]
+ else:
+ assert payload["Granularity"] == "DAILY"
+ assert set(transport.call_args.kwargs["redact_values"]) == {"AKIAEXAMPLE", "example-secret", "example-session"}
+ transport.return_value.close.assert_called_once()
+
+
+ "name,key,token",
+ [
+ ("savings_plans", "savingsPlans", "nextToken"),
+ ("coverage_daily", "SavingsPlansCoverages", "NextToken"),
+ ("utilization_details_daily", "SavingsPlansUtilizationDetails", "NextToken"),
+ ],
+)
[email protected]("terminal", [None, ""])
+def test_pagination_continues_after_empty_page(
+ transport: MagicMock, manager: MagicMock, name: str, key: str, token: str, terminal: str | None
+) -> None:
+ item = (
+ {"savingsPlanArn": "arn:aws:savingsplans::123456789012:savingsplan/example"}
+ if name == "savings_plans"
+ else {"TimePeriod": {"Start": "2025-01-10", "End": "2025-01-11"}}
+ )
+ transport.return_value.post.side_effect = [
+ response({key: [], token: "next"}),
+ response({key: [item], token: terminal}),
+ ]
+ rows = run_source(manager, name, start_date="2025-01-10")
+ assert len(rows) == 1
+ calls = transport.return_value.post.call_args_list
+ first, second = [json.loads(call.kwargs["data"]) for call in calls]
+ assert token not in first
+ assert second == {**first, token: "next"}
+ assert manager.save_state.call_args.args[0].completed
+ manager.clear_state.assert_not_called()
+ assert manager.safe_point.call_count == 2
+
+
+ "incremental,last_value,expected",
+ [
+ (False, "2025-01-10", "2025-01-01"),
+ (True, None, "2025-01-01"),
+ (True, "2025-01-10T00:00:00Z", "2025-01-03"),
+ (True, dt.datetime(2025, 1, 5, tzinfo=dt.UTC), "2025-01-01"),
+ ],
+)
+def test_time_filter_and_restatement(
+ transport: MagicMock, manager: MagicMock, incremental: bool, last_value: Any, expected: str
+) -> None:
+ run_source(manager, "coverage_daily", incremental, last_value)
+ payload = json.loads(transport.return_value.post.call_args.kwargs["data"])
+ assert payload["TimePeriod"] == {"Start": expected, "End": "2025-01-11"}
+ assert "GroupBy" not in payload
+
+
+def test_details_use_daily_windows_and_preserve_attributes(transport: MagicMock, manager: MagicMock) -> None:
+ def answer(url: str, *, data: bytes, **kwargs: Any) -> requests.Response:
+ payload = json.loads(data)
+ return response(
+ {
+ "TimePeriod": payload["TimePeriod"],
+ "SavingsPlansUtilizationDetails": [
+ {
+ "SavingsPlanArn": "arn:aws:savingsplans::123456789012:savingsplan/example",
+ "Attributes": {"AccountId": "001234567890"},
+ "Utilization": {"TotalCommitment": "1.234567890123456789"},
+ "Savings": {"NetSavings": ""},
+ }
+ ],
+ }
+ )
+
+ transport.return_value.post.side_effect = answer
+ rows = run_source(manager, "utilization_details_daily", start_date="2025-01-09")
+ assert [row["period_start"] for row in rows] == [dt.datetime(2025, 1, day, tzinfo=dt.UTC) for day in (9, 10)]
+ assert rows[0]["attributes"] == {"AccountId": "001234567890"}
+ assert rows[0]["utilization_total_commitment"] == Decimal("1.234567890123456789")
+ assert rows[0]["savings_net_savings"] is None
+ assert rows[0]["savings_plan_arn"] == rows[1]["savings_plan_arn"]
+
+
+def test_plan_inventory_ignores_incremental_cursor(transport: MagicMock, manager: MagicMock) -> None:
+ transport.return_value.post.return_value = response(
+ {
+ "savingsPlans": [
+ {
+ "savingsPlanArn": "arn:aws:savingsplans::123456789012:savingsplan/example",
+ "start": "2025-01-01T00:00:00Z",
+ "commitment": "0.1234567890123456789",
+ "tags": {"account": "001"},
+ }
+ ]
+ }
+ )
+ rows = run_source(manager, "savings_plans", True, "invalid")
+ assert json.loads(transport.return_value.post.call_args.kwargs["data"]) == {"maxResults": 100}
+ assert rows[0]["start"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ assert rows[0]["commitment"] == Decimal("0.1234567890123456789")
+ assert rows[0]["tags"] == {"account": "001"}
+
+
+def test_resume_keeps_original_window_and_stages_before_yield(transport: MagicMock, manager: MagicMock) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AwsSavingsPlansResumeConfig(
+ next_token="resume",
+ window_start="2025-01-02",
+ window_end="2025-01-03",
+ end_date="2025-01-03",
+ )
+ transport.return_value.post.return_value = response(
+ {"SavingsPlansCoverages": [{"TimePeriod": {"Start": "2025-01-02", "End": "2025-01-03"}}]}
+ )
+ source = aws_savings_plans_source(
+ config(), "coverage_daily", manager, True, "2025-01-10", SAVINGS_PLANS_API_VERSION
+ )
+ iterator = iter(cast(Iterable[Any], source.items()))
+ next(iterator)
+ assert json.loads(transport.return_value.post.call_args.kwargs["data"]) == {
+ "TimePeriod": {"Start": "2025-01-02", "End": "2025-01-03"},
+ "MaxResults": 100,
+ "Granularity": "DAILY",
+ "NextToken": "resume",
+ }
+ assert manager.save_state.call_args.args[0].completed
+ assert list(iterator) == []
+ manager.clear_state.assert_not_called()
+ assert source.on_complete is not None
+ source.on_complete()
+ manager.clear_state.assert_called_once()
+
+
[email protected]("completed,start_date", [(True, "2025-01-01"), (False, "2025-01-12")])
+def test_completed_or_future_window_makes_no_requests(
+ transport: MagicMock, manager: MagicMock, completed: bool, start_date: str
+) -> None:
+ if completed:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AwsSavingsPlansResumeConfig(completed=True)
+ assert run_source(manager, "coverage_daily", start_date=start_date) == []
+ transport.return_value.post.assert_not_called()
+
+
+def test_repeated_token_fails_instead_of_looping(transport: MagicMock, manager: MagicMock) -> None:
+ transport.return_value.post.return_value = response({"savingsPlans": [], "nextToken": "same"})
+ with pytest.raises(ValueError, match="repeated pagination token"):
+ run_source(manager, "savings_plans")
+ assert transport.return_value.post.call_count == 2
+ transport.return_value.close.assert_called_once()
+
+
+ "body,headers,status,code,error_type",
+ [
+ (
+ {"__type": "vendor#AccessDeniedException", "message": "private detail"},
+ {},
+ 400,
+ "AccessDeniedException",
+ AwsSavingsPlansError,
+ ),
+ (
+ {},
+ {"x-amzn-ErrorType": "InvalidSignatureException:detail"},
+ 403,
+ "InvalidSignatureException",
+ AwsSavingsPlansError,
+ ),
+ ({"code": "UnrecognizedClientException"}, {}, 400, "UnrecognizedClientException", AwsSavingsPlansError),
+ ([], {}, 502, "HTTP 502", AwsSavingsPlansError),
+ ({"__type": "LimitExceededException"}, {}, 400, "LimitExceededException", AwsSavingsPlansThrottledError),
+ ({"__type": "LimitExceededException"}, {}, 429, "LimitExceededException", AwsSavingsPlansError),
+ ],
+)
+def test_error_parsing_and_no_duplicate_status_retry(
+ transport: MagicMock, body: Any, headers: dict[str, str], status: int, code: str, error_type: type[Exception]
+) -> None:
+ transport.return_value.post.return_value = response(body, status, headers)
+ client = AwsSavingsPlansClient(config(), SAVINGS_PLANS_API_VERSION)
+ with pytest.raises(error_type) as error:
+ cast(Any, AwsSavingsPlansClient.request).__wrapped__(client, ENDPOINTS["savings_plans"], {})
+ assert type(error.value) is error_type
+ assert str(error.value) == f"AWS Savings Plans request failed: {code}"
+ assert transport.return_value.post.call_count == 1
+
+
+ "code,schema,valid,message",
+ [
+ ("AccessDeniedException", None, True, None),
+ ("AccessDeniedException", "coverage_daily", False, "ce:GetSavingsPlansCoverage"),
+ ("UnauthorizedException", None, True, None),
+ ("UnauthorizedException", "savings_plans", False, "savingsplans:DescribeSavingsPlans"),
+ ("InvalidSignatureException", None, False, "signature"),
+ ("UnrecognizedClientException", None, False, "credentials"),
+ ("ExpiredTokenException", None, False, "expired"),
+ ("SubscriptionRequiredException", None, False, "Enable Cost Explorer"),
+ ("DataUnavailableException", "utilization_daily", False, "no data"),
+ ],
+)
+def test_credential_errors(
+ transport: MagicMock, code: str, schema: str | None, valid: bool, message: str | None
+) -> None:
+ transport.return_value.post.return_value = response({"__type": code, "message": "private IAM ARN"}, 400)
+ result, reason = validate_credentials(config(), schema)
+ assert result is valid
+ assert reason is None if message is None else message in (reason or "")
+ assert "private" not in (reason or "")
+ assert transport.return_value.post.call_count == 1
+ transport.return_value.close.assert_called_once()
+
+
[email protected]("schema,key", [(None, "maxResults"), ("coverage_daily", "MaxResults")])
+def test_validation_probe_is_one_small_request(transport: MagicMock, schema: str | None, key: str) -> None:
+ assert validate_credentials(config(), schema) == (True, None)
+ assert transport.return_value.post.call_count == 1
+ assert json.loads(transport.return_value.post.call_args.kwargs["data"])[key] == 1
+
+
[email protected]("start_date", [None, "2020-01-01"])
+def test_history_is_bounded(transport: MagicMock, manager: MagicMock, start_date: str | None) -> None:
+ run_source(manager, "utilization_daily", start_date=start_date)
+ calls = [json.loads(call.kwargs["data"]) for call in transport.return_value.post.call_args_list]
+ assert calls[0]["TimePeriod"]["Start"] == "2024-01-12"
+ assert calls[-1]["TimePeriod"]["End"] == "2025-01-11"
+ assert all(first["TimePeriod"]["End"] == second["TimePeriod"]["Start"] for first, second in zip(calls, calls[1:]))
+
+
+ "start_date,schema,expected",
+ [
+ ("invalid", None, "YYYY-MM-DD"),
+ ("2025-01-01", "unknown", "Unknown"),
+ ],
+)
+def test_invalid_configuration_makes_no_requests(
+ transport: MagicMock, start_date: str, schema: str | None, expected: str
+) -> None:
+ valid, message = validate_credentials(config(start_date), schema)
+ assert not valid
+ assert expected in (message or "")
+ transport.return_value.post.assert_not_called()
+
+
+def test_network_failure_closes_session(transport: MagicMock) -> None:
+ transport.return_value.post.side_effect = requests.Timeout("private connection detail")
+ assert validate_credentials(config()) == (False, "Could not reach AWS. Try again later.")
+ transport.return_value.close.assert_called_once()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans_source.py
new file mode 100644
index 000000000000..206328d26179
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_savings_plans/tests/test_aws_savings_plans_source.py
@@ -0,0 +1,85 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+import time_machine
+from unittest.mock import MagicMock, patch
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_savings_plans.source import (
+ AwsSavingsPlansSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+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.awssavingsplans import (
+ AwsSavingsPlansSourceConfig,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.aws_savings_plans.aws_savings_plans"
+
+
[email protected]("name,incremental", [("savings_plans", False), ("coverage_daily", True), ("missing", None)])
+def test_schema_filter_keeps_sync_capabilities(name: str, incremental: bool | None) -> None:
+ config = AwsSavingsPlansSourceConfig(aws_access_key_id="", aws_secret_access_key="")
+ schemas = AwsSavingsPlansSource().get_schemas(config, 1, names=[name])
+ if incremental is None:
+ assert schemas == []
+ else:
+ assert len(schemas) == 1
+ assert schemas[0].name == name
+ assert schemas[0].supports_incremental is incremental
+ assert not schemas[0].supports_append
+
+
+ "name,incremental,start,partition",
+ [
+ ("savings_plans", False, None, None),
+ ("coverage_daily", True, "2025-01-03", ["period_start"]),
+ ("utilization_daily", False, "2025-01-01", ["period_start"]),
+ ],
+)
+def test_pipeline_passes_cursor_and_partition_settings(
+ name: str, incremental: bool, start: str | None, partition: list[str] | None
+) -> None:
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.schema_name = name
+ inputs.should_use_incremental_field = incremental
+ inputs.db_incremental_field_last_value = "2025-01-10"
+ inputs.api_version = None
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ config = AwsSavingsPlansSourceConfig(
+ aws_access_key_id="example", aws_secret_access_key="secret", start_date="2025-01-01"
+ )
+ response = requests.Response()
+ response.status_code = 200
+ response._content = b"{}"
+ with time_machine.travel("2025-01-12", tick=False), patch(f"{MODULE}.make_tracked_session") as factory:
+ factory.return_value.post.return_value = response
+ result = AwsSavingsPlansSource().source_for_pipeline(config, manager, inputs)
+ assert list(cast(Iterable[Any], result.items())) == []
+ payload = json.loads(factory.return_value.post.call_args.kwargs["data"])
+ assert payload.get("TimePeriod", {}).get("Start") == start
+ assert result.partition_keys == partition
+ assert result.sort_mode == "desc"
+
+
+ "code,permanent",
+ [
+ ("AccessDeniedException", True),
+ ("UnrecognizedClientException", True),
+ ("InvalidSignatureException", True),
+ ("SubscriptionRequiredException", True),
+ ("ValidationException", True),
+ ("HTTP 503", False),
+ ("LimitExceededException", False),
+ ],
+)
+def test_sync_error_matching(code: str, permanent: bool) -> None:
+ errors = AwsSavingsPlansSource().get_non_retryable_errors()
+ assert error_message_matches(f"AWS Savings Plans request failed: {code}", errors) is permanent
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssavingsplans.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssavingsplans.py
index 2c6d7b52e88b..7157dfc98d3b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssavingsplans.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awssavingsplans.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AwsSavingsPlansSourceConfig(config.Config):
- pass
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ aws_session_token: str | None = None
+ start_date: str | None = None