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 goldcast import source (#67789)

Tom Owers681c42f4f3c7
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 a8f4ceb8546c..1d887152fa16 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -156,6 +156,7 @@ the row lists both.
| gitlab | HTTP | requests | ✅ |
| gladly | HTTP | requests | ✅ |
| gocardless | HTTP | requests | ✅ |
+| goldcast | HTTP | requests | ✅ |
| gong | HTTP | requests | ✅ |
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
| google_analytics | HTTP | requests (`AuthorizedSession` + `TrackedHTTPAdapter`) | ✅ |
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 8773588d895e..6b07f63708c1 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
@@ -1360,7 +1360,7 @@ class GojiberrySourceConfig(config.Config):
@config.config
class GoldcastSourceConfig(config.Config):
- pass
+ access_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/canonical_descriptions.py
new file mode 100644
index 000000000000..8b18bfeceb98
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/canonical_descriptions.py
@@ -0,0 +1,130 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://customapi.goldcast.io/swagger-ui/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "organizations": {
+ "description": "The Goldcast organization (workspace) that owns the events, including its branding, plan, and integration settings.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the organization.",
+ "name": "Display name of the organization.",
+ "short_name": "Short slug used in URLs and vanity domains.",
+ "tier": "Subscription tier of the organization.",
+ "created_at": "Timestamp when the organization was created.",
+ "updated_at": "Timestamp when the organization was last updated.",
+ "contract_start_date": "Start date of the organization's contract.",
+ "contract_end_date": "End date of the organization's contract.",
+ "is_webhook_enabled": "Whether webhooks are enabled for the organization.",
+ "hubspot_portal_id": "Connected HubSpot portal id, if the HubSpot integration is set up.",
+ },
+ },
+ "events": {
+ "description": "A Goldcast event — the base object of the platform. An event is a virtual or hybrid gathering that can contain sessions, agenda items, tracks, and members.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the event.",
+ "title": "Title of the event.",
+ "description": "Description of the event.",
+ "timezone": "Timezone the event is scheduled in.",
+ "start_time": "Scheduled start time of the event.",
+ "end_time": "Scheduled end time of the event.",
+ "registrant_count": "Number of people registered for the event.",
+ "is_single_session": "Whether the event has a single session (vs multiple sessions).",
+ "created_by_user": "The user who created the event.",
+ "created_at": "Timestamp when the event was created.",
+ "updated_at": "Timestamp when the event was last updated.",
+ "deleted": "Whether the event has been deleted.",
+ },
+ },
+ "agenda_items": {
+ "description": "Agenda items scheduled within events — the individual slots that make up an event's programme.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the agenda item.",
+ "event": "Id of the event this agenda item belongs to.",
+ "title": "Title of the agenda item.",
+ "description": "Description of the agenda item.",
+ "kind": "Type of agenda item.",
+ "start_time": "Scheduled start time of the agenda item.",
+ "end_time": "Scheduled end time of the agenda item.",
+ "is_live": "Whether the agenda item is currently live.",
+ "live_start_time": "Actual time the agenda item went live.",
+ "live_end_time": "Actual time the agenda item ended.",
+ },
+ },
+ "discussion_groups": {
+ "description": "Discussion groups (breakout rooms and booths) within events, where attendees gather for smaller conversations.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the discussion group.",
+ "event": "Id of the event this discussion group belongs to.",
+ "title": "Title of the discussion group.",
+ "description": "Description of the discussion group.",
+ "capacity": "Maximum number of participants allowed.",
+ "is_live": "Whether the discussion group is currently live.",
+ "is_booth": "Whether this discussion group is a booth.",
+ "is_breakout": "Whether this discussion group is a breakout room.",
+ "starts_at": "Scheduled start time of the discussion group.",
+ "ends_at": "Scheduled end time of the discussion group.",
+ "created_at": "Timestamp when the discussion group was created.",
+ "updated_at": "Timestamp when the discussion group was last updated.",
+ },
+ },
+ "tracks": {
+ "description": "Tracks group related agenda items within an event, letting attendees follow a themed strand of sessions.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the track.",
+ "event": "Id of the event this track belongs to.",
+ "title": "Title of the track.",
+ "agenda_items": "Agenda items associated with this track.",
+ "allowed_ticket_types": "Ticket types allowed to access this track.",
+ "sort_priority": "Ordering priority of the track.",
+ "custom": "Whether this is a custom track.",
+ "created_at": "Timestamp when the track was created.",
+ "updated_at": "Timestamp when the track was last updated.",
+ },
+ },
+ "webinars": {
+ "description": "Webinar configuration and schedule for each event. Fetched per event, so `event` identifies the parent event.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the webinar.",
+ "event": "Id of the parent event (injected during sync to make the row unique table-wide).",
+ "title": "Title of the webinar.",
+ "description": "Description of the webinar.",
+ "timezone": "Timezone the webinar is scheduled in.",
+ "schedule": "Scheduling details for the webinar.",
+ "registrant_count": "Number of people registered for the webinar.",
+ "created_at": "Timestamp when the webinar was created.",
+ "updated_at": "Timestamp when the webinar was last updated.",
+ },
+ },
+ "event_members": {
+ "description": "People associated with an event — registrants and attendees — including their attendance, engagement, and marketing attribution. Fetched per event.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the event member.",
+ "event": "Id of the event this member belongs to.",
+ "user": "Id of the underlying user record.",
+ "event_role": "Role of the member in the event (e.g. attendee, speaker, organizer).",
+ "attended": "Whether the member attended the event.",
+ "entered": "Whether the member entered the event.",
+ "attendance_status": "Attendance status of the member.",
+ "is_engaged": "Whether the member was engaged during the event.",
+ "is_in_person": "Whether the member attended in person (for hybrid events).",
+ "demo_requested": "Whether the member requested a demo.",
+ "quality_rating": "Lead quality rating assigned to the member.",
+ "salesforce_member_id": "Corresponding Salesforce campaign member id, if synced.",
+ "marketo_lead_id": "Corresponding Marketo lead id, if synced.",
+ "utm_campaign": "UTM campaign attributed to the member's registration.",
+ "utm_source": "UTM source attributed to the member's registration.",
+ "utm_medium": "UTM medium attributed to the member's registration.",
+ "created_at": "Timestamp when the event member was created.",
+ "updated_at": "Timestamp when the event member was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/goldcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/goldcast.py
new file mode 100644
index 000000000000..cd329b069e93
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/goldcast.py
@@ -0,0 +1,171 @@
+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.goldcast.settings import (
+ GOLDCAST_ENDPOINTS,
+ GoldcastEndpointConfig,
+)
+
+GOLDCAST_BASE_URL = "https://customapi.goldcast.io"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class GoldcastRetryableError(Exception):
+ pass
+
+
+def _get_headers(access_key: str) -> dict[str, str]:
+ # Goldcast uses a static personal access token with the non-standard `Token` scheme
+ # (not `Bearer`), created by an org admin in Studio Settings > Tokens.
+ return {
+ "Authorization": f"Token {access_key}",
+ "Accept": "application/json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ GoldcastRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise GoldcastRetryableError(f"Goldcast API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Only a tightly capped excerpt of the body is logged: Goldcast error bodies can echo
+ # customer tenant records, so the full response must never land verbatim in our logs.
+ body_excerpt = response.text[:200]
+ logger.error(f"Goldcast API error: status={response.status_code}, body_excerpt={body_excerpt!r}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _extract_rows(data: Any) -> list[dict[str, Any]]:
+ """Normalize a Goldcast response into a list of row dicts.
+
+ Collection endpoints return a bare JSON array; the single-object organization endpoint may
+ return an object. Some deployments could wrap results in a `results`/`data` envelope, so those
+ are unwrapped defensively.
+ """
+ if isinstance(data, list):
+ return [row for row in data if isinstance(row, dict)]
+ if isinstance(data, dict):
+ for key in ("results", "data"):
+ inner = data.get(key)
+ if isinstance(inner, list):
+ return [row for row in inner if isinstance(row, dict)]
+ return [data]
+ return []
+
+
+def validate_credentials(access_key: str) -> bool:
+ # `/core/organization/` is the cheapest authenticated probe (a single org object). A 200 means
+ # the token is genuine and API access is enabled for the account.
+ url = f"{GOLDCAST_BASE_URL}/core/organization/"
+ try:
+ # `redact_values` masks the token from any captured HTTP sample — it rides in the
+ # non-standard `Token` auth header the name-based scrubbers can't recognise.
+ response = make_tracked_session(redact_values=(access_key,)).get(
+ url, headers=_get_headers(access_key), timeout=10
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _iter_event_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[str]:
+ """Yield every event id, used to drive the per-event fan-out endpoints."""
+ data = _fetch(session, f"{GOLDCAST_BASE_URL}/event/", headers, logger)
+ for event in _extract_rows(data):
+ # `id` is the required fan-out key: a missing or empty value must raise loudly rather than
+ # silently under-syncing its webinars/event_members with no signal in the logs.
+ event_id = event["id"]
+ if not event_id:
+ raise ValueError(f"Goldcast event is missing a valid id: {event}")
+ yield str(event_id)
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: GoldcastEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fetch a child endpoint once per event, stamping the parent event id onto each row."""
+ for event_id in _iter_event_ids(session, headers, logger):
+ url = f"{GOLDCAST_BASE_URL}{config.path.format(event=event_id)}"
+ try:
+ data = _fetch(session, url, headers, logger)
+ except requests.HTTPError as exc:
+ # An event with no child resources (or one deleted between enumeration and this fetch)
+ # can 404. Skip it rather than failing the whole sync; any other error is re-raised.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Goldcast: {config.name} not found for event {event_id}, skipping")
+ continue
+ raise
+
+ rows = _extract_rows(data)
+ for row in rows:
+ row[config.parent_event_field] = event_id
+ if rows:
+ yield rows
+
+
+def get_rows(
+ access_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = GOLDCAST_ENDPOINTS[endpoint]
+ headers = _get_headers(access_key)
+ # One session reused across every request so urllib3 keeps the connection alive.
+ # `redact_values` masks the token from captured samples — it rides in the non-standard
+ # `Token` auth header the name-based scrubbers can't recognise.
+ session = make_tracked_session(redact_values=(access_key,))
+
+ if config.fan_out_over_events:
+ yield from _get_fan_out_rows(session, headers, logger, config)
+ return
+
+ data = _fetch(session, f"{GOLDCAST_BASE_URL}{config.path}", headers, logger)
+ rows = _extract_rows(data)
+ if rows:
+ yield rows
+
+
+def goldcast_source(
+ access_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ endpoint_config = GOLDCAST_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(access_key=access_key, endpoint=endpoint, logger=logger),
+ primary_keys=endpoint_config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/settings.py
new file mode 100644
index 000000000000..870d929c2830
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/settings.py
@@ -0,0 +1,72 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+
+@dataclass
+class GoldcastEndpointConfig:
+ name: str
+ # Path relative to the Goldcast base URL. For fan-out endpoints this is a template with an
+ # `{event}` placeholder that is filled per parent event id.
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation-time field to partition by. Left None when the endpoint exposes no such
+ # field (never partition on `updated_at`, which rewrites partitions on every sync).
+ partition_key: Optional[str] = None
+ # When True this is a per-event fan-out endpoint: iterate every event id from the events
+ # endpoint and request `path` once per event. `path` must contain an `{event}` placeholder.
+ fan_out_over_events: bool = False
+ # For fan-out children, the parent event id is written into each row under this key so the
+ # composite primary key is unique table-wide (child ids are only guaranteed unique per parent).
+ parent_event_field: str = "event"
+ should_sync_default: bool = True
+
+
+# Goldcast's public API exposes full collections with no pagination and no server-side
+# modified-at/updated-at filter, so every endpoint is full refresh only. `agenda_items` carries no
+# creation timestamp, so it is left unpartitioned; every other endpoint partitions on `created_at`.
+GOLDCAST_ENDPOINTS: dict[str, GoldcastEndpointConfig] = {
+ "organizations": GoldcastEndpointConfig(
+ name="organizations",
+ path="/core/organization/",
+ partition_key="created_at",
+ ),
+ "events": GoldcastEndpointConfig(
+ name="events",
+ path="/event/",
+ partition_key="created_at",
+ ),
+ "agenda_items": GoldcastEndpointConfig(
+ name="agenda_items",
+ path="/event/agenda-item/",
+ ),
+ "discussion_groups": GoldcastEndpointConfig(
+ name="discussion_groups",
+ path="/event/discussion-groups/",
+ partition_key="created_at",
+ ),
+ "tracks": GoldcastEndpointConfig(
+ name="tracks",
+ path="/event/tracks/",
+ partition_key="created_at",
+ ),
+ # Fan-out: one request per event id. The event id is in the URL path and not present on the
+ # returned webinar rows, so it is injected under `event` to form the composite primary key.
+ "webinars": GoldcastEndpointConfig(
+ name="webinars",
+ path="/event/webinars/{event}/",
+ primary_keys=["event", "id"],
+ partition_key="created_at",
+ fan_out_over_events=True,
+ ),
+ # Fan-out: one request per event id, passed as an `?event=` query param. Rows already carry an
+ # `event` field; it is re-stamped defensively so the composite key is always populated.
+ "event_members": GoldcastEndpointConfig(
+ name="event_members",
+ path="/event/event-members/?event={event}",
+ primary_keys=["event", "id"],
+ partition_key="created_at",
+ fan_out_over_events=True,
+ ),
+}
+
+ENDPOINTS = tuple(GOLDCAST_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/source.py
index a3d907b0198e..1bdabeada7d0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/source.py
@@ -1,19 +1,40 @@
-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.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GoldcastSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.goldcast import (
+ goldcast_source,
+ validate_credentials as validate_goldcast_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.settings import (
+ ENDPOINTS,
+ GOLDCAST_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class GoldcastSource(SimpleSource[GoldcastSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GOLDCAST
@@ -24,7 +45,83 @@ class GoldcastSource(SimpleSource[GoldcastSourceConfig]):
name=SchemaExternalDataSourceType.GOLDCAST,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="Goldcast",
- iconPath="/static/services/goldcast.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Goldcast API token to sync your virtual event and webinar data into the PostHog Data warehouse.
+
+An org admin can create a personal access token in Goldcast Studio under **Settings → Tokens**. The token is shown only once, so copy it immediately.
+
+API access requires a Pro, Premium, or Enterprise plan, and the token feature must be enabled by Goldcast support.""",
+ iconPath="/static/services/goldcast.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/goldcast",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_key",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked token surfaces as a requests HTTPError when `_fetch` 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/query.
+ "401 Client Error: Unauthorized for url: https://customapi.goldcast.io": "Your Goldcast API token is invalid or has been revoked. Create a new token in Goldcast Studio under Settings → Tokens, then reconnect.",
+ "403 Client Error: Forbidden for url: https://customapi.goldcast.io": "Your Goldcast API token does not have API access. Confirm your plan supports the API and that Goldcast support has enabled the token feature, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: GoldcastSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Goldcast exposes no server-side timestamp filter, so every endpoint is full refresh only
+ # — incremental would re-fetch every record each sync anyway.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ detected_primary_keys=GOLDCAST_ENDPOINTS[endpoint].primary_keys,
+ should_sync_default=GOLDCAST_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: GoldcastSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_goldcast_credentials(config.access_key):
+ return True, None
+
+ return False, "Invalid Goldcast API token"
+
+ def source_for_pipeline(self, config: GoldcastSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return goldcast_source(
+ access_key=config.access_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/tests/test_goldcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/tests/test_goldcast.py
new file mode 100644
index 000000000000..0012df6e8b5d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/tests/test_goldcast.py
@@ -0,0 +1,332 @@
+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.goldcast import goldcast
+from products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.goldcast import (
+ GoldcastRetryableError,
+ _extract_rows,
+ get_rows,
+ goldcast_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.settings import GOLDCAST_ENDPOINTS
+
+
+class TestExtractRows:
+ @parameterized.expand(
+ [
+ ("bare_list", [{"id": "a"}, {"id": "b"}], [{"id": "a"}, {"id": "b"}]),
+ # The organization endpoint returns a single object, not a collection.
+ ("single_object", {"id": "org1"}, [{"id": "org1"}]),
+ # Defensive: unwrap a results/data envelope if a deployment ever wraps collections.
+ ("results_envelope", {"results": [{"id": "a"}]}, [{"id": "a"}]),
+ ("data_envelope", {"data": [{"id": "a"}]}, [{"id": "a"}]),
+ # Non-dict entries (e.g. stray ids) are dropped so downstream row handling stays safe.
+ ("filters_non_dicts", [{"id": "a"}, "junk", 5], [{"id": "a"}]),
+ ("empty_list", [], []),
+ ("unexpected_scalar", "nope", []),
+ ]
+ )
+ def test_normalizes_response_shapes(self, _name: str, payload: Any, expected: list[dict]) -> None:
+ assert _extract_rows(payload) == expected
+
+
+class TestFetchRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_status_codes_are_retried(self, _name: str, status_code: int) -> None:
+ # A 429/5xx must retry rather than fail the whole sync.
+ bad = MagicMock()
+ bad.status_code = status_code
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = [{"id": "a"}]
+
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(goldcast._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = goldcast._fetch(session, "https://customapi.goldcast.io/event/", {}, MagicMock())
+
+ assert result == [{"id": "a"}]
+ assert session.get.call_count == 2
+
+ @parameterized.expand(
+ [
+ ("chunked_encoding", requests.exceptions.ChunkedEncodingError("Connection broken")),
+ ("read_timeout", requests.ReadTimeout("Read timed out.")),
+ ("connection_error", requests.ConnectionError("Connection reset by peer")),
+ ]
+ )
+ def test_transient_network_errors_are_retried(self, _name: str, transient_error: Exception) -> None:
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = []
+
+ session = MagicMock()
+ session.get.side_effect = [transient_error, good]
+
+ with patch.object(goldcast._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = goldcast._fetch(session, "https://customapi.goldcast.io/event/", {}, MagicMock())
+
+ assert result == []
+ assert session.get.call_count == 2
+
+ def test_client_error_raises_and_is_not_retried(self) -> None:
+ # A 401/403 is a credential problem; it must raise immediately, not burn retries.
+ resp = MagicMock()
+ resp.status_code = 401
+ resp.ok = False
+ resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=resp)
+
+ session = MagicMock()
+ session.get.return_value = resp
+
+ with patch.object(goldcast._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(requests.HTTPError):
+ goldcast._fetch(session, "https://customapi.goldcast.io/event/", {}, MagicMock())
+
+ assert session.get.call_count == 1
+
+ def test_error_body_is_not_logged_verbatim(self) -> None:
+ # Goldcast error bodies can echo customer tenant records, so a full body must never land
+ # in our logs — only a tightly capped excerpt is allowed.
+ sensitive_body = "SECRET-TENANT-RECORD-" + "x" * 5000
+ resp = MagicMock()
+ resp.status_code = 400
+ resp.ok = False
+ resp.text = sensitive_body
+ resp.raise_for_status.side_effect = requests.HTTPError("400 Client Error", response=resp)
+
+ session = MagicMock()
+ session.get.return_value = resp
+ logger = MagicMock()
+
+ with pytest.raises(requests.HTTPError):
+ goldcast._fetch(session, "https://customapi.goldcast.io/event/", {}, logger)
+
+ logged = " ".join(str(call.args[0]) for call in logger.error.call_args_list)
+ assert sensitive_body not in logged
+ assert len(logged) < 500
+
+ def test_retryable_error_reraised_after_exhausting_attempts(self) -> None:
+ bad = MagicMock()
+ bad.status_code = 500
+ session = MagicMock()
+ session.get.return_value = bad
+
+ with patch.object(goldcast._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(GoldcastRetryableError):
+ goldcast._fetch(session, "https://customapi.goldcast.io/event/", {}, MagicMock())
+
+ assert session.get.call_count == 5
+
+
+def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> None:
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(goldcast, "_fetch", fake_fetch)
+ monkeypatch.setattr(goldcast, "make_tracked_session", lambda *a, **k: MagicMock())
+
+
+class TestGetRowsTopLevel:
+ def test_yields_all_rows_from_a_collection_endpoint(self, monkeypatch: Any) -> None:
+ _patch_fetch(monkeypatch, {"https://customapi.goldcast.io/event/": [{"id": "e1"}, {"id": "e2"}]})
+
+ batches = list(get_rows(access_key="tok", endpoint="events", logger=MagicMock()))
+
+ assert batches == [[{"id": "e1"}, {"id": "e2"}]]
+
+ def test_empty_collection_yields_nothing(self, monkeypatch: Any) -> None:
+ _patch_fetch(monkeypatch, {"https://customapi.goldcast.io/event/": []})
+
+ assert list(get_rows(access_key="tok", endpoint="events", logger=MagicMock())) == []
+
+
+class TestGetRowsFanOut:
+ def test_stamps_parent_event_id_onto_each_child_row(self, monkeypatch: Any) -> None:
+ # The parent event id must be injected so the composite ["event", "id"] key is unique
+ # table-wide — webinar rows carry no `event` field of their own.
+ _patch_fetch(
+ monkeypatch,
+ {
+ "https://customapi.goldcast.io/event/": [{"id": "e1"}, {"id": "e2"}],
+ "https://customapi.goldcast.io/event/webinars/e1/": [{"id": "w1"}],
+ "https://customapi.goldcast.io/event/webinars/e2/": [{"id": "w2"}, {"id": "w3"}],
+ },
+ )
+
+ rows = [row for batch in get_rows(access_key="tok", endpoint="webinars", logger=MagicMock()) for row in batch]
+
+ assert rows == [
+ {"id": "w1", "event": "e1"},
+ {"id": "w2", "event": "e2"},
+ {"id": "w3", "event": "e2"},
+ ]
+
+ def test_event_members_query_param_path_and_stamping(self, monkeypatch: Any) -> None:
+ _patch_fetch(
+ monkeypatch,
+ {
+ "https://customapi.goldcast.io/event/": [{"id": "e1"}],
+ # event_members already carries `event`; stamping re-affirms it to the parent id.
+ "https://customapi.goldcast.io/event/event-members/?event=e1": [{"id": "m1", "event": "stale"}],
+ },
+ )
+
+ rows = [
+ row for batch in get_rows(access_key="tok", endpoint="event_members", logger=MagicMock()) for row in batch
+ ]
+
+ assert rows == [{"id": "m1", "event": "e1"}]
+
+ def test_child_404_for_one_event_is_skipped_not_fatal(self, monkeypatch: Any) -> None:
+ not_found = requests.HTTPError("404 Client Error", response=MagicMock(status_code=404))
+ _patch_fetch(
+ monkeypatch,
+ {
+ "https://customapi.goldcast.io/event/": [{"id": "e1"}, {"id": "e2"}],
+ "https://customapi.goldcast.io/event/webinars/e1/": not_found,
+ "https://customapi.goldcast.io/event/webinars/e2/": [{"id": "w2"}],
+ },
+ )
+
+ rows = [row for batch in get_rows(access_key="tok", endpoint="webinars", logger=MagicMock()) for row in batch]
+
+ assert rows == [{"id": "w2", "event": "e2"}]
+
+ def test_child_non_404_error_propagates(self, monkeypatch: Any) -> None:
+ # 5xx/429 are retried inside _fetch and surface as GoldcastRetryableError, so the case that
+ # actually reaches the fan-out's `except HTTPError` branch is a non-404 4xx (e.g. a 403).
+ forbidden = requests.HTTPError("403 Client Error", response=MagicMock(status_code=403))
+ _patch_fetch(
+ monkeypatch,
+ {
+ "https://customapi.goldcast.io/event/": [{"id": "e1"}],
+ "https://customapi.goldcast.io/event/webinars/e1/": forbidden,
+ },
+ )
+
+ with pytest.raises(requests.HTTPError):
+ list(get_rows(access_key="tok", endpoint="webinars", logger=MagicMock()))
+
+ def test_event_missing_id_key_fails_loudly(self, monkeypatch: Any) -> None:
+ # A malformed parent event (missing the required `id` fan-out key) must raise rather than
+ # silently under-sync that event's children with no signal.
+ _patch_fetch(
+ monkeypatch,
+ {"https://customapi.goldcast.io/event/": [{"name": "no id"}]},
+ )
+
+ with pytest.raises(KeyError):
+ list(get_rows(access_key="tok", endpoint="webinars", logger=MagicMock()))
+
+ @parameterized.expand([("empty_string", ""), ("none", None), ("zero", 0)])
+ def test_event_with_falsy_id_fails_loudly(self, _name: str, falsy_id: Any) -> None:
+ # A falsy `id` (empty string, None, 0) must raise too — silently skipping it would
+ # under-sync that event's children exactly like a missing key would.
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ _patch_fetch(
+ monkeypatch,
+ {"https://customapi.goldcast.io/event/": [{"id": falsy_id}]},
+ )
+
+ with pytest.raises(ValueError):
+ list(get_rows(access_key="tok", endpoint="webinars", logger=MagicMock()))
+
+
+class TestGoldcastSourceResponse:
+ @parameterized.expand(
+ [
+ ("events", ["id"], "created_at"),
+ ("organizations", ["id"], "created_at"),
+ # agenda_items has no creation timestamp, so it must not be partitioned.
+ ("agenda_items", ["id"], None),
+ # Fan-out children carry the parent id in a composite key for table-wide uniqueness.
+ ("webinars", ["event", "id"], "created_at"),
+ ("event_members", ["event", "id"], "created_at"),
+ ]
+ )
+ def test_partition_and_primary_keys_per_endpoint(
+ self, endpoint: str, expected_keys: list[str], partition_key: str | None
+ ) -> None:
+ response = goldcast_source(access_key="tok", endpoint=endpoint, logger=MagicMock())
+
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+
+ def test_every_endpoint_declares_a_primary_key(self) -> None:
+ # A non-unique / missing key seeds duplicate rows that make every later merge multi-match.
+ for name, config in GOLDCAST_ENDPOINTS.items():
+ assert config.primary_keys, f"{name} has no primary key"
+
+
+class TestValidateCredentials:
+ def test_valid_token_returns_true(self) -> None:
+ session = MagicMock()
+ session.get.return_value.status_code = 200
+ with patch.object(goldcast, "make_tracked_session", return_value=session):
+ assert validate_credentials("tok") is True
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_non_200_returns_false(self, _name: str, status_code: int) -> None:
+ session = MagicMock()
+ session.get.return_value.status_code = status_code
+ with patch.object(goldcast, "make_tracked_session", return_value=session):
+ assert validate_credentials("tok") is False
+
+ def test_network_error_returns_false(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(goldcast, "make_tracked_session", return_value=session):
+ assert validate_credentials("tok") is False
+
+
+class TestTokenRedaction:
+ # The token rides in a non-standard `Token` auth header the name-based scrubbers can't
+ # recognise, so every tracked session must register it with `redact_values` or it leaks
+ # into captured HTTP samples.
+ def test_get_rows_registers_token_for_redaction(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def spy_session(*_a: Any, **kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ return MagicMock()
+
+ monkeypatch.setattr(goldcast, "make_tracked_session", spy_session)
+ monkeypatch.setattr(goldcast, "_fetch", lambda *_a, **_k: [])
+
+ list(get_rows(access_key="super-secret", endpoint="events", logger=MagicMock()))
+
+ assert captured.get("redact_values") == ("super-secret",)
+
+ def test_validate_credentials_registers_token_for_redaction(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def spy_session(*_a: Any, **kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ session = MagicMock()
+ session.get.return_value.status_code = 200
+ return session
+
+ monkeypatch.setattr(goldcast, "make_tracked_session", spy_session)
+
+ validate_credentials("super-secret")
+
+ assert captured.get("redact_values") == ("super-secret",)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/tests/test_goldcast_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/tests/test_goldcast_source.py
new file mode 100644
index 000000000000..247997100e41
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/goldcast/tests/test_goldcast_source.py
@@ -0,0 +1,136 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.settings import (
+ ENDPOINTS,
+ GOLDCAST_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.source import GoldcastSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(access_key: str = "tok") -> Any:
+ config = MagicMock()
+ config.access_key = access_key
+ return config
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert GoldcastSource().source_type == ExternalDataSourceType.GOLDCAST
+
+ def test_config_is_alpha_and_unreleased(self) -> None:
+ config = GoldcastSource().get_source_config
+ # The task ships Goldcast behind unreleasedSource=True at alpha while it's still unproven.
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/goldcast"
+
+ def test_single_secret_token_field(self) -> None:
+ fields = {f.name: f for f in GoldcastSource().get_source_config.fields if isinstance(f, SourceFieldInputConfig)}
+ assert set(fields) == {"access_key"}
+ assert fields["access_key"].required is True
+ # The token is a credential, so it must be stored as a secret password field.
+ assert fields["access_key"].secret is True
+
+
+class TestGetSchemas:
+ def test_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = GoldcastSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Goldcast exposes no server-side timestamp filter, so nothing is incremental/append.
+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_detected_primary_keys_match_settings(self) -> None:
+ schemas = {s.name: s for s in GoldcastSource().get_schemas(_config(), team_id=1)}
+ for name, config in GOLDCAST_ENDPOINTS.items():
+ assert schemas[name].detected_primary_keys == config.primary_keys
+
+ def test_names_filter_restricts_output(self) -> None:
+ schemas = GoldcastSource().get_schemas(_config(), team_id=1, names=["events", "webinars"])
+ assert {s.name for s in schemas} == {"events", "webinars"}
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://customapi.goldcast.io/event/",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://customapi.goldcast.io/core/organization/",
+ ),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = GoldcastSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='customapi.goldcast.io', port=443): Read timed out."),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://customapi.goldcast.io/event/"),
+ ]
+ )
+ def test_transient_errors_stay_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = GoldcastSource().get_non_retryable_errors()
+ assert not any(key in observed_error for key in non_retryable)
+
+
+class TestValidateCredentials:
+ def test_valid_token_passes(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.source.validate_goldcast_credentials",
+ return_value=True,
+ ):
+ assert GoldcastSource().validate_credentials(_config(), team_id=1) == (True, None)
+
+ def test_invalid_token_surfaces_message(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.source.validate_goldcast_credentials",
+ return_value=False,
+ ):
+ valid, message = GoldcastSource().validate_credentials(_config(), team_id=1)
+ assert valid is False
+ assert message == "Invalid Goldcast API token"
+
+
+class TestSourceForPipeline:
+ def test_plumbs_access_key_and_endpoint_through(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "webinars"
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.goldcast.source.goldcast_source"
+ ) as mock_source:
+ GoldcastSource().source_for_pipeline(_config(access_key="secret"), inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["access_key"] == "secret"
+ assert kwargs["endpoint"] == "webinars"
+
+
+class TestDocumentedTables:
+ def test_static_catalog_is_published_for_public_docs(self) -> None:
+ source = GoldcastSource()
+ # A static, no-I/O catalog opts into public docs so the Supported tables section renders.
+ assert source.lists_tables_without_credentials is True
+ tables = source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ # Full refresh must be advertised for every endpoint (no server-side cursor).
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ def test_canonical_descriptions_key_on_endpoint_names(self) -> None:
+ # Canonical descriptions must key on schema/endpoint names so enrichment applies them.
+ assert set(CANONICAL_DESCRIPTIONS).issubset(set(ENDPOINTS))