:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add AWS Budgets import source (#84475)
Tom Owerse6704848d558
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/aws_budgets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/aws_budgets.pynew file mode 100644index 000000000000..081911aa0d65--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/aws_budgets.py@@ -0,0 +1,724 @@+import re+import json+import datetime as dt+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode++# nosemgrep: python.lang.security.use-defused-xml.use-defused-xml (Element is only the node type for annotations — all parsing goes through defusedxml below)+from xml.etree.ElementTree import Element++import requests+import structlog+import defusedxml.ElementTree as DET+from botocore.auth import SigV4Auth+from botocore.awsrequest import AWSRequest+from botocore.credentials import Credentials+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.settings import (+ AWS_BUDGETS_ENDPOINTS,+ AWS_JSON_CONTENT_TYPE,+ BUDGETS_ENDPOINT_URL,+ BUDGETS_SIGNING_NAME,+ BUDGETS_SIGNING_REGION,+ BUDGETS_TARGET_PREFIX,+ COST_TYPE_MEMBERS,+ DEFAULT_HISTORY_LOOKBACK_DAYS,+ HISTORY_RESTATEMENT_LOOKBACK_DAYS,+ HISTORY_TIME_UNITS,+ REQUEST_TIMEOUT_SECONDS,+ STS_API_VERSION,+ STS_ENDPOINT_URL,+ STS_SIGNING_NAME,+ STS_SIGNING_REGION,+ AwsBudgetsEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++LOGGER = structlog.get_logger(__name__)++MAX_THROTTLE_ATTEMPTS = 6++# Budgets is a POST-only JSON RPC, and the tracked session's default policy only retries+# idempotent verbs, so POST is opted in explicitly for the transport-level statuses.+TRANSPORT_RETRY = Retry(+ total=3,+ backoff_factor=1,+ status_forcelist=(429, 500, 502, 503, 504),+ allowed_methods=frozenset(["POST"]),+ raise_on_status=False,+)++# AWS returns these as HTTP 400 with the code in the body, so the transport can't see them.+THROTTLING_ERROR_CODES = frozenset({"ThrottlingException", "TooManyRequestsException", "RequestLimitExceeded"})++_STALE_TOKEN_CODES = ("InvalidNextTokenException", "ExpiredNextTokenException")++# Failures that belong to one budget rather than to the sync. `NotFoundException` means the budget+# was deleted between listing it and asking for its detail;+# `BillingViewHealthStatusException` is matched defensively, since AWS documents an unhealthy+# billing view on a budget but doesn't list that code among the operation's errors.+_SKIPPABLE_BUDGET_ERROR_CODES = ("NotFoundException", "BillingViewHealthStatusException")++_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")++_ACCOUNT_ID_PATTERN = re.compile(r"^\d{12}$")++# Codes that mean the key itself is bad, as opposed to a valid key missing an IAM permission.+_CREDENTIAL_ERROR_CODES = (+ "UnrecognizedClientException",+ "InvalidClientTokenId",+ "SignatureDoesNotMatch",+ "InvalidSignatureException",+ "ExpiredTokenException",+ "AccessDenied",+)+++class AwsBudgetsError(Exception):+ pass+++class AwsBudgetsThrottledError(AwsBudgetsError):+ pass++[email protected](frozen=True)+class AwsBudgetsResumeConfig:+ """Where a previous attempt stopped: the page token, plus the budget it was fanning out to."""++ next_token: Optional[str] = None+ budget_name: Optional[str] = None++[email protected](frozen=True)+class BudgetRef:+ """The parts of a listed budget the per-budget operations need."""++ name: str+ time_unit: Optional[str]++[email protected](frozen=True)+class TimeWindow:+ start: dt.datetime+ end: dt.datetime+++def _snake(name: str) -> str:+ """`IncludeTax` -> `include_tax`, `UseAmortized` -> `use_amortized`."""+ return _CAMEL_BOUNDARY.sub("_", name).lower()+++def _parse_timestamp(value: Any) -> Optional[dt.datetime]:+ """Budgets serializes timestamps as epoch seconds under the JSON 1.1 protocol."""+ if isinstance(value, int | float) and not isinstance(value, bool):+ return dt.datetime.fromtimestamp(value, tz=dt.UTC)+ return coerce_datetime(value)+++def coerce_datetime(value: Any) -> Optional[dt.datetime]:+ if isinstance(value, dt.datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=dt.UTC)+ if isinstance(value, dt.date):+ return dt.datetime(value.year, value.month, value.day, tzinfo=dt.UTC)+ if isinstance(value, int | float) and not isinstance(value, bool):+ return dt.datetime.fromtimestamp(value, tz=dt.UTC)+ if isinstance(value, str) and value:+ try:+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=dt.UTC)+ return None+++def cost_type_columns(cost_types: Optional[dict[str, Any]]) -> dict[str, Any]:+ # Driven off the documented member list rather than the response, so a budget type that+ # carries no cost types still lands with the same columns.+ members = cost_types or {}+ return {f"cost_types_{_snake(member)}": members.get(member) for member in COST_TYPE_MEMBERS}+++def normalize_budget(budget: dict[str, Any]) -> dict[str, Any]:+ """One row per budget. Monetary amounts stay strings, exactly as AWS returns them."""+ limit = budget.get("BudgetLimit") or {}+ calculated = budget.get("CalculatedSpend") or {}+ actual = calculated.get("ActualSpend") or {}+ forecasted = calculated.get("ForecastedSpend") or {}+ period = budget.get("TimePeriod") or {}+ auto_adjust = budget.get("AutoAdjustData") or {}+ historical = auto_adjust.get("HistoricalOptions") or {}+ health = budget.get("HealthStatus") or {}++ return {+ "budget_name": budget.get("BudgetName"),+ "budget_type": budget.get("BudgetType"),+ "time_unit": budget.get("TimeUnit"),+ "budget_limit_amount": limit.get("Amount"),+ "budget_limit_unit": limit.get("Unit"),+ "actual_spend_amount": actual.get("Amount"),+ "actual_spend_unit": actual.get("Unit"),+ "forecasted_spend_amount": forecasted.get("Amount"),+ "forecasted_spend_unit": forecasted.get("Unit"),+ "time_period_start": _parse_timestamp(period.get("Start")),+ "time_period_end": _parse_timestamp(period.get("End")),+ "last_updated_time": _parse_timestamp(budget.get("LastUpdatedTime")),+ # Caller-defined maps and the recursive filter expression are kept whole: flattening them+ # would mint one column per key the customer happens to filter on.+ "planned_budget_limits": budget.get("PlannedBudgetLimits"),+ "cost_filters": budget.get("CostFilters"),+ "filter_expression": budget.get("FilterExpression"),+ "metrics": budget.get("Metrics"),+ "billing_view_arn": budget.get("BillingViewArn"),+ "auto_adjust_type": auto_adjust.get("AutoAdjustType"),+ "auto_adjust_budget_adjustment_period": historical.get("BudgetAdjustmentPeriod"),+ "auto_adjust_look_back_available_periods": historical.get("LookBackAvailablePeriods"),+ "auto_adjust_last_time": _parse_timestamp(auto_adjust.get("LastAutoAdjustTime")),+ "health_status": health.get("Status"),+ "health_status_reason": health.get("StatusReason"),+ "health_status_last_updated_time": _parse_timestamp(health.get("LastUpdatedTime")),+ **cost_type_columns(budget.get("CostTypes")),+ }+++def normalize_history_rows(budget: BudgetRef, body: dict[str, Any]) -> list[dict[str, Any]]:+ """One row per budget period. The response wraps the series in a single history object."""+ history = body.get("BudgetPerformanceHistory") or {}+ base: dict[str, Any] = {+ "budget_name": history.get("BudgetName") or budget.name,+ "budget_type": history.get("BudgetType"),+ "time_unit": history.get("TimeUnit"),+ "billing_view_arn": history.get("BillingViewArn"),+ "cost_filters": history.get("CostFilters"),+ **cost_type_columns(history.get("CostTypes")),+ }++ rows: list[dict[str, Any]] = []+ for amounts in history.get("BudgetedAndActualAmountsList") or []:+ period = amounts.get("TimePeriod") or {}+ budgeted = amounts.get("BudgetedAmount") or {}+ actual = amounts.get("ActualAmount") or {}+ rows.append(+ {+ **base,+ "period_start": _parse_timestamp(period.get("Start")),+ "period_end": _parse_timestamp(period.get("End")),+ "budgeted_amount": budgeted.get("Amount"),+ "budgeted_unit": budgeted.get("Unit"),+ "actual_amount": actual.get("Amount"),+ "actual_unit": actual.get("Unit"),+ }+ )+ return rows+++def normalize_notification_rows(budget: BudgetRef, body: dict[str, Any]) -> list[dict[str, Any]]:+ return [+ {+ "budget_name": budget.name,+ "notification_type": notification.get("NotificationType"),+ "comparison_operator": notification.get("ComparisonOperator"),+ "threshold": notification.get("Threshold"),+ "threshold_type": notification.get("ThresholdType"),+ "notification_state": notification.get("NotificationState"),+ }+ for notification in body.get("Notifications") or []+ ]+++def rows_for_budget(+ endpoint_config: AwsBudgetsEndpointConfig, budget: BudgetRef, body: dict[str, Any]+) -> list[dict[str, Any]]:+ if endpoint_config.name == "budget_performance_history":+ return normalize_history_rows(budget, body)+ return normalize_notification_rows(budget, body)+++def _error_code(response: requests.Response) -> str:+ header = response.headers.get("x-amzn-ErrorType") or ""+ if header:+ return header.split(":")[0].split("#")[-1]+ try:+ body = response.json()+ except ValueError:+ return f"HTTP {response.status_code}"+ raw = body.get("__type") or body.get("code") or f"HTTP {response.status_code}"+ return str(raw).split("#")[-1]+++def _error_message(response: requests.Response) -> str:+ try:+ body = response.json()+ except ValueError:+ return response.text[:500]+ message = body.get("message") or body.get("Message") or ""+ return str(message)[:500]+++def error_for_response(response: requests.Response) -> AwsBudgetsError:+ code = _error_code(response)+ text = f"AWS Budgets request failed: {code} - {_error_message(response)}"+ # 429 and 5xx are already retried by the tracked transport; only the app-level throttling+ # codes, which arrive as HTTP 400, need a second bounded retry here.+ if code in THROTTLING_ERROR_CODES:+ return AwsBudgetsThrottledError(text)+ return AwsBudgetsError(text)+++def make_session(secret_access_key: str, session_token: Optional[str]) -> requests.Session:+ redact = tuple(value for value in (secret_access_key, session_token) if value)+ return make_tracked_session(retry=TRANSPORT_RETRY, redact_values=redact)+++@retry(+ retry=retry_if_exception_type(AwsBudgetsThrottledError),+ stop=stop_after_attempt(MAX_THROTTLE_ATTEMPTS),+ wait=wait_exponential_jitter(initial=5, max=120),+ reraise=True,+)+def send_operation(+ session: requests.Session,+ credentials: Credentials,+ operation: str,+ payload: dict[str, Any],+) -> dict[str, Any]:+ """Sign one Budgets JSON-RPC call with SigV4 and send it over the tracked session."""+ body = json.dumps(payload).encode()+ aws_request = AWSRequest(+ method="POST",+ url=BUDGETS_ENDPOINT_URL,+ data=body,+ headers={+ "Content-Type": AWS_JSON_CONTENT_TYPE,+ "X-Amz-Target": f"{BUDGETS_TARGET_PREFIX}.{operation}",+ },+ )+ SigV4Auth(credentials, BUDGETS_SIGNING_NAME, BUDGETS_SIGNING_REGION).add_auth(aws_request)++ response = session.post(+ BUDGETS_ENDPOINT_URL,+ data=body,+ headers=dict(aws_request.headers.items()),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if response.status_code >= 400:+ raise error_for_response(response)++ return response.json()+++def _sts_error(response: requests.Response) -> AwsBudgetsError:+ """STS speaks the query protocol, so its errors are XML rather than JSON."""+ code = f"HTTP {response.status_code}"+ message = ""+ try:+ root: Element = DET.fromstring(response.text)+ except Exception:+ return AwsBudgetsError(f"AWS STS request failed: {code} - {response.text[:500]}")++ for element in root.iter():+ tag = element.tag.rsplit("}", 1)[-1]+ if tag == "Code" and element.text:+ code = element.text+ elif tag == "Message" and element.text:+ message = element.text[:500]+ return AwsBudgetsError(f"AWS STS request failed: {code} - {message}")+++def fetch_account_id(session: requests.Session, credentials: Credentials) -> str:+ """Derive the 12-digit account id the Budgets operations require.++ `sts:GetCallerIdentity` needs no IAM permission, so this doubles as the probe that tells a+ genuine-but-under-permissioned key apart from an invalid one.+ """+ body = urlencode({"Action": "GetCallerIdentity", "Version": STS_API_VERSION}).encode()+ aws_request = AWSRequest(+ method="POST",+ url=STS_ENDPOINT_URL,+ data=body,+ headers={"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"},+ )+ SigV4Auth(credentials, STS_SIGNING_NAME, STS_SIGNING_REGION).add_auth(aws_request)++ response = session.post(+ STS_ENDPOINT_URL,+ data=body,+ headers=dict(aws_request.headers.items()),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if response.status_code >= 400:+ raise _sts_error(response)++ try:+ root: Element = DET.fromstring(response.text)+ except Exception as error:+ raise AwsBudgetsError("AWS STS returned a response we could not read") from error++ for element in root.iter():+ if element.tag.rsplit("}", 1)[-1] == "Account" and element.text:+ account_id = element.text.strip()+ if _ACCOUNT_ID_PATTERN.match(account_id):+ return account_id++ raise AwsBudgetsError("AWS STS did not return an account ID for these credentials")+++def resolve_history_window(+ should_use_incremental_field: bool, db_incremental_field_last_value: Any, now: dt.datetime+) -> TimeWindow:+ """The period range this run asks AWS for.++ An incremental run rewinds behind the stored watermark because actual spend for recent periods+ keeps being restated until the bill finalizes.+ """+ floor = now - dt.timedelta(days=DEFAULT_HISTORY_LOOKBACK_DAYS)++ start = floor+ if should_use_incremental_field:+ watermark = coerce_datetime(db_incremental_field_last_value)+ if watermark is not None:+ start = max(floor, watermark - dt.timedelta(days=HISTORY_RESTATEMENT_LOOKBACK_DAYS))++ # Reaches past now so the period in progress is included; its actual spend merges again on+ # every later run.+ return TimeWindow(start=start, end=now + dt.timedelta(days=1))+++def _has_code(error: AwsBudgetsError, codes: tuple[str, ...]) -> bool:+ text = str(error)+ return any(code in text for code in codes)+++def _walk_pages(+ session: requests.Session,+ credentials: Credentials,+ operation: str,+ payload: dict[str, Any],+ start_token: Optional[str],+ logger: FilteringBoundLogger,+) -> Iterator[tuple[dict[str, Any], Optional[str]]]:+ """Yield each response page with the token that follows it."""+ token = start_token+ resumed = start_token is not None++ while True:+ page_payload = dict(payload)+ if token:+ page_payload["NextToken"] = token++ try:+ body = send_operation(session, credentials, operation, page_payload)+ except AwsBudgetsError as error:+ # A token saved by an earlier attempt can expire; restart the walk instead of failing+ # the job. Merge on the primary key absorbs the re-read rows.+ if resumed and _has_code(error, _STALE_TOKEN_CODES):+ logger.debug(f"Saved AWS Budgets page token is no longer valid; restarting. operation={operation}")+ token = None+ resumed = False+ continue+ raise+ resumed = False++ token = body.get("NextToken")+ yield body, token+ if not token:+ return+++def list_budgets(+ session: requests.Session,+ credentials: Credentials,+ account_id: str,+ page_size: int,+ logger: FilteringBoundLogger,+) -> list[BudgetRef]:+ """Every budget on the account, in the order AWS lists them.++ The per-budget operations need the whole list up front: resuming a fan-out means finding the+ budget the previous attempt stopped on.+ """+ payload: dict[str, Any] = {"AccountId": account_id, "MaxResults": page_size}+ budgets: list[BudgetRef] = []+ for body, _ in _walk_pages(session, credentials, "DescribeBudgets", payload, None, logger):+ for budget in body.get("Budgets") or []:+ name = budget.get("BudgetName")+ if isinstance(name, str) and name:+ budgets.append(BudgetRef(name=name, time_unit=budget.get("TimeUnit")))+ return budgets+++def resume_position(budgets: list[BudgetRef], resume: Optional[AwsBudgetsResumeConfig]) -> tuple[int, Optional[str]]:+ """Where to pick a fan-out up. A budget that no longer exists restarts the run."""+ if resume is None or resume.budget_name is None:+ return 0, None++ for index, budget in enumerate(budgets):+ if budget.name == resume.budget_name:+ return index, resume.next_token++ return 0, None+++def _budget_rows(+ session: requests.Session,+ credentials: Credentials,+ account_id: str,+ endpoint_config: AwsBudgetsEndpointConfig,+ resumable_source_manager: ResumableSourceManager[AwsBudgetsResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_token = resume.next_token if resume is not None else None+ if start_token:+ logger.debug("Resuming AWS Budgets sync from a saved page token. endpoint=budgets")++ payload: dict[str, Any] = {+ "AccountId": account_id,+ "MaxResults": endpoint_config.page_size,+ # Budgets created with a filter expression only report it when asked.+ "ShowFilterExpression": True,+ }++ for body, next_token in _walk_pages(session, credentials, endpoint_config.operation, payload, start_token, logger):+ rows = [normalize_budget(budget) for budget in body.get("Budgets") or []]+ if rows:+ yield rows+ # Saved after yielding: a crash re-yields the last page, which merges away on the primary+ # key, rather than skipping it.+ resumable_source_manager.save_state(AwsBudgetsResumeConfig(next_token=next_token))++ resumable_source_manager.clear_state()+++def _fanout_rows(+ session: requests.Session,+ credentials: Credentials,+ account_id: str,+ endpoint_config: AwsBudgetsEndpointConfig,+ resumable_source_manager: ResumableSourceManager[AwsBudgetsResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ budgets = list_budgets(session, credentials, account_id, AWS_BUDGETS_ENDPOINTS["budgets"].page_size, logger)+ if endpoint_config.supports_time_period:+ budgets = [budget for budget in budgets if (budget.time_unit or "") in HISTORY_TIME_UNITS]+ if not budgets:+ resumable_source_manager.clear_state()+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ index, token = resume_position(budgets, resume)+ if resume is not None:+ logger.debug(f"Resuming AWS Budgets sync. endpoint={endpoint_config.name}, budget_name={budgets[index].name}")++ payload_extra: dict[str, Any] = {}+ if endpoint_config.supports_time_period:+ window = resolve_history_window(+ should_use_incremental_field, db_incremental_field_last_value, dt.datetime.now(dt.UTC)+ )+ payload_extra["TimePeriod"] = {"Start": int(window.start.timestamp()), "End": int(window.end.timestamp())}++ for budget in budgets[index:]:+ payload: dict[str, Any] = {+ "AccountId": account_id,+ "BudgetName": budget.name,+ "MaxResults": endpoint_config.page_size,+ **payload_extra,+ }++ try:+ for body, next_token in _walk_pages(+ session, credentials, endpoint_config.operation, payload, token, logger+ ):+ rows = rows_for_budget(endpoint_config, budget, body)+ if rows:+ yield rows+ resumable_source_manager.save_state(+ AwsBudgetsResumeConfig(next_token=next_token, budget_name=budget.name)+ )+ except AwsBudgetsError as error:+ if not _has_code(error, _SKIPPABLE_BUDGET_ERROR_CODES):+ raise+ logger.debug(f"Skipping a budget AWS could not report on. budget_name={budget.name}, error={error}")++ token = None++ resumable_source_manager.clear_state()+++def get_rows(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[AwsBudgetsResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = AWS_BUDGETS_ENDPOINTS[endpoint]+ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)+ account_id = fetch_account_id(session, credentials)++ if endpoint_config.per_budget:+ yield from _fanout_rows(+ session,+ credentials,+ account_id,+ endpoint_config,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ logger,+ )+ return++ yield from _budget_rows(session, credentials, account_id, endpoint_config, resumable_source_manager, logger)+++def _permission_reason(error: AwsBudgetsError) -> Optional[str]:+ text = str(error)+ if "AccessDeniedException" in text:+ return "The connected IAM user or role is not allowed to read this table"+ if _has_code(error, _CREDENTIAL_ERROR_CODES):+ return "AWS rejected the access key. Please check the access key ID and secret access key."+ return None+++def endpoint_permission_reason(+ session: requests.Session,+ credentials: Credentials,+ account_id: str,+ endpoint_config: AwsBudgetsEndpointConfig,+) -> Optional[str]:+ """Probe the calls a sync of this endpoint issues. `None` when reachable.++ Only a real denial counts as unreachable: throttles, 5xx and network errors leave the endpoint+ reported as reachable, so a blip can't hide tables from the schema picker.+ """+ try:+ budgets = list_budgets(session, credentials, account_id, 1, LOGGER)+ if not endpoint_config.per_budget:+ return None++ eligible = [+ budget+ for budget in budgets+ if not endpoint_config.supports_time_period or (budget.time_unit or "") in HISTORY_TIME_UNITS+ ]+ for budget in eligible[:1]:+ payload: dict[str, Any] = {"AccountId": account_id, "BudgetName": budget.name, "MaxResults": 1}+ send_operation(session, credentials, endpoint_config.operation, payload)+ except AwsBudgetsError as error:+ if _has_code(error, _SKIPPABLE_BUDGET_ERROR_CODES):+ return None+ return _permission_reason(error)+ except Exception:+ return None+ return None+++def probe_endpoint_permissions(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ endpoints: list[str],+) -> dict[str, str | None]:+ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)++ try:+ account_id = fetch_account_id(session, credentials)+ except Exception:+ return dict.fromkeys(endpoints)++ reasons: dict[str, str | None] = {}+ for endpoint in endpoints:+ endpoint_config = AWS_BUDGETS_ENDPOINTS.get(endpoint)+ reasons[endpoint] = (+ endpoint_permission_reason(session, credentials, account_id, endpoint_config)+ if endpoint_config is not None+ else None+ )+ return reasons+++def validate_credentials(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ schema_name: Optional[str] = None,+) -> tuple[bool, Optional[str]]:+ if not aws_access_key_id or not aws_secret_access_key:+ return False, "AWS access key ID and secret access key are required"++ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)++ try:+ account_id = fetch_account_id(session, credentials)+ except AwsBudgetsError as error:+ return False, str(error)+ except Exception:+ return False, "Could not reach AWS to check these credentials. Please try again."++ if schema_name is not None and schema_name in AWS_BUDGETS_ENDPOINTS:+ reason = endpoint_permission_reason(session, credentials, account_id, AWS_BUDGETS_ENDPOINTS[schema_name])+ return reason is None, reason++ try:+ send_operation(session, credentials, "DescribeBudgets", {"AccountId": account_id, "MaxResults": 1})+ except AwsBudgetsError as error:+ # STS already proved the key is genuine, so a denial here is a missing IAM permission. It+ # is reported per table in the schema picker rather than blocking source creation.+ if "AccessDeniedException" in str(error):+ return True, None+ return False, str(error)+ except Exception:+ return False, "Could not reach the AWS Budgets API. Please try again."++ return True, None+++def aws_budgets_source(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[AwsBudgetsResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ endpoint_config = AWS_BUDGETS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ aws_access_key_id=aws_access_key_id,+ aws_secret_access_key=aws_secret_access_key,+ aws_session_token=aws_session_token,+ endpoint=endpoint,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ logger=logger,+ ),+ primary_keys=endpoint_config.primary_key,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ # AWS documents no ordering for these operations, and the per-budget fan-out restarts each+ # budget's history at its earliest period, so the incremental watermark must only commit+ # once a walk completes. "desc" gives exactly that single end-of-run commit.+ sort_mode="desc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/canonical_descriptions.pynew file mode 100644index 000000000000..7c437087604a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/canonical_descriptions.py@@ -0,0 +1,81 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_COST_TYPE_COLUMNS: dict[str, str] = {+ "cost_types_include_tax": "Whether the budget counts tax.",+ "cost_types_include_subscription": "Whether the budget counts subscriptions.",+ "cost_types_use_blended": "Whether the budget measures spend with blended rates.",+ "cost_types_include_refund": "Whether the budget counts refunds.",+ "cost_types_include_credit": "Whether the budget counts credits.",+ "cost_types_include_upfront": "Whether the budget counts upfront reservation fees.",+ "cost_types_include_recurring": "Whether the budget counts recurring reservation charges.",+ "cost_types_include_other_subscription": "Whether the budget counts other subscription costs.",+ "cost_types_include_support": "Whether the budget counts support fees.",+ "cost_types_include_discount": "Whether the budget counts discounts.",+ "cost_types_use_amortized": "Whether the budget measures spend with amortized rates.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "budgets": {+ "description": "Budgets configured on the AWS account, with the limit each one tracks and the actual and forecasted spend against it.",+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_budgets_DescribeBudgets.html",+ "columns": {+ "budget_name": "Name of the budget, unique within the account.",+ "budget_type": "What the budget tracks: COST, USAGE, RI_UTILIZATION, RI_COVERAGE, SAVINGS_PLANS_UTILIZATION or SAVINGS_PLANS_COVERAGE.",+ "time_unit": "How often the budget resets its actual and forecasted spend: DAILY, MONTHLY, QUARTERLY, ANNUALLY or CUSTOM.",+ "budget_limit_amount": "Total amount of cost or usage the budget tracks. Returned as a string, as AWS reports it.",+ "budget_limit_unit": "Unit of the budget limit, a currency for cost budgets.",+ "actual_spend_amount": "Cost or usage recorded against the budget so far in the current period.",+ "actual_spend_unit": "Unit of the actual spend.",+ "forecasted_spend_amount": "Cost or usage AWS forecasts for the whole current period.",+ "forecasted_spend_unit": "Unit of the forecasted spend.",+ "time_period_start": "Start of the period the budget covers.",+ "time_period_end": "End of the period the budget covers. AWS defaults this far into the future when it isn't set.",+ "last_updated_time": "Last time the budget itself was changed.",+ "planned_budget_limits": "Current and future limits per period, for budgets whose limit changes over time.",+ "cost_filters": "Filters that narrow what the budget tracks, such as Region, service, linked account, or tag.",+ "filter_expression": "Filtering dimensions and values applied to the budget, in the newer expression form.",+ "metrics": "Metrics the budget aggregates, such as UnblendedCost or AmortizedCost.",+ "billing_view_arn": "Billing view the budget reads its data from.",+ "auto_adjust_type": "How an auto-adjusting budget sets its limit: HISTORICAL or FORECAST.",+ "auto_adjust_budget_adjustment_period": "Number of periods a historical auto-adjusting budget averages over.",+ "auto_adjust_look_back_available_periods": "Number of past periods AWS actually has data for.",+ "auto_adjust_last_time": "Last time AWS auto-adjusted the budget's limit.",+ "health_status": "Whether the budget's billing view is HEALTHY or UNHEALTHY.",+ "health_status_reason": "Why the budget is unhealthy, such as a billing view it can no longer read.",+ "health_status_last_updated_time": "Last time the health status changed.",+ **_COST_TYPE_COLUMNS,+ },+ },+ "budget_performance_history": {+ "description": "Budgeted versus actual amounts for each period a budget has covered. AWS keeps no history for annual budgets.",+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_budgets_DescribeBudgetPerformanceHistory.html",+ "columns": {+ "budget_name": "Name of the budget the period belongs to.",+ "budget_type": "What the budget tracked during the period.",+ "time_unit": "Length of each period: DAILY, MONTHLY or QUARTERLY.",+ "billing_view_arn": "Billing view the budget read its data from.",+ "cost_filters": "Cost filters the budget had during the period.",+ "period_start": "Start of the period this comparison covers.",+ "period_end": "End of the period this comparison covers.",+ "budgeted_amount": "Amount of cost or usage budgeted for the period.",+ "budgeted_unit": "Unit of the budgeted amount.",+ "actual_amount": "Actual cost or usage recorded for the period.",+ "actual_unit": "Unit of the actual amount.",+ **_COST_TYPE_COLUMNS,+ },+ },+ "notifications": {+ "description": "Alert thresholds attached to each budget, and whether each one is currently in alarm.",+ "docs_url": "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_budgets_DescribeNotificationsForBudget.html",+ "columns": {+ "budget_name": "Name of the budget the notification belongs to.",+ "notification_type": "Whether the notification watches spend so far (ACTUAL) or forecasted spend (FORECASTED).",+ "comparison_operator": "How the threshold is compared: GREATER_THAN, LESS_THAN or EQUAL_TO.",+ "threshold": "Value the notification fires at.",+ "threshold_type": "Whether the threshold is a PERCENTAGE of the budget or an ABSOLUTE_VALUE.",+ "notification_state": "Whether the notification is currently OK or in ALARM.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/settings.pynew file mode 100644index 000000000000..f672be0415ff--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/settings.py@@ -0,0 +1,107 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# AWS Budgets is a global service: one endpoint for the whole partition, always signed against+# us-east-1 whatever region the customer works in.+BUDGETS_ENDPOINT_URL = "https://budgets.amazonaws.com/"+BUDGETS_SIGNING_REGION = "us-east-1"+BUDGETS_SIGNING_NAME = "budgets"+BUDGETS_TARGET_PREFIX = "AWSBudgetServiceGateway"+AWS_JSON_CONTENT_TYPE = "application/x-amz-json-1.1"++# Every Budgets operation requires the 12-digit account id, so it is derived once per sync from+# the credentials themselves instead of asking the customer to paste it. GetCallerIdentity needs+# no IAM permission, and STS is reached through its own global endpoint.+STS_ENDPOINT_URL = "https://sts.amazonaws.com/"+STS_SIGNING_REGION = "us-east-1"+STS_SIGNING_NAME = "sts"+STS_API_VERSION = "2011-06-15"++REQUEST_TIMEOUT_SECONDS = 60++# AWS keeps a limited window of budget history (60 days of DAILY periods, the current month plus+# 12 for MONTHLY, 4 quarters for QUARTERLY), so a year-wide first request covers every grain.+DEFAULT_HISTORY_LOOKBACK_DAYS = 365+# Actual spend for a period keeps moving until the bill finalizes, so an incremental run re-reads+# a trailing window rather than trusting the stored watermark.+HISTORY_RESTATEMENT_LOOKBACK_DAYS = 7++# DescribeBudgetPerformanceHistory covers DAILY, MONTHLY and QUARTERLY budgets only, so budgets on+# any other time unit are skipped instead of spending a request that cannot return history.+HISTORY_TIME_UNITS = frozenset({"DAILY", "MONTHLY", "QUARTERLY"})++# Members of the CostTypes structure. Emitted as columns on every row, present or not, so the+# table shape does not change with whichever budget happens to land in a batch.+COST_TYPE_MEMBERS = (+ "IncludeTax",+ "IncludeSubscription",+ "UseBlended",+ "IncludeRefund",+ "IncludeCredit",+ "IncludeUpfront",+ "IncludeRecurring",+ "IncludeOtherSubscription",+ "IncludeSupport",+ "IncludeDiscount",+ "UseAmortized",+)+++@dataclass(frozen=True)+class AwsBudgetsEndpointConfig:+ name: str+ # Operation name, dispatched through the `X-Amz-Target` header.+ operation: str+ primary_key: list[str]+ # `MaxResults` per request. DescribeBudgets allows up to 1000, the per-budget operations 100.+ page_size: int+ # Per-budget operations are fanned out over the budgets DescribeBudgets returns.+ per_budget: bool = False+ # Only the history operation takes a server-side `TimePeriod`, which is what makes it the+ # single genuinely incremental table here.+ supports_time_period: bool = False+ partition_key: str | None = None+++AWS_BUDGETS_ENDPOINTS: dict[str, AwsBudgetsEndpointConfig] = {+ "budgets": AwsBudgetsEndpointConfig(+ name="budgets",+ operation="DescribeBudgets",+ primary_key=["budget_name"],+ page_size=100,+ ),+ "budget_performance_history": AwsBudgetsEndpointConfig(+ name="budget_performance_history",+ operation="DescribeBudgetPerformanceHistory",+ primary_key=["budget_name", "period_start"],+ page_size=100,+ per_budget=True,+ supports_time_period=True,+ partition_key="period_start",+ ),+ "notifications": AwsBudgetsEndpointConfig(+ name="notifications",+ operation="DescribeNotificationsForBudget",+ # A notification carries no id of its own; a budget's notifications are distinguished by+ # the alert they describe.+ primary_key=["budget_name", "notification_type", "comparison_operator", "threshold", "threshold_type"],+ page_size=100,+ per_budget=True,+ ),+}++ENDPOINTS = tuple(AWS_BUDGETS_ENDPOINTS.keys())++# `budgets` and `notifications` have no server-side time filter at all, so they stay full refresh.+# `period_start` is the boundary the history operation itself filters on.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "budget_performance_history": [incremental_field("period_start")],+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ "budgets": "Budgets configured on the account, with their limit, actual spend, and forecasted spend.",+ "budget_performance_history": "Budgeted versus actual amounts for each period a budget has covered.",+ "notifications": "Alert thresholds attached to each budget, and whether they are currently in alarm.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/source.pyindex ce7b567aff93..c62beb9ec672 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/source.py@@ -1,13 +1,36 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.aws_budgets import (+ AwsBudgetsResumeConfig,+ aws_budgets_source,+ probe_endpoint_permissions,+ validate_credentials as validate_aws_budgets_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsbudgets import (AwsBudgetsSourceConfig,)@@ -15,18 +38,136 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwsBudgetsSource(SimpleSource[AwsBudgetsSourceConfig]):+class AwsBudgetsSource(ResumableSource[AwsBudgetsSourceConfig, AwsBudgetsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ # The Budgets API carries no version token in its requests: the endpoint has no version path+ # segment and the `X-Amz-Target` prefix is unversioned, so there is nothing to pin.+ api_docs_url = "https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Operations_AWS_Budgets.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AWSBUDGETS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "AWS STS request failed: InvalidClientTokenId": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",+ "AWS STS request failed: SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",+ "AWS STS request failed: ExpiredToken": "The AWS session token has expired. Please reconnect with fresh credentials.",+ "AWS STS request failed: AccessDenied": "AWS would not confirm which account these credentials belong to. Please reconnect with a different access key.",+ "AWS Budgets request failed: UnrecognizedClientException": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",+ "AWS Budgets request failed: SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",+ "AWS Budgets request failed: ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",+ "AWS Budgets request failed: AccessDeniedException": "These AWS credentials are missing AWS Budgets read permissions. Grant budgets:DescribeBudgets, budgets:DescribeBudgetPerformanceHistory and budgets:DescribeNotificationsForBudget to the IAM user or role.",+ "AWS access key ID and secret access key are required": "Enter both an AWS access key ID and a secret access key.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AwsBudgetsSourceConfig,+ 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: AwsBudgetsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_aws_budgets_credentials(+ config.aws_access_key_id,+ config.aws_secret_access_key,+ config.aws_session_token,+ schema_name=schema_name,+ )++ def get_endpoint_permissions(+ self, config: AwsBudgetsSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None+ ) -> dict[str, str | None]:+ return probe_endpoint_permissions(+ config.aws_access_key_id,+ config.aws_secret_access_key,+ config.aws_session_token,+ endpoints,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwsBudgetsResumeConfig]:+ return ResumableSourceManager[AwsBudgetsResumeConfig](inputs, AwsBudgetsResumeConfig)++ def source_for_pipeline(+ self,+ config: AwsBudgetsSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwsBudgetsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aws_budgets_source(+ aws_access_key_id=config.aws_access_key_id,+ aws_secret_access_key=config.aws_secret_access_key,+ aws_session_token=config.aws_session_token,+ endpoint=inputs.schema_name,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ logger=inputs.logger,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AWS_BUDGETS,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,- label="Amazon Web Services (AWS Budgets)",+ label="AWS Budgets",+ caption="""Sync your AWS budgets, their spend history, and their alert thresholds into the PostHog Data warehouse.++Create an IAM user or role with the `budgets:DescribeBudgets`, `budgets:DescribeBudgetPerformanceHistory` and `budgets:DescribeNotificationsForBudget` permissions, then paste its access key ID and secret access key. Add a session token too if you are using temporary credentials.++AWS Budgets is a global service, so there is no region to pick. PostHog looks up which account the credentials belong to and reads that account's budgets.""",iconPath="/static/services/aws_budgets.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/aws-budgets",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["aws", "finops", "cloud spend", "budgets"],+ 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",+ caption="Only for temporary credentials. Session tokens expire after a few hours, so scheduled syncs will fail once the token expires. Use a permanent access key (starts with AKIA) for recurring imports.",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets.pynew file mode 100644index 000000000000..2c192424f791--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets.py@@ -0,0 +1,805 @@+import json+import datetime as dt+from typing import Any, Optional, cast++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+import structlog+from tenacity import wait_none++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets import aws_budgets+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.aws_budgets import (+ AwsBudgetsError,+ AwsBudgetsResumeConfig,+ AwsBudgetsThrottledError,+ BudgetRef,+ error_for_response,+ fetch_account_id,+ get_rows,+ normalize_budget,+ normalize_history_rows,+ normalize_notification_rows,+ probe_endpoint_permissions,+ resolve_history_window,+ resume_position,+ send_operation,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.settings import BUDGETS_ENDPOINT_URL+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++LOGGER = structlog.get_logger()++ACCOUNT_ID = "123456789012"++MARCH_1 = 1709251200 # 2024-03-01T00:00:00Z+APRIL_1 = 1711929600 # 2024-04-01T00:00:00Z+++class FakeResumeManager(ResumableSourceManager[AwsBudgetsResumeConfig]):+ def __init__(self, state: Optional[AwsBudgetsResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[AwsBudgetsResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[AwsBudgetsResumeConfig]:+ return self.state++ def save_state(self, data: AwsBudgetsResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def without_retry_backoff(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(cast(Any, send_operation).retry, "wait", wait_none())+++def make_response(+ status_code: int, payload: Optional[dict[str, Any]] = None, headers: Optional[dict[str, str]] = None+) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response.headers.update(headers or {})+ response._content = json.dumps(payload if payload is not None else {}).encode()+ return response+++def make_xml_response(status_code: int, body: str) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response._content = body.encode()+ return response+++def budgets_page(budgets: list[dict[str, Any]], next_token: Optional[str] = None) -> dict[str, Any]:+ body: dict[str, Any] = {"Budgets": budgets}+ if next_token is not None:+ body["NextToken"] = next_token+ return body+++def history_page(+ amounts: list[dict[str, Any]],+ next_token: Optional[str] = None,+ budget_name: str = "monthly-cost",+ time_unit: str = "MONTHLY",+) -> dict[str, Any]:+ body: dict[str, Any] = {+ "BudgetPerformanceHistory": {+ "BudgetName": budget_name,+ "BudgetType": "COST",+ "TimeUnit": time_unit,+ "BudgetedAndActualAmountsList": amounts,+ }+ }+ if next_token is not None:+ body["NextToken"] = next_token+ return body+++FULL_BUDGET: dict[str, Any] = {+ "BudgetName": "monthly-cost",+ "BudgetType": "COST",+ "TimeUnit": "MONTHLY",+ "BudgetLimit": {"Amount": "1000.0", "Unit": "USD"},+ "PlannedBudgetLimits": {"1709251200": {"Amount": "900.0", "Unit": "USD"}},+ "CostFilters": {"Service": ["AmazonS3"]},+ "FilterExpression": {"Dimensions": {"Key": "SERVICE", "Values": ["AmazonS3"]}},+ "Metrics": ["UnblendedCost"],+ "CostTypes": {"IncludeTax": True, "UseAmortized": False},+ "TimePeriod": {"Start": MARCH_1, "End": APRIL_1},+ "CalculatedSpend": {+ "ActualSpend": {"Amount": "412.75", "Unit": "USD"},+ "ForecastedSpend": {"Amount": "980.10", "Unit": "USD"},+ },+ "LastUpdatedTime": MARCH_1,+ "AutoAdjustData": {+ "AutoAdjustType": "HISTORICAL",+ "HistoricalOptions": {"BudgetAdjustmentPeriod": 6, "LookBackAvailablePeriods": 3},+ "LastAutoAdjustTime": MARCH_1,+ },+ "BillingViewArn": "arn:aws:billing::123456789012:billingview/primary",+ "HealthStatus": {"Status": "UNHEALTHY", "StatusReason": "FILTER_INVALID", "LastUpdatedTime": MARCH_1},+}+++class TestNormalizeBudget:+ def test_a_full_budget_flattens_into_stable_columns(self) -> None:+ row = normalize_budget(FULL_BUDGET)++ assert row["budget_name"] == "monthly-cost"+ assert row["budget_type"] == "COST"+ assert row["time_unit"] == "MONTHLY"+ # AWS reports every monetary amount as a string; converting would lose precision the+ # customer's own bill is stated in.+ assert row["budget_limit_amount"] == "1000.0"+ assert row["budget_limit_unit"] == "USD"+ assert row["actual_spend_amount"] == "412.75"+ assert row["forecasted_spend_amount"] == "980.10"+ assert row["time_period_start"] == dt.datetime(2024, 3, 1, tzinfo=dt.UTC)+ assert row["time_period_end"] == dt.datetime(2024, 4, 1, tzinfo=dt.UTC)+ assert row["last_updated_time"] == dt.datetime(2024, 3, 1, tzinfo=dt.UTC)+ assert row["auto_adjust_type"] == "HISTORICAL"+ assert row["auto_adjust_budget_adjustment_period"] == 6+ assert row["auto_adjust_look_back_available_periods"] == 3+ assert row["auto_adjust_last_time"] == dt.datetime(2024, 3, 1, tzinfo=dt.UTC)+ assert row["health_status"] == "UNHEALTHY"+ assert row["health_status_reason"] == "FILTER_INVALID"+ assert row["health_status_last_updated_time"] == dt.datetime(2024, 3, 1, tzinfo=dt.UTC)+ assert row["cost_types_include_tax"] is True+ assert row["cost_types_use_amortized"] is False++ def test_customer_defined_maps_are_kept_whole_instead_of_becoming_columns(self) -> None:+ row = normalize_budget(FULL_BUDGET)++ assert row["planned_budget_limits"] == {"1709251200": {"Amount": "900.0", "Unit": "USD"}}+ assert row["cost_filters"] == {"Service": ["AmazonS3"]}+ assert row["filter_expression"] == {"Dimensions": {"Key": "SERVICE", "Values": ["AmazonS3"]}}+ assert row["metrics"] == ["UnblendedCost"]++ def test_a_sparse_budget_keeps_the_same_columns(self) -> None:+ # Budget types other than COST carry no cost types, and RI budgets carry no limit; the+ # Arrow schema must not shift between pages depending on which budgets landed in them.+ sparse = normalize_budget({"BudgetName": "ri-coverage", "BudgetType": "RI_COVERAGE", "TimeUnit": "DAILY"})++ assert set(sparse.keys()) == set(normalize_budget(FULL_BUDGET).keys())+ assert sparse["budget_limit_amount"] is None+ assert sparse["cost_types_include_tax"] is None+ assert sparse["health_status"] is None++ @pytest.mark.parametrize(+ "value,expected",+ [+ (MARCH_1, dt.datetime(2024, 3, 1, tzinfo=dt.UTC)),+ (1709251200.5, dt.datetime(2024, 3, 1, 0, 0, 0, 500000, tzinfo=dt.UTC)),+ ("2024-03-01T00:00:00Z", dt.datetime(2024, 3, 1, tzinfo=dt.UTC)),+ (None, None),+ ("not-a-date", None),+ ],+ )+ def test_timestamps_are_parsed_from_the_json_protocols_epoch_seconds(self, value: Any, expected: Any) -> None:+ assert normalize_budget({"LastUpdatedTime": value})["last_updated_time"] == expected+++class TestNormalizeHistoryRows:+ AMOUNTS = [+ {+ "BudgetedAmount": {"Amount": "1000.0", "Unit": "USD"},+ "ActualAmount": {"Amount": "812.5", "Unit": "USD"},+ "TimePeriod": {"Start": MARCH_1, "End": APRIL_1},+ },+ {+ "BudgetedAmount": {"Amount": "1000.0", "Unit": "USD"},+ "ActualAmount": {"Amount": "97.25", "Unit": "USD"},+ "TimePeriod": {"Start": APRIL_1, "End": APRIL_1 + 86400},+ },+ ]++ def test_one_row_per_period_carries_the_budgets_identity(self) -> None:+ rows = normalize_history_rows(BudgetRef(name="monthly-cost", time_unit="MONTHLY"), history_page(self.AMOUNTS))++ assert [row["period_start"] for row in rows] == [+ dt.datetime(2024, 3, 1, tzinfo=dt.UTC),+ dt.datetime(2024, 4, 1, tzinfo=dt.UTC),+ ]+ assert [row["actual_amount"] for row in rows] == ["812.5", "97.25"]+ assert {row["budget_name"] for row in rows} == {"monthly-cost"}+ assert rows[0]["budgeted_amount"] == "1000.0"+ assert rows[0]["period_end"] == dt.datetime(2024, 4, 1, tzinfo=dt.UTC)+ assert rows[0]["time_unit"] == "MONTHLY"++ def test_the_budget_name_falls_back_to_the_parent_when_aws_omits_it(self) -> None:+ # The primary key is (budget_name, period_start), so a missing name would collapse every+ # budget's history onto one set of keys.+ body = {"BudgetPerformanceHistory": {"BudgetedAndActualAmountsList": self.AMOUNTS}}++ rows = normalize_history_rows(BudgetRef(name="quarterly-usage", time_unit="QUARTERLY"), body)++ assert {row["budget_name"] for row in rows} == {"quarterly-usage"}++ @pytest.mark.parametrize("body", [{}, {"BudgetPerformanceHistory": {}}, {"BudgetPerformanceHistory": None}])+ def test_a_budget_with_no_recorded_history_yields_no_rows(self, body: dict[str, Any]) -> None:+ assert normalize_history_rows(BudgetRef(name="monthly-cost", time_unit="MONTHLY"), body) == []+++class TestNormalizeNotificationRows:+ def test_rows_carry_the_budget_name_that_makes_the_primary_key_unique(self) -> None:+ body = {+ "Notifications": [+ {+ "NotificationType": "ACTUAL",+ "ComparisonOperator": "GREATER_THAN",+ "Threshold": 80.0,+ "ThresholdType": "PERCENTAGE",+ "NotificationState": "ALARM",+ },+ {+ "NotificationType": "FORECASTED",+ "ComparisonOperator": "GREATER_THAN",+ "Threshold": 100.0,+ "ThresholdType": "PERCENTAGE",+ "NotificationState": "OK",+ },+ ]+ }++ rows = normalize_notification_rows(BudgetRef(name="monthly-cost", time_unit="MONTHLY"), body)++ assert [row["notification_type"] for row in rows] == ["ACTUAL", "FORECASTED"]+ assert [row["threshold"] for row in rows] == [80.0, 100.0]+ assert {row["budget_name"] for row in rows} == {"monthly-cost"}+ assert rows[0]["notification_state"] == "ALARM"++ def test_a_budget_with_no_notifications_yields_no_rows(self) -> None:+ assert normalize_notification_rows(BudgetRef(name="monthly-cost", time_unit="MONTHLY"), {}) == []+++class TestErrorClassification:+ @pytest.mark.parametrize("code", ["ThrottlingException", "TooManyRequestsException", "RequestLimitExceeded"])+ def test_throttling_codes_are_retryable(self, code: str) -> None:+ response = make_response(400, {"__type": f"com.amazon.coral.availability#{code}", "message": "slow down"})++ error = error_for_response(response)++ assert isinstance(error, AwsBudgetsThrottledError)+ assert f"AWS Budgets request failed: {code}" in str(error)++ @pytest.mark.parametrize(+ "code", ["AccessDeniedException", "UnrecognizedClientException", "ExpiredTokenException", "NotFoundException"]+ )+ def test_permanent_codes_are_not_retryable_and_stringify_for_the_source_mapping(self, code: str) -> None:+ response = make_response(400, {"__type": code, "message": "nope"})++ error = error_for_response(response)++ assert not isinstance(error, AwsBudgetsThrottledError)+ assert str(error) == f"AWS Budgets request failed: {code} - nope"++ def test_the_error_type_header_wins_over_the_body(self) -> None:+ response = make_response(+ 400,+ {"message": "nope"},+ headers={"x-amzn-ErrorType": "AccessDeniedException:http://internal.amazon.com/coral/"},+ )++ assert str(error_for_response(response)) == "AWS Budgets request failed: AccessDeniedException - nope"++ def test_a_non_json_error_body_still_produces_a_usable_message(self) -> None:+ response = requests.Response()+ response.status_code = 503+ response._content = b"<html>gateway</html>"++ assert "HTTP 503" in str(error_for_response(response))+++class TestSendOperation:+ def test_requests_are_sigv4_signed_for_the_global_endpoint_and_dispatched_via_x_amz_target(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_response(200, {"Budgets": []})++ with freeze_time("2024-03-05T10:00:00Z"):+ send_operation(+ session, aws_budgets.Credentials("AKIAEXAMPLE", "secret"), "DescribeBudgets", {"AccountId": ACCOUNT_ID}+ )++ _, kwargs = session.post.call_args+ assert session.post.call_args[0][0] == BUDGETS_ENDPOINT_URL+ assert kwargs["headers"]["X-Amz-Target"] == "AWSBudgetServiceGateway.DescribeBudgets"+ assert kwargs["headers"]["Content-Type"] == "application/x-amz-json-1.1"+ # Budgets is global: signing anywhere but us-east-1 returns SignatureDoesNotMatch.+ assert kwargs["headers"]["Authorization"].startswith(+ "AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/20240305/us-east-1/budgets/aws4_request"+ )+ assert json.loads(kwargs["data"]) == {"AccountId": ACCOUNT_ID}++ def test_temporary_credentials_carry_the_session_token(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_response(200, {})++ send_operation(+ session, aws_budgets.Credentials("AKIAEXAMPLE", "secret", "session-token"), "DescribeBudgets", {}+ )++ assert session.post.call_args[1]["headers"]["X-Amz-Security-Token"] == "session-token"++ def test_throttled_calls_are_retried_until_they_succeed(self, monkeypatch: pytest.MonkeyPatch) -> None:+ without_retry_backoff(monkeypatch)+ session = mock.MagicMock(spec=requests.Session)+ session.post.side_effect = [+ make_response(400, {"__type": "ThrottlingException", "message": "slow down"}),+ make_response(200, {"Budgets": []}),+ ]++ body = send_operation(session, aws_budgets.Credentials("k", "s"), "DescribeBudgets", {})++ assert body == {"Budgets": []}+ assert session.post.call_count == 2++ def test_permanent_errors_are_raised_without_retrying(self, monkeypatch: pytest.MonkeyPatch) -> None:+ without_retry_backoff(monkeypatch)+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_response(400, {"__type": "AccessDeniedException", "message": "denied"})++ with pytest.raises(AwsBudgetsError):+ send_operation(session, aws_budgets.Credentials("k", "s"), "DescribeBudgets", {})++ assert session.post.call_count == 1+++IDENTITY_XML = """<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">+ <GetCallerIdentityResult>+ <Arn>arn:aws:iam::123456789012:user/finops</Arn>+ <UserId>AIDAEXAMPLE</UserId>+ <Account>123456789012</Account>+ </GetCallerIdentityResult>+</GetCallerIdentityResponse>"""++STS_ERROR_XML = """<ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/">+ <Error>+ <Type>Sender</Type>+ <Code>InvalidClientTokenId</Code>+ <Message>The security token included in the request is invalid.</Message>+ </Error>+</ErrorResponse>"""+++class TestFetchAccountId:+ def test_the_account_id_is_read_from_the_signed_sts_call(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_xml_response(200, IDENTITY_XML)++ assert fetch_account_id(session, aws_budgets.Credentials("AKIAEXAMPLE", "secret")) == ACCOUNT_ID+ assert session.post.call_args[0][0] == "https://sts.amazonaws.com/"+ assert session.post.call_args[1]["data"] == b"Action=GetCallerIdentity&Version=2011-06-15"+ assert session.post.call_args[1]["headers"]["Authorization"].startswith(+ "AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/"+ )++ def test_an_sts_error_surfaces_the_aws_code_so_the_source_can_map_it(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_xml_response(403, STS_ERROR_XML)++ with pytest.raises(AwsBudgetsError) as error:+ fetch_account_id(session, aws_budgets.Credentials("k", "s"))++ assert str(error.value).startswith("AWS STS request failed: InvalidClientTokenId - ")++ @pytest.mark.parametrize(+ "body",+ [+ "<GetCallerIdentityResponse><GetCallerIdentityResult><Arn>arn</Arn></GetCallerIdentityResult></GetCallerIdentityResponse>",+ "<GetCallerIdentityResponse><GetCallerIdentityResult><Account>12345</Account></GetCallerIdentityResult></GetCallerIdentityResponse>",+ "not xml at all",+ ],+ )+ def test_a_response_without_a_usable_account_id_fails_loudly(self, body: str) -> None:+ # Every Budgets operation requires the account id, so guessing one would produce a+ # confusing NotFoundException much later in the sync.+ session = mock.MagicMock(spec=requests.Session)+ session.post.return_value = make_xml_response(200, body)++ with pytest.raises(AwsBudgetsError):+ fetch_account_id(session, aws_budgets.Credentials("k", "s"))+++class TestResolveHistoryWindow:+ NOW = dt.datetime(2024, 6, 1, 12, 0, tzinfo=dt.UTC)++ def test_a_full_refresh_reaches_back_a_year_to_cover_every_grain(self) -> None:+ window = resolve_history_window(False, None, self.NOW)++ assert window.start == dt.datetime(2023, 6, 2, 12, 0, tzinfo=dt.UTC)+ # The period in progress is included so its actual spend keeps merging.+ assert window.end == dt.datetime(2024, 6, 2, 12, 0, tzinfo=dt.UTC)++ @pytest.mark.parametrize(+ "watermark",+ ["2024-05-20", "2024-05-20T00:00:00Z", dt.date(2024, 5, 20), dt.datetime(2024, 5, 20, tzinfo=dt.UTC)],+ )+ def test_incremental_rewinds_behind_the_watermark_to_re_read_restated_spend(self, watermark: Any) -> None:+ assert resolve_history_window(True, watermark, self.NOW).start == dt.datetime(2024, 5, 13, tzinfo=dt.UTC)++ def test_a_watermark_older_than_the_lookback_floor_does_not_widen_the_window(self) -> None:+ assert resolve_history_window(True, "2019-01-01", self.NOW).start == dt.datetime(+ 2023, 6, 2, 12, 0, tzinfo=dt.UTC+ )++ @pytest.mark.parametrize("watermark", [None, "not-a-date"])+ def test_an_unusable_watermark_falls_back_to_the_full_window(self, watermark: Any) -> None:+ assert resolve_history_window(True, watermark, self.NOW).start == dt.datetime(2023, 6, 2, 12, 0, tzinfo=dt.UTC)+++class TestResumePosition:+ BUDGETS = [+ BudgetRef(name="a", time_unit="MONTHLY"),+ BudgetRef(name="b", time_unit="MONTHLY"),+ BudgetRef(name="c", time_unit="DAILY"),+ ]++ def test_a_saved_budget_resumes_at_that_budget_and_page(self) -> None:+ assert resume_position(self.BUDGETS, AwsBudgetsResumeConfig(next_token="tok", budget_name="b")) == (1, "tok")++ @pytest.mark.parametrize(+ "resume",+ [None, AwsBudgetsResumeConfig(), AwsBudgetsResumeConfig(next_token="tok", budget_name="deleted")],+ )+ def test_anything_we_cannot_place_restarts_the_fan_out(self, resume: Optional[AwsBudgetsResumeConfig]) -> None:+ # A budget deleted since the last attempt must not silently skip the budgets before it.+ assert resume_position(self.BUDGETS, resume) == (0, None)+++class TestGetBudgetRows:+ def _run(+ self, responses: list[Any], manager: FakeResumeManager+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ with (+ mock.patch.object(aws_budgets, "fetch_account_id", return_value=ACCOUNT_ID),+ mock.patch.object(aws_budgets, "send_operation", side_effect=responses) as send,+ ):+ batches = list(+ get_rows(+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ aws_session_token=None,+ endpoint="budgets",+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ logger=LOGGER,+ )+ )+ return batches, send++ def test_pagination_stops_when_aws_stops_returning_a_token(self) -> None:+ manager = FakeResumeManager()++ batches, send = self._run(+ [+ budgets_page([{"BudgetName": "a"}], next_token="page-2"),+ budgets_page([{"BudgetName": "b"}]),+ ],+ manager,+ )++ assert [row["budget_name"] for batch in batches for row in batch] == ["a", "b"]+ assert send.call_args_list[0][0][3].get("NextToken") is None+ assert send.call_args_list[1][0][3]["NextToken"] == "page-2"++ def test_the_filter_expression_is_requested_because_aws_hides_it_by_default(self) -> None:+ _, send = self._run([budgets_page([])], FakeResumeManager())++ assert send.call_args_list[0][0][3]["ShowFilterExpression"] is True+ assert send.call_args_list[0][0][3]["AccountId"] == ACCOUNT_ID++ def test_state_is_saved_after_each_page_and_cleared_once_the_walk_completes(self) -> None:+ manager = FakeResumeManager()++ self._run(+ [budgets_page([{"BudgetName": "a"}], next_token="page-2"), budgets_page([{"BudgetName": "b"}])], manager+ )++ assert manager.saved == [+ AwsBudgetsResumeConfig(next_token="page-2"),+ AwsBudgetsResumeConfig(next_token=None),+ ]+ assert manager.cleared is True++ def test_a_saved_token_resumes_the_walk_where_it_stopped(self) -> None:+ manager = FakeResumeManager(AwsBudgetsResumeConfig(next_token="page-7"))++ _, send = self._run([budgets_page([{"BudgetName": "a"}])], manager)++ assert send.call_count == 1+ assert send.call_args_list[0][0][3]["NextToken"] == "page-7"++ @pytest.mark.parametrize("code", ["ExpiredNextTokenException", "InvalidNextTokenException"])+ def test_a_stale_saved_token_restarts_the_walk_rather_than_failing_the_job(self, code: str) -> None:+ manager = FakeResumeManager(AwsBudgetsResumeConfig(next_token="stale"))++ batches, send = self._run(+ [+ AwsBudgetsError(f"AWS Budgets request failed: {code} - gone"),+ budgets_page([{"BudgetName": "a"}]),+ ],+ manager,+ )++ assert [row["budget_name"] for batch in batches for row in batch] == ["a"]+ assert "NextToken" not in send.call_args_list[1][0][3]++ def test_a_stale_token_error_on_a_fresh_walk_is_not_swallowed(self) -> None:+ # Without a saved token the error means something else is wrong; retrying from scratch+ # would loop forever.+ with pytest.raises(AwsBudgetsError):+ self._run(+ [AwsBudgetsError("AWS Budgets request failed: InvalidNextTokenException - gone")], FakeResumeManager()+ )+++@freeze_time("2024-06-01T12:00:00Z")+class TestGetFanoutRows:+ LISTED = budgets_page(+ [+ {"BudgetName": "monthly-cost", "TimeUnit": "MONTHLY"},+ {"BudgetName": "yearly-cost", "TimeUnit": "ANNUALLY"},+ {"BudgetName": "daily-usage", "TimeUnit": "DAILY"},+ ]+ )++ def _run(+ self,+ responses: list[Any],+ manager: FakeResumeManager,+ endpoint: str = "budget_performance_history",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ with (+ mock.patch.object(aws_budgets, "fetch_account_id", return_value=ACCOUNT_ID),+ mock.patch.object(aws_budgets, "send_operation", side_effect=responses) as send,+ ):+ batches = list(+ get_rows(+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ aws_session_token=None,+ endpoint=endpoint,+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ logger=LOGGER,+ )+ )+ return batches, send++ def test_history_skips_budgets_aws_keeps_no_history_for(self) -> None:+ # DescribeBudgetPerformanceHistory covers DAILY, MONTHLY and QUARTERLY budgets only.+ _, send = self._run(+ [self.LISTED, history_page([], budget_name="monthly-cost"), history_page([], budget_name="daily-usage")],+ FakeResumeManager(),+ )++ requested = [call[0][3]["BudgetName"] for call in send.call_args_list[1:]]+ assert requested == ["monthly-cost", "daily-usage"]++ def test_notifications_are_requested_for_every_budget_and_carry_no_time_period(self) -> None:+ _, send = self._run(+ [self.LISTED, {"Notifications": []}, {"Notifications": []}, {"Notifications": []}],+ FakeResumeManager(),+ endpoint="notifications",+ )++ requested = [call[0][3]["BudgetName"] for call in send.call_args_list[1:]]+ assert requested == ["monthly-cost", "yearly-cost", "daily-usage"]+ assert all("TimePeriod" not in call[0][3] for call in send.call_args_list[1:])++ def test_the_history_window_is_sent_as_epoch_seconds(self) -> None:+ _, send = self._run(+ [self.LISTED, history_page([]), history_page([])],+ FakeResumeManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-05-20",+ )++ assert send.call_args_list[1][0][3]["TimePeriod"] == {+ "Start": int(dt.datetime(2024, 5, 13, tzinfo=dt.UTC).timestamp()),+ "End": int(dt.datetime(2024, 6, 2, 12, 0, tzinfo=dt.UTC).timestamp()),+ }++ def test_state_records_the_budget_being_walked_so_a_retry_does_not_restart_the_fan_out(self) -> None:+ manager = FakeResumeManager()++ self._run(+ [+ self.LISTED,+ history_page([], next_token="page-2", budget_name="monthly-cost"),+ history_page([], budget_name="monthly-cost"),+ history_page([], budget_name="daily-usage"),+ ],+ manager,+ )++ assert manager.saved == [+ AwsBudgetsResumeConfig(next_token="page-2", budget_name="monthly-cost"),+ AwsBudgetsResumeConfig(next_token=None, budget_name="monthly-cost"),+ AwsBudgetsResumeConfig(next_token=None, budget_name="daily-usage"),+ ]+ assert manager.cleared is True++ def test_resuming_picks_up_at_the_saved_budget_and_page(self) -> None:+ manager = FakeResumeManager(AwsBudgetsResumeConfig(next_token="page-9", budget_name="daily-usage"))++ _, send = self._run([self.LISTED, history_page([], budget_name="daily-usage")], manager)++ assert [call[0][3]["BudgetName"] for call in send.call_args_list[1:]] == ["daily-usage"]+ assert send.call_args_list[1][0][3]["NextToken"] == "page-9"++ def test_the_saved_page_token_is_not_reused_on_the_next_budget(self) -> None:+ # A token belongs to one budget's walk; sending it to the next budget would be rejected.+ manager = FakeResumeManager(AwsBudgetsResumeConfig(next_token="page-9", budget_name="monthly-cost"))++ _, send = self._run(+ [self.LISTED, history_page([], budget_name="monthly-cost"), history_page([], budget_name="daily-usage")],+ manager,+ )++ assert send.call_args_list[1][0][3]["NextToken"] == "page-9"+ assert "NextToken" not in send.call_args_list[2][0][3]++ @pytest.mark.parametrize("code", ["NotFoundException", "BillingViewHealthStatusException"])+ def test_a_budget_aws_cannot_report_on_is_skipped_without_failing_the_sync(self, code: str) -> None:+ batches, send = self._run(+ [+ self.LISTED,+ AwsBudgetsError(f"AWS Budgets request failed: {code} - nope"),+ history_page(+ [+ {+ "BudgetedAmount": {"Amount": "5", "Unit": "USD"},+ "ActualAmount": {"Amount": "1", "Unit": "USD"},+ "TimePeriod": {"Start": MARCH_1, "End": APRIL_1},+ }+ ],+ budget_name="daily-usage",+ ),+ ],+ FakeResumeManager(),+ )++ assert [row["budget_name"] for batch in batches for row in batch] == ["daily-usage"]+ assert send.call_count == 3++ def test_a_denial_mid_fan_out_still_fails_the_sync(self) -> None:+ # Skipping it would silently produce a table missing most of its rows.+ with pytest.raises(AwsBudgetsError):+ self._run(+ [self.LISTED, AwsBudgetsError("AWS Budgets request failed: AccessDeniedException - denied")],+ FakeResumeManager(),+ )++ def test_an_account_with_no_eligible_budgets_makes_no_further_requests(self) -> None:+ manager = FakeResumeManager()++ batches, send = self._run([budgets_page([{"BudgetName": "yearly", "TimeUnit": "ANNUALLY"}])], manager)++ assert batches == []+ assert send.call_count == 1+ assert manager.cleared is True+++class TestValidateCredentials:+ def test_missing_credentials_short_circuit_without_a_request(self) -> None:+ with mock.patch.object(aws_budgets, "fetch_account_id") as fetch:+ assert validate_credentials("", "secret", None) == (+ False,+ "AWS access key ID and secret access key are required",+ )++ fetch.assert_not_called()++ def test_a_successful_probe_validates(self) -> None:+ with (+ mock.patch.object(aws_budgets, "fetch_account_id", return_value=ACCOUNT_ID),+ mock.patch.object(aws_budgets, "send_operation", return_value=budgets_page([])) as send,+ ):+ assert validate_credentials("key", "secret", None) == (True, None)++ assert send.call_args[0][2] == "DescribeBudgets"++ def test_a_rejected_key_is_reported_with_the_aws_code(self) -> None:+ error = AwsBudgetsError("AWS STS request failed: InvalidClientTokenId - bad key")++ with mock.patch.object(aws_budgets, "fetch_account_id", side_effect=error):+ assert validate_credentials("key", "secret", None) == (False, str(error))++ def test_a_genuine_key_without_budgets_permissions_can_still_connect(self) -> None:+ # Per-table access is reported in the schema picker; blocking source creation would stop a+ # user who only wants the tables their key can read.+ with (+ mock.patch.object(aws_budgets, "fetch_account_id", return_value=ACCOUNT_ID),+ mock.patch.object(+ aws_budgets,+ "send_operation",+ side_effect=AwsBudgetsError("AWS Budgets request failed: AccessDeniedException - denied"),+ ),+ ):+ assert validate_credentials("key", "secret", None) == (True, None)++ def test_a_denial_for_a_named_schema_is_reported(self) -> None:+ with (+ mock.patch.object(aws_budgets, "fetch_account_id", return_value=ACCOUNT_ID),+ mock.patch.object(+ aws_budgets,+ "send_operation",+ side_effect=AwsBudgetsError("AWS Budgets request failed: AccessDeniedException - denied"),+ ),+ ):+ valid, reason = validate_credentials("key", "secret", None, schema_name="budgets")++ assert valid is False+ assert reason == "The connected IAM user or role is not allowed to read this table"++ def test_a_transport_failure_does_not_leak_internals(self) -> None:+ with mock.patch.object(aws_budgets, "fetch_account_id", side_effect=requests.ConnectionError("boom")):+ assert validate_credentials("key", "secret", None) == (+ False,+ "Could not reach AWS to check these credentials. Please try again.",+ )+++class TestProbeEndpointPermissions:+ def test_reachable_endpoints_report_no_reason(self) -> None:+ with (+ mock.patch.object(aws_budgets, "fetch_account_id", return_value=ACCOUNT_ID),+ mock.patch.object(+ aws_budgets,+ "send_operation",+ side_effect=lambda *args, **kwargs: budgets_page([{"BudgetName": "a", "TimeUnit": "MONTHLY"}]),+ ),+ ):+ reasons = probe_endpoint_permissions("key", "secret", None, ["budgets", "notifications"])++ assert reasons == {"budgets": None, "notifications": None}++ def test_a_denied_endpoint_names_the_problem(self) -> None:+ with (+ mock.patch.object(aws_budgets, "fetch_account_id", return_value=ACCOUNT_ID),+ mock.patch.object(+ aws_budgets,+ "send_operation",+ side_effect=AwsBudgetsError("AWS Budgets request failed: AccessDeniedException - denied"),+ ),+ ):+ reasons = probe_endpoint_permissions("key", "secret", None, ["budgets"])++ assert reasons == {"budgets": "The connected IAM user or role is not allowed to read this table"}++ @pytest.mark.parametrize(+ "failure",+ [+ AwsBudgetsError("AWS Budgets request failed: ThrottlingException - slow down"),+ requests.ConnectionError("boom"),+ ],+ )+ def test_a_blip_leaves_the_endpoint_reported_as_reachable(self, failure: Exception) -> None:+ # Otherwise a throttle would hide tables from the schema picker.+ with (+ mock.patch.object(aws_budgets, "fetch_account_id", return_value=ACCOUNT_ID),+ mock.patch.object(aws_budgets, "send_operation", side_effect=failure),+ ):+ assert probe_endpoint_permissions("key", "secret", None, ["budgets"]) == {"budgets": None}++ def test_credentials_aws_will_not_identify_leave_every_endpoint_unjudged(self) -> None:+ with mock.patch.object(aws_budgets, "fetch_account_id", side_effect=requests.ConnectionError("boom")):+ assert probe_endpoint_permissions("key", "secret", None, ["budgets", "notifications"]) == {+ "budgets": None,+ "notifications": None,+ }diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets_source.pynew file mode 100644index 000000000000..7b31e09649b8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_budgets/tests/test_aws_budgets_source.py@@ -0,0 +1,254 @@+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++import structlog++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets import (+ aws_budgets as transport_module,+ source as source_module,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.aws_budgets import (+ AwsBudgetsResumeConfig,+ BudgetRef,+ normalize_budget,+ normalize_history_rows,+ normalize_notification_rows,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.settings import (+ AWS_BUDGETS_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_budgets.source import AwsBudgetsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsbudgets import (+ AwsBudgetsSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def make_inputs(+ schema_name: str,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="period_start",+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestAwsBudgetsSource:+ def setup_method(self) -> None:+ self.source = AwsBudgetsSource()+ self.config = AwsBudgetsSourceConfig(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ aws_session_token=None,+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.AWSBUDGETS++ def test_source_is_released_and_labelled_alpha(self) -> None:+ config = self.source.get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING++ def test_the_credential_form_asks_only_for_an_iam_key(self) -> None:+ # Budgets is global, so there is no region to route on and none to ask for.+ fields = [cast(SourceFieldInputConfig, field) for field in self.source.get_source_config.fields]++ assert [field.name for field in fields] == [+ "aws_access_key_id",+ "aws_secret_access_key",+ "aws_session_token",+ ]+ assert [field.required for field in fields] == [True, True, False]+ secret_fields = [field.name for field in fields if field.type == SourceFieldInputConfigType.PASSWORD]+ assert secret_fields == ["aws_secret_access_key", "aws_session_token"]++ def test_the_table_catalog_renders_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ assert self.source.api_docs_url.startswith("https://")++ def test_get_schemas_lists_every_endpoint_with_its_description(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ assert all(schema.description for schema in schemas)++ def test_only_the_history_table_syncs_incrementally(self) -> None:+ # Budgets and notifications have no server-side time filter, so an "incremental" sync of+ # them would still read everything.+ by_name = {schema.name: schema for schema in self.source.get_schemas(self.config, team_id=1)}++ assert by_name["budget_performance_history"].supports_incremental is True+ assert [f["field"] for f in by_name["budget_performance_history"].incremental_fields] == ["period_start"]+ assert by_name["budgets"].supports_incremental is False+ assert by_name["notifications"].supports_incremental is False++ def test_a_schema_filter_narrows_the_list(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["notifications"])++ assert [schema.name for schema in schemas] == ["notifications"]++ def test_validate_credentials_passes_the_schema_through(self) -> None:+ with mock.patch.object(+ source_module, "validate_aws_budgets_credentials", return_value=(True, None)+ ) as validate:+ assert self.source.validate_credentials(self.config, team_id=1, schema_name="budgets") == (True, None)++ assert validate.call_args[1]["schema_name"] == "budgets"+ assert validate.call_args[0][:3] == ("AKIAEXAMPLE", "secret", None)++ def test_endpoint_permissions_are_probed_for_the_requested_endpoints(self) -> None:+ with mock.patch.object(source_module, "probe_endpoint_permissions", return_value={"budgets": None}) as probe:+ assert self.source.get_endpoint_permissions(self.config, team_id=1, endpoints=["budgets"]) == {+ "budgets": None+ }++ assert probe.call_args[0][3] == ["budgets"]++ def test_the_resume_manager_is_bound_to_the_sources_own_state_shape(self) -> None:+ manager = self.source.get_resumable_source_manager(make_inputs("budgets"))++ assert manager._data_class is AwsBudgetsResumeConfig++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_for_pipeline_declares_the_endpoints_primary_key(self, endpoint: str) -> None:+ response = self.source.source_for_pipeline(+ self.config, self.source.get_resumable_source_manager(make_inputs(endpoint)), make_inputs(endpoint)+ )++ assert response.name == endpoint+ assert response.primary_keys == AWS_BUDGETS_ENDPOINTS[endpoint].primary_key+ # AWS documents no ordering for these operations, so the watermark may only commit at the+ # end of a completed walk.+ assert response.sort_mode == "desc"++ def test_only_the_history_table_is_partitioned_by_period(self) -> None:+ history = self.source.source_for_pipeline(+ self.config,+ self.source.get_resumable_source_manager(make_inputs("budget_performance_history")),+ make_inputs("budget_performance_history"),+ )+ budgets = self.source.source_for_pipeline(+ self.config,+ self.source.get_resumable_source_manager(make_inputs("budgets")),+ make_inputs("budgets"),+ )++ assert history.partition_keys == ["period_start"]+ assert history.partition_mode == "datetime"+ assert history.partition_format == "month"+ assert budgets.partition_keys is None+ assert budgets.partition_mode is None++ @pytest.mark.parametrize(+ "should_use_incremental_field,expected_watermark",+ [(True, "2024-05-20"), (False, None)],+ )+ def test_the_watermark_only_reaches_the_transport_on_an_incremental_sync(+ self, should_use_incremental_field: bool, expected_watermark: Any+ ) -> None:+ inputs = make_inputs(+ "budget_performance_history",+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value="2024-05-20",+ )+ response = self.source.source_for_pipeline(+ self.config, self.source.get_resumable_source_manager(inputs), inputs+ )++ with mock.patch.object(transport_module, "get_rows", return_value=iter([])) as get_rows:+ list(cast("Iterable[Any]", response.items()))++ assert get_rows.call_args[1]["should_use_incremental_field"] is should_use_incremental_field+ assert get_rows.call_args[1]["db_incremental_field_last_value"] == expected_watermark+ assert get_rows.call_args[1]["endpoint"] == "budget_performance_history"++ def test_credential_failures_are_reported_instead_of_retried_forever(self) -> None:+ errors = self.source.get_non_retryable_errors()++ assert all(message for message in errors.values())+ # Each key has to be a prefix of a message the transport actually raises, or the mapping+ # silently never matches.+ for key in errors:+ assert key.startswith(("AWS Budgets request failed: ", "AWS STS request failed: ", "AWS access key ID"))+++class TestCanonicalDescriptions:+ def test_every_documented_table_is_a_table_the_source_syncs(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS) <= set(ENDPOINTS)++ @pytest.mark.parametrize(+ "endpoint,columns",+ [+ (+ "budgets",+ set(+ normalize_budget(+ {+ "BudgetName": "b",+ "BudgetLimit": {},+ "CalculatedSpend": {"ActualSpend": {}, "ForecastedSpend": {}},+ "TimePeriod": {},+ "AutoAdjustData": {"HistoricalOptions": {}},+ "HealthStatus": {},+ "CostTypes": {},+ }+ )+ ),+ ),+ (+ "budget_performance_history",+ set(+ normalize_history_rows(+ BudgetRef(name="b", time_unit="MONTHLY"),+ {+ "BudgetPerformanceHistory": {+ "BudgetedAndActualAmountsList": [+ {"BudgetedAmount": {}, "ActualAmount": {}, "TimePeriod": {}}+ ]+ }+ },+ )[0]+ ),+ ),+ (+ "notifications",+ set(normalize_notification_rows(BudgetRef(name="b", time_unit="MONTHLY"), {"Notifications": [{}]})[0]),+ ),+ ],+ )+ def test_documented_columns_match_the_columns_the_source_emits(self, endpoint: str, columns: set[str]) -> None:+ # A renamed column would otherwise leave a description attached to a column that no longer+ # exists, and the real one silently undocumented.+ documented = set(CANONICAL_DESCRIPTIONS[endpoint].get("columns") or {})++ assert documented == columnsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsbudgets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsbudgets.pyindex 0ce0ad53de28..f900bd833248 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsbudgets.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsbudgets.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AwsBudgetsSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ aws_session_token: str | None = None