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 eventbrite import source (#61160)

Tom Owerse84157ce1fb5
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 32e90d5e94a0..c9c4b2a5a9b6 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -61,6 +61,7 @@ the row lists both.
| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |
| doit | HTTP | requests | ✅ |
| drip | HTTP | requests | ✅ |
+| eventbrite | HTTP | requests | ✅ |
| github | HTTP | requests | ✅ |
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
@@ -162,7 +163,6 @@ doesn't conflict with concurrent PRs.
- datadog
- dynamodb
- elasticsearch
-- eventbrite
- facebook_pages
- firebase
- freshdesk
diff --git a/posthog/temporal/data_imports/sources/eventbrite/eventbrite.py b/posthog/temporal/data_imports/sources/eventbrite/eventbrite.py
new file mode 100644
index 000000000000..19f1e2978832
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/eventbrite/eventbrite.py
@@ -0,0 +1,244 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.eventbrite.settings import (
+ EVENTBRITE_ENDPOINTS,
+ ORG_EVENTS_PATH,
+ ORGANIZATIONS_PATH,
+ EndpointScope,
+ EventbriteEndpointConfig,
+)
+
+EVENTBRITE_BASE_URL = "https://www.eventbriteapi.com/v3"
+
+
+class EventbriteRetryableError(Exception):
+ pass
+
+
+class EventbriteResumeConfig:
+ # Continuation token for the next page. Only persisted for top-level endpoints — fan-out
+ # endpoints restart from the first parent on resume and rely on merge dedupe (same as Stripe's
+ # nested-resource handling), since parent ordering is not guaranteed stable.
+ continuation: str
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_changed_since(value: Any) -> str:
+ """Format an incremental value for Eventbrite's `changed_since` filter (ISO 8601 UTC, Z suffix)."""
+ if isinstance(value, datetime):
+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def validate_credentials(api_token: str) -> bool:
+ url = f"{EVENTBRITE_BASE_URL}/users/me/"
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_token), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type((EventbriteRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(url, params=params, timeout=60)
+
+ # Eventbrite enforces a strict per-token rate limit; honor it via retry/backoff.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise EventbriteRetryableError(f"Eventbrite API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Eventbrite API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _iter_pages(
+ session: requests.Session,
+ url: str,
+ base_params: dict[str, Any],
+ data_key: str,
+ logger: FilteringBoundLogger,
+ start_continuation: Optional[str] = None,
+) -> Iterator[tuple[dict[str, Any], Optional[str]]]:
+ """Yield (record, resume_continuation) across continuation-token pages of a single list endpoint.
+
+ `resume_continuation` is the token a caller should persist right after yielding the record so a
+ crash resumes without skipping any records. For every item except the last on its page it is the
+ *current* page's token, so resume re-fetches the current page and replays its remaining items
+ (merge dedupes already-persisted ones). Only for the final item of a page — once the whole page is
+ accounted for — is it the *next* page's token (or None on the last page). Saving the next-page
+ token mid-page would skip the current page's remaining records on resume.
+ """
+ continuation = start_continuation
+ while True:
+ current_continuation = continuation
+ params = dict(base_params)
+ if current_continuation:
+ params["continuation"] = current_continuation
+
+ data = _fetch_page(session, url, params, logger)
+ items = data.get(data_key, []) or []
+ pagination = data.get("pagination") or {}
+ next_continuation = pagination.get("continuation") if pagination.get("has_more_items") else None
+
+ last_index = len(items) - 1
+ for index, item in enumerate(items):
+ resume_continuation = next_continuation if index == last_index else current_continuation
+ yield item, resume_continuation
+
+ if not next_continuation:
+ break
+ continuation = next_continuation
+
+
+def _iter_organization_ids(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[str]:
+ url = f"{EVENTBRITE_BASE_URL}{ORGANIZATIONS_PATH}"
+ for org, _ in _iter_pages(session, url, {}, "organizations", logger):
+ # Fail fast on a malformed response rather than silently dropping all of an org's children.
+ yield str(org["id"])
+
+
+def _iter_event_ids(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[str]:
+ for org_id in _iter_organization_ids(session, logger):
+ url = f"{EVENTBRITE_BASE_URL}{ORG_EVENTS_PATH.format(organization_id=org_id)}"
+ for event, _ in _iter_pages(session, url, {}, "events", logger):
+ yield str(event["id"])
+
+
+def _iter_records(
+ session: requests.Session,
+ config: EventbriteEndpointConfig,
+ logger: FilteringBoundLogger,
+ changed_since: Optional[str],
+ resume: Optional[EventbriteResumeConfig],
+) -> Iterator[tuple[dict[str, Any], Optional[str]]]:
+ base_params: dict[str, Any] = {}
+ if changed_since:
+ base_params["changed_since"] = changed_since
+
+ if config.scope == EndpointScope.TOP_LEVEL:
+ url = f"{EVENTBRITE_BASE_URL}{config.path}"
+ start = resume.continuation if resume else None
+ yield from _iter_pages(session, url, base_params, config.data_key, logger, start_continuation=start)
+ return
+
+ if config.scope == EndpointScope.ORG:
+ parent_ids = _iter_organization_ids(session, logger)
+ placeholder = "organization_id"
+ else:
+ parent_ids = _iter_event_ids(session, logger)
+ placeholder = "event_id"
+
+ # Fan-out: paginate the child endpoint per parent. We never persist a resume token here, so
+ # downstream always sees next_continuation=None for these records.
+ for parent_id in parent_ids:
+ url = f"{EVENTBRITE_BASE_URL}{config.path.format(**{placeholder: parent_id})}"
+ for record, _ in _iter_pages(session, url, base_params, config.data_key, logger):
+ yield record, None
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EventbriteResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = EVENTBRITE_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_get_headers(api_token))
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+
+ # Only narrow with the server-side `changed_since` filter when the endpoint supports it and the
+ # user's chosen cursor is the field that filter targets (`changed`). Honors inputs.incremental_field
+ # rather than assuming it.
+ changed_since: Optional[str] = None
+ if (
+ should_use_incremental_field
+ and config.changed_since_field
+ and db_incremental_field_last_value
+ and incremental_field in (None, config.changed_since_field)
+ ):
+ changed_since = _format_changed_since(db_incremental_field_last_value)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ logger.debug(f"Eventbrite: resuming {endpoint} from continuation token")
+
+ for record, resume_continuation in _iter_records(session, config, logger, changed_since, resume):
+ batcher.batch(record)
+
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ # Save state after yielding so a crash re-yields the last batch (merge dedupes on PK).
+ if resume_continuation:
+ resumable_source_manager.save_state(EventbriteResumeConfig(continuation=resume_continuation))
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def eventbrite_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EventbriteResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = EVENTBRITE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/eventbrite/settings.py b/posthog/temporal/data_imports/sources/eventbrite/settings.py
new file mode 100644
index 000000000000..ffb4cd99424d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/eventbrite/settings.py
@@ -0,0 +1,120 @@
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+class EndpointScope(Enum):
+ """How an endpoint is reached.
+
+ - TOP_LEVEL: a single list endpoint, no parent needed.
+ - ORG: fanned out per organization (path has an `{organization_id}` placeholder).
+ - EVENT: fanned out per event (path has an `{event_id}` placeholder); events are
+ themselves discovered per organization, so this is a two-level fan-out.
+ """
+
+ TOP_LEVEL = "top_level"
+ ORG = "org"
+ EVENT = "event"
+
+
+@dataclass
+class EventbriteEndpointConfig:
+ name: str
+ path: str
+ data_key: str # Key the list lives under in the JSON envelope, e.g. {"events": [...]}
+ scope: EndpointScope
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ partition_key: Optional[str] = None # Stable created-style field for datetime partitioning
+ # Resource change-timestamp field targeted by Eventbrite's server-side `changed_since` filter
+ # (e.g. `changed`). When set, the endpoint supports true incremental sync; otherwise full refresh.
+ changed_since_field: Optional[str] = None
+
+
+def _changed_incremental_field() -> list[IncrementalField]:
+ return [
+ {
+ "label": "changed",
+ "type": IncrementalFieldType.DateTime,
+ "field": "changed",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+# Path to discover the organizations that own all org-scoped and event-scoped resources.
+ORGANIZATIONS_PATH = "/users/me/organizations/"
+ORG_EVENTS_PATH = "/organizations/{organization_id}/events/"
+
+
+# Stream list cross-referenced against the Airbyte `source-eventbrite` connector (the canonical
+# implementation). Only `orders` and `attendees` expose a documented server-side `changed_since`
+# filter, so only those advertise incremental sync — everything else is full refresh.
+EVENTBRITE_ENDPOINTS: dict[str, EventbriteEndpointConfig] = {
+ "organizations": EventbriteEndpointConfig(
+ name="organizations",
+ path=ORGANIZATIONS_PATH,
+ data_key="organizations",
+ scope=EndpointScope.TOP_LEVEL,
+ partition_key="created",
+ ),
+ "categories": EventbriteEndpointConfig(
+ name="categories",
+ path="/categories/",
+ data_key="categories",
+ scope=EndpointScope.TOP_LEVEL,
+ ),
+ "formats": EventbriteEndpointConfig(
+ name="formats",
+ path="/formats/",
+ data_key="formats",
+ scope=EndpointScope.TOP_LEVEL,
+ ),
+ "events": EventbriteEndpointConfig(
+ name="events",
+ path=ORG_EVENTS_PATH,
+ data_key="events",
+ scope=EndpointScope.ORG,
+ partition_key="created",
+ ),
+ "venues": EventbriteEndpointConfig(
+ name="venues",
+ path="/organizations/{organization_id}/venues/",
+ data_key="venues",
+ scope=EndpointScope.ORG,
+ ),
+ "orders": EventbriteEndpointConfig(
+ name="orders",
+ path="/organizations/{organization_id}/orders/",
+ data_key="orders",
+ scope=EndpointScope.ORG,
+ partition_key="created",
+ changed_since_field="changed",
+ incremental_fields=_changed_incremental_field(),
+ ),
+ "attendees": EventbriteEndpointConfig(
+ name="attendees",
+ path="/events/{event_id}/attendees/",
+ data_key="attendees",
+ scope=EndpointScope.EVENT,
+ partition_key="created",
+ changed_since_field="changed",
+ incremental_fields=_changed_incremental_field(),
+ ),
+ "ticket_classes": EventbriteEndpointConfig(
+ name="ticket_classes",
+ path="/events/{event_id}/ticket_classes/",
+ data_key="ticket_classes",
+ scope=EndpointScope.EVENT,
+ ),
+}
+
+ENDPOINTS = tuple(EVENTBRITE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in EVENTBRITE_ENDPOINTS.items()
+}
+
+INCREMENTAL_ENDPOINTS = tuple(name for name, config in EVENTBRITE_ENDPOINTS.items() if config.changed_since_field)
diff --git a/posthog/temporal/data_imports/sources/eventbrite/source.py b/posthog/temporal/data_imports/sources/eventbrite/source.py
index a6c109a735ff..c965828ec4c3 100644
--- a/posthog/temporal/data_imports/sources/eventbrite/source.py
+++ b/posthog/temporal/data_imports/sources/eventbrite/source.py
@@ -1,19 +1,35 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.eventbrite.eventbrite import (
+ EventbriteResumeConfig,
+ eventbrite_source,
+ validate_credentials as validate_eventbrite_credentials,
+)
+from posthog.temporal.data_imports.sources.eventbrite.settings import (
+ ENDPOINTS,
+ INCREMENTAL_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from posthog.temporal.data_imports.sources.generated_configs import EventbriteSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class EventbriteSource(SimpleSource[EventbriteSourceConfig]):
+class EventbriteSource(ResumableSource[EventbriteSourceConfig, EventbriteResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.EVENTBRITE
@@ -23,7 +39,85 @@ class EventbriteSource(SimpleSource[EventbriteSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.EVENTBRITE,
label="Eventbrite",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Eventbrite private token to automatically pull your Eventbrite data into the PostHog Data warehouse.
+
+You can create a private token under your [Eventbrite account settings](https://www.eventbrite.com/account-settings/apps) on the **API Keys** page (the **Private token** field of your API key).
+
+The token needs read access to your organizations, events, orders, and attendees.
+""",
iconPath="/static/services/eventbrite.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/eventbrite",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Private token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Your Eventbrite private token",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: EventbriteSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint in INCREMENTAL_ENDPOINTS,
+ supports_append=endpoint in INCREMENTAL_ENDPOINTS,
+ incremental_fields=INCREMENTAL_FIELDS.get(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 get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://www.eventbriteapi.com": "Your Eventbrite private token is invalid or has been revoked. Please generate a new token and reconnect.",
+ "403 Client Error: Forbidden for url: https://www.eventbriteapi.com": "Your Eventbrite private token does not have permission to access this resource. Please check the token's permissions and try again.",
+ }
+
+ def validate_credentials(
+ self, config: EventbriteSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_eventbrite_credentials(config.api_token):
+ return True, None
+
+ return False, "Invalid Eventbrite private token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EventbriteResumeConfig]:
+ return ResumableSourceManager[EventbriteResumeConfig](inputs, EventbriteResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: EventbriteSourceConfig,
+ resumable_source_manager: ResumableSourceManager[EventbriteResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return eventbrite_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/eventbrite/tests/test_eventbrite.py b/posthog/temporal/data_imports/sources/eventbrite/tests/test_eventbrite.py
new file mode 100644
index 000000000000..ac953b718e0e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/eventbrite/tests/test_eventbrite.py
@@ -0,0 +1,215 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.eventbrite import eventbrite as eb
+from posthog.temporal.data_imports.sources.eventbrite.eventbrite import (
+ EventbriteResumeConfig,
+ _format_changed_since,
+ _iter_pages,
+ _iter_records,
+ eventbrite_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.eventbrite.settings import EVENTBRITE_ENDPOINTS
+
+LOGGER = mock.MagicMock()
+SESSION = mock.MagicMock()
+
+
+def _page(data_key: str, items: list[dict[str, Any]], continuation: str | None) -> dict[str, Any]:
+ return {
+ data_key: items,
+ "pagination": {"has_more_items": continuation is not None, "continuation": continuation},
+ }
+
+
+class TestFormatChangedSince:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("already-a-cursor", "already-a-cursor"),
+ ],
+ )
+ def test_format_changed_since(self, value: object, expected: str) -> None:
+ assert _format_changed_since(value) == expected
+
+ def test_no_plus_offset_in_output(self) -> None:
+ result = _format_changed_since(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+ assert "+00:00" not in result
+ assert result.endswith("Z")
+
+
+class TestIterPages:
+ @mock.patch.object(eb, "_fetch_page")
+ def test_follows_continuation_until_exhausted(self, mock_fetch: mock.MagicMock) -> None:
+ mock_fetch.side_effect = [
+ _page("events", [{"id": "1"}, {"id": "2"}], "tok2"),
+ _page("events", [{"id": "3"}], None),
+ ]
+
+ results = list(_iter_pages(SESSION, "https://x/events/", {}, "events", LOGGER))
+
+ assert [record["id"] for record, _ in results] == ["1", "2", "3"]
+ # Resume token: mid-page items carry the current page's token (None for the first page, which
+ # restarts from the start); only the last item of a page advances to the next page's token.
+ assert [token for _, token in results] == [None, "tok2", None]
+ assert mock_fetch.call_count == 2
+
+ @mock.patch.object(eb, "_fetch_page")
+ def test_starts_from_resume_continuation(self, mock_fetch: mock.MagicMock) -> None:
+ mock_fetch.side_effect = [_page("events", [{"id": "9"}], None)]
+
+ list(_iter_pages(SESSION, "https://x/events/", {}, "events", LOGGER, start_continuation="resume-tok"))
+
+ _, _, params, _ = mock_fetch.call_args[0]
+ assert params["continuation"] == "resume-tok"
+
+ @mock.patch.object(eb, "_fetch_page")
+ def test_mid_page_records_carry_current_page_token(self, mock_fetch: mock.MagicMock) -> None:
+ # Resuming from a mid-page record must re-fetch the page it came from, not the next one,
+ # otherwise the rest of that page is skipped. Non-final items therefore carry the token that
+ # fetched their own (here second) page rather than the next page's token.
+ mock_fetch.side_effect = [
+ _page("events", [{"id": "1"}], "tok2"),
+ _page("events", [{"id": "2"}, {"id": "3"}], "tok3"),
+ _page("events", [{"id": "4"}], None),
+ ]
+
+ results = list(_iter_pages(SESSION, "https://x/events/", {}, "events", LOGGER))
+
+ assert [record["id"] for record, _ in results] == ["1", "2", "3", "4"]
+ assert [token for _, token in results] == ["tok2", "tok2", "tok3", None]
+
+ @mock.patch.object(eb, "_fetch_page")
+ def test_handles_empty_page(self, mock_fetch: mock.MagicMock) -> None:
+ mock_fetch.side_effect = [_page("events", [], None)]
+
+ assert list(_iter_pages(SESSION, "https://x/events/", {}, "events", LOGGER)) == []
+
+
+class TestIterRecords:
+ @mock.patch.object(eb, "_fetch_page")
+ def test_top_level_uses_resume_continuation(self, mock_fetch: mock.MagicMock) -> None:
+ mock_fetch.side_effect = [_page("organizations", [{"id": "o1"}], None)]
+ config = EVENTBRITE_ENDPOINTS["organizations"]
+
+ list(_iter_records(SESSION, config, LOGGER, None, EventbriteResumeConfig(continuation="resume-tok")))
+
+ _, url, params, _ = mock_fetch.call_args[0]
+ assert url.endswith("/users/me/organizations/")
+ assert params["continuation"] == "resume-tok"
+
+ @mock.patch.object(eb, "_fetch_page")
+ def test_org_fan_out_builds_child_urls_and_no_resume_token(self, mock_fetch: mock.MagicMock) -> None:
+ def router(_session: Any, url: str, _params: dict[str, Any], _logger: Any) -> dict[str, Any]:
+ if url.endswith("/users/me/organizations/"):
+ return _page("organizations", [{"id": "org1"}, {"id": "org2"}], None)
+ if url.endswith("/organizations/org1/events/"):
+ return _page("events", [{"id": "e1"}], None)
+ if url.endswith("/organizations/org2/events/"):
+ return _page("events", [{"id": "e2"}], None)
+ raise AssertionError(f"unexpected url {url}")
+
+ mock_fetch.side_effect = router
+ config = EVENTBRITE_ENDPOINTS["events"]
+
+ results = list(_iter_records(SESSION, config, LOGGER, None, None))
+
+ assert [record["id"] for record, _ in results] == ["e1", "e2"]
+ assert all(token is None for _, token in results)
+
+ @mock.patch.object(eb, "_fetch_page")
+ def test_event_fan_out_is_two_levels(self, mock_fetch: mock.MagicMock) -> None:
+ def router(_session: Any, url: str, _params: dict[str, Any], _logger: Any) -> dict[str, Any]:
+ if url.endswith("/users/me/organizations/"):
+ return _page("organizations", [{"id": "org1"}], None)
+ if url.endswith("/organizations/org1/events/"):
+ return _page("events", [{"id": "e1"}, {"id": "e2"}], None)
+ if url.endswith("/events/e1/attendees/"):
+ return _page("attendees", [{"id": "a1"}], None)
+ if url.endswith("/events/e2/attendees/"):
+ return _page("attendees", [{"id": "a2"}], None)
+ raise AssertionError(f"unexpected url {url}")
+
+ mock_fetch.side_effect = router
+ config = EVENTBRITE_ENDPOINTS["attendees"]
+
+ results = list(_iter_records(SESSION, config, LOGGER, None, None))
+
+ assert [record["id"] for record, _ in results] == ["a1", "a2"]
+
+ @mock.patch.object(eb, "_fetch_page")
+ def test_changed_since_applied_only_to_child_endpoint(self, mock_fetch: mock.MagicMock) -> None:
+ seen_params: dict[str, dict[str, Any]] = {}
+
+ def router(_session: Any, url: str, params: dict[str, Any], _logger: Any) -> dict[str, Any]:
+ seen_params[url] = params
+ if url.endswith("/users/me/organizations/"):
+ return _page("organizations", [{"id": "org1"}], None)
+ if url.endswith("/organizations/org1/orders/"):
+ return _page("orders", [{"id": "ord1"}], None)
+ raise AssertionError(f"unexpected url {url}")
+
+ mock_fetch.side_effect = router
+ config = EVENTBRITE_ENDPOINTS["orders"]
+
+ list(_iter_records(SESSION, config, LOGGER, "2026-01-01T00:00:00Z", None))
+
+ # The parent organizations listing must not be narrowed by the child's incremental filter.
+ org_url = next(u for u in seen_params if u.endswith("/users/me/organizations/"))
+ order_url = next(u for u in seen_params if u.endswith("/organizations/org1/orders/"))
+ assert "changed_since" not in seen_params[org_url]
+ assert seen_params[order_url]["changed_since"] == "2026-01-01T00:00:00Z"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ @mock.patch.object(eb, "make_tracked_session")
+ def test_validate_credentials_status_mapping(
+ self, mock_session_factory: mock.MagicMock, status_code: int, expected: bool
+ ) -> None:
+ session = mock.MagicMock()
+ session.get.return_value.status_code = status_code
+ mock_session_factory.return_value = session
+
+ assert validate_credentials("token") is expected
+
+ @mock.patch.object(eb, "make_tracked_session")
+ def test_validate_credentials_swallows_exceptions(self, mock_session_factory: mock.MagicMock) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = Exception("network down")
+ mock_session_factory.return_value = session
+
+ assert validate_credentials("token") is False
+
+
+class TestEventbriteSourceResponse:
+ @pytest.mark.parametrize("endpoint", ["organizations", "events", "orders", "attendees"])
+ def test_partitioned_endpoints(self, endpoint: str) -> None:
+ response = eventbrite_source(
+ api_token="token", endpoint=endpoint, logger=LOGGER, resumable_source_manager=mock.MagicMock()
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "week"
+ assert response.partition_keys == ["created"]
+
+ @pytest.mark.parametrize("endpoint", ["categories", "formats", "venues", "ticket_classes"])
+ def test_non_partitioned_endpoints(self, endpoint: str) -> None:
+ response = eventbrite_source(
+ api_token="token", endpoint=endpoint, logger=LOGGER, resumable_source_manager=mock.MagicMock()
+ )
+
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/posthog/temporal/data_imports/sources/eventbrite/tests/test_eventbrite_source.py b/posthog/temporal/data_imports/sources/eventbrite/tests/test_eventbrite_source.py
new file mode 100644
index 000000000000..ce8d78bad5f8
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/eventbrite/tests/test_eventbrite_source.py
@@ -0,0 +1,159 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.eventbrite.eventbrite import EventbriteResumeConfig
+from posthog.temporal.data_imports.sources.eventbrite.settings import ENDPOINTS, INCREMENTAL_ENDPOINTS
+from posthog.temporal.data_imports.sources.eventbrite.source import EventbriteSource
+from posthog.temporal.data_imports.sources.generated_configs import EventbriteSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestEventbriteSource:
+ def setup_method(self):
+ self.source = EventbriteSource()
+ self.team_id = 123
+ self.config = EventbriteSourceConfig(api_token="test-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.EVENTBRITE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Eventbrite"
+ assert config.label == "Eventbrite"
+ assert config.releaseStatus == "alpha"
+ assert config.iconPath == "/static/services/eventbrite.png"
+ assert len(config.fields) == 1
+
+ token_field = config.fields[0]
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.name == "api_token"
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.required is True
+ assert token_field.secret is True
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ [
+ "401 Client Error: Unauthorized for url: https://www.eventbriteapi.com",
+ "403 Client Error: Forbidden for url: https://www.eventbriteapi.com",
+ ],
+ )
+ def test_non_retryable_errors_includes_eventbrite_key(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_non_retryable_errors_matches_observed_error_message(self):
+ observed_error = (
+ "401 Client Error: Unauthorized for url: https://www.eventbriteapi.com/v3/users/me/organizations/"
+ )
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "401 Client Error: Unauthorized for url: https://a.klaviyo.com/api/accounts",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_other_vendors(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_lists_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_incremental_flags_match_settings(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ for schema in schemas:
+ expected = schema.name in INCREMENTAL_ENDPOINTS
+ assert schema.supports_incremental is expected
+ assert schema.supports_append is expected
+ if expected:
+ assert schema.incremental_fields, f"{schema.name} should advertise incremental fields"
+ else:
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_incremental_endpoints_are_orders_and_attendees(self):
+ assert set(INCREMENTAL_ENDPOINTS) == {"orders", "attendees"}
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["events"])
+
+ assert len(schemas) == 1
+ assert schemas[0].name == "events"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["nonexistent"])
+
+ assert schemas == []
+
+ @pytest.mark.parametrize(
+ "credentials_valid, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Eventbrite private token"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.eventbrite.source.validate_eventbrite_credentials")
+ def test_validate_credentials(self, mock_validate, credentials_valid, expected_valid, expected_message):
+ mock_validate.return_value = credentials_valid
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_token)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ inputs.logger = mock.MagicMock()
+
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert manager._data_class is EventbriteResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.eventbrite.source.eventbrite_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_eventbrite_source):
+ manager = mock.MagicMock()
+ inputs = mock.MagicMock()
+ inputs.schema_name = "orders"
+ inputs.logger = mock.MagicMock()
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = "changed"
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_eventbrite_source.assert_called_once_with(
+ api_token=self.config.api_token,
+ endpoint="orders",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field="changed",
+ )
+
+ @mock.patch("posthog.temporal.data_imports.sources.eventbrite.source.eventbrite_source")
+ def test_source_for_pipeline_nulls_last_value_when_not_incremental(self, mock_eventbrite_source):
+ manager = mock.MagicMock()
+ inputs = mock.MagicMock()
+ inputs.schema_name = "events"
+ inputs.logger = mock.MagicMock()
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_eventbrite_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None
+ assert kwargs["should_use_incremental_field"] is False
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 856c029e7286..c16a88d926c6 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -324,7 +324,7 @@ class ElasticsearchSourceConfig(config.Config):
@config.config
class EventbriteSourceConfig(config.Config):
- pass
+ api_token: str
@config.config