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 humanitec import source (#112221)

Tom Owersf67127db8a21
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 e2f2e87c96c4..a16382c99e7a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -413,6 +413,7 @@ the row lists both.
| hookdeck | HTTP | requests + `rest_source.RESTClient` | ✅ |
| hoorayhr | HTTP | requests + `rest_source.RESTClient` | ✅ |
| housecall_pro | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| humanitec | HTTP | requests | ✅ |
| humanitix | HTTP | requests | ✅ |
| hubplanner | HTTP | requests | ✅ |
| hubspot | HTTP | requests | ✅ |
@@ -1186,7 +1187,6 @@ doesn't conflict with concurrent PRs.
- hootsuite
- hostaway
- hubplanner
-- humanitec
- humanitix
- ikas
- illumina_basespace
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/humanitec.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/humanitec.py
index ac4e2ef39c24..dd5e75efffa8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/humanitec.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/humanitec.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class HumanitecSourceConfig(config.Config):
- pass
+ api_token: str
+ organization_id: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/canonical_descriptions.py
new file mode 100644
index 000000000000..322f32fbc57c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/canonical_descriptions.py
@@ -0,0 +1,83 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitec.settings import API_DOCS_URL
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "applications": {
+ "description": "Applications group workloads that deploy together into an environment.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Application ID.",
+ "org_id": "Organization that contains the application.",
+ "name": "Application name.",
+ "created_at": "Time when the application was created.",
+ "envs": "Environments associated with the application.",
+ "status": "Current application status.",
+ },
+ },
+ "environments": {
+ "description": "Environments provide independent spaces where applications run.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Environment ID within the application.",
+ "app_id": "Application ID from the parent application.",
+ "name": "Environment name.",
+ "type": "Environment type used to group and manage environments.",
+ "created_at": "Time when the environment was created.",
+ "last_deploy": "Last deployment in the environment, if one exists.",
+ "status": "Current environment status.",
+ },
+ },
+ "deployments": {
+ "description": "Deployments record changes to the running state of an environment.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Deployment ID.",
+ "app_id": "Application ID from the parent application.",
+ "env_id": "Environment where the deployment occurred.",
+ "created_at": "Time when the deployment started.",
+ "created_by": "User who started the deployment.",
+ "status": "Deployment status: pending, in progress, succeeded, or failed.",
+ "status_changed_at": "Time of the last status change. For completed deployments, this is the completion time.",
+ "delta_id": "Delta that describes the deployment changes.",
+ "set_id": "Deployment set that describes the resulting environment state.",
+ },
+ },
+ "active_resources": {
+ "description": "Active resources are infrastructure resources provisioned for an environment.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "gu_res_id": "Globally unique resource ID.",
+ "app_id": "Application associated with the resource.",
+ "env_id": "Environment associated with the resource.",
+ "def_id": "Resource definition used to provision the resource.",
+ "deploy_id": "Deployment that last provisioned the resource.",
+ "type": "Resource type.",
+ "status": "Current resource status: pending, active, or deleting.",
+ "updated_at": "Time when a deployment last provisioned the resource.",
+ },
+ },
+ "environment_types": {
+ "description": "Environment types group environments for management and resource selection.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Environment type ID within the organization.",
+ "description": "Description of the environment type.",
+ },
+ },
+ "pipelines": {
+ "description": "Pipelines define automated deployment workflows within an application.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "id": "Pipeline ID within the application.",
+ "app_id": "Application that contains the pipeline.",
+ "org_id": "Organization that contains the pipeline.",
+ "name": "Pipeline name.",
+ "status": "Current pipeline status.",
+ "version": "ID of the current pipeline version.",
+ "created_at": "Time when the pipeline was created.",
+ "trigger_types": "Trigger types in the current pipeline schema.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/humanitec.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/humanitec.py
new file mode 100644
index 000000000000..c8701d110360
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/humanitec.py
@@ -0,0 +1,149 @@
+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.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+ rest_api_resources,
+)
+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.typing import (
+ ClientConfig,
+ 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.humanitec import (
+ HumanitecSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitec.settings import (
+ API_BASE_URL,
+ AUTH_ERROR,
+ ENDPOINTS,
+ INVALID_ORGANIZATION_ERROR,
+ ORGANIZATION_ERROR,
+ PERMISSION_ERROR,
+)
+
+
+@frozen
+class HumanitecResumeConfig:
+ paginator_state: dict[str, Any]
+
+
+def client_config(config: HumanitecSourceConfig) -> ClientConfig:
+ if len(config.organization_id) > 50 or not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", config.organization_id):
+ raise ValueError(INVALID_ORGANIZATION_ERROR)
+ return {
+ "base_url": API_BASE_URL,
+ "auth": {"type": "bearer", "token": config.api_token},
+ "paginator": "single_page",
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": (10, 60),
+ }
+
+
+def application_environments(row: dict[str, Any]) -> list[dict[str, Any]]:
+ # The application list includes environment IDs, so child syncs need no separate environment lookup.
+ return [{"app_id": row["id"], "env_id": environment["id"]} for environment in row["envs"]]
+
+
+def validate_credentials(config: HumanitecSourceConfig) -> tuple[bool, str | None]:
+ try:
+ client = client_config(config)
+ except ValueError as error:
+ return False, str(error)
+
+ resource = rest_api_resource(
+ {
+ "client": client,
+ "resources": [
+ {"name": "organization", "endpoint": {"path": f"orgs/{config.organization_id}", "data_selector": "$"}}
+ ],
+ },
+ team_id=0,
+ job_id="",
+ db_incremental_field_last_value=None,
+ )
+ try:
+ next(iter(resource))
+ except HTTPError as error:
+ if error.response is None:
+ raise
+ message = {401: AUTH_ERROR, 403: PERMISSION_ERROR, 404: ORGANIZATION_ERROR}.get(error.response.status_code)
+ if message:
+ return False, message
+ raise
+ return True, None
+
+
+def humanitec_source(
+ config: HumanitecSourceConfig,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ manager: ResumableSourceManager[HumanitecResumeConfig],
+) -> SourceResponse:
+ settings = schema_for_resource(ENDPOINTS, endpoint)
+ client = client_config(config)
+ prefix = f"orgs/{config.organization_id}/"
+ params: dict[str, Any] = {"per_page": 100} if settings.paginated else {}
+ target_endpoint: Endpoint = {
+ "path": prefix + settings.path,
+ "data_selector": "$",
+ "paginator": "header_link" if settings.paginated else "single_page",
+ "params": params,
+ }
+ target: EndpointResource = {"name": endpoint, "endpoint": target_endpoint}
+ resources: list[str | EndpointResource] = []
+ if settings.parent:
+ parent: EndpointResource = {
+ "name": settings.parent,
+ "endpoint": {"path": prefix + "apps", "data_selector": "$"},
+ }
+ fields = {"id": "app_id"}
+ if settings.parent == "application_environments":
+ parent["data_map"] = application_environments
+ fields = {"app_id": "app_id", "env_id": "env_id"}
+ for field, param in fields.items():
+ params[param] = {"type": "resolve", "resource": settings.parent, "field": field}
+ target["include_from_parent"] = list(fields)
+ target["data_map"] = rename_parent_fields(settings.parent, fields)
+ resources.append(parent)
+ resources.append(target)
+
+ resume = manager.load_state() if manager.can_resume() else None
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ manager.save_state(HumanitecResumeConfig(paginator_state=state))
+
+ rest_config: RESTAPIConfig = {
+ "client": client,
+ "resource_defaults": {"write_disposition": "replace"},
+ "resources": resources,
+ }
+ resource = next(
+ resource
+ for resource in rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.paginator_state if resume else None,
+ )
+ if resource.name == endpoint
+ )
+ return SourceResponse(
+ name=endpoint, items=lambda: resource, primary_keys=list(settings.primary_keys), sort_mode=None
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/settings.py
new file mode 100644
index 000000000000..46af6ea4ffef
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/settings.py
@@ -0,0 +1,41 @@
+from typing import Literal
+
+from posthog.dataclasses import frozen
+
+API_BASE_URL = "https://api.humanitec.io/"
+API_DOCS_URL = "https://api-docs.humanitec.com/"
+
+
+@frozen
+class HumanitecEndpoint:
+ path: str
+ primary_keys: tuple[str, ...]
+ parent: Literal["applications", "application_environments"] | None = None
+ paginated: bool = False
+
+
+ENDPOINTS: dict[str, HumanitecEndpoint] = {
+ "applications": HumanitecEndpoint(path="apps", primary_keys=("id",)),
+ "environments": HumanitecEndpoint(path="apps/{app_id}/envs", primary_keys=("app_id", "id"), parent="applications"),
+ "deployments": HumanitecEndpoint(
+ path="apps/{app_id}/envs/{env_id}/deploys",
+ primary_keys=("app_id", "env_id", "id"),
+ parent="application_environments",
+ ),
+ "active_resources": HumanitecEndpoint(
+ path="apps/{app_id}/envs/{env_id}/resources",
+ primary_keys=("app_id", "env_id", "gu_res_id"),
+ parent="application_environments",
+ ),
+ "environment_types": HumanitecEndpoint(path="env-types", primary_keys=("id",)),
+ "pipelines": HumanitecEndpoint(
+ path="apps/{app_id}/pipelines", primary_keys=("app_id", "id"), parent="applications", paginated=True
+ ),
+}
+
+AUTH_ERROR = "Humanitec rejected the API token. Check the token and its expiration date."
+PERMISSION_ERROR = "The Humanitec token cannot read this resource. Check the service user's roles in your organization."
+ORGANIZATION_ERROR = (
+ "Humanitec could not find the organization. Check the organization ID and the service user's access."
+)
+INVALID_ORGANIZATION_ERROR = "Enter a Humanitec organization ID with lowercase letters, numbers, and single hyphens."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/source.py
index 10315090a800..0818f7e601b3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/source.py
@@ -1,20 +1,89 @@
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.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.humanitec import (
HumanitecSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitec.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitec.humanitec import (
+ HumanitecResumeConfig,
+ humanitec_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitec.settings import (
+ API_DOCS_URL,
+ AUTH_ERROR,
+ ENDPOINTS,
+ PERMISSION_ERROR,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HumanitecSource(SimpleSource[HumanitecSourceConfig]):
+class HumanitecSource(ResumableSource[HumanitecSourceConfig, HumanitecResumeConfig]):
+ lists_tables_without_credentials = True
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HUMANITEC
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {"401 Client Error": AUTH_ERROR, "403 Client Error": PERMISSION_ERROR}
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: HumanitecSourceConfig,
+ 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: HumanitecSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HumanitecResumeConfig]:
+ return ResumableSourceManager(inputs, HumanitecResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HumanitecSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HumanitecResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return humanitec_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 +91,31 @@ class HumanitecSource(SimpleSource[HumanitecSourceConfig]):
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Humanitec",
iconPath="/static/services/humanitec.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "In Humanitec, open Service users. Select a user. Select Add new API token. "
+ "Use a service user with read access to the applications and environments you want to sync. "
+ "This source connects to the Platform Orchestrator API at api.humanitec.io."
+ ),
+ 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="example-org",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/tests/test_humanitec.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/tests/test_humanitec.py
new file mode 100644
index 000000000000..c08c7c8dae34
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitec/tests/test_humanitec.py
@@ -0,0 +1,276 @@
+import json
+from collections.abc import Iterable, Iterator
+from http import HTTPStatus
+from typing import cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import PreparedRequest, Response
+from requests.exceptions import HTTPError
+
+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.humanitec import (
+ HumanitecSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitec.humanitec import (
+ HumanitecResumeConfig,
+ humanitec_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitec.source import HumanitecSource
+
+BASE = "https://api.humanitec.io/orgs/example-org"
+CONFIG = HumanitecSourceConfig(api_token="test-token", organization_id="example-org")
+
+
+def source_items(source: SourceResponse) -> Iterable[list[dict[str, object]]]:
+ return cast(Iterable[list[dict[str, object]]], source.items())
+
+
+def response(body: object, status: int = 200, next_url: str | None = None) -> Response:
+ result = Response()
+ result.status_code = status
+ result.reason = HTTPStatus(status).phrase
+ result._content = json.dumps(body).encode()
+ result.headers["Content-Type"] = "application/json"
+ if next_url:
+ result.headers["Link"] = f'<{next_url}>; rel="next"'
+ return result
+
+
+def http() -> Iterator[MagicMock]:
+ session = MagicMock()
+ session.headers = {}
+ session.prepare_request.side_effect = lambda request: request.prepare()
+ session.responses = []
+
+ def send(request: PreparedRequest, **kwargs: object) -> Response:
+ result = session.responses.pop(0)
+ result.url = request.url
+ result.request = request
+ return result
+
+ session.send.side_effect = send
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session",
+ return_value=session,
+ ):
+ yield session
+
+
+def manager() -> MagicMock:
+ result = MagicMock(spec=ResumableSourceManager)
+ result.can_resume.return_value = False
+ return result
+
+
[email protected]("endpoint,path", [("applications", "apps"), ("environment_types", "env-types")])
[email protected]("rows", [[], [{"id": "example"}]])
+def test_single_page_lists(
+ http: MagicMock, manager: MagicMock, endpoint: str, path: str, rows: list[dict[str, str]]
+) -> None:
+ http.responses = [response(rows)]
+ source = humanitec_source(CONFIG, endpoint, 1, "job", manager)
+ assert [row for page in source_items(source) for row in page] == rows
+ http.send.assert_called_once()
+ request = http.send.call_args.args[0]
+ assert request.url == f"{BASE}/{path}"
+ assert request.headers["Authorization"] == "Bearer test-token"
+ assert http.send.call_args.kwargs["allow_redirects"] is False
+
+
+ "endpoint,suffix,key", [("deployments", "deploys", "id"), ("active_resources", "resources", "gu_res_id")]
+)
+def test_environment_children_keep_parent_keys(
+ http: MagicMock, manager: MagicMock, endpoint: str, suffix: str, key: str
+) -> None:
+ http.responses = [
+ response(
+ [
+ {"id": "app-a", "envs": [{"id": "staging"}, {"id": "production"}]},
+ {"id": "empty-app", "envs": []},
+ {"id": "app-b", "envs": [{"id": "staging"}]},
+ ]
+ ),
+ response([{key: "same-id", "env_id": "staging"}]),
+ response([]),
+ response([{key: "same-id", "env_id": "staging"}]),
+ ]
+ source = humanitec_source(CONFIG, endpoint, 1, "job", manager)
+ rows = [row for page in source_items(source) for row in page]
+ assert rows == [
+ {key: "same-id", "app_id": "app-a", "env_id": "staging"},
+ {key: "same-id", "app_id": "app-b", "env_id": "staging"},
+ ]
+ assert len({tuple(row[field] for field in source.primary_keys or []) for row in rows}) == 2
+ assert [call.args[0].url for call in http.send.call_args_list] == [
+ f"{BASE}/apps",
+ f"{BASE}/apps/app-a/envs/staging/{suffix}",
+ f"{BASE}/apps/app-a/envs/production/{suffix}",
+ f"{BASE}/apps/app-b/envs/staging/{suffix}",
+ ]
+
+
+def test_environments_keep_application_id(http: MagicMock, manager: MagicMock) -> None:
+ http.responses = [
+ response([{"id": "app-a"}, {"id": "app-b"}]),
+ response([{"id": "staging"}]),
+ response([{"id": "staging"}]),
+ ]
+ source = humanitec_source(CONFIG, "environments", 1, "job", manager)
+ rows = [row for page in source_items(source) for row in page]
+ assert rows == [{"id": "staging", "app_id": "app-a"}, {"id": "staging", "app_id": "app-b"}]
+ assert len({tuple(row[field] for field in source.primary_keys or []) for row in rows}) == 2
+
+
[email protected]("first_page", [[], [{"id": "first"}]])
+def test_pipeline_pagination_and_checkpoints(
+ http: MagicMock, manager: MagicMock, first_page: list[dict[str, str]]
+) -> None:
+ next_url = f"{BASE}/apps/app-a/pipelines?page=cursor-2&per_page=100"
+ http.responses = [response([{"id": "app-a"}]), response(first_page, next_url=next_url), response([{"id": "last"}])]
+ source = humanitec_source(CONFIG, "pipelines", 1, "job", manager)
+ assert [row for page in source_items(source) for row in page] == [
+ *[{**row, "app_id": "app-a"} for row in first_page],
+ {"id": "last", "app_id": "app-a"},
+ ]
+ requests = [call.args[0] for call in http.send.call_args_list]
+ assert requests[0].url == f"{BASE}/apps"
+ assert parse_qs(urlsplit(requests[1].url).query) == {"per_page": ["100"]}
+ assert requests[2].url == next_url
+ assert all(request.headers["Authorization"] == "Bearer test-token" for request in requests)
+ states = [call.args[0].paginator_state for call in manager.save_state.call_args_list]
+ assert states[0] == {
+ "completed": [],
+ "current": "orgs/example-org/apps/app-a/pipelines",
+ "child_state": {"next_url": next_url},
+ }
+ assert states[-1] == {"completed": ["orgs/example-org/apps/app-a/pipelines"], "current": None, "child_state": None}
+
+
+def test_resume_skips_completed_parents_and_uses_saved_page(http: MagicMock, manager: MagicMock) -> None:
+ next_url = f"{BASE}/apps/app-b/pipelines?page=cursor-2"
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = HumanitecResumeConfig(
+ paginator_state={
+ "completed": ["orgs/example-org/apps/app-a/pipelines"],
+ "current": "orgs/example-org/apps/app-b/pipelines",
+ "child_state": {"next_url": next_url},
+ }
+ )
+ http.responses = [response([{"id": "app-a"}, {"id": "app-b"}]), response([{"id": "last"}])]
+ source = humanitec_source(CONFIG, "pipelines", 1, "job", manager)
+ assert list(source_items(source)) == [[{"id": "last", "app_id": "app-b"}]]
+ assert [call.args[0].url for call in http.send.call_args_list] == [f"{BASE}/apps", next_url]
+
+
+ "status,expected", [(200, None), (401, "rejected the API token"), (403, "cannot read"), (404, "could not find")]
+)
+def test_credential_probe(http: MagicMock, status: int, expected: str | None) -> None:
+ http.responses = [
+ response(
+ {"id": "example-org"}
+ if status == 200
+ else {"error": f"HTTP-{status}", "message": HTTPStatus(status).phrase},
+ status,
+ )
+ ]
+ valid, error = validate_credentials(CONFIG)
+ assert valid is (status == 200)
+ assert (error is None) if expected is None else expected in cast(str, error)
+ http.send.assert_called_once()
+ assert http.send.call_args.args[0].url == BASE
+ assert http.send.call_args.args[0].headers["Authorization"] == "Bearer test-token"
+
+
[email protected]("status", [401, 403])
+def test_authentication_errors_are_terminal(http: MagicMock, manager: MagicMock, status: int) -> None:
+ http.responses = [response({"error": f"HTTP-{status}", "message": HTTPStatus(status).phrase}, status)]
+ source = humanitec_source(CONFIG, "applications", 1, "job", manager)
+ with pytest.raises(HTTPError) as error:
+ list(source_items(source))
+ assert any(pattern in str(error.value) for pattern in HumanitecSource().get_non_retryable_errors())
+ http.send.assert_called_once()
+
+
[email protected]("status", [429, 500, 503])
+def test_transient_probe_errors_propagate(http: MagicMock, status: int) -> None:
+ http.responses = [response({"error": f"HTTP-{status}"}, status)]
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.DEFAULT_RETRY_ATTEMPTS", 1
+ ):
+ with pytest.raises(RESTClientRetryableError):
+ validate_credentials(CONFIG)
+ http.send.assert_called_once()
+
+
+ "organization",
+ ["", "../users", "example/org", "https://example.com", "UPPERCASE", "bad--id", "a" * 49 + "!", "a" * 51],
+)
+def test_invalid_organization_never_sends_token(http: MagicMock, manager: MagicMock, organization: str) -> None:
+ config = HumanitecSourceConfig(api_token="test-token", organization_id=organization)
+ valid, error = validate_credentials(config)
+ assert not valid
+ assert error and "organization ID" in error
+ with pytest.raises(ValueError, match="organization ID"):
+ humanitec_source(config, "applications", 1, "job", manager)
+ http.send.assert_not_called()
+
+
+ "next_url", ["https://example.com/steal", "http://api.humanitec.io/orgs/example-org/apps/app-a/pipelines"]
+)
+def test_pipeline_links_cannot_retarget_credentials(http: MagicMock, manager: MagicMock, next_url: str) -> None:
+ http.responses = [response([{"id": "app-a"}]), response([{"id": "first"}], next_url=next_url)]
+ source = humanitec_source(CONFIG, "pipelines", 1, "job", manager)
+ with pytest.raises(ValueError, match="Refusing to send"):
+ list(source_items(source))
+ assert http.send.call_count == 2
+
+
+def test_unknown_table(http: MagicMock, manager: MagicMock) -> None:
+ with pytest.raises(UnknownResourceError):
+ humanitec_source(CONFIG, "missing", 1, "job", manager)
+ http.send.assert_not_called()
+
+
+ "endpoint,completed_path",
+ [
+ ("environments", "orgs/example-org/apps/app-a/envs"),
+ ("deployments", "orgs/example-org/apps/app-a/envs/staging/deploys"),
+ ("active_resources", "orgs/example-org/apps/app-a/envs/staging/resources"),
+ ("pipelines", "orgs/example-org/apps/app-a/pipelines"),
+ ],
+)
+def test_resume_after_final_parent_does_not_repeat_rows(
+ http: MagicMock, manager: MagicMock, endpoint: str, completed_path: str
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = HumanitecResumeConfig(
+ paginator_state={"completed": [completed_path], "current": None, "child_state": None}
+ )
+ http.responses = [response([{"id": "app-a", "envs": [{"id": "staging"}]}])]
+ source = humanitec_source(CONFIG, endpoint, 1, "job", manager)
+ assert list(source_items(source)) == []
+ http.send.assert_called_once()
+ assert http.send.call_args.args[0].url == f"{BASE}/apps"
+
+
+def test_unexpected_probe_error_is_not_reported_as_invalid_credentials(http: MagicMock) -> None:
+ http.responses = [response({"error": "HTTP-400"}, 400)]
+ with pytest.raises(HTTPError):
+ validate_credentials(CONFIG)
+ http.send.assert_called_once()