Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement the astronomer (astro) import source (#112202)

Tom Owersb901a5ee0aa8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 3c1d282b0e74..3d7e17be5b96 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -96,6 +96,7 @@ the row lists both.
| ashby | HTTP | requests | ✅ |
| asknicely | HTTP | requests | ✅ |
| assemblyai | HTTP | requests | ✅ |
+| astronomer | HTTP | requests | ✅ |
| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ |
| attio | HTTP | requests + `rest_source.RESTClient` | ✅ |
| automox | HTTP | requests | ✅ |
@@ -961,7 +962,6 @@ doesn't conflict with concurrent PRs.
- appwrite
- arxiv
- asknicely
-- astronomer
- athenahealth
- atlan
- audiogo
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/astronomer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/astronomer.py
new file mode 100644
index 000000000000..d3f647fbeae1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/astronomer.py
@@ -0,0 +1,171 @@
+import re
+from typing import Any
+
+from requests.exceptions import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.astronomer.settings import (
+ AUTH_ERROR,
+ BASE_URL,
+ ENDPOINTS,
+ PAGE_SIZE,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ rename_parent_fields,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+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 schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.astronomer import (
+ AstronomerSourceConfig,
+)
+
+
+@frozen
+class AstronomerResumeConfig:
+ paginator_state: dict[str, Any]
+
+
+def organization_path(organization_id: str) -> str:
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", organization_id):
+ raise ValueError("Enter the Astronomer organization ID, not a URL.")
+ return f"organizations/{organization_id}/"
+
+
+def validate_credentials(config: AstronomerSourceConfig, schema_name: str | None = None) -> tuple[bool, str | None]:
+ try:
+ prefix = organization_path(config.organization_id)
+ except ValueError as error:
+ return False, str(error)
+
+ name = schema_name or "deployments"
+ endpoint = schema_for_resource(ENDPOINTS, name)
+ client = RESTClient(
+ base_url=BASE_URL,
+ auth=BearerTokenAuth(token=config.api_token),
+ paginator=SinglePagePaginator(),
+ allow_redirects=False,
+ request_timeout=(10, 60),
+ )
+ permission = endpoint["permission"]
+ try:
+ if name == "deploys":
+ permission = ENDPOINTS["deployments"]["permission"]
+ parents = next(
+ client.paginate(path=prefix + "deployments", params={"limit": 1}, data_selector="deployments")
+ )
+ if not parents:
+ return True, None
+ path = endpoint["path"].format(deployment_id=parents[0]["id"])
+ permission = endpoint["permission"]
+ else:
+ path = endpoint["path"]
+ next(client.paginate(path=prefix + path, params={"limit": 1}, data_selector=name))
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status == 401:
+ return False, AUTH_ERROR
+ if status == 403:
+ if schema_name is None:
+ return True, None
+ return False, f"Astronomer denied access. Grant `{permission}` to the API token."
+ if status == 404:
+ return False, "Astronomer could not find the resource. Check the organization ID and the token permissions."
+ raise
+ return True, None
+
+
+def warehouse_row(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ key: value
+ for key, value in row.items()
+ if key not in {"environmentVariables", "bundleUploadUrl", "dagsUploadUrl"}
+ }
+
+
+def endpoint_resource(name: str, prefix: str) -> EndpointResource:
+ endpoint = schema_for_resource(ENDPOINTS, name)
+ request: Endpoint = {
+ "path": prefix + endpoint["path"],
+ "data_selector": name,
+ "data_selector_required": True,
+ "params": {"sorts": "createdAt:asc"},
+ }
+ resource: EndpointResource = {
+ "name": name,
+ "table_name": name,
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": request,
+ "data_map": warehouse_row,
+ }
+ if name == "deploys":
+ resource["include_from_parent"] = ["id"]
+ request["params"] = {"deployment_id": {"type": "resolve", "resource": "deployments", "field": "id"}}
+ return resource
+
+
+def astronomer_source(
+ config: AstronomerSourceConfig,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AstronomerResumeConfig],
+) -> SourceResponse:
+ settings = schema_for_resource(ENDPOINTS, endpoint)
+ prefix = organization_path(config.organization_id)
+ resource = endpoint_resource(endpoint, prefix)
+ resources: list[str | EndpointResource] = [resource]
+ if endpoint == "deploys":
+ resources.insert(0, endpoint_resource("deployments", prefix))
+
+ api_config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ "auth": {"type": "bearer", "token": config.api_token},
+ "allow_redirects": False,
+ "request_timeout": (10, 60),
+ "paginator": {"type": "offset", "limit": PAGE_SIZE, "total_path": "totalCount"},
+ },
+ "resources": resources,
+ }
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(AstronomerResumeConfig(paginator_state=state))
+
+ built = rest_api_resources(
+ api_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.paginator_state if resume else None,
+ )
+ result = next(item for item in built if item.name == endpoint)
+ if endpoint == "deploys":
+ result.add_map(rename_parent_fields("deployments", {"id": "deploymentId"}))
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: result,
+ primary_keys=settings["primary_keys"],
+ partition_mode="datetime",
+ partition_keys=["createdAt"],
+ partition_format="month",
+ sort_mode=None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/canonical_descriptions.py
new file mode 100644
index 000000000000..332e8c4c172d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/canonical_descriptions.py
@@ -0,0 +1,54 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "deployments": {
+ "description": "Airflow environments in an Astro organization.",
+ "docs_url": "https://www.astronomer.io/docs/astro/api/v-1/api-reference/deployment/list-deployments",
+ "columns": {
+ "id": "The identifier of the deployment.",
+ "name": "The deployment name.",
+ "createdAt": "The time when the deployment was created, in UTC.",
+ "updatedAt": "The time when the deployment was last updated, in UTC.",
+ },
+ },
+ "deploys": {
+ "description": "Code and image deploys for each Astro deployment.",
+ "docs_url": "https://www.astronomer.io/docs/astro/api/v-1/api-reference/deploy/list-deploys",
+ "columns": {
+ "id": "The identifier of the deploy.",
+ "deploymentId": "The identifier of the deployment that received the deploy.",
+ "createdAt": "The time when the deploy was created, in UTC.",
+ "status": "The deploy status: INITIALIZED, DEPLOYED, or FAILED.",
+ "type": "The deploy type: IMAGE_AND_DAG, IMAGE_ONLY, or DAG_ONLY.",
+ "airflowVersion": "The Airflow version used by the deploy.",
+ "astroRuntimeVersion": "The Astro Runtime version used by the deploy.",
+ "imageTag": "The image tag for the deploy.",
+ },
+ },
+ "workspaces": {
+ "description": "Groups of deployments in an Astro organization.",
+ "docs_url": "https://www.astronomer.io/docs/astro/api/api-reference/workspace/list-workspaces",
+ "columns": {
+ "id": "The identifier of the workspace.",
+ "name": "The workspace name.",
+ "organizationId": "The identifier of the organization that owns the workspace.",
+ "createdAt": "The time when the workspace was created, in UTC.",
+ "updatedAt": "The time when the workspace was last updated, in UTC.",
+ },
+ },
+ "clusters": {
+ "description": "Kubernetes clusters that host Astro deployments.",
+ "docs_url": "https://www.astronomer.io/docs/astro/api/v-1/api-reference/cluster/list-clusters",
+ "columns": {
+ "id": "The identifier of the cluster.",
+ "name": "The cluster name.",
+ "cloudProvider": "The cloud provider that hosts the cluster.",
+ "region": "The region where the cluster was created.",
+ "status": "The cluster status.",
+ "createdAt": "The time when the cluster was created, in UTC.",
+ "updatedAt": "The time when the cluster was last updated, in UTC.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/settings.py
new file mode 100644
index 000000000000..1f29411bf5f3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/settings.py
@@ -0,0 +1,36 @@
+from typing import TypedDict
+
+
+class AstronomerEndpoint(TypedDict):
+ path: str
+ primary_keys: list[str]
+ permission: str
+
+
+BASE_URL = "https://api.astronomer.io/v1/"
+PAGE_SIZE = 100
+ENDPOINTS: dict[str, AstronomerEndpoint] = {
+ "deployments": {
+ "path": "deployments",
+ "primary_keys": ["id"],
+ "permission": "organization.deployments.get",
+ },
+ "deploys": {
+ "path": "deployments/{deployment_id}/deploys",
+ "primary_keys": ["deploymentId", "id"],
+ "permission": "deployment.deploys.get",
+ },
+ "workspaces": {
+ "path": "workspaces",
+ "primary_keys": ["id"],
+ "permission": "organization.workspaces.get",
+ },
+ "clusters": {
+ "path": "clusters",
+ "primary_keys": ["id"],
+ "permission": "organization.clusters.get",
+ },
+}
+
+AUTH_ERROR = "Astronomer rejected the API token. Check that the token is correct and has not expired."
+ACCESS_ERROR = "Astronomer denied access. Check the token permissions and the organization ID."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/source.py
index 9083eb453576..cebcbce2d4d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/source.py
@@ -1,8 +1,36 @@
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.astronomer.astronomer import (
+ AstronomerResumeConfig,
+ astronomer_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.astronomer.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.astronomer.settings import (
+ ACCESS_ERROR,
+ AUTH_ERROR,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.astronomer import (
AstronomerSourceConfig,
)
@@ -10,11 +38,53 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AstronomerSource(SimpleSource[AstronomerSourceConfig]):
+class AstronomerSource(ResumableSource[AstronomerSourceConfig, AstronomerResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v1",)
+ default_version = "v1"
+ api_docs_url = "https://www.astronomer.io/docs/astro/api/versioning-and-support"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ASTRONOMER
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {"401 Client Error": AUTH_ERROR, "403 Client Error": ACCESS_ERROR}
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AstronomerSourceConfig,
+ 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)
+
+ def validate_credentials(
+ self,
+ config: AstronomerSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AstronomerResumeConfig]:
+ return ResumableSourceManager(inputs, AstronomerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AstronomerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AstronomerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return astronomer_source(config, inputs.schema_name, inputs.team_id, inputs.job_id, resumable_source_manager)
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -22,6 +92,33 @@ class AstronomerSource(SimpleSource[AstronomerSourceConfig]):
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Astronomer (Astro)",
iconPath="/static/services/astronomer.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Import Astro deployments, deploy history, workspaces, and clusters. "
+ "Create an organization API token in Astro under Settings > Access Management > API Tokens. "
+ "Grant `organization.deployments.get`, `deployment.deploys.get`, `organization.workspaces.get`, "
+ "and `organization.clusters.get` for the tables you select. "
+ "Airflow DAG runs and task instances are not included."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="organization_id",
+ label="Organization ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/tests/test_astronomer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/tests/test_astronomer.py
new file mode 100644
index 000000000000..fc6d48c63d12
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/tests/test_astronomer.py
@@ -0,0 +1,256 @@
+from collections.abc import Iterable
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import responses
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.astronomer.astronomer import (
+ AstronomerResumeConfig,
+ astronomer_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.astronomer.source import AstronomerSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+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 UnknownResourceError
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.astronomer import (
+ AstronomerSourceConfig,
+)
+
+BASE = "https://api.astronomer.io/v1/organizations/example-org"
+CONFIG = AstronomerSourceConfig(api_token="test-token", organization_id="example-org")
+
+
+def manager(state: dict[str, Any] | None = None) -> MagicMock:
+ result = MagicMock(spec=ResumableSourceManager)
+ result.can_resume.return_value = state is not None
+ result.load_state.return_value = AstronomerResumeConfig(paginator_state=state) if state is not None else None
+ return result
+
+
+def items(response: SourceResponse) -> Iterable[Any]:
+ return cast(Iterable[Any], response.items())
+
+
[email protected]("table", ["deployments", "workspaces", "clusters"])
[email protected]("last_page_size", [0, 1, 100])
+def test_list_pagination_auth_and_terminal_page(table: str, last_page_size: int) -> None:
+ rows = [{"id": f"row-{index}"} for index in range(100 + last_page_size)]
+ responses.get(f"{BASE}/{table}", json={table: rows[:100], "totalCount": 200})
+ responses.get(f"{BASE}/{table}", json={table: rows[100:], "totalCount": len(rows)})
+ checkpoint = manager()
+ result = astronomer_source(CONFIG, table, 1, "test-job", checkpoint)
+
+ assert [row for page in items(result) for row in page] == rows
+ assert len(responses.calls) == 2
+ for offset, call in zip([0, 100], responses.calls):
+ assert call.request.headers["Authorization"] == "Bearer test-token"
+ assert parse_qs(urlparse(call.request.url).query) == {
+ "offset": [str(offset)],
+ "limit": ["100"],
+ "sorts": ["createdAt:asc"],
+ }
+ checkpoint.save_state.assert_called_once_with(AstronomerResumeConfig(paginator_state={"offset": 100}))
+
+
+def test_resume_starts_at_saved_offset() -> None:
+ responses.get(f"{BASE}/workspaces", json={"workspaces": [{"id": "last"}], "totalCount": 201})
+ result = astronomer_source(CONFIG, "workspaces", 1, "test-job", manager({"offset": 200}))
+ assert [row for page in items(result) for row in page] == [{"id": "last"}]
+ assert parse_qs(urlparse(responses.calls[0].request.url).query)["offset"] == ["200"]
+
+
+def test_deploy_history_paginates_each_parent_and_preserves_unique_keys() -> None:
+ responses.get(f"{BASE}/deployments", json={"deployments": [{"id": "first"}, {"id": "second"}], "totalCount": 2})
+ first_page = [{"id": f"deploy-{index}"} for index in range(100)]
+ responses.get(f"{BASE}/deployments/first/deploys", json={"deploys": first_page, "totalCount": 101})
+ responses.get(f"{BASE}/deployments/first/deploys", json={"deploys": [{"id": "last"}], "totalCount": 101})
+ responses.get(f"{BASE}/deployments/second/deploys", json={"deploys": [{"id": "last"}], "totalCount": 1})
+ checkpoint = manager()
+ result = astronomer_source(CONFIG, "deploys", 1, "test-job", checkpoint)
+ rows = [row for page in items(result) for row in page]
+
+ assert len(rows) == 102
+ assert rows[-2:] == [{"id": "last", "deploymentId": "first"}, {"id": "last", "deploymentId": "second"}]
+ assert len({tuple(row[key] for key in result.primary_keys or []) for row in rows}) == 102
+ for offset, call in zip([0, 100, 0], responses.calls[1:]):
+ assert parse_qs(urlparse(call.request.url).query) == {"offset": [str(offset)], "limit": ["100"]}
+ assert call.request.headers["Authorization"] == "Bearer test-token"
+ states = [call.args[0].paginator_state for call in checkpoint.save_state.call_args_list]
+ assert any(state["child_state"] == {"offset": 100} for state in states)
+ assert states[-1]["completed"] == [
+ "organizations/example-org/deployments/first/deploys",
+ "organizations/example-org/deployments/second/deploys",
+ ]
+
+
+def test_deploy_resume_skips_completed_parents_and_continues_child_page() -> None:
+ responses.get(f"{BASE}/deployments", json={"deployments": [{"id": "first"}, {"id": "second"}], "totalCount": 2})
+ responses.get(f"{BASE}/deployments/second/deploys", json={"deploys": [{"id": "last"}], "totalCount": 101})
+ checkpoint = manager(
+ {
+ "completed": ["organizations/example-org/deployments/first/deploys"],
+ "current": "organizations/example-org/deployments/second/deploys",
+ "child_state": {"offset": 100},
+ }
+ )
+ result = astronomer_source(CONFIG, "deploys", 1, "test-job", checkpoint)
+ assert [row for page in items(result) for row in page] == [{"id": "last", "deploymentId": "second"}]
+ assert len(responses.calls) == 2
+ assert parse_qs(urlparse(responses.calls[1].request.url).query)["offset"] == ["100"]
+
+
[email protected]("empty_parent", [True, False])
+def test_deploys_with_no_rows(empty_parent: bool) -> None:
+ responses.get(
+ f"{BASE}/deployments", json={"deployments": [] if empty_parent else [{"id": "first"}], "totalCount": 1}
+ )
+ if not empty_parent:
+ responses.get(f"{BASE}/deployments/first/deploys", json={"deploys": [], "totalCount": 0})
+ result = astronomer_source(CONFIG, "deploys", 1, "test-job", manager())
+ assert [row for page in items(result) for row in page] == []
+ assert len(responses.calls) == (1 if empty_parent else 2)
+
+
+ ("status", "schema", "valid", "message"),
+ [
+ (200, None, True, None),
+ (401, None, False, "API token"),
+ (403, None, True, None),
+ (403, "clusters", False, "organization.clusters.get"),
+ (404, None, False, "organization ID"),
+ ],
+)
+def test_credential_probe_status_mapping(status: int, schema: str | None, valid: bool, message: str | None) -> None:
+ table = schema or "deployments"
+ responses.get(f"{BASE}/{table}", json={table: []}, status=status)
+ actual_valid, actual_message = validate_credentials(CONFIG, schema)
+ assert actual_valid is valid
+ if message:
+ assert actual_message and message in actual_message
+ else:
+ assert actual_message is None
+ assert len(responses.calls) == 1
+ assert parse_qs(urlparse(responses.calls[0].request.url).query) == {"limit": ["1"]}
+ assert responses.calls[0].request.headers["Authorization"] == "Bearer test-token"
+
+
[email protected]("parent_status, child_status", [(403, None), (200, 403), (200, 200), (200, None)])
+def test_deploy_permission_probe(parent_status: int, child_status: int | None) -> None:
+ responses.get(
+ f"{BASE}/deployments",
+ json={"deployments": [] if child_status is None else [{"id": "first"}]},
+ status=parent_status,
+ )
+ if child_status is not None:
+ responses.get(f"{BASE}/deployments/first/deploys", json={"deploys": []}, status=child_status)
+ valid, message = validate_credentials(CONFIG, "deploys")
+ assert valid is (parent_status == 200 and child_status != 403)
+ if parent_status == 403:
+ assert message and "organization.deployments.get" in message
+ elif child_status == 403:
+ assert message and "deployment.deploys.get" in message
+ else:
+ assert message is None
+
+
[email protected]("organization_id", ["", "../example", "https://example.com", "a?b", "a#b", "a/b"])
+def test_invalid_organization_never_sends_token(organization_id: str) -> None:
+ config = AstronomerSourceConfig(api_token="test-token", organization_id=organization_id)
+ valid, message = validate_credentials(config)
+ assert not valid
+ assert message and "organization ID" in message
+ with pytest.raises(ValueError, match="organization ID"):
+ astronomer_source(config, "deployments", 1, "test-job", manager())
+ assert not responses.calls
+
+
[email protected]("status", [401, 403, 400, 429, 500])
+def test_sync_errors_and_retry_classification(status: int) -> None:
+ responses.get(f"{BASE}/deployments", json={"error": "test_error"}, status=status)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.RESTClient._send_request.retry.sleep"
+ ):
+ result = astronomer_source(CONFIG, "deployments", 1, "test-job", manager())
+ expected = RESTClientRetryableError if status in (429, 500) else HTTPError
+ with pytest.raises(expected) as caught:
+ list(items(result))
+ mapped = [
+ message
+ for pattern, message in AstronomerSource().get_non_retryable_errors().items()
+ if pattern in str(caught.value)
+ ]
+ assert bool(mapped) is (status in (401, 403))
+ assert (len(responses.calls) > 1) is (status in (429, 500))
+
+
+def test_validation_does_not_hide_unexpected_http_errors() -> None:
+ responses.get(f"{BASE}/deployments", json={"error": "bad_request"}, status=400)
+ with pytest.raises(HTTPError):
+ validate_credentials(CONFIG)
+
+
[email protected]("operation", ["validate", "sync"])
+def test_unknown_table(operation: str) -> None:
+ with pytest.raises(UnknownResourceError):
+ if operation == "validate":
+ validate_credentials(CONFIG, "unknown")
+ else:
+ astronomer_source(CONFIG, "unknown", 1, "test-job", manager())
+ assert not responses.calls
+
+
[email protected]("table", ["deployments", "deploys"])
+def test_warehouse_rows_exclude_environment_values_and_upload_urls(table: str) -> None:
+ path = table
+ if table == "deploys":
+ responses.get(f"{BASE}/deployments", json={"deployments": [{"id": "first"}], "totalCount": 1})
+ path = "deployments/first/deploys"
+ responses.get(
+ f"{BASE}/{path}",
+ json={
+ table: [
+ {
+ "id": "row-1",
+ "status": "DEPLOYED",
+ "environmentVariables": [{"key": "SECRET", "value": "fake-secret", "isSecret": True}],
+ "bundleUploadUrl": "https://example.com/upload?token=fake",
+ "dagsUploadUrl": "https://example.com/upload?token=fake",
+ }
+ ],
+ "totalCount": 1,
+ },
+ )
+ result = astronomer_source(CONFIG, table, 1, "test-job", manager())
+ expected = {"id": "row-1", "status": "DEPLOYED"}
+ if table == "deploys":
+ expected["deploymentId"] = "first"
+ assert [row for page in items(result) for row in page] == [expected]
+
+
+def test_missing_collection_fails_instead_of_replacing_table_with_no_rows() -> None:
+ responses.get(f"{BASE}/deployments", json={"unexpected": []})
+ result = astronomer_source(CONFIG, "deployments", 1, "test-job", manager())
+ with pytest.raises(ValueError, match="Required data_selector"):
+ list(items(result))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/astronomer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/astronomer.py
index 93958194b1c7..a5b9bb1a4882 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/astronomer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/astronomer.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AstronomerSourceConfig(config.Config):
- pass
+ api_token: str
+ organization_id: str