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 heroku import source (#70713)

Tom Owersf91d7a4998be
diff --git a/frontend/public/services/heroku.svg b/frontend/public/services/heroku.svg
new file mode 100644
index 000000000000..be7ae8874251
--- /dev/null
+++ b/frontend/public/services/heroku.svg
@@ -0,0 +1 @@
+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="#430098"><title>Heroku</title><path d="M20.61 0H3.39C2.189 0 1.23.96 1.23 2.16v19.681c0 1.198.959 2.159 2.16 2.159h17.22c1.2 0 2.159-.961 2.159-2.159V2.16C22.77.96 21.811 0 20.61 0zm.96 21.841c0 .539-.421.96-.96.96H3.39c-.54 0-.96-.421-.96-.96V2.16c0-.54.42-.961.96-.961h17.22c.539 0 .96.421.96.961v19.681zM6.63 20.399L9.33 18l-2.7-2.4v4.799zm9.72-9.719c-.479-.48-1.379-1.08-2.879-1.08-1.621 0-3.301.421-4.5.84V3.6h-2.4v10.38l1.68-.78s2.76-1.26 5.16-1.26c1.2 0 1.5.66 1.5 1.26v7.2h2.4v-7.2c.059-.179.059-1.501-.961-2.52zM13.17 7.5h2.4c1.08-1.26 1.62-2.521 1.8-3.9h-2.399c-.241 1.379-.841 2.64-1.801 3.9z"/></svg>
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 93315e314d2b..2757b2e46008 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -218,6 +218,7 @@ the row lists both.
| height | HTTP | requests | ✅ |
| helicone | HTTP | requests | ✅ |
| hellobaton | HTTP | requests | ✅ |
+| heroku | HTTP | requests | ✅ |
| hetzner | HTTP | requests | ✅ |
| hibob | HTTP | requests | ✅ |
| humanitix | HTTP | requests | ✅ |
@@ -667,7 +668,6 @@ doesn't conflict with concurrent PRs.
- harvey
- heap
- helpscout
-- heroku
- hetzner
- hex
- heygen
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 7b1992ecde16..da4bbf860a4b 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
@@ -1909,7 +1909,7 @@ class HelpScoutSourceConfig(config.Config):
@config.config
class HerokuSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/canonical_descriptions.py
new file mode 100644
index 000000000000..9b34d35be683
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/canonical_descriptions.py
@@ -0,0 +1,203 @@
+# Descriptions sourced from the official Heroku Platform API v3 reference
+# (https://devcenter.heroku.com/articles/platform-api-reference).
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "apps": {
+ "description": "An app represents the program that you would like to deploy and run on Heroku.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#app",
+ "columns": {
+ "acm": "ACM status of this app.",
+ "archived_at": "When the app was archived.",
+ "build_stack": "Identity of the stack that will be used for new builds.",
+ "buildpack_provided_description": "Description from buildpack of app.",
+ "created_at": "When the app was created.",
+ "generation": "Generation of the Heroku platform for this app.",
+ "git_url": "Git repo URL of app.",
+ "id": "Unique identifier of app.",
+ "internal_routing": "Describes whether a Private Spaces app is externally routable or not.",
+ "maintenance": "Maintenance status of app.",
+ "name": "Unique name of app.",
+ "organization": "Identity of team.",
+ "owner": "Identity of app owner.",
+ "region": "Identity of app region.",
+ "released_at": "When the app was released.",
+ "repo_size": "Git repo size in bytes of app.",
+ "slug_size": "Slug size in bytes of app.",
+ "space": "Identity of space.",
+ "stack": "Identity of app stack.",
+ "team": "Identity of team.",
+ "updated_at": "When the app was updated.",
+ "web_url": "Web URL of app.",
+ },
+ },
+ "addons": {
+ "description": "Add-ons represent add-ons that have been provisioned and attached to one or more apps.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#add-on",
+ "columns": {
+ "actions": "Provider actions for this specific add-on.",
+ "addon_service": "Identity of add-on service.",
+ "app": "Billing application associated with this add-on.",
+ "billed_price": "Billed price.",
+ "billing_entity": "Billing entity associated with this add-on.",
+ "config_vars": "Config vars exposed to the owning app by this add-on.",
+ "created_at": "When the add-on was created.",
+ "id": "Unique identifier of add-on.",
+ "name": "Globally unique name of the add-on.",
+ "plan": "Identity of add-on plan.",
+ "provider_id": "Id of this add-on with its provider.",
+ "state": "State in the add-on's lifecycle.",
+ "updated_at": "When the add-on was updated.",
+ "web_url": "URL for logging into web interface of add-on (e.g. a dashboard).",
+ },
+ },
+ "builds": {
+ "description": "A build represents the process of transforming a code tarball into build artifacts.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#build",
+ "columns": {
+ "app": "App that the build belongs to.",
+ "buildpacks": "Buildpacks executed for this build, in order.",
+ "created_at": "When the build was created.",
+ "generation": "Generation of build.",
+ "id": "Unique identifier of build.",
+ "output_stream_url": "Always null: the build output stream URL grants access without Heroku auth, so PostHog does not sync it.",
+ "release": "Release resulting from the build.",
+ "slug": "Slug created by this build (only applicable for Cedar-generation apps).",
+ "source_blob": "Source code tarball used to create the build (its signed download URL is not synced).",
+ "stack": "Stack of build.",
+ "status": "Status of build.",
+ "updated_at": "When the build was updated.",
+ "user": "User that started the build.",
+ },
+ },
+ "collaborators": {
+ "description": "A collaborator represents an account that has been given access to an app on Heroku.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#collaborator",
+ "columns": {
+ "app": "App the collaborator belongs to.",
+ "created_at": "When the collaborator was created.",
+ "id": "Unique identifier of collaborator.",
+ "permissions": "Permissions the collaborator has on the app.",
+ "role": "Role in the team.",
+ "updated_at": "When the collaborator was updated.",
+ "user": "Identity of collaborated account.",
+ },
+ },
+ "domains": {
+ "description": "Domains define what web routes should be routed to an app on Heroku.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#domain",
+ "columns": {
+ "acm_status": "Status of this record's ACM.",
+ "acm_status_reason": "Reason for the status of this record's ACM.",
+ "app": "App that owns the domain.",
+ "cname": "Canonical name record, the address to point a domain at.",
+ "created_at": "When the domain was created.",
+ "hostname": "Full hostname.",
+ "id": "Unique identifier of this domain.",
+ "kind": "Type of domain name.",
+ "sni_endpoint": "SNI endpoint the domain is associated with.",
+ "status": "Status of this record's cname.",
+ "updated_at": "When the domain was updated.",
+ },
+ },
+ "dynos": {
+ "description": "Dynos encapsulate running processes of an app on Heroku.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#dyno",
+ "columns": {
+ "app": "App the dyno belongs to.",
+ "attach_url": "Always null: the dyno attach URL grants access to the running process, so PostHog does not sync it.",
+ "command": "Command used to start this process.",
+ "created_at": "When the dyno was created.",
+ "id": "Unique identifier of this dyno.",
+ "name": "The name of this process on this dyno.",
+ "release": "App release of the dyno.",
+ "size": "Dyno size.",
+ "state": "Current status of process (either: crashed, down, idle, starting, or up).",
+ "type": "Type of process.",
+ "updated_at": "When the process last changed state.",
+ },
+ },
+ "formation": {
+ "description": "The formation of processes that should be maintained for an app — the process types, dyno sizes, and quantities the app is scaled to.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#formation",
+ "columns": {
+ "app": "App the formation belongs to.",
+ "command": "Command to use to launch this process.",
+ "created_at": "When the process type was created.",
+ "dyno_size": "Dyno size.",
+ "id": "Unique identifier of this process type.",
+ "quantity": "Number of processes to maintain.",
+ "size": "Deprecated, refer to 'dyno_size' instead.",
+ "type": "Type of process to maintain.",
+ "updated_at": "When the dyno type was updated.",
+ },
+ },
+ "invoices": {
+ "description": "An invoice is an itemized bill of goods for an account which includes pricing and charges.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#invoice",
+ "columns": {
+ "charges_total": "Total charges on this invoice.",
+ "created_at": "When the invoice was created.",
+ "credits_total": "Total credits on this invoice.",
+ "id": "Unique identifier of this invoice.",
+ "number": "Human readable invoice number.",
+ "period_end": "The ending date that the invoice covers.",
+ "period_start": "The starting date that this invoice covers.",
+ "state": "Payment status for this invoice (pending, successful, failed).",
+ "total": "Combined total of charges and credits on this invoice.",
+ "updated_at": "When the invoice was updated.",
+ },
+ },
+ "pipelines": {
+ "description": "A pipeline allows grouping of apps into different stages.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#pipeline",
+ "columns": {
+ "created_at": "When the pipeline was created.",
+ "generation": "The generation of the Heroku platform for this pipeline.",
+ "id": "Unique identifier of pipeline.",
+ "name": "Name of pipeline.",
+ "owner": "Owner of a pipeline.",
+ "updated_at": "When the pipeline was updated.",
+ },
+ },
+ "releases": {
+ "description": "A release represents a combination of code, config vars and add-ons for an app on Heroku.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#release",
+ "columns": {
+ "addon_plan_names": "Add-on plans installed on the app for this release.",
+ "app": "App involved in the release.",
+ "artifacts": "Build artifacts for the release.",
+ "created_at": "When the release was created.",
+ "current": "Indicates this release as being the current one for the app.",
+ "description": "Description of changes in this release.",
+ "eligible_for_rollback": "Indicates if this release is eligible for rollback.",
+ "id": "Unique identifier of release.",
+ "output_stream_url": "Always null: the release command output stream URL grants access without Heroku auth, so PostHog does not sync it.",
+ "slug": "Slug running in this release.",
+ "status": "Current status of the release.",
+ "updated_at": "When the release was updated.",
+ "user": "User that created the release.",
+ "version": "Unique version assigned to the release.",
+ },
+ },
+ "teams": {
+ "description": "Teams allow you to manage access to a shared group of applications and other resources.",
+ "docs_url": "https://devcenter.heroku.com/articles/platform-api-reference#team",
+ "columns": {
+ "created_at": "When the team was created.",
+ "credit_card_collections": "Whether charges incurred by the team are paid by credit card.",
+ "default": "Whether to use this team when none is specified.",
+ "enterprise_account": "Enterprise account associated with the team.",
+ "id": "Unique identifier of team.",
+ "identity_provider": "Identity provider associated with the team.",
+ "membership_limit": "Upper limit of members allowed in a team.",
+ "name": "Unique name of team.",
+ "provisioned_licenses": "Whether the team is provisioned licenses by Salesforce.",
+ "role": "Role in the team.",
+ "type": "Type of team.",
+ "updated_at": "When the team was updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/heroku.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/heroku.py
new file mode 100644
index 000000000000..00b7548c3009
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/heroku.py
@@ -0,0 +1,256 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+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.heroku.settings import (
+ DEFAULT_PAGE_SIZE,
+ HEROKU_BASE_URL,
+ HEROKU_ENDPOINTS,
+ MAX_PAGES_PER_LIST,
+ HerokuEndpointConfig,
+)
+
+
+class HerokuRetryableError(Exception):
+ pass
+
+
+class HerokuResumeConfig:
+ # Verbatim `Next-Range` header value to resume pagination from. None means "start the
+ # list at its first page".
+ next_range: str | None = None
+ # For fan-out endpoints: the app currently being processed. A stable app-ID bookmark
+ # (not a positional index) so apps created/deleted between a crash and the retry can't
+ # resume us into the wrong app. None for top-level endpoints.
+ app_id: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # Every Platform API request must pin version 3 via the Accept header.
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/vnd.heroku+json; version=3",
+ }
+
+
+def _initial_range_header(config: HerokuEndpointConfig) -> str:
+ # Explicit ascending order on a stable attribute keeps page boundaries deterministic
+ # while rows are inserted mid-sync. Default page size is 200; 1000 is the hard max.
+ return f"{config.range_attribute} ..; order=asc,max={DEFAULT_PAGE_SIZE}"
+
+
+def validate_credentials(api_key: str) -> bool:
+ url = f"{HEROKU_BASE_URL}/account"
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ HerokuRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(6),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ range_header: str,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], str | None]:
+ """Fetch one page of a Heroku list endpoint.
+
+ Heroku paginates via headers: the request carries a `Range` header, and a 206 response
+ carries a `Next-Range` header holding the opaque cursor for the following page. Returns
+ the page's rows and the `Next-Range` value (None on the final page).
+ """
+ response = session.get(url, headers={**headers, "Range": range_header}, timeout=60)
+
+ # Token bucket of 4,500 requests/hour per account refills continuously (~75/min), so
+ # backing off and retrying a 429 is enough — no Retry-After header to honor.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise HerokuRetryableError(f"Heroku API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404 is expected during fan-out (an app deleted mid-sync) and handled by the caller.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Heroku API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, list):
+ raise ValueError(f"Unexpected Heroku response shape (expected a list): url={url}")
+
+ return data, response.headers.get("Next-Range")
+
+
+def _redact_sensitive_fields(row: dict[str, Any], paths: list[str]) -> dict[str, Any]:
+ """Null out capability URLs (dotted paths) so they never land in the warehouse."""
+ for path in paths:
+ *parents, leaf = path.split(".")
+ node: Any = row
+ for key in parents:
+ node = node.get(key) if isinstance(node, dict) else None
+ if node is None:
+ break
+ if isinstance(node, dict) and leaf in node:
+ node[leaf] = None
+ return row
+
+
+def _iter_pages(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ config: HerokuEndpointConfig,
+ logger: FilteringBoundLogger,
+ start_range: str | None = None,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Walk a list endpoint page by page, yielding (rows, next_range) tuples."""
+ range_header = start_range or _initial_range_header(config)
+ for _page_number in range(MAX_PAGES_PER_LIST):
+ rows, next_range = _fetch_page(session, url, headers, range_header, logger)
+ if config.sensitive_fields:
+ rows = [_redact_sensitive_fields(row, config.sensitive_fields) for row in rows]
+ yield rows, next_range
+ if not next_range:
+ return
+ range_header = next_range
+ logger.warning(
+ f"Heroku: page cap reached, list truncated. endpoint={config.name}, url={url}, max_pages={MAX_PAGES_PER_LIST}"
+ )
+
+
+def _iter_app_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[str]:
+ """Page through /apps and yield each app's id."""
+ for rows, _next_range in _iter_pages(session, f"{HEROKU_BASE_URL}/apps", headers, HEROKU_ENDPOINTS["apps"], logger):
+ for row in rows:
+ yield row["id"]
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HerokuResumeConfig],
+ config: HerokuEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over every app, yielding pages of the per-app child endpoint.
+
+ Rows already embed the parent as a nested `app` object ({id, name}), so no extra parent
+ column is injected; Heroku ids are globally unique UUIDs, so `id` stays a valid table-wide
+ primary key across apps.
+ """
+ app_ids = list(_iter_app_ids(session, headers, logger))
+
+ # Resolve the saved app-ID bookmark to the slice of apps still to process. If the
+ # bookmarked app no longer exists (deleted between attempts), start over from the first
+ # app — the full refresh just re-fetches rows it already wrote.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = app_ids
+ resume_range: str | None = None
+ if resume is not None and resume.app_id is not None and resume.app_id in app_ids:
+ remaining = app_ids[app_ids.index(resume.app_id) :]
+ resume_range = resume.next_range
+ logger.debug(f"Heroku: resuming {config.name} from app_id={resume.app_id}")
+
+ for index, app_id in enumerate(remaining):
+ url = f"{HEROKU_BASE_URL}{config.path.format(app_id=app_id)}"
+ start_range = resume_range
+ resume_range = None # only the resumed-into app uses the saved cursor
+
+ try:
+ for rows, next_range in _iter_pages(session, url, headers, config, logger, start_range=start_range):
+ if rows:
+ yield rows
+ # Save AFTER yielding (and only when more pages remain) so a crash
+ # re-yields the last page rather than skipping it.
+ if next_range:
+ resumable_source_manager.save_state(HerokuResumeConfig(next_range=next_range, app_id=app_id))
+ except requests.HTTPError as exc:
+ # An app deleted between enumeration and this fetch 404s. Skip it rather than
+ # failing the whole sync — the data is genuinely gone. Anything else re-raises.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Heroku: app {app_id} not found while fetching {config.name}, skipping")
+ else:
+ raise
+
+ # Advance the bookmark to the next app so a crash between apps resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(HerokuResumeConfig(next_range=None, app_id=remaining[index + 1]))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HerokuResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = HEROKU_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every page (and, for fan-out, every app) so urllib3 keeps
+ # the connection alive instead of re-handshaking per request. Capture is disabled because
+ # several endpoints return capability URLs carrying secrets (builds' `source_blob.url`,
+ # dynos' `rendezvous://.../secret` `attach_url`) that the name-based sample scrubbers
+ # can't recognise — `_redact_sensitive_fields` only scrubs the yielded rows, not the raw
+ # response the transport would otherwise capture.
+ session = make_tracked_session(capture=False)
+
+ if config.fan_out_over_apps:
+ yield from _get_fan_out_rows(session, headers, logger, resumable_source_manager, config)
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_range = resume.next_range if resume else None
+ if start_range:
+ logger.debug(f"Heroku: resuming {endpoint} from saved Next-Range cursor")
+
+ url = f"{HEROKU_BASE_URL}{config.path}"
+ for rows, next_range in _iter_pages(session, url, headers, config, logger, start_range=start_range):
+ if rows:
+ yield rows
+ if next_range:
+ resumable_source_manager.save_state(HerokuResumeConfig(next_range=next_range))
+
+
+def heroku_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HerokuResumeConfig],
+) -> SourceResponse:
+ config = HEROKU_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/settings.py
new file mode 100644
index 000000000000..f60cd8611a6e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/settings.py
@@ -0,0 +1,101 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+HEROKU_BASE_URL = "https://api.heroku.com"
+
+# Heroku pages via the `Range` request header / `Next-Range` response header.
+# Default page size is 200; the hard max is 1000.
+DEFAULT_PAGE_SIZE = 1000
+
+# Hard cap on pages walked per list (per app for fan-out endpoints) so a runaway
+# cursor can't scan unbounded history. 1000-row pages make this 100k rows per list.
+MAX_PAGES_PER_LIST = 100
+
+
+@dataclass
+class HerokuEndpointConfig:
+ name: str
+ path: str # contains an {app_id} placeholder for fan-out endpoints
+ fan_out_over_apps: bool = False
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation timestamp used for datetime partitioning. All Heroku resources carry
+ # `created_at`; never partition on `updated_at` (partitions would rewrite every sync).
+ partition_key: str | None = "created_at"
+ # Attribute used in the `Range` header for stable pagination. `id` is Heroku's default
+ # sort attribute and is accepted on every list endpoint.
+ range_attribute: str = "id"
+ should_sync_default: bool = True
+ # Dotted paths of capability URLs nulled before rows are yielded. These URLs grant
+ # access (source downloads, output streams, dyno attach) without Heroku auth, so they
+ # must not land in the warehouse where any member with query access could read them.
+ sensitive_fields: list[str] = field(default_factory=list)
+
+
+# Heroku's Platform API v3 exposes no updated-since/created-since query filters, so every
+# endpoint syncs as a full refresh. The `Range` header can filter some endpoints server-side
+# (e.g. /apps advertises ranges on `updated_at`), but that behavior is per-endpoint and
+# unverified against the live API, so we don't build incremental sync on it yet.
+HEROKU_ENDPOINTS: dict[str, HerokuEndpointConfig] = {
+ "apps": HerokuEndpointConfig(
+ name="apps",
+ path="/apps",
+ ),
+ "addons": HerokuEndpointConfig(
+ name="addons",
+ path="/addons",
+ ),
+ "builds": HerokuEndpointConfig(
+ name="builds",
+ path="/apps/{app_id}/builds",
+ fan_out_over_apps=True,
+ sensitive_fields=["output_stream_url", "source_blob.url"],
+ ),
+ "collaborators": HerokuEndpointConfig(
+ name="collaborators",
+ path="/apps/{app_id}/collaborators",
+ fan_out_over_apps=True,
+ ),
+ "domains": HerokuEndpointConfig(
+ name="domains",
+ path="/apps/{app_id}/domains",
+ fan_out_over_apps=True,
+ ),
+ # Dynos are a point-in-time snapshot of running processes; the list is small and churns
+ # constantly, so partitioning adds nothing.
+ "dynos": HerokuEndpointConfig(
+ name="dynos",
+ path="/apps/{app_id}/dynos",
+ fan_out_over_apps=True,
+ partition_key=None,
+ sensitive_fields=["attach_url"],
+ ),
+ "formation": HerokuEndpointConfig(
+ name="formation",
+ path="/apps/{app_id}/formation",
+ fan_out_over_apps=True,
+ partition_key=None,
+ ),
+ "invoices": HerokuEndpointConfig(
+ name="invoices",
+ path="/account/invoices",
+ ),
+ "pipelines": HerokuEndpointConfig(
+ name="pipelines",
+ path="/pipelines",
+ ),
+ "releases": HerokuEndpointConfig(
+ name="releases",
+ path="/apps/{app_id}/releases",
+ fan_out_over_apps=True,
+ sensitive_fields=["output_stream_url"],
+ ),
+ "teams": HerokuEndpointConfig(
+ name="teams",
+ path="/teams",
+ ),
+}
+
+ENDPOINTS = tuple(HEROKU_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in HEROKU_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/source.py
index 09db297965e5..5a8b65498ade 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/source.py
@@ -1,19 +1,43 @@
-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 HerokuSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.heroku import (
+ HerokuResumeConfig,
+ heroku_source,
+ validate_credentials as validate_heroku_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.settings import (
+ ENDPOINTS,
+ HEROKU_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HerokuSource(SimpleSource[HerokuSourceConfig]):
+class HerokuSource(ResumableSource[HerokuSourceConfig, HerokuResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HEROKU
@@ -24,8 +48,101 @@ class HerokuSource(SimpleSource[HerokuSourceConfig]):
name=SchemaExternalDataSourceType.HEROKU,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Heroku",
- iconPath="/static/services/heroku.png",
- keywords=["heroku", "paas", "deploys", "dynos"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Heroku API key to pull your Heroku platform data (apps, releases, builds, dynos, add-ons, and more) into the PostHog Data warehouse.
+
+You can find your API key in your [Heroku account settings](https://dashboard.heroku.com/account) under **API Key**, or create a long-lived token with the Heroku CLI: `heroku authorizations:create`.
+""",
+ iconPath="/static/services/heroku.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/heroku",
+ keywords=["paas", "deploys", "dynos"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="HRKU-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked Heroku API key surfaces as a requests HTTPError when
+ # `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy a credential
+ # problem, so stop the sync. Match the stable status text and base host, not the
+ # per-request path.
+ "401 Client Error: Unauthorized for url: https://api.heroku.com": "Your Heroku API key is invalid or has been revoked. Generate a new key in your Heroku account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.heroku.com": "Your Heroku API key does not have access to this data. Check the token's scope (or your account's access to the resource), then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: HerokuSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "dynos":
+ return "A point-in-time snapshot of the processes currently running on each app"
+ if endpoint == "invoices":
+ return "Invoices for your personal Heroku account; team invoices are not included"
+ if endpoint == "teams":
+ return "Only returns data for accounts that belong to Heroku Teams or Enterprise"
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ # Heroku's API has no server-side updated-since/created-since filters, so every
+ # endpoint is full refresh only.
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=HEROKU_ENDPOINTS[endpoint].should_sync_default,
+ description=_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: HerokuSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_heroku_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Heroku API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HerokuResumeConfig]:
+ return ResumableSourceManager[HerokuResumeConfig](inputs, HerokuResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HerokuSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HerokuResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return heroku_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku.py
new file mode 100644
index 000000000000..af7b071e4ddf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku.py
@@ -0,0 +1,281 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.heroku import (
+ HerokuResumeConfig,
+ get_rows,
+ heroku_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.settings import (
+ DEFAULT_PAGE_SIZE,
+ HEROKU_ENDPOINTS,
+ MAX_PAGES_PER_LIST,
+)
+
+PATCH_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.heroku.heroku.make_tracked_session"
+
+
+def _response(
+ status_code: int = 200, json_data: list[dict[str, Any]] | None = None, next_range: str | None = None
+) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.headers = {"Next-Range": next_range} if next_range else {}
+ response.json.return_value = json_data if json_data is not None else []
+ response.text = ""
+ if status_code >= 400:
+ error = requests.HTTPError(f"{status_code} Client Error: for url: https://api.heroku.com", response=response)
+ response.raise_for_status.side_effect = error
+ return response
+
+
+def _manager(resume: HerokuResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+class TestPagination:
+ def test_follows_next_range_header_until_absent(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(206, [{"id": "a"}], next_range="id ]a..; order=asc,max=1000"),
+ _response(200, [{"id": "b"}]),
+ ]
+ manager = _manager()
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", "apps", MagicMock(), manager))
+
+ assert pages == [[{"id": "a"}], [{"id": "b"}]]
+ first_headers = session.get.call_args_list[0].kwargs["headers"]
+ second_headers = session.get.call_args_list[1].kwargs["headers"]
+ assert first_headers["Range"] == f"id ..; order=asc,max={DEFAULT_PAGE_SIZE}"
+ assert second_headers["Range"] == "id ]a..; order=asc,max=1000"
+ assert first_headers["Accept"] == "application/vnd.heroku+json; version=3"
+ assert first_headers["Authorization"] == "Bearer key"
+
+ def test_saves_state_after_yield_only_when_more_pages_remain(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(206, [{"id": "a"}], next_range="id ]a..; order=asc,max=1000"),
+ _response(200, [{"id": "b"}]),
+ ]
+ manager = _manager()
+
+ with patch(PATCH_PATH, return_value=session):
+ iterator = get_rows("key", "apps", MagicMock(), manager)
+ next(iterator)
+ manager.save_state.assert_not_called()
+ next(iterator)
+
+ manager.save_state.assert_called_once_with(HerokuResumeConfig(next_range="id ]a..; order=asc,max=1000"))
+
+ def test_resumes_top_level_endpoint_from_saved_cursor(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [_response(200, [{"id": "b"}])]
+ manager = _manager(HerokuResumeConfig(next_range="id ]a..; order=asc,max=1000"))
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", "apps", MagicMock(), manager))
+
+ assert pages == [[{"id": "b"}]]
+ assert session.get.call_args_list[0].kwargs["headers"]["Range"] == "id ]a..; order=asc,max=1000"
+
+ def test_page_cap_stops_unbounded_scans_and_warns(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(206, [{"id": "a"}], next_range="id ]a..; order=asc,max=1000")
+ logger = MagicMock()
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", "apps", logger, _manager()))
+
+ assert len(pages) == MAX_PAGES_PER_LIST
+ assert session.get.call_count == MAX_PAGES_PER_LIST
+ logger.warning.assert_called_once()
+
+
+class TestRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])
+ def test_retries_transient_statuses_then_succeeds(self, _name: str, status_code: int) -> None:
+ session = MagicMock()
+ session.get.side_effect = [_response(status_code), _response(200, [{"id": "a"}])]
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", "apps", MagicMock(), _manager()))
+
+ assert pages == [[{"id": "a"}]]
+ assert session.get.call_count == 2
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_credential_errors_raise_without_retry(self, _name: str, status_code: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status_code)
+
+ with patch(PATCH_PATH, return_value=session):
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("key", "apps", MagicMock(), _manager()))
+
+ assert session.get.call_count == 1
+
+
+class TestFanOut:
+ def test_fans_out_over_every_app(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(200, [{"id": "app-1"}, {"id": "app-2"}]),
+ _response(200, [{"id": "rel-1", "app": {"id": "app-1"}}]),
+ _response(200, [{"id": "rel-2", "app": {"id": "app-2"}}]),
+ ]
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", "releases", MagicMock(), _manager()))
+
+ assert pages == [
+ [{"id": "rel-1", "app": {"id": "app-1"}}],
+ [{"id": "rel-2", "app": {"id": "app-2"}}],
+ ]
+ urls = [call.args[0] for call in session.get.call_args_list]
+ assert urls == [
+ "https://api.heroku.com/apps",
+ "https://api.heroku.com/apps/app-1/releases",
+ "https://api.heroku.com/apps/app-2/releases",
+ ]
+
+ def test_app_deleted_mid_sync_is_skipped(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(200, [{"id": "app-1"}, {"id": "app-2"}]),
+ _response(404),
+ _response(200, [{"id": "rel-2", "app": {"id": "app-2"}}]),
+ ]
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", "releases", MagicMock(), _manager()))
+
+ assert pages == [[{"id": "rel-2", "app": {"id": "app-2"}}]]
+
+ def test_resumes_from_bookmarked_app_with_saved_cursor(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(200, [{"id": "app-1"}, {"id": "app-2"}, {"id": "app-3"}]),
+ _response(200, [{"id": "rel-2"}]),
+ _response(200, [{"id": "rel-3"}]),
+ ]
+ saved_cursor = "id ]rel-1..; order=asc,max=1000"
+ manager = _manager(HerokuResumeConfig(next_range=saved_cursor, app_id="app-2"))
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", "releases", MagicMock(), manager))
+
+ assert pages == [[{"id": "rel-2"}], [{"id": "rel-3"}]]
+ urls = [call.args[0] for call in session.get.call_args_list]
+ assert "https://api.heroku.com/apps/app-1/releases" not in urls
+ assert session.get.call_args_list[1].kwargs["headers"]["Range"] == saved_cursor
+ # The next app starts from a fresh first page, not the resumed cursor.
+ assert session.get.call_args_list[2].kwargs["headers"]["Range"] == f"id ..; order=asc,max={DEFAULT_PAGE_SIZE}"
+ manager.save_state.assert_called_with(HerokuResumeConfig(next_range=None, app_id="app-3"))
+
+ def test_deleted_bookmark_app_restarts_from_first_app(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(200, [{"id": "app-1"}]),
+ _response(200, [{"id": "rel-1"}]),
+ ]
+ manager = _manager(HerokuResumeConfig(next_range="id ]x..; order=asc,max=1000", app_id="app-gone"))
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", "releases", MagicMock(), manager))
+
+ assert pages == [[{"id": "rel-1"}]]
+ assert session.get.call_args_list[1].kwargs["headers"]["Range"] == f"id ..; order=asc,max={DEFAULT_PAGE_SIZE}"
+
+
+class TestSensitiveFieldRedaction:
+ @parameterized.expand(
+ [
+ (
+ "build_capability_urls_nulled",
+ "builds",
+ {
+ "id": "b-1",
+ "output_stream_url": "https://build-output.heroku.com/streams/secret",
+ "source_blob": {"url": "https://signed.example.com/tarball?sig=secret", "checksum": "SHA256:abc"},
+ },
+ {"id": "b-1", "output_stream_url": None, "source_blob": {"url": None, "checksum": "SHA256:abc"}},
+ ),
+ (
+ "release_output_stream_nulled",
+ "releases",
+ {"id": "r-1", "output_stream_url": "https://release-output.heroku.com/streams/secret", "version": 3},
+ {"id": "r-1", "output_stream_url": None, "version": 3},
+ ),
+ (
+ "dyno_attach_url_nulled",
+ "dynos",
+ {"id": "d-1", "attach_url": "rendezvous://rendezvous.runtime.heroku.com:5000/secret", "state": "up"},
+ {"id": "d-1", "attach_url": None, "state": "up"},
+ ),
+ (
+ "row_without_sensitive_fields_untouched",
+ "builds",
+ {"id": "b-2", "status": "succeeded"},
+ {"id": "b-2", "status": "succeeded"},
+ ),
+ ]
+ )
+ def test_capability_urls_never_reach_the_warehouse(
+ self, _name: str, endpoint: str, row: dict[str, Any], expected: dict[str, Any]
+ ) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(200, [{"id": "app-1"}]),
+ _response(200, [row]),
+ ]
+
+ with patch(PATCH_PATH, return_value=session):
+ pages = list(get_rows("key", endpoint, MagicMock(), _manager()))
+
+ assert pages == [[expected]]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", 200, True), ("unauthorized", 401, False)])
+ def test_maps_account_probe_status(self, _name: str, status_code: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status_code)
+
+ with patch(PATCH_PATH, return_value=session):
+ assert validate_credentials("key") is expected
+
+ def test_network_error_is_invalid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+
+ with patch(PATCH_PATH, return_value=session):
+ assert validate_credentials("key") is False
+
+
+class TestSourceResponse:
+ @parameterized.expand([(name,) for name in HEROKU_ENDPOINTS])
+ def test_source_response_matches_endpoint_settings(self, endpoint: str) -> None:
+ response = heroku_source("key", endpoint, MagicMock(), _manager())
+ config = HEROKU_ENDPOINTS[endpoint]
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ # updated_at moves on every write, which would rewrite partitions each sync.
+ assert config.partition_key != "updated_at"
+ else:
+ assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku_source.py
new file mode 100644
index 000000000000..20b0d13f6662
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/heroku/tests/test_heroku_source.py
@@ -0,0 +1,119 @@
+from unittest.mock import MagicMock, patch
+
+import requests
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.heroku import HerokuResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.heroku.source import HerokuSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.heroku.source"
+
+
+def _source_inputs(schema_name: str = "apps") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestHerokuSource:
+ def setup_method(self) -> None:
+ self.source = HerokuSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HEROKU
+
+ def test_source_config_requires_api_key_as_secret(self) -> None:
+ config = self.source.get_source_config
+ api_key_fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key"]
+ assert len(api_key_fields) == 1
+ assert api_key_fields[0].secret
+ assert api_key_fields[0].required
+ assert api_key_fields[0].type == "password"
+
+ def test_docs_url_matches_heroku_slug(self) -> None:
+ assert self.source.get_source_config.docsUrl == "https://posthog.com/docs/cdp/sources/heroku"
+
+ def test_get_schemas_returns_full_refresh_only_endpoints(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1)
+
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Heroku has no server-side timestamp filters; flipping any of these on without one
+ # would sync incorrect incremental data.
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["apps", "releases"])
+ assert {s.name for s in schemas} == {"apps", "releases"}
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)
+
+ def test_validate_credentials_maps_probe_result(self) -> None:
+ config = MagicMock()
+ config.api_key = "key"
+
+ with patch(f"{SOURCE_PATH}.validate_heroku_credentials", return_value=True) as probe:
+ assert self.source.validate_credentials(config, team_id=1) == (True, None)
+ probe.assert_called_once_with("key")
+
+ with patch(f"{SOURCE_PATH}.validate_heroku_credentials", return_value=False):
+ valid, message = self.source.validate_credentials(config, team_id=1)
+ assert not valid
+ assert message == "Invalid Heroku API key"
+
+ def test_resumable_source_manager_bound_to_heroku_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_source_inputs())
+ assert manager._data_class is HerokuResumeConfig
+
+ def test_source_for_pipeline_plumbs_config_and_schema(self) -> None:
+ config = MagicMock()
+ config.api_key = "key"
+ inputs = _source_inputs(schema_name="releases")
+ manager = MagicMock()
+
+ with patch(f"{SOURCE_PATH}.heroku_source") as mocked_source:
+ response = self.source.source_for_pipeline(config, manager, inputs)
+
+ assert response is mocked_source.return_value
+ mocked_source.assert_called_once_with(
+ api_key="key",
+ endpoint="releases",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ )
+
+ def test_non_retryable_error_keys_match_requests_error_strings(self) -> None:
+ # `get_non_retryable_errors` keys are matched as substrings of the raised error; if
+ # the key format drifts from what requests actually produces, credential failures
+ # retry forever instead of disabling the source.
+ response = requests.Response()
+ response.status_code = 401
+ response.reason = "Unauthorized" # verified live: Heroku sends this phrase over HTTP/1.1
+ response.url = "https://api.heroku.com/apps/some-app/releases"
+ try:
+ response.raise_for_status()
+ raise AssertionError("raise_for_status did not raise")
+ except requests.HTTPError as e:
+ error_string = str(e)
+
+ assert any(key in error_string for key in self.source.get_non_retryable_errors())