:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the aws glue data catalog import source (#110797)
Tom Owersba0ca660b715
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 134edaa89096..cfbbd06d59cf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -105,6 +105,7 @@ the row lists both.| aws_budgets | HTTP | requests | ✅ || aws_cost_anomaly_detection | HTTP | requests | ✅ || aws_cost_explorer | HTTP | requests | ✅ |+| aws_glue_data_catalog | HTTP | requests | ✅ || aws_organizations | HTTP | requests | ✅ || aws_ses | HTTP | requests | ✅ || azure_cost_management | HTTP | requests | ✅ |@@ -919,7 +920,6 @@ doesn't conflict with concurrent PRs.- aws_config- aws_connect- aws_cost_and_usage_report-- aws_glue_data_catalog- aws_guardduty- aws_health- aws_iam_access_analyzerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/aws_glue_data_catalog.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/aws_glue_data_catalog.pynew file mode 100644index 000000000000..1d7afe6a8f6e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/aws_glue_data_catalog.py@@ -0,0 +1,310 @@+from __future__ import annotations++import re+import json+from collections.abc import Iterator+from datetime import UTC, datetime+from typing import TYPE_CHECKING, 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_glue_data_catalog.settings import (+ BODY_RETRY_CODES,+ CONTENT_TYPE,+ ENDPOINTS,+ ERROR_MESSAGES,+ REQUEST_TIMEOUT_SECONDS,+ TARGET_PREFIXES,+ GlueEndpoint,+)+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.typings import SourceResponse++if TYPE_CHECKING:+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsgluedatacatalog import (+ AwsGlueDataCatalogSourceConfig,+ )+++TRANSPORT_RETRY = BoundedRetry(+ total=3,+ backoff_factor=1,+ status_forcelist=(429, 500, 502, 503, 504),+ allowed_methods=frozenset({"POST"}),+ raise_on_status=False,+)+_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")+_REGION_PATTERN = re.compile(r"(?:us-gov|[a-z]{2})-[a-z]+-\d+")+++@frozen+class AwsGlueDataCatalogResumeConfig:+ next_token: str | None = None+ completed: bool = False+++@frozen+class GluePage:+ items: list[dict[str, Any]]+ next_token: str | None+++class AwsGlueError(Exception):+ def __init__(self, code: str, message: str) -> None:+ self.code = code+ super().__init__(f"AWS Glue request failed: {code} - {message}")+++class AwsGlueRetryableError(AwsGlueError):+ pass+++def error_for_response(response: requests.Response) -> AwsGlueError:+ try:+ body = response.json()+ except ValueError:+ body = {}+ if not isinstance(body, dict):+ body = {}+ raw_code = response.headers.get("x-amzn-ErrorType") or body.get("__type") or body.get("code")+ code = str(raw_code or f"HTTP {response.status_code}").split(":", 1)[0].rsplit("#", 1)[-1]+ message = str(body.get("Message") or body.get("message") or response.text)[:500]+ # The transport handles HTTP retries. Only body-coded HTTP 400 failures need a separate retry.+ error_class = AwsGlueRetryableError if response.status_code == 400 and code in BODY_RETRY_CODES else AwsGlueError+ return error_class(code, message)+++class AwsGlueClient:+ def __init__(self, config: AwsGlueDataCatalogSourceConfig, api_version: str) -> None:+ if not config.aws_access_key_id or not config.aws_secret_access_key:+ raise ValueError("Enter both an AWS access key ID and a secret access key.")+ if not _REGION_PATTERN.fullmatch(config.aws_region):+ raise ValueError("Enter an AWS region such as us-east-1.")+ if api_version not in TARGET_PREFIXES:+ raise ValueError(f"Unsupported AWS Glue API version: {api_version}")+ self.region = config.aws_region+ suffix = "amazonaws.com.cn" if self.region.startswith("cn-") else "amazonaws.com"+ self.url = f"https://glue.{self.region}.{suffix}/"+ self.target_prefix = TARGET_PREFIXES[api_version]+ self.signer = SigV4Auth(+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),+ "glue",+ self.region,+ )+ self.session = make_tracked_session(+ retry=TRANSPORT_RETRY,+ redact_values=tuple(value for value in (config.aws_secret_access_key, config.aws_session_token) if value),+ )++ def close(self) -> None:+ self.session.close()++ @retry(+ retry=retry_if_exception_type(AwsGlueRetryableError),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:+ body = json.dumps(payload).encode("utf-8")+ request = AWSRequest(+ method="POST",+ url=self.url,+ data=body,+ headers={"Content-Type": CONTENT_TYPE, "X-Amz-Target": f"{self.target_prefix}.{operation}"},+ )+ self.signer.add_auth(request)+ response = self.session.post(+ self.url,+ data=body,+ headers=dict(request.headers),+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ )+ if response.status_code != 200:+ raise error_for_response(response)+ result = response.json()+ if not isinstance(result, dict):+ raise ValueError("AWS Glue returned an invalid response.")+ return result++ def pages(+ self,+ endpoint: GlueEndpoint,+ payload: dict[str, Any],+ start_token: str | None = None,+ ) -> Iterator[GluePage]:+ token = start_token+ while True:+ params = {"MaxResults": endpoint.page_size, **payload}+ if token:+ params["NextToken"] = token+ body = self.request(endpoint.operation, params)+ items = body[endpoint.result_key]+ if not isinstance(items, list) or any(not isinstance(item, dict) for item in items):+ raise ValueError("AWS Glue returned an invalid list response.")+ next_token = body.get("NextToken") or None+ if next_token is not None and not isinstance(next_token, str):+ raise ValueError("AWS Glue returned an invalid pagination token.")+ if next_token and next_token == token:+ raise ValueError("AWS Glue returned a repeated pagination token.")+ yield GluePage(items=items, next_token=next_token)+ if next_token is None:+ return+ token = next_token+++def normalize_row(endpoint: str, item: dict[str, Any], region: str, parent_payload: dict[str, Any]) -> dict[str, Any]:+ row = {_CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in item.items()}+ row["region"] = region+ for column in ENDPOINTS[endpoint].timestamp_columns:+ value = row.get(column)+ if isinstance(value, int | float) and not isinstance(value, bool):+ row[column] = datetime.fromtimestamp(value, tz=UTC)+ for key in ("DatabaseName", "TableName", "JobName", "CatalogId"):+ if key in parent_payload:+ row[_CAMEL_BOUNDARY.sub("_", key).lower()] = parent_payload[key]+ if endpoint == "partitions":+ # JSON preserves value boundaries, so different partition tuples cannot share a key.+ row["partition_values"] = json.dumps(item["Values"], ensure_ascii=False, separators=(",", ":"))+ return row+++def parent_payload(endpoint: str, parent: dict[str, Any]) -> dict[str, Any]:+ if endpoint == "job_runs":+ return {"JobName": parent["name"]}+ payload = {"DatabaseName": parent["name"] if endpoint == "tables" else parent["database_name"]}+ if parent.get("catalog_id"):+ payload["CatalogId"] = parent["catalog_id"]+ if endpoint == "partitions":+ payload["TableName"] = parent["name"]+ return payload+++def walk_rows(+ client: AwsGlueClient,+ endpoint: str,+ manager: ResumableSourceManager[AwsGlueDataCatalogResumeConfig],+ checkpoint: bool = False,+) -> Iterator[list[dict[str, Any]]]:+ spec = ENDPOINTS[endpoint]+ if spec.parent:+ for parents in walk_rows(client, spec.parent, manager):+ for parent in parents:+ payload = parent_payload(endpoint, parent)+ for page in client.pages(spec, payload):+ if page.items:+ yield [normalize_row(endpoint, item, client.region, payload) for item in page.items]+ manager.safe_point()+ return++ state = manager.load_state() if checkpoint and manager.can_resume() else None+ if state and state.completed:+ return+ for page in client.pages(spec, {}, start_token=state.next_token if state else None):+ rows = [normalize_row(endpoint, item, client.region, {}) for item in page.items]+ if checkpoint:+ manager.save_state(+ AwsGlueDataCatalogResumeConfig(next_token=page.next_token, completed=page.next_token is None)+ )+ if rows:+ yield rows+ manager.safe_point()+++def aws_glue_data_catalog_source(+ config: AwsGlueDataCatalogSourceConfig,+ endpoint: str,+ api_version: str,+ manager: ResumableSourceManager[AwsGlueDataCatalogResumeConfig],+) -> SourceResponse:+ if endpoint not in ENDPOINTS:+ raise ValueError(f"Unknown AWS Glue table: {endpoint}")+ spec = ENDPOINTS[endpoint]+ # Parent lists have no stable order. Dependent tables restart discovery after an interrupted sync.+ supports_resume = spec.parent is None++ def get_rows() -> Iterator[list[dict[str, Any]]]:+ client = AwsGlueClient(config, api_version)+ try:+ yield from walk_rows(client, endpoint, manager, checkpoint=supports_resume)+ finally:+ client.close()++ return SourceResponse(+ name=endpoint,+ items=get_rows,+ primary_keys=list(spec.primary_keys),+ sort_mode=None,+ supports_resume=supports_resume,+ on_complete=manager.clear_state if supports_resume else None,+ )+++def probe_endpoint(client: AwsGlueClient, endpoint: str) -> dict[str, Any] | None:+ spec = ENDPOINTS[endpoint]+ payload: dict[str, Any] = {}+ if spec.parent:+ parent = probe_endpoint(client, spec.parent)+ if parent is None:+ return None+ payload = parent_payload(endpoint, parent)+ body = client.request(spec.operation, {**payload, "MaxResults": 1})+ items = body.get(spec.result_key) or []+ return normalize_row(endpoint, items[0], client.region, payload) if items else None+++def validate_credentials(+ config: AwsGlueDataCatalogSourceConfig, api_version: str, schema_name: str | None = None+) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in ENDPOINTS:+ return False, f"Unknown AWS Glue table: {schema_name}"+ try:+ client = AwsGlueClient(config, api_version)+ except ValueError as error:+ return False, str(error)+ try:+ probe_endpoint(client, schema_name or "databases")+ return True, None+ except AwsGlueError as error:+ if schema_name is None and error.code in {"AccessDenied", "AccessDeniedException"}:+ return True, None+ return False, ERROR_MESSAGES.get(+ error.code, "AWS Glue could not verify access. Try again after checking AWS service status."+ )+ except requests.RequestException:+ return False, "Could not connect to AWS Glue. Check the region and try again."+ finally:+ client.close()+++def probe_endpoint_permissions(+ config: AwsGlueDataCatalogSourceConfig, api_version: str, endpoints: list[str]+) -> dict[str, str | None]:+ try:+ client = AwsGlueClient(config, api_version)+ except ValueError as error:+ return dict.fromkeys(endpoints, str(error))+ permissions: dict[str, str | None] = {}+ try:+ for endpoint in endpoints:+ if endpoint not in ENDPOINTS:+ continue+ permissions[endpoint] = None+ try:+ probe_endpoint(client, endpoint)+ except AwsGlueError as error:+ permissions[endpoint] = ERROR_MESSAGES.get(error.code)+ except requests.RequestException:+ pass+ return permissions+ finally:+ client.close()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/canonical_descriptions.pynew file mode 100644index 000000000000..57f372949e48--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/canonical_descriptions.py@@ -0,0 +1,94 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "databases": {+ "description": "Databases in the account's default AWS Glue Data Catalog in the selected region.",+ "docs_url": "https://docs.aws.amazon.com/glue/latest/webapi/API_Database.html",+ "columns": {+ "name": "Database name within the catalog.",+ "catalog_id": "Identifier of the Data Catalog that contains the database.",+ "description": "Description of the database.",+ "location_uri": "Location of the database, such as an HDFS path.",+ "create_time": "Time when the database was created.",+ "parameters": "Database properties defined by the user.",+ "region": "AWS region selected for this source.",+ },+ },+ "tables": {+ "description": "Table definitions in the catalog, including column schemas and storage settings.",+ "docs_url": "https://docs.aws.amazon.com/glue/latest/webapi/API_Table.html",+ "columns": {+ "name": "Table name within the database.",+ "database_name": "Name of the database that contains the table.",+ "catalog_id": "Identifier of the Data Catalog that contains the table.",+ "table_type": "Type of table, such as EXTERNAL_TABLE or VIRTUAL_VIEW.",+ "storage_descriptor": "Physical storage settings, including columns, location, and data formats.",+ "partition_keys": "Columns that define the table partitions, in partition order.",+ "create_time": "Time when the table was created.",+ "update_time": "Time when the table was last updated.",+ "region": "AWS region selected for this source.",+ },+ },+ "partitions": {+ "description": "Partitions of catalog tables, with their values and storage settings.",+ "docs_url": "https://docs.aws.amazon.com/glue/latest/webapi/API_Partition.html",+ "columns": {+ "database_name": "Name of the database that contains the partition.",+ "table_name": "Name of the table that contains the partition.",+ "catalog_id": "Identifier of the Data Catalog that contains the partition.",+ "values": "Partition values in the order of the table's partition keys.",+ "partition_values": "JSON representation of the ordered partition values, used as part of the primary key.",+ "creation_time": "Time when the partition was created.",+ "storage_descriptor": "Physical storage settings for the partition.",+ "region": "AWS region selected for this source.",+ },+ },+ "jobs": {+ "description": "AWS Glue job definitions and their execution settings.",+ "docs_url": "https://docs.aws.amazon.com/glue/latest/webapi/API_Job.html",+ "columns": {+ "name": "Name of the job.",+ "role": "IAM role associated with the job.",+ "command": "Command that runs the job, including its script location.",+ "created_on": "Time when the job was created.",+ "last_modified_on": "Time when the job definition was last updated.",+ "glue_version": "Glue runtime version for the job.",+ "worker_type": "Type of worker allocated to the job.",+ "number_of_workers": "Number of workers allocated to the job.",+ "region": "AWS region selected for this source.",+ },+ },+ "job_runs": {+ "description": "Execution records for each Glue job, including status, timing, and resource usage.",+ "docs_url": "https://docs.aws.amazon.com/glue/latest/webapi/API_JobRun.html",+ "columns": {+ "id": "Identifier of the job run.",+ "job_name": "Name of the job that produced this run.",+ "job_run_state": "Current state of the run.",+ "started_on": "Time when the run started.",+ "completed_on": "Time when the run completed.",+ "last_modified_on": "Time when the run was last modified.",+ "execution_time": "Time in seconds that the run consumed resources.",+ "dpu_seconds": "Total DPU usage in seconds for supported job types.",+ "error_message": "Error message associated with the run.",+ "region": "AWS region selected for this source.",+ },+ },+ "crawlers": {+ "description": "Crawler definitions, their current state, and details of the latest crawl.",+ "docs_url": "https://docs.aws.amazon.com/glue/latest/webapi/API_Crawler.html",+ "columns": {+ "name": "Name of the crawler.",+ "database_name": "Database where the crawler stores its results.",+ "role": "IAM role used by the crawler.",+ "state": "Current state of the crawler.",+ "targets": "Data stores that the crawler scans.",+ "last_crawl": "Details of the crawler's latest execution.",+ "creation_time": "Time when the crawler was created.",+ "last_updated": "Time when the crawler was last updated.",+ "region": "AWS region selected for this source.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/settings.pynew file mode 100644index 000000000000..f4676ae88b11--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/settings.py@@ -0,0 +1,92 @@+from posthog.dataclasses import frozen++GLUE_API_VERSION = "2017-03-31"+TARGET_PREFIXES = {GLUE_API_VERSION: "AWSGlue"}+CONTENT_TYPE = "application/x-amz-json-1.1"+REQUEST_TIMEOUT_SECONDS = 60+++@frozen+class GlueEndpoint:+ operation: str+ result_key: str+ primary_keys: tuple[str, ...]+ parent: str | None = None+ page_size: int = 100+ timestamp_columns: tuple[str, ...] = ()+++ENDPOINTS: dict[str, GlueEndpoint] = {+ "databases": GlueEndpoint(+ operation="GetDatabases",+ result_key="DatabaseList",+ primary_keys=("region", "name"),+ timestamp_columns=("create_time",),+ ),+ "tables": GlueEndpoint(+ operation="GetTables",+ result_key="TableList",+ primary_keys=("region", "database_name", "name"),+ parent="databases",+ timestamp_columns=("create_time", "update_time", "last_access_time", "last_analyzed_time"),+ ),+ "partitions": GlueEndpoint(+ operation="GetPartitions",+ result_key="Partitions",+ primary_keys=("region", "database_name", "table_name", "partition_values"),+ parent="tables",+ timestamp_columns=("creation_time", "last_access_time", "last_analyzed_time"),+ ),+ "jobs": GlueEndpoint(+ operation="GetJobs",+ result_key="Jobs",+ primary_keys=("region", "name"),+ timestamp_columns=("created_on", "last_modified_on"),+ ),+ "job_runs": GlueEndpoint(+ operation="GetJobRuns",+ result_key="JobRuns",+ primary_keys=("region", "job_name", "id"),+ parent="jobs",+ timestamp_columns=("started_on", "last_modified_on", "completed_on"),+ ),+ "crawlers": GlueEndpoint(+ operation="GetCrawlers",+ result_key="Crawlers",+ primary_keys=("region", "name"),+ timestamp_columns=("creation_time", "last_updated"),+ ),+}++ENDPOINT_DESCRIPTIONS = {+ "databases": "Databases in the account's default Data Catalog.",+ "tables": "Table definitions, columns, and storage metadata for each database.",+ "partitions": "Partition values and storage metadata for each table.",+ "jobs": "Job definitions and execution settings.",+ "job_runs": "Job execution history, status, duration, and resource usage.",+ "crawlers": "Crawler settings, state, and the latest crawl result.",+}++ERROR_MESSAGES = {+ "AccessDeniedException": "AWS denied access. Grant the required Glue read permissions and check Lake Formation permissions.",+ "AccessDenied": "AWS denied access. Grant the required Glue read permissions and check Lake Formation permissions.",+ "UnrecognizedClientException": "AWS rejected the credentials. Check the access key ID, secret access key, and session token.",+ "InvalidClientTokenId": "AWS rejected the access key ID. Check that the key is active.",+ "SignatureDoesNotMatch": "AWS rejected the signature. Enter the correct secret access key.",+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and session token.",+ "ExpiredTokenException": "The AWS session token expired. Enter new credentials.",+ "ExpiredToken": "The AWS session token expired. Enter new credentials.",+ "OptInRequired": "Enable AWS Glue for this account and region, then reconnect.",+ "SubscriptionRequiredException": "Enable AWS Glue for this account and region, then reconnect.",+ "SubscriptionRequired": "Enable AWS Glue for this account and region, then reconnect.",+}++BODY_RETRY_CODES = frozenset(+ {+ "ThrottlingException",+ "Throttling",+ "TooManyRequestsException",+ "OperationTimeoutException",+ "FederationSourceRetryableException",+ }+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/source.pyindex fa8e2c300a0f..da5259e99730 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/source.py@@ -1,8 +1,35 @@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_glue_data_catalog.aws_glue_data_catalog import (+ AwsGlueDataCatalogResumeConfig,+ aws_glue_data_catalog_source,+ probe_endpoint_permissions,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_glue_data_catalog.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ ERROR_MESSAGES,+ GLUE_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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsgluedatacatalog import (AwsGlueDataCatalogSourceConfig,)@@ -10,18 +37,123 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwsGlueDataCatalogSource(SimpleSource[AwsGlueDataCatalogSourceConfig]):+class AwsGlueDataCatalogSource(ResumableSource[AwsGlueDataCatalogSourceConfig, AwsGlueDataCatalogResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = (GLUE_API_VERSION,)+ default_version = GLUE_API_VERSION+ api_docs_url = "https://docs.aws.amazon.com/glue/latest/webapi/API_Operations.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AWSGLUEDATACATALOG+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {f"AWS Glue request failed: {code}": message for code, message in ERROR_MESSAGES.items()}++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_glue_data_catalog.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AwsGlueDataCatalogSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, {}, names, descriptions=ENDPOINT_DESCRIPTIONS)++ def validate_credentials(+ self,+ config: AwsGlueDataCatalogSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(config, self.resolve_api_version(api_version), schema_name)++ def get_endpoint_permissions(+ self,+ config: AwsGlueDataCatalogSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ return probe_endpoint_permissions(config, self.resolve_api_version(api_version), endpoints)++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[AwsGlueDataCatalogResumeConfig]:+ return ResumableSourceManager(inputs, AwsGlueDataCatalogResumeConfig)++ def source_for_pipeline(+ self,+ config: AwsGlueDataCatalogSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwsGlueDataCatalogResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aws_glue_data_catalog_source(+ config, inputs.schema_name, self.resolve_api_version(inputs.api_version), resumable_source_manager+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.AWSGLUEDATACATALOG,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Amazon Web Services (AWS Glue)",+ label="AWS Glue Data Catalog",+ caption=(+ "Sync catalog metadata, job history, and crawlers from one AWS region. "+ "Grant `glue:GetDatabases`, `glue:GetTables`, and `glue:GetPartitions` for catalog tables. "+ "Grant `glue:GetJobs`, `glue:GetJobRuns`, and `glue:GetCrawlers` for jobs and crawlers. "+ "Lake Formation permissions can also restrict catalog access. "+ "Enter the access key ID and secret access key. Add a session token for temporary credentials."+ ),iconPath="/static/services/aws_glue_data_catalog.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/aws-glue-data-catalog",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["aws", "glue", "data catalog", "etl"],+ 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="Temporary credentials expire. Replace them before the next scheduled sync.",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="aws_region",+ label="AWS region",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="us-east-1",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/tests/test_aws_glue_data_catalog.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/tests/test_aws_glue_data_catalog.pynew file mode 100644index 000000000000..f4a0d1991027--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_glue_data_catalog/tests/test_aws_glue_data_catalog.py@@ -0,0 +1,409 @@+import json+from collections.abc import Iterable+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest.mock import Mock, patch++import requests+from tenacity import wait_none++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_glue_data_catalog import (+ aws_glue_data_catalog as glue,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_glue_data_catalog.settings import (+ ENDPOINTS,+ GLUE_API_VERSION,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_glue_data_catalog.source import (+ AwsGlueDataCatalogSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsgluedatacatalog import (+ AwsGlueDataCatalogSourceConfig,+)+++def config(region: str = "eu-west-1", token: str | None = None) -> AwsGlueDataCatalogSourceConfig:+ return AwsGlueDataCatalogSourceConfig(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="example-secret",+ aws_session_token=token,+ aws_region=region,+ )+++def response(body: object, 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 manager(state: glue.AwsGlueDataCatalogResumeConfig | None = None) -> Mock:+ result = Mock(spec=ResumableSourceManager)+ result.can_resume.return_value = state is not None+ result.load_state.return_value = state+ return result+++ "region,token,host",+ [+ ("eu-west-1", None, "glue.eu-west-1.amazonaws.com"),+ ("cn-north-1", "example-token", "glue.cn-north-1.amazonaws.com.cn"),+ ("us-gov-west-1", "example-token", "glue.us-gov-west-1.amazonaws.com"),+ ],+)+def test_signed_request_uses_tracked_transport(region: str, token: str | None, host: str) -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ session = factory.return_value+ session.post.return_value = response({"DatabaseList": []})+ client = glue.AwsGlueClient(config(region, token), GLUE_API_VERSION)+ assert client.request("GetDatabases", {"MaxResults": 1}) == {"DatabaseList": []}++ args, kwargs = session.post.call_args+ assert args == (f"https://{host}/",)+ assert json.loads(kwargs["data"]) == {"MaxResults": 1}+ headers = kwargs["headers"]+ assert headers["X-Amz-Target"] == "AWSGlue.GetDatabases"+ assert headers["Content-Type"] == "application/x-amz-json-1.1"+ assert f"/{region}/glue/aws4_request" in headers["Authorization"]+ assert "SignedHeaders=content-type;host;x-amz-date" in headers["Authorization"]+ assert headers["X-Amz-Date"]+ assert headers.get("X-Amz-Security-Token") == token+ assert kwargs["allow_redirects"] is False+ assert kwargs["timeout"] == 60+ redacted = factory.call_args.kwargs["redact_values"]+ assert "example-secret" in redacted+ if token:+ assert token in redacted+ retry_policy = factory.call_args.kwargs["retry"]+ assert retry_policy.is_retry("POST", 429)+ assert retry_policy.is_retry("POST", 503)+ assert not retry_policy.is_retry("POST", 403)+++ "region,version,expected",+ [+ ("eu-west-1.example.com/path", GLUE_API_VERSION, "Enter an AWS region"),+ ("", GLUE_API_VERSION, "Enter an AWS region"),+ ("eu-west-1", "2099-01-01", "Unsupported AWS Glue API version"),+ ],+)+def test_rejects_invalid_region_or_version_before_http(region: str, version: str, expected: str) -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ with pytest.raises(ValueError, match=expected):+ glue.AwsGlueClient(config(region), version)+ factory.assert_not_called()++[email protected]("terminal_token", [None, ""])+def test_pagination_includes_empty_and_terminal_pages(terminal_token: str | None) -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ session = factory.return_value+ session.post.side_effect = [+ response({"DatabaseList": [], "NextToken": "second"}),+ response({"DatabaseList": [{"Name": "analytics"}], "NextToken": terminal_token}),+ ]+ client = glue.AwsGlueClient(config(), GLUE_API_VERSION)+ pages = list(client.pages(ENDPOINTS["databases"], {}))++ assert [page.items for page in pages] == [[], [{"Name": "analytics"}]]+ assert [json.loads(call.kwargs["data"]) for call in session.post.call_args_list] == [+ {"MaxResults": 100},+ {"MaxResults": 100, "NextToken": "second"},+ ]+++ "payload,error",+ [+ ({"DatabaseList": [], "NextToken": "same"}, "repeated pagination token"),+ ({"DatabaseList": [], "NextToken": 123}, "invalid pagination token"),+ ({"DatabaseList": "bad"}, "invalid list response"),+ ({"DatabaseList": ["bad"]}, "invalid list response"),+ ],+)+def test_rejects_malformed_pages(payload: dict[str, Any], error: str) -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ factory.return_value.post.return_value = response(payload)+ client = glue.AwsGlueClient(config(), GLUE_API_VERSION)+ with pytest.raises(ValueError, match=error):+ list(client.pages(ENDPOINTS["databases"], {}, start_token="same"))+++ "status,body,headers,code,retryable",+ [+ (+ 400,+ {"__type": "com.amazonaws.glue#AccessDeniedException", "Message": "Access denied"},+ {},+ "AccessDeniedException",+ False,+ ),+ (400, {"__type": "ThrottlingException"}, {}, "ThrottlingException", True),+ (400, {"__type": "OperationTimeoutException"}, {}, "OperationTimeoutException", True),+ (500, {"__type": "ThrottlingException"}, {}, "ThrottlingException", False),+ (429, {}, {}, "HTTP 429", False),+ (403, {}, {"x-amzn-ErrorType": "InvalidSignatureException:detail"}, "InvalidSignatureException", False),+ (502, ["unexpected"], {}, "HTTP 502", False),+ ],+)+def test_error_classification(status: int, body: object, headers: dict[str, str], code: str, retryable: bool) -> None:+ error = glue.error_for_response(response(body, status, headers))+ assert error.code == code+ assert isinstance(error, glue.AwsGlueRetryableError) is retryable++[email protected]("status,attempts", [(400, 2), (429, 1), (500, 1)])+def test_body_retry_does_not_repeat_transport_retries(status: int, attempts: int) -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ session = factory.return_value+ session.post.side_effect = [+ response({"__type": "ThrottlingException"}, status),+ response({"DatabaseList": []}),+ ]+ client = glue.AwsGlueClient(config(), GLUE_API_VERSION)+ request = cast(Any, client.request).retry_with(wait=wait_none())+ if status == 400:+ assert request(client, "GetDatabases", {}) == {"DatabaseList": []}+ else:+ with pytest.raises(glue.AwsGlueError):+ request(client, "GetDatabases", {})+ assert session.post.call_count == attempts+++ "endpoint,result_key", [("databases", "DatabaseList"), ("jobs", "Jobs"), ("crawlers", "Crawlers")]+)+def test_top_level_resume_checkpoints_before_yield_and_clears_after_completion(endpoint: str, result_key: str) -> None:+ resume = manager(glue.AwsGlueDataCatalogResumeConfig(next_token="saved"))+ with patch.object(glue, "make_tracked_session") as factory:+ session = factory.return_value+ session.post.return_value = response({result_key: [{"Name": "example"}]})+ source = glue.aws_glue_data_catalog_source(config(), endpoint, GLUE_API_VERSION, resume)+ batches = iter(cast(Iterable[list[dict[str, Any]]], source.items()))+ assert next(batches)[0]["name"] == "example"+ resume.save_state.assert_called_once_with(glue.AwsGlueDataCatalogResumeConfig(completed=True))+ resume.clear_state.assert_not_called()+ assert list(batches) == []+ session.close.assert_called_once()+ assert json.loads(session.post.call_args.kwargs["data"]) == {"MaxResults": 100, "NextToken": "saved"}+ assert source.on_complete is not None+ source.on_complete()+ resume.clear_state.assert_called_once()+++def test_completed_resume_does_not_restart_and_empty_pages_reach_safe_points() -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ resume = manager(glue.AwsGlueDataCatalogResumeConfig(completed=True))+ source = glue.aws_glue_data_catalog_source(config(), "databases", GLUE_API_VERSION, resume)+ assert list(cast(Iterable[Any], source.items())) == []+ factory.return_value.post.assert_not_called()++ resume = manager()+ factory.return_value.post.side_effect = [+ response({"DatabaseList": [], "NextToken": "more"}),+ response({"DatabaseList": []}),+ ]+ source = glue.aws_glue_data_catalog_source(config(), "databases", GLUE_API_VERSION, resume)+ assert list(cast(Iterable[Any], source.items())) == []+ assert resume.safe_point.call_count == 2+ assert [call.args[0] for call in resume.save_state.call_args_list] == [+ glue.AwsGlueDataCatalogResumeConfig(next_token="more"),+ glue.AwsGlueDataCatalogResumeConfig(completed=True),+ ]+++def test_partition_walk_pages_each_parent_and_preserves_table_wide_keys() -> None:+ resume = manager(glue.AwsGlueDataCatalogResumeConfig(next_token="irrelevant"))+ with patch.object(glue, "make_tracked_session") as factory:+ session = factory.return_value+ session.post.side_effect = [+ response({"DatabaseList": [{"Name": "first", "CatalogId": "123456789012"}], "NextToken": "db-page"}),+ response({"TableList": [{"Name": "events"}], "NextToken": "table-page"}),+ response({"Partitions": [{"Values": ["a,b", "c"]}], "NextToken": "partition-page"}),+ response({"Partitions": [{"Values": ["a", "b,c"]}]}),+ response({"TableList": [{"Name": "users"}]}),+ response({"Partitions": []}),+ response({"DatabaseList": [{"Name": "second", "CatalogId": "123456789012"}]}),+ response({"TableList": [{"Name": "events"}]}),+ response({"Partitions": [{"Values": ["a,b", "c"]}]}),+ ]+ source = glue.aws_glue_data_catalog_source(config(), "partitions", GLUE_API_VERSION, resume)+ rows = [row for batch in cast(Iterable[list[dict[str, Any]]], source.items()) for row in batch]++ assert len(rows) == 3+ assert source.primary_keys is not None+ assert len({tuple(row[key] for key in source.primary_keys) for row in rows}) == 3+ assert all(row["catalog_id"] == "123456789012" and row["region"] == "eu-west-1" for row in rows)+ payloads = [json.loads(call.kwargs["data"]) for call in session.post.call_args_list]+ assert payloads[0] == {"MaxResults": 100}+ assert payloads[1] == {"MaxResults": 100, "DatabaseName": "first", "CatalogId": "123456789012"}+ assert payloads[3] == {+ "MaxResults": 100,+ "DatabaseName": "first",+ "TableName": "events",+ "CatalogId": "123456789012",+ "NextToken": "partition-page",+ }+ assert payloads[4]["NextToken"] == "table-page"+ assert payloads[6] == {"MaxResults": 100, "NextToken": "db-page"}+ assert payloads[8]["DatabaseName"] == "second"+ assert "NextToken" not in payloads[8]+ assert not source.supports_resume+ resume.can_resume.assert_not_called()+ resume.save_state.assert_not_called()+ session.close.assert_called_once()+++def test_job_run_full_refresh_keeps_old_runs_and_namespaces_ids_by_job() -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ session = factory.return_value+ session.post.side_effect = [+ response({"Jobs": [{"Name": "first"}, {"Name": "second"}]}),+ response({"JobRuns": [{"Id": "run-1", "StartedOn": 1735689600}], "NextToken": "older"}),+ response({"JobRuns": [{"Id": "run-0", "StartedOn": 0}]}),+ response({"JobRuns": [{"Id": "run-1", "StartedOn": 0}]}),+ ]+ source = glue.aws_glue_data_catalog_source(config(), "job_runs", GLUE_API_VERSION, manager())+ rows = [row for batch in cast(Iterable[list[dict[str, Any]]], source.items()) for row in batch]+ assert [(row["job_name"], row["id"]) for row in rows] == [+ ("first", "run-1"),+ ("first", "run-0"),+ ("second", "run-1"),+ ]+ assert rows[0]["started_on"] == datetime(2025, 1, 1, tzinfo=UTC)+ assert rows[1]["started_on"] == datetime(1970, 1, 1, tzinfo=UTC)+ assert [json.loads(call.kwargs["data"]) for call in session.post.call_args_list] == [+ {"MaxResults": 100},+ {"MaxResults": 100, "JobName": "first"},+ {"MaxResults": 100, "JobName": "first", "NextToken": "older"},+ {"MaxResults": 100, "JobName": "second"},+ ]++[email protected]("value", [None, False, "2025-01-01T00:00:00Z", 1735689600])+def test_normalization_preserves_nested_columns_and_handles_optional_timestamps(value: object) -> None:+ descriptor = {"Columns": [{"Name": "event_name", "Type": "string"}]}+ row = glue.normalize_row(+ "tables",+ {"Name": "events", "CreateTime": value, "StorageDescriptor": descriptor},+ "eu-west-1",+ {"DatabaseName": "analytics"},+ )+ assert row["storage_descriptor"] == descriptor+ assert row["database_name"] == "analytics"+ assert row["create_time"] == (datetime(2025, 1, 1, tzinfo=UTC) if value == 1735689600 else value)++[email protected]("schema_name", [None, "databases"])+ "code",+ [+ "AccessDenied",+ "AccessDeniedException",+ "UnrecognizedClientException",+ "InvalidSignatureException",+ "ExpiredTokenException",+ "SubscriptionRequiredException",+ ],+)+def test_validation_maps_errors_and_accepts_create_time_permission_denials(schema_name: str | None, code: str) -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ factory.return_value.post.return_value = response({"__type": code, "Message": "Request denied"}, 403)+ valid, reason = glue.validate_credentials(config(), GLUE_API_VERSION, schema_name)+ accepted = schema_name is None and code in {"AccessDenied", "AccessDeniedException"}+ assert valid is accepted+ if accepted:+ assert reason is None+ else:+ assert reason+ error = glue.error_for_response(response({"__type": code}, 403))+ mappings = AwsGlueDataCatalogSource().get_non_retryable_errors()+ assert any(pattern in str(error) and message == reason for pattern, message in mappings.items())+ factory.return_value.close.assert_called_once()+++def test_creation_probes_once_and_selected_child_checks_parent_and_child() -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ session = factory.return_value+ session.post.return_value = response({"DatabaseList": []})+ assert glue.validate_credentials(config(), GLUE_API_VERSION) == (True, None)+ assert session.post.call_count == 1+ assert json.loads(session.post.call_args.kwargs["data"]) == {"MaxResults": 1}++ session.reset_mock()+ session.post.side_effect = [+ response({"Jobs": [{"Name": "example"}]}),+ response({"__type": "AccessDeniedException"}, 403),+ ]+ valid, reason = glue.validate_credentials(config(), GLUE_API_VERSION, "job_runs")+ assert not valid and reason+ assert json.loads(session.post.call_args.kwargs["data"]) == {"MaxResults": 1, "JobName": "example"}++[email protected]("endpoint", ["tables", "partitions", "job_runs"])+def test_probe_with_no_parents_makes_no_child_request(endpoint: str) -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ factory.return_value.post.return_value = response({"Jobs": [], "DatabaseList": []})+ assert glue.validate_credentials(config(), GLUE_API_VERSION, endpoint) == (True, None)+ assert factory.return_value.post.call_count == 1+++def test_invalid_config_and_unknown_tables_fail_without_requests() -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ invalid = config()+ invalid.aws_secret_access_key = ""+ assert glue.validate_credentials(invalid, GLUE_API_VERSION) == (+ False,+ "Enter both an AWS access key ID and a secret access key.",+ )+ assert glue.validate_credentials(config(), GLUE_API_VERSION, "unknown") == (+ False,+ "Unknown AWS Glue table: unknown",+ )+ with pytest.raises(ValueError, match="Unknown AWS Glue table"):+ glue.aws_glue_data_catalog_source(config(), "unknown", GLUE_API_VERSION, manager())+ factory.assert_not_called()+++def test_network_validation_error_and_failed_iteration_close_session() -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ session = factory.return_value+ session.post.side_effect = requests.Timeout("example timeout")+ assert glue.validate_credentials(config(), GLUE_API_VERSION) == (+ False,+ "Could not connect to AWS Glue. Check the region and try again.",+ )+ session.close.assert_called_once()+ session.reset_mock()+ source = glue.aws_glue_data_catalog_source(config(), "databases", GLUE_API_VERSION, manager())+ with pytest.raises(requests.Timeout):+ list(cast(Iterable[Any], source.items()))+ session.close.assert_called_once()+++ "error", [glue.AwsGlueError("InternalServiceException", "example"), requests.Timeout("example")]+)+def test_permission_probes_do_not_hide_tables_on_transient_failures(error: Exception) -> None:+ with patch.object(glue, "make_tracked_session"), patch.object(glue.AwsGlueClient, "request", side_effect=error):+ assert glue.probe_endpoint_permissions(config(), GLUE_API_VERSION, ["databases", "unknown"]) == {+ "databases": None+ }+++def test_permission_probe_reports_denial_and_invalid_config() -> None:+ with patch.object(glue, "make_tracked_session") as factory:+ factory.return_value.post.return_value = response({"__type": "AccessDeniedException"}, 403)+ permissions = glue.probe_endpoint_permissions(config(), GLUE_API_VERSION, ["databases"])+ assert permissions["databases"] and "Grant" in permissions["databases"]+ assert glue.probe_endpoint_permissions(config("bad"), GLUE_API_VERSION, ["jobs"]) == {+ "jobs": "Enter an AWS region such as us-east-1."+ }diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsgluedatacatalog.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsgluedatacatalog.pyindex d6c2a06040ee..346138352273 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsgluedatacatalog.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsgluedatacatalog.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AwsGlueDataCatalogSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ aws_region: str+ aws_session_token: str | None = None