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 spacelift import source (#71245)

Tom Owers48cb7ccea8fd
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 9ef463846529..426f6f20d5c3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -457,6 +457,7 @@ the row lists both.
| snowplow | HTTP | requests | ✅ |
| solarwinds_service_desk | HTTP | requests | ✅ |
| sonarqube | HTTP | requests | ✅ |
+| spacelift | HTTP (GraphQL) | requests | ✅ |
| sparkpost | HTTP | requests | ✅ |
| split_io | HTTP | requests | ✅ |
| square | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index b245f0624bf0..e57288996203 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -4035,7 +4035,9 @@ class SourcegraphSourceConfig(config.Config):
@config.config
class SpaceliftSourceConfig(config.Config):
- pass
+ account_name: str
+ api_key_id: str
+ api_key_secret: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/canonical_descriptions.py
new file mode 100644
index 000000000000..52153a5319b7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/canonical_descriptions.py
@@ -0,0 +1,154 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "stacks": {
+ "description": "Infrastructure-as-code stacks: the core unit tying a VCS repository to Terraform/OpenTofu/Pulumi state, with current status and drift information.",
+ "docs_url": "https://docs.spacelift.io/concepts/stack/",
+ "columns": {
+ "id": "Unique identifier (slug) of the stack.",
+ "name": "Human-readable name of the stack.",
+ "administrative": "Whether the stack has administrative permissions on the Spacelift account.",
+ "api_host": "API host the stack's VCS provider is served from.",
+ "branch": "VCS branch the stack tracks.",
+ "created_at": "Unix timestamp (seconds) when the stack was created.",
+ "deleted": "Whether the stack has been deleted.",
+ "deleting": "Whether the stack is currently being deleted.",
+ "description": "Free-form description of the stack.",
+ "is_drifted": "Whether drift detection found the live infrastructure differing from the desired state.",
+ "labels": "Labels attached to the stack.",
+ "locked_at": "Unix timestamp (seconds) when the stack was locked, if locked.",
+ "locked_by": "Username that locked the stack, if locked.",
+ "manages_state_file": "Whether Spacelift manages the stack's Terraform state file.",
+ "namespace": "VCS namespace (organization or user) of the stack's repository.",
+ "project_root": "Directory inside the repository the stack operates on.",
+ "provider": "VCS provider hosting the stack's repository (e.g. GITHUB, GITLAB).",
+ "repository": "Name of the repository the stack tracks.",
+ "repository_url": "Full URL of the tracked repository.",
+ "space": "ID of the Spacelift space the stack belongs to.",
+ "state": "Current state of the stack (e.g. FINISHED, FAILED, UNCONFIRMED).",
+ "state_set_at": "Unix timestamp (seconds) when the current state was set.",
+ "terraform_version": "Terraform/OpenTofu version the stack uses.",
+ "vcs_detached": "Whether the stack's VCS integration has been deleted.",
+ },
+ },
+ "runs": {
+ "description": "Historical record of every run across all stacks and modules: deployments (tracked runs), previews (proposed runs), tasks, and drift-detection runs, with timing, state, and change counts.",
+ "docs_url": "https://docs.spacelift.io/concepts/run/",
+ "columns": {
+ "id": "Unique identifier (ULID) of the run.",
+ "branch": "VCS branch the run executed against.",
+ "commit": "Commit the run executed: author, hash, message, timestamp, and URL.",
+ "created_at": "Unix timestamp (seconds) when the run was created.",
+ "updated_at": "Unix timestamp (seconds) when the run was last updated.",
+ "delta": "Resource change counts produced by the run (added, changed, deleted).",
+ "drift_detection": "Whether the run was triggered by drift detection.",
+ "expired": "Whether the run expired before being confirmed.",
+ "finished": "Whether the run has reached a terminal state.",
+ "needs_approval": "Whether the run is blocked waiting for an approval policy.",
+ "state": "Current state of the run (e.g. QUEUED, PLANNING, FINISHED, FAILED).",
+ "title": "Human-readable title of the run.",
+ "triggered_by": "User or trigger that started the run, if any.",
+ "type": "Type of the run (e.g. TRACKED, PROPOSED, TASK).",
+ "is_module": "Whether the run belongs to a module rather than a stack.",
+ "stack_id": "ID of the stack or module the run belongs to.",
+ "stack_name": "Name of the stack or module the run belongs to.",
+ },
+ },
+ "policies": {
+ "description": "Open Policy Agent (Rego) policies controlling login, access, approval, push, and notification behavior across the account.",
+ "docs_url": "https://docs.spacelift.io/concepts/policy/",
+ "columns": {
+ "id": "Unique identifier (slug) of the policy.",
+ "name": "Human-readable name of the policy.",
+ "description": "Free-form description of the policy.",
+ "type": "Policy type (e.g. ACCESS, APPROVAL, LOGIN, PLAN, PUSH, NOTIFICATION).",
+ "body": "Rego source code of the policy.",
+ "space": "ID of the Spacelift space the policy belongs to.",
+ "labels": "Labels attached to the policy.",
+ "created_at": "Unix timestamp (seconds) when the policy was created.",
+ "updated_at": "Unix timestamp (seconds) when the policy was last updated.",
+ },
+ },
+ "contexts": {
+ "description": "Reusable bundles of environment variables and mounted files attached to stacks.",
+ "docs_url": "https://docs.spacelift.io/concepts/configuration/context",
+ "columns": {
+ "id": "Unique identifier (slug) of the context.",
+ "name": "Human-readable name of the context.",
+ "description": "Free-form description of the context.",
+ "space": "ID of the Spacelift space the context belongs to.",
+ "labels": "Labels attached to the context.",
+ "created_at": "Unix timestamp (seconds) when the context was created.",
+ "updated_at": "Unix timestamp (seconds) when the context was last updated.",
+ },
+ },
+ "modules": {
+ "description": "Terraform modules published to the Spacelift module registry, with their tracked repository and current version.",
+ "docs_url": "https://docs.spacelift.io/vendors/terraform/module-registry",
+ "columns": {
+ "id": "Unique identifier (slug) of the module.",
+ "name": "Human-readable name of the module.",
+ "administrative": "Whether the module has administrative permissions on the Spacelift account.",
+ "branch": "VCS branch the module tracks.",
+ "created_at": "Unix timestamp (seconds) when the module was created.",
+ "current": "Current (latest) published version of the module.",
+ "description": "Free-form description of the module.",
+ "labels": "Labels attached to the module.",
+ "namespace": "VCS namespace (organization or user) of the module's repository.",
+ "owner_subdomain": "Subdomain of the Spacelift account that owns the module.",
+ "project_root": "Directory inside the repository the module lives in.",
+ "provider": "VCS provider hosting the module's repository.",
+ "public": "Whether the module is publicly visible.",
+ "repository": "Name of the repository the module tracks.",
+ "space": "ID of the Spacelift space the module belongs to.",
+ "terraform_provider": "Cloud provider the module targets (registry naming).",
+ "workflow_tool": "IaC tool the module uses (e.g. TERRAFORM_FOSS, OPEN_TOFU).",
+ },
+ },
+ "worker_pools": {
+ "description": "Private worker pools that execute runs, with queue depth and busy-worker counts.",
+ "docs_url": "https://docs.spacelift.io/concepts/worker-pools/",
+ "columns": {
+ "id": "Unique identifier of the worker pool.",
+ "name": "Human-readable name of the worker pool.",
+ "description": "Free-form description of the worker pool.",
+ "space": "ID of the Spacelift space the worker pool belongs to.",
+ "labels": "Labels attached to the worker pool.",
+ "created_at": "Unix timestamp (seconds) when the worker pool was created.",
+ "updated_at": "Unix timestamp (seconds) when the worker pool was last updated.",
+ "deleted": "Whether the worker pool has been deleted.",
+ "busy_workers": "Number of workers currently processing a run.",
+ "pending_runs": "Number of runs queued for this worker pool.",
+ },
+ },
+ "spaces": {
+ "description": "Organizational spaces grouping stacks, policies, and other resources into an access-control hierarchy.",
+ "docs_url": "https://docs.spacelift.io/concepts/spaces/",
+ "columns": {
+ "id": "Unique identifier (slug) of the space.",
+ "name": "Human-readable name of the space.",
+ "description": "Free-form description of the space.",
+ "parent_space": "ID of the parent space in the hierarchy, if any.",
+ "inherit_entities": "Whether the space inherits entities (contexts, policies, worker pools) from its parent.",
+ "labels": "Labels attached to the space.",
+ },
+ },
+ "managed_entities": {
+ "description": "Individual infrastructure resources (Terraform/OpenTofu entities) managed across all stacks, including drift status per resource.",
+ "docs_url": "https://docs.spacelift.io/concepts/resources",
+ "columns": {
+ "id": "Identifier of the managed entity within its stack.",
+ "address": "Terraform address of the resource (e.g. aws_instance.web).",
+ "name": "Name of the resource.",
+ "type": "Resource type (e.g. aws_instance).",
+ "parent": "Address of the parent module the resource belongs to.",
+ "drifted": "Whether the resource has drifted from its desired state.",
+ "stack_id": "ID of the stack managing the resource.",
+ "stack_name": "Name of the stack managing the resource.",
+ "creator": "Run that created the resource.",
+ "updater": "Run that last updated the resource.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/settings.py
new file mode 100644
index 000000000000..ca066fdc1b3e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/settings.py
@@ -0,0 +1,260 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ PartitionFormat,
+ PartitionMode,
+ SortMode,
+)
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+SPACELIFT_HOST_TEMPLATE = "https://{account_name}.app.spacelift.io/graphql"
+SPACELIFT_PAGE_SIZE = 100
+
+CREATED_AT = "createdAt"
+
+# Runs mutate after creation (queued -> in progress -> finished/failed) but the only
+# server-side filter Spacelift's search API supports is a time range on `createdAt`,
+# so incremental syncs re-pull a trailing window and let the delta merge collapse
+# state changes onto the primary key. Runs typically settle within hours; a week
+# covers long-lived approvals and drift-detection reruns without re-reading history.
+RUNS_INCREMENTAL_LOOKBACK_SECONDS = 7 * 24 * 60 * 60
+
+INCREMENTAL_CREATED_AT_FIELDS: list[IncrementalField] = [
+ {
+ "label": CREATED_AT,
+ "type": IncrementalFieldType.Integer,
+ "field": CREATED_AT,
+ "field_type": IncrementalFieldType.Integer,
+ },
+]
+
+
+@dataclass
+class SpaceliftEndpointConfig:
+ name: str
+ # Top-level GraphQL field, e.g. "searchStacks". Fields prefixed "search" are
+ # Relay-style connections taking a `SearchInput!`; anything else is a plain
+ # list query with no pagination (e.g. "spaces").
+ graphql_field: str
+ # GraphQL selection set for one row (the connection node or list element).
+ node_selection: str
+ is_connection: bool = True
+ # searchRuns nodes are `RunWithStack { run {...} stack {...} }` rather than a
+ # flat object; the transport flattens them into run rows with stack context.
+ flatten_run_with_stack: bool = False
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Rows per page. Most connections accept 100; searchModules rejects anything over 50.
+ page_size: int = SPACELIFT_PAGE_SIZE
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ partition_key: str | None = None
+ partition_mode: PartitionMode | None = None
+ partition_format: PartitionFormat | None = None
+ sort_mode: SortMode = "asc"
+
+
+# Field selections verified against the live Spacelift GraphQL schema (validation-level,
+# unauthenticated). Timestamps (`createdAt`, `updatedAt`, ...) are Unix epoch seconds (Int).
+STACK_SELECTION = """
+id
+name
+administrative
+apiHost
+branch
+createdAt
+deleted
+deleting
+description
+isDrifted
+labels
+lockedAt
+lockedBy
+managesStateFile
+namespace
+projectRoot
+provider
+repository
+repositoryURL
+space
+state
+stateSetAt
+terraformVersion
+vcsDetached
+"""
+
+RUN_SELECTION = """
+id
+branch
+commit {
+ authorLogin
+ authorName
+ hash
+ message
+ timestamp
+ url
+}
+createdAt
+updatedAt
+delta {
+ addCount
+ changeCount
+ deleteCount
+ resources
+}
+driftDetection
+expired
+finished
+needsApproval
+state
+title
+triggeredBy
+type
+"""
+
+POLICY_SELECTION = """
+id
+name
+description
+type
+body
+space
+labels
+createdAt
+updatedAt
+"""
+
+CONTEXT_SELECTION = """
+id
+name
+description
+space
+labels
+createdAt
+updatedAt
+"""
+
+MODULE_SELECTION = """
+id
+name
+administrative
+apiHost
+branch
+createdAt
+current {
+ id
+ number
+}
+description
+labels
+namespace
+ownerSubdomain
+projectRoot
+provider
+public
+repository
+space
+terraformProvider
+workflowTool
+"""
+
+WORKER_POOL_SELECTION = """
+id
+name
+description
+space
+labels
+createdAt
+updatedAt
+deleted
+busyWorkers
+pendingRuns
+"""
+
+SPACE_SELECTION = """
+id
+name
+description
+parentSpace
+inheritEntities
+labels
+"""
+
+MANAGED_ENTITY_SELECTION = """
+id
+address
+name
+type
+parent
+drifted
+stackId
+stackName
+creator {
+ id
+}
+updater {
+ id
+}
+"""
+
+SPACELIFT_ENDPOINTS: dict[str, SpaceliftEndpointConfig] = {
+ "stacks": SpaceliftEndpointConfig(
+ name="stacks",
+ graphql_field="searchStacks",
+ node_selection=STACK_SELECTION,
+ ),
+ # Account-wide across every stack and module, newest-first (the API's default
+ # order; `orderBy` semantics aren't verifiable without credentials, so we rely
+ # on the default and report sort_mode="desc" — the watermark then only persists
+ # at successful job end, which is safe in either order).
+ "runs": SpaceliftEndpointConfig(
+ name="runs",
+ graphql_field="searchRuns",
+ node_selection=RUN_SELECTION,
+ flatten_run_with_stack=True,
+ incremental_fields=INCREMENTAL_CREATED_AT_FIELDS,
+ partition_key=CREATED_AT,
+ partition_mode="datetime",
+ partition_format="month",
+ sort_mode="desc",
+ ),
+ "policies": SpaceliftEndpointConfig(
+ name="policies",
+ graphql_field="searchPolicies",
+ node_selection=POLICY_SELECTION,
+ ),
+ "contexts": SpaceliftEndpointConfig(
+ name="contexts",
+ graphql_field="searchContexts",
+ node_selection=CONTEXT_SELECTION,
+ ),
+ "modules": SpaceliftEndpointConfig(
+ name="modules",
+ graphql_field="searchModules",
+ node_selection=MODULE_SELECTION,
+ page_size=50,
+ ),
+ "worker_pools": SpaceliftEndpointConfig(
+ name="worker_pools",
+ graphql_field="searchWorkerPools",
+ node_selection=WORKER_POOL_SELECTION,
+ ),
+ "spaces": SpaceliftEndpointConfig(
+ name="spaces",
+ graphql_field="spaces",
+ node_selection=SPACE_SELECTION,
+ is_connection=False,
+ ),
+ # Terraform/OpenTofu resources tracked across stacks. Entity ids aren't documented
+ # as globally unique, so the key includes the owning stack.
+ "managed_entities": SpaceliftEndpointConfig(
+ name="managed_entities",
+ graphql_field="searchManagedEntities",
+ node_selection=MANAGED_ENTITY_SELECTION,
+ primary_keys=["stackId", "id"],
+ ),
+}
+
+ENDPOINTS = tuple(SPACELIFT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SPACELIFT_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/source.py
index d516006659e2..e0bff219a398 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/source.py
@@ -1,30 +1,179 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SpaceliftSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ RUNS_INCREMENTAL_LOOKBACK_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.spacelift import (
+ SpaceliftResumeConfig,
+ spacelift_source,
+ validate_credentials as validate_spacelift_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SpaceliftSource(SimpleSource[SpaceliftSourceConfig]):
+class SpaceliftSource(ResumableSource[SpaceliftSourceConfig, SpaceliftResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SPACELIFT
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The account name picks the host the stored API key secret is sent to
+ # (https://<account_name>.app.spacelift.io); retargeting it must re-require the secret.
+ return ["account_name"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SPACELIFT,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Spacelift",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Spacelift API key to pull your infrastructure-as-code stacks, runs, policies, and managed resources into the PostHog Data warehouse.
+
+Create an API key under **Organization settings** → **API keys** in your Spacelift account. Grant it at least read access to the spaces you want to sync.
+
+Your account name is the subdomain you use to access Spacelift (e.g. `my-company` for `my-company.app.spacelift.io`).
+""",
iconPath="/static/services/spacelift.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/spacelift",
+ keywords=["terraform", "opentofu", "iac", "pulumi"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="account_name",
+ label="Account name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-company",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key_id",
+ label="API key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key_secret",
+ label="API key secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Raised by the apiKeyUser token exchange when the key id/secret is wrong or revoked.
+ "Invalid Spacelift API key": "Your Spacelift API key is invalid or has been revoked. Create a new API key in your Spacelift organization settings, then reconnect.",
+ # Raised when a query stays unauthorized after a fresh token, i.e. the key lacks space access.
+ "Spacelift API returned unauthorized": "Your Spacelift API key does not have access to this data. Grant the key read access to the relevant spaces in Spacelift, then reconnect.",
+ "Invalid Spacelift account name": "The Spacelift account name is invalid. Enter only the subdomain of your Spacelift URL (e.g. `my-company` for `my-company.app.spacelift.io`).",
+ }
+
+ @staticmethod
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "runs":
+ return (
+ "All runs across every stack and module. Incremental syncs re-pull the last "
+ f"{RUNS_INCREMENTAL_LOOKBACK_SECONDS // 86400} days so state changes on recent runs are captured"
+ )
+ if endpoint == "managed_entities":
+ return "Terraform/OpenTofu resources managed across your stacks, including drift status"
+ return None
+
+ def get_schemas(
+ self,
+ config: SpaceliftSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ # Incremental runs re-pull a lookback window whose rows only merge
+ # dedupes, so append mode would materialize duplicates. The lookback
+ # is applied in the transport (the framework-level lookback only
+ # shifts datetime cursors, and Spacelift's are epoch-second ints).
+ supports_incremental=has_incremental,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=self._description(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: SpaceliftSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_spacelift_credentials(config.account_name, config.api_key_id, config.api_key_secret)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SpaceliftResumeConfig]:
+ return ResumableSourceManager[SpaceliftResumeConfig](inputs, SpaceliftResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SpaceliftSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SpaceliftResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return spacelift_source(
+ account_name=config.account_name,
+ api_key_id=config.api_key_id,
+ api_key_secret=config.api_key_secret,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/spacelift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/spacelift.py
new file mode 100644
index 000000000000..0b219fdf8374
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/spacelift.py
@@ -0,0 +1,376 @@
+import re
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.settings import (
+ RUNS_INCREMENTAL_LOOKBACK_SECONDS,
+ SPACELIFT_ENDPOINTS,
+ SPACELIFT_HOST_TEMPLATE,
+ SpaceliftEndpointConfig,
+)
+
+# Spacelift publishes no rate limits; ride out transient 429/5xx bursts in-process
+# before letting Temporal reschedule the activity (which resumes from the saved cursor).
+SPACELIFT_MAX_RETRY_ATTEMPTS = 5
+# Refresh the ~10h API-key JWT this long before its reported expiry.
+TOKEN_REFRESH_MARGIN_SECONDS = 5 * 60
+
+_ACCOUNT_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
+
+TOKEN_EXCHANGE_MUTATION = """
+mutation GetSpaceliftToken($id: ID!, $secret: String!) {
+ apiKeyUser(id: $id, secret: $secret) {
+ jwt
+ validUntil
+ }
+}
+"""
+
+
+class SpaceliftRetryableError(Exception):
+ pass
+
+
+class SpaceliftAuthError(Exception):
+ pass
+
+
+class SpaceliftPermissionError(Exception):
+ pass
+
+
+class SpaceliftResumeConfig:
+ # Relay `after` cursor of the next page to fetch for the current endpoint.
+ cursor: str
+
+
+def normalize_account_name(account_name: str) -> str:
+ """Validate and normalize the Spacelift account subdomain.
+
+ The account name is interpolated into the request host, so anything that isn't a
+ plain DNS label must be rejected — otherwise a crafted value could redirect the
+ stored API secret to an attacker-controlled host.
+ """
+ normalized = account_name.strip().lower()
+ if not normalized or not _ACCOUNT_NAME_RE.match(normalized):
+ raise ValueError(f"Invalid Spacelift account name: {account_name!r}")
+ return normalized
+
+
+def _graphql_url(account_name: str) -> str:
+ return SPACELIFT_HOST_TEMPLATE.format(account_name=normalize_account_name(account_name))
+
+
+def build_query(config: SpaceliftEndpointConfig) -> str:
+ if not config.is_connection:
+ return f"query {{ {config.graphql_field} {{ {config.node_selection} }} }}"
+
+ if config.flatten_run_with_stack:
+ node_selection = f"isModule run {{ {config.node_selection} }} stack {{ id name }}"
+ else:
+ node_selection = config.node_selection
+
+ return f"""
+query Search($input: SearchInput!) {{
+ {config.graphql_field}(input: $input) {{
+ edges {{
+ cursor
+ node {{ {node_selection} }}
+ }}
+ pageInfo {{
+ endCursor
+ hasNextPage
+ }}
+ }}
+}}
+"""
+
+
+def to_unix_seconds(value: Any) -> int | None:
+ """Coerce an incremental watermark into the Unix-seconds Int Spacelift timestamps use."""
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ return int(value)
+ if isinstance(value, datetime):
+ return int(value.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time()).timestamp())
+ if isinstance(value, str):
+ stripped = value.strip()
+ if stripped.isdigit():
+ return int(stripped)
+ try:
+ return int(datetime.fromisoformat(stripped).timestamp())
+ except ValueError:
+ return None
+ return None
+
+
+def build_incremental_predicates(incremental_field: str, last_value: Any) -> list[dict[str, Any]] | None:
+ """Build the server-side `timeInRange` predicate for an incremental sync.
+
+ Mirrors the filter the Spacelift UI itself sends to `searchRuns`. The watermark is
+ shifted back by a lookback window so runs that changed state after first being
+ synced are re-pulled; the delta merge dedupes them on the primary key. (The
+ framework-level lookback only applies to datetime cursors, and Spacelift's are
+ epoch-second ints, so the overlap is applied here.)
+ """
+ start = to_unix_seconds(last_value)
+ if start is None:
+ return None
+ start = max(0, start - RUNS_INCREMENTAL_LOOKBACK_SECONDS)
+ return [{"field": incremental_field, "constraint": {"timeInRange": {"start": start}}}]
+
+
+class SpaceliftClient:
+ def __init__(self, account_name: str, api_key_id: str, api_key_secret: str) -> None:
+ self._graphql_url = _graphql_url(account_name)
+ self._api_key_id = api_key_id
+ self._api_key_secret = api_key_secret
+ # The token exchange sends the API-key secret in a GraphQL `secret` variable and
+ # receives a minted JWT — field names the sample scrubber's denylist can't
+ # recognise — so keep this session's traffic out of HTTP sample capture entirely
+ # (still metered and logged) and mask the static secret wherever it appears.
+ # The host derives from a user-supplied field, so never follow redirects that
+ # could bounce a credential-bearing request elsewhere.
+ self._session = make_tracked_session(
+ headers={"Content-Type": "application/json"},
+ redact_values=(api_key_secret,),
+ capture=False,
+ allow_redirects=False,
+ )
+ self._jwt: str | None = None
+ self._jwt_valid_until: float = 0.0
+
+ def close(self) -> None:
+ self._session.close()
+
+ @retry(
+ retry=retry_if_exception_type(SpaceliftRetryableError),
+ stop=stop_after_attempt(SPACELIFT_MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def _post(self, body: dict[str, Any], headers: dict[str, str] | None = None) -> dict[str, Any]:
+ try:
+ response = self._session.post(self._graphql_url, json=body, headers=headers, timeout=60)
+ except (requests.ConnectionError, requests.Timeout, requests.exceptions.ChunkedEncodingError) as e:
+ # POSTs get no transport-level retry from urllib3, so route transient
+ # network failures through the same backoff path as 429/5xx.
+ raise SpaceliftRetryableError(f"Spacelift: transient network error - {e}") from e
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SpaceliftRetryableError(f"Spacelift: retryable HTTP error {response.status_code}")
+
+ try:
+ payload = response.json()
+ except Exception as e:
+ if not response.ok:
+ raise Exception(f"{response.status_code} Client Error: {response.reason} (Spacelift API)") from e
+ # A 2xx that won't parse is almost always a truncated transfer, not a
+ # stable response — ride it out on the backoff path.
+ raise SpaceliftRetryableError(f"Spacelift: incomplete JSON response ({e})") from e
+
+ if not isinstance(payload, dict):
+ raise Exception(f"Unexpected Spacelift response format: {type(payload).__name__}")
+
+ return payload
+
+ def _exchange_token(self) -> None:
+ payload = self._post(
+ {"query": TOKEN_EXCHANGE_MUTATION, "variables": {"id": self._api_key_id, "secret": self._api_key_secret}}
+ )
+
+ errors = payload.get("errors")
+ if errors:
+ messages = "; ".join(e.get("message", "") for e in errors)
+ raise SpaceliftAuthError(f"Invalid Spacelift API key: token exchange failed ({messages})")
+
+ # Spacelift signals a bad key id/secret with a null user, not a GraphQL error.
+ user = (payload.get("data") or {}).get("apiKeyUser")
+ if not isinstance(user, dict) or not user.get("jwt"):
+ raise SpaceliftAuthError("Invalid Spacelift API key: the API key ID or secret is incorrect")
+
+ self._jwt = user["jwt"]
+ valid_until = to_unix_seconds(user.get("validUntil"))
+ # The JWT lasts ~10h; fall back to a conservative window if the API omits the expiry.
+ self._jwt_valid_until = float(valid_until) if valid_until else time.time() + 8 * 60 * 60
+
+ def _ensure_token(self) -> str:
+ if self._jwt is None or time.time() >= self._jwt_valid_until - TOKEN_REFRESH_MARGIN_SECONDS:
+ self._exchange_token()
+ assert self._jwt is not None
+ return self._jwt
+
+ def execute(self, query: str, variables: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Run an authenticated GraphQL query, refreshing the JWT once if it expired mid-sync."""
+ for attempt in range(2):
+ jwt = self._ensure_token()
+ payload = self._post(
+ {"query": query, "variables": variables or {}}, headers={"Authorization": f"Bearer {jwt}"}
+ )
+
+ errors = payload.get("errors")
+ if errors:
+ messages = "; ".join(e.get("message", "") for e in errors)
+ if "unauthorized" in messages.lower():
+ if attempt == 0:
+ self._jwt = None
+ continue
+ raise SpaceliftPermissionError(
+ f"Spacelift API returned unauthorized: the API key lacks access to this data ({messages})"
+ )
+ raise Exception(f"Spacelift GraphQL error: {messages}")
+
+ data = payload.get("data")
+ if not isinstance(data, dict):
+ raise Exception(f"Unexpected Spacelift response format. Keys: {list(payload.keys())}")
+ return data
+
+ raise SpaceliftPermissionError("Spacelift API returned unauthorized: the API key lacks access to this data")
+
+
+def _normalize_run_node(node: dict[str, Any]) -> dict[str, Any]:
+ """Flatten a `RunWithStack` node into a run row carrying its stack context."""
+ row = dict(node.get("run") or {})
+ stack = node.get("stack") or {}
+ row["isModule"] = node.get("isModule")
+ row["stackId"] = stack.get("id")
+ row["stackName"] = stack.get("name")
+ return row
+
+
+def _get_rows(
+ client: SpaceliftClient,
+ endpoint_config: SpaceliftEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SpaceliftResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ query = build_query(endpoint_config)
+
+ try:
+ if not endpoint_config.is_connection:
+ data = client.execute(query)
+ rows = data.get(endpoint_config.graphql_field) or []
+ if rows:
+ yield rows
+ return
+
+ search_input: dict[str, Any] = {"first": endpoint_config.page_size, "after": None}
+
+ if should_use_incremental_field and incremental_field:
+ predicates = build_incremental_predicates(incremental_field, db_incremental_field_last_value)
+ if predicates:
+ search_input["predicates"] = predicates
+ logger.debug(f"Spacelift: incremental sync for {endpoint_config.name} with predicates {predicates}")
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None and resume_config.cursor:
+ search_input["after"] = resume_config.cursor
+ logger.debug(f"Spacelift: resuming {endpoint_config.name} from saved cursor")
+
+ while True:
+ data = client.execute(query, {"input": search_input})
+ connection = data.get(endpoint_config.graphql_field) or {}
+ edges = connection.get("edges") or []
+ page_info = connection.get("pageInfo") or {}
+
+ if endpoint_config.flatten_run_with_stack:
+ rows = [_normalize_run_node(edge.get("node") or {}) for edge in edges]
+ else:
+ rows = [edge.get("node") for edge in edges if edge.get("node") is not None]
+
+ if rows:
+ yield rows
+
+ if not page_info.get("hasNextPage"):
+ break
+
+ end_cursor = page_info.get("endCursor")
+ if not end_cursor:
+ # A hasNextPage=True page with no cursor would loop forever on itself;
+ # fail loudly instead of silently returning partial results.
+ raise Exception(f"Spacelift: hasNextPage=True but endCursor is empty for {endpoint_config.name}")
+
+ # Save AFTER yielding so a crash re-yields the last page rather than
+ # skipping it — the merge dedupes on the primary key.
+ resumable_source_manager.save_state(SpaceliftResumeConfig(cursor=end_cursor))
+ search_input["after"] = end_cursor
+ finally:
+ client.close()
+
+
+def spacelift_source(
+ account_name: str,
+ api_key_id: str,
+ api_key_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SpaceliftResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = SPACELIFT_ENDPOINTS.get(endpoint)
+ if endpoint_config is None:
+ raise ValueError(f"Unknown Spacelift endpoint: {endpoint}")
+
+ def get_rows() -> Iterator[list[dict[str, Any]]]:
+ client = SpaceliftClient(account_name, api_key_id, api_key_secret)
+ yield from _get_rows(
+ client=client,
+ endpoint_config=endpoint_config,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=get_rows,
+ primary_keys=endpoint_config.primary_keys,
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1 if endpoint_config.partition_mode else None,
+ partition_size=1 if endpoint_config.partition_mode else None,
+ partition_mode=endpoint_config.partition_mode,
+ partition_format=endpoint_config.partition_format,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def validate_credentials(account_name: str, api_key_id: str, api_key_secret: str) -> tuple[bool, str | None]:
+ try:
+ client = SpaceliftClient(account_name, api_key_id, api_key_secret)
+ except ValueError as e:
+ return False, str(e)
+
+ try:
+ client._ensure_token()
+ return True, None
+ except SpaceliftAuthError as e:
+ return False, str(e)
+ except Exception as e:
+ return False, f"Could not verify Spacelift credentials: {e}"
+ finally:
+ client.close()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/tests/test_spacelift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/tests/test_spacelift.py
new file mode 100644
index 000000000000..cfc5af9ce4b9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/tests/test_spacelift.py
@@ -0,0 +1,399 @@
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.settings import (
+ RUNS_INCREMENTAL_LOOKBACK_SECONDS,
+ SPACELIFT_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.spacelift import (
+ SpaceliftAuthError,
+ SpaceliftClient,
+ SpaceliftPermissionError,
+ SpaceliftResumeConfig,
+ build_incremental_predicates,
+ build_query,
+ normalize_account_name,
+ spacelift_source,
+ to_unix_seconds,
+ validate_credentials,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.spacelift"
+
+TOKEN_PAYLOAD = {"data": {"apiKeyUser": {"jwt": "jwt-1", "validUntil": 99999999999}}}
+
+
+def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ resp.json.return_value = payload
+ return resp
+
+
+def _search_page(
+ graphql_field: str, nodes: list[dict[str, Any]], end_cursor: str = "", has_next: bool = False
+) -> mock.MagicMock:
+ return _response(
+ {
+ "data": {
+ graphql_field: {
+ "edges": [{"cursor": end_cursor, "node": node} for node in nodes],
+ "pageInfo": {"endCursor": end_cursor, "hasNextPage": has_next},
+ }
+ }
+ }
+ )
+
+
+def _make_manager(resume_state: SpaceliftResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _mock_session(mock_make_session: mock.MagicMock, responses: list[mock.MagicMock]) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.post.side_effect = responses
+ mock_make_session.return_value = session
+ return session
+
+
+def _query_calls(session: mock.MagicMock) -> list[Any]:
+ # Skip the initial apiKeyUser token exchange, leaving the data queries.
+ return session.post.call_args_list[1:]
+
+
+class TestSpacelift:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("my-company", "my-company"),
+ (" My-Company ", "my-company"),
+ ("acme2", "acme2"),
+ ],
+ )
+ def test_normalize_account_name_accepts_dns_labels(self, raw, expected):
+ assert normalize_account_name(raw) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ "",
+ " ",
+ "evil.com",
+ "evil.com/graphql?",
+ "acme@attacker",
+ "-leading-dash",
+ "under_score",
+ "spa ce",
+ ],
+ )
+ def test_normalize_account_name_rejects_host_injection(self, raw):
+ with pytest.raises(ValueError):
+ normalize_account_name(raw)
+
+ @pytest.mark.parametrize("endpoint", [name for name, c in SPACELIFT_ENDPOINTS.items() if c.is_connection])
+ def test_build_query_for_connections(self, endpoint):
+ config = SPACELIFT_ENDPOINTS[endpoint]
+ query = build_query(config)
+ assert f"{config.graphql_field}(input: $input)" in query
+ assert "pageInfo" in query
+ assert "endCursor" in query
+
+ def test_build_query_wraps_runs_in_run_with_stack(self):
+ query = build_query(SPACELIFT_ENDPOINTS["runs"])
+ assert "isModule run {" in query
+ assert "stack { id name }" in query
+
+ def test_build_query_for_plain_list(self):
+ query = build_query(SPACELIFT_ENDPOINTS["spaces"])
+ assert "SearchInput" not in query
+ assert "spaces {" in query
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (1700000000, 1700000000),
+ (1700000000.9, 1700000000),
+ ("1700000000", 1700000000),
+ (datetime(2024, 1, 1, tzinfo=UTC), 1704067200),
+ ("2024-01-01T00:00:00+00:00", 1704067200),
+ (date(1970, 1, 1), 0),
+ (None, None),
+ ("not-a-date", None),
+ (True, None),
+ ],
+ )
+ def test_to_unix_seconds(self, value, expected):
+ assert to_unix_seconds(value) == expected
+
+ def test_incremental_predicates_apply_lookback(self):
+ predicates = build_incremental_predicates("createdAt", 1700000000)
+ assert predicates == [
+ {
+ "field": "createdAt",
+ "constraint": {"timeInRange": {"start": 1700000000 - RUNS_INCREMENTAL_LOOKBACK_SECONDS}},
+ }
+ ]
+
+ def test_incremental_predicates_clamp_at_zero(self):
+ predicates = build_incremental_predicates("createdAt", 10)
+ assert predicates is not None
+ assert predicates[0]["constraint"]["timeInRange"]["start"] == 0
+
+ def test_incremental_predicates_none_for_unparseable_value(self):
+ assert build_incremental_predicates("createdAt", "garbage") is None
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_session_keeps_credentials_out_of_sample_capture(self, mock_make_session):
+ # The exchange body carries the raw secret and the response a minted JWT — names
+ # the sample scrubber can't recognise, so the session must opt out of capture.
+ SpaceliftClient("my-company", "key-id", "key-secret")
+
+ kwargs = mock_make_session.call_args.kwargs
+ assert kwargs["capture"] is False
+ assert kwargs["allow_redirects"] is False
+ assert "key-secret" in kwargs["redact_values"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_token_exchange_null_user_raises_auth_error(self, mock_make_session):
+ # Spacelift signals a bad key with apiKeyUser=null and no GraphQL error.
+ _mock_session(mock_make_session, [_response({"data": {"apiKeyUser": None}})])
+
+ client = SpaceliftClient("my-company", "key-id", "key-secret")
+ with pytest.raises(SpaceliftAuthError):
+ client._ensure_token()
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_execute_sends_bearer_token(self, mock_make_session):
+ session = _mock_session(
+ mock_make_session,
+ [_response(TOKEN_PAYLOAD), _search_page("searchStacks", [{"id": "stack-1"}])],
+ )
+
+ client = SpaceliftClient("my-company", "key-id", "key-secret")
+ data = client.execute("query { x }")
+
+ assert data["searchStacks"]["edges"][0]["node"] == {"id": "stack-1"}
+ assert _query_calls(session)[0].kwargs["headers"] == {"Authorization": "Bearer jwt-1"}
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_execute_refreshes_token_once_on_unauthorized(self, mock_make_session):
+ # A JWT expiring mid-sync surfaces as an `unauthorized` GraphQL error; one
+ # re-exchange must recover, a second unauthorized is a real permission gap.
+ session = _mock_session(
+ mock_make_session,
+ [
+ _response(TOKEN_PAYLOAD),
+ _response({"errors": [{"message": "unauthorized"}], "data": None}),
+ _response({"data": {"apiKeyUser": {"jwt": "jwt-2", "validUntil": 99999999999}}}),
+ _search_page("searchStacks", [{"id": "stack-1"}]),
+ ],
+ )
+
+ client = SpaceliftClient("my-company", "key-id", "key-secret")
+ data = client.execute("query { x }")
+
+ assert data["searchStacks"]["edges"][0]["node"] == {"id": "stack-1"}
+ assert session.post.call_args_list[3].kwargs["headers"] == {"Authorization": "Bearer jwt-2"}
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_execute_raises_permission_error_when_still_unauthorized(self, mock_make_session):
+ _mock_session(
+ mock_make_session,
+ [
+ _response(TOKEN_PAYLOAD),
+ _response({"errors": [{"message": "unauthorized"}], "data": None}),
+ _response(TOKEN_PAYLOAD),
+ _response({"errors": [{"message": "unauthorized"}], "data": None}),
+ ],
+ )
+
+ client = SpaceliftClient("my-company", "key-id", "key-secret")
+ with pytest.raises(SpaceliftPermissionError):
+ client.execute("query { x }")
+
+ @mock.patch("tenacity.nap.time")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_retryable_statuses_are_retried(self, mock_make_session, mock_nap):
+ _mock_session(
+ mock_make_session,
+ [
+ _response({}, status_code=429),
+ _response({}, status_code=503),
+ _response(TOKEN_PAYLOAD),
+ ],
+ )
+
+ client = SpaceliftClient("my-company", "key-id", "key-secret")
+ assert client._ensure_token() == "jwt-1"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_pagination_follows_cursor_and_saves_state_after_yield(self, mock_make_session):
+ session = _mock_session(
+ mock_make_session,
+ [
+ _response(TOKEN_PAYLOAD),
+ _search_page("searchStacks", [{"id": "stack-1"}], end_cursor="cur-1", has_next=True),
+ _search_page("searchStacks", [{"id": "stack-2"}], end_cursor="cur-2", has_next=False),
+ ],
+ )
+ manager = _make_manager()
+
+ response = spacelift_source("my-company", "key-id", "key-secret", "stacks", mock.MagicMock(), manager)
+ batches = list(cast(Iterable[Any], response.items()))
+
+ assert batches == [[{"id": "stack-1"}], [{"id": "stack-2"}]]
+ # The cursor checkpoints only between pages, pointing at the next page to fetch.
+ manager.save_state.assert_called_once_with(SpaceliftResumeConfig(cursor="cur-1"))
+ assert _query_calls(session)[1].kwargs["json"]["variables"]["input"]["after"] == "cur-1"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_resume_starts_from_saved_cursor(self, mock_make_session):
+ session = _mock_session(
+ mock_make_session,
+ [_response(TOKEN_PAYLOAD), _search_page("searchStacks", [{"id": "stack-9"}])],
+ )
+ manager = _make_manager(SpaceliftResumeConfig(cursor="saved-cursor"))
+
+ response = spacelift_source("my-company", "key-id", "key-secret", "stacks", mock.MagicMock(), manager)
+ list(cast(Iterable[Any], response.items()))
+
+ assert _query_calls(session)[0].kwargs["json"]["variables"]["input"]["after"] == "saved-cursor"
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_runs_rows_flatten_run_with_stack(self, mock_make_session):
+ node = {
+ "isModule": False,
+ "run": {"id": "run-1", "state": "FINISHED", "createdAt": 1700000100},
+ "stack": {"id": "stack-1", "name": "core-infra"},
+ }
+ _mock_session(mock_make_session, [_response(TOKEN_PAYLOAD), _search_page("searchRuns", [node])])
+ manager = _make_manager()
+
+ response = spacelift_source("my-company", "key-id", "key-secret", "runs", mock.MagicMock(), manager)
+ batches = list(cast(Iterable[Any], response.items()))
+
+ assert batches == [
+ [
+ {
+ "id": "run-1",
+ "state": "FINISHED",
+ "createdAt": 1700000100,
+ "isModule": False,
+ "stackId": "stack-1",
+ "stackName": "core-infra",
+ }
+ ]
+ ]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_sync_sends_time_range_predicate(self, mock_make_session):
+ session = _mock_session(mock_make_session, [_response(TOKEN_PAYLOAD), _search_page("searchRuns", [])])
+ manager = _make_manager()
+
+ response = spacelift_source(
+ "my-company",
+ "key-id",
+ "key-secret",
+ "runs",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ incremental_field="createdAt",
+ )
+ list(cast(Iterable[Any], response.items()))
+
+ sent_input = _query_calls(session)[0].kwargs["json"]["variables"]["input"]
+ assert sent_input["predicates"] == [
+ {
+ "field": "createdAt",
+ "constraint": {"timeInRange": {"start": 1700000000 - RUNS_INCREMENTAL_LOOKBACK_SECONDS}},
+ }
+ ]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_full_refresh_sends_no_predicates(self, mock_make_session):
+ session = _mock_session(mock_make_session, [_response(TOKEN_PAYLOAD), _search_page("searchRuns", [])])
+ manager = _make_manager()
+
+ response = spacelift_source("my-company", "key-id", "key-secret", "runs", mock.MagicMock(), manager)
+ list(cast(Iterable[Any], response.items()))
+
+ assert "predicates" not in _query_calls(session)[0].kwargs["json"]["variables"]["input"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_plain_list_endpoint_yields_rows_without_pagination(self, mock_make_session):
+ _mock_session(
+ mock_make_session,
+ [_response(TOKEN_PAYLOAD), _response({"data": {"spaces": [{"id": "root"}, {"id": "legacy"}]}})],
+ )
+ manager = _make_manager()
+
+ response = spacelift_source("my-company", "key-id", "key-secret", "spaces", mock.MagicMock(), manager)
+ batches = list(cast(Iterable[Any], response.items()))
+
+ assert batches == [[{"id": "root"}, {"id": "legacy"}]]
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_next_page_without_cursor_raises(self, mock_make_session):
+ # hasNextPage=True with an empty endCursor would loop on the same page forever.
+ _mock_session(
+ mock_make_session,
+ [_response(TOKEN_PAYLOAD), _search_page("searchStacks", [{"id": "stack-1"}], has_next=True)],
+ )
+ manager = _make_manager()
+
+ response = spacelift_source("my-company", "key-id", "key-secret", "stacks", mock.MagicMock(), manager)
+ with pytest.raises(Exception, match="endCursor is empty"):
+ list(cast(Iterable[Any], response.items()))
+
+ def test_unknown_endpoint_raises(self):
+ with pytest.raises(ValueError, match="Unknown Spacelift endpoint"):
+ spacelift_source("my-company", "key-id", "key-secret", "nope", mock.MagicMock(), _make_manager())
+
+ @pytest.mark.parametrize(
+ "endpoint, expected_sort_mode, expected_primary_keys",
+ [
+ ("stacks", "asc", ["id"]),
+ ("runs", "desc", ["id"]),
+ ("managed_entities", "asc", ["stackId", "id"]),
+ ],
+ )
+ def test_source_response_metadata(self, endpoint, expected_sort_mode, expected_primary_keys):
+ response = spacelift_source("my-company", "key-id", "key-secret", endpoint, mock.MagicMock(), _make_manager())
+ assert response.name == endpoint
+ assert response.sort_mode == expected_sort_mode
+ assert response.primary_keys == expected_primary_keys
+
+ def test_runs_partitions_on_created_at(self):
+ response = spacelift_source("my-company", "key-id", "key-secret", "runs", mock.MagicMock(), _make_manager())
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_success(self, mock_make_session):
+ _mock_session(mock_make_session, [_response(TOKEN_PAYLOAD)])
+
+ assert validate_credentials("my-company", "key-id", "key-secret") == (True, None)
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_bad_key(self, mock_make_session):
+ _mock_session(mock_make_session, [_response({"data": {"apiKeyUser": None}})])
+
+ is_valid, message = validate_credentials("my-company", "key-id", "key-secret")
+ assert is_valid is False
+ assert message is not None and "Invalid Spacelift API key" in message
+
+ def test_validate_credentials_invalid_account_name_never_hits_network(self):
+ is_valid, message = validate_credentials("evil.com/x", "key-id", "key-secret")
+ assert is_valid is False
+ assert message is not None and "Invalid Spacelift account name" in message
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/tests/test_spacelift_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/tests/test_spacelift_source.py
new file mode 100644
index 000000000000..50e9806cbdf9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/spacelift/tests/test_spacelift_source.py
@@ -0,0 +1,159 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SpaceliftSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.source import SpaceliftSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.spacelift import SpaceliftResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.spacelift.source"
+
+
+class TestSpaceliftSource:
+ def setup_method(self):
+ self.source = SpaceliftSource()
+ self.team_id = 123
+ self.config = SpaceliftSourceConfig(account_name="my-company", api_key_id="key-id", api_key_secret="key-secret")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.SPACELIFT
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Spacelift"
+ assert config.label == "Spacelift"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/spacelift.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/spacelift"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["account_name", "api_key_id", "api_key_secret"]
+
+ def test_api_key_secret_field_is_secret_password(self):
+ config = self.source.get_source_config
+ secret_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key_secret"
+ )
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+ assert secret_field.secret is True
+ assert secret_field.required is True
+
+ def test_account_name_is_a_connection_host_field(self):
+ # Retargeting the account subdomain must force re-entering the API secret,
+ # otherwise a PATCH could redirect the stored secret to an attacker's host.
+ assert self.source.connection_host_fields == ["account_name"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "Invalid Spacelift API key: the API key ID or secret is incorrect",
+ "Spacelift API returned unauthorized: the API key lacks access to this data (unauthorized)",
+ "Invalid Spacelift account name: 'evil.com/x'",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "Spacelift: retryable HTTP error 503",
+ "Spacelift GraphQL error: internal error",
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_transient_failures(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_runs_supports_incremental(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["runs"].supports_incremental is True
+ assert [f["field"] for f in schemas["runs"].incremental_fields] == ["createdAt"]
+ assert schemas["runs"].incremental_fields == INCREMENTAL_FIELDS["runs"]
+ for name, schema in schemas.items():
+ # Incremental re-pulls a lookback window that only merge dedupes.
+ assert schema.supports_append is False
+ if name != "runs":
+ assert schema.supports_incremental is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["runs", "stacks"])
+ assert {schema.name for schema in schemas} == {"runs", "stacks"}
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_without_credentials(self):
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return",
+ [
+ (True, None),
+ (False, "Invalid Spacelift API key: the API key ID or secret is incorrect"),
+ ],
+ )
+ @mock.patch(f"{_SOURCE_MODULE}.validate_spacelift_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ assert self.source.validate_credentials(self.config, self.team_id) == mock_return
+ mock_validate.assert_called_once_with("my-company", "key-id", "key-secret")
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SpaceliftResumeConfig
+
+ @mock.patch(f"{_SOURCE_MODULE}.spacelift_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "runs"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ inputs.incremental_field = "createdAt"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["account_name"] == "my-company"
+ assert kwargs["api_key_id"] == "key-id"
+ assert kwargs["api_key_secret"] == "key-secret"
+ assert kwargs["endpoint"] == "runs"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+ assert kwargs["incremental_field"] == "createdAt"
+
+ @mock.patch(f"{_SOURCE_MODULE}.spacelift_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "runs"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None