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 eventzilla import source (#67827)

Tom Owers5f0a02c18d1f
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 6e226323d032..120d5e1d4fc7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -141,6 +141,7 @@ the row lists both.
| emailoctopus | HTTP | requests | ✅ |
| eventbrite | HTTP | requests | ✅ |
| eventee | HTTP | requests | ✅ |
+| eventzilla | HTTP | requests | ✅ |
| everhour | HTTP | requests | ✅ |
| exchange_rates_api | HTTP | requests | ✅ |
| ezofficeinventory | HTTP | requests | ✅ |
@@ -432,7 +433,6 @@ doesn't conflict with concurrent PRs.
- eloqua
- employment_hero
- encharge
-- eventzilla
- expensify
- facebook_pages
- fastbill
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/canonical_descriptions.py
new file mode 100644
index 000000000000..18235aaae625
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/canonical_descriptions.py
@@ -0,0 +1,84 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the Eventzilla API v2 reference (https://developer.eventzilla.net/docs/). Partial
+# coverage is fine — any endpoint/column not listed here falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "events": {
+ "description": "Events created in your Eventzilla account, with their scheduling, capacity, and status.",
+ "docs_url": "https://developer.eventzilla.net/docs/",
+ "columns": {
+ "id": "Unique identifier for the event.",
+ "title": "Event title.",
+ "description": "Event description (HTML).",
+ "currency": "Currency the event's tickets are priced in.",
+ "start_date": "Date the event starts.",
+ "end_date": "Date the event ends.",
+ "start_time": "Time the event starts.",
+ "end_time": "Time the event ends.",
+ "date_id": "Identifier of the event's date (events can have multiple dates).",
+ "time_zone": "Time zone the event is scheduled in.",
+ "tickets_sold": "Number of tickets sold so far.",
+ "total_tickets": "Total number of tickets available.",
+ "status": "Event status (e.g. Live, Draft, Unpublished, Completed).",
+ },
+ },
+ "categories": {
+ "description": "The reference list of event categories available in Eventzilla.",
+ "docs_url": "https://developer.eventzilla.net/docs/",
+ "columns": {
+ "category": "Name of the category.",
+ },
+ },
+ "users": {
+ "description": "Users (organizers) in your Eventzilla account.",
+ "docs_url": "https://developer.eventzilla.net/docs/",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "last_seen": "Timestamp the user was last seen.",
+ },
+ },
+ "attendees": {
+ "description": "Attendees registered for each event. Fetched per event.",
+ "docs_url": "https://developer.eventzilla.net/docs/",
+ "columns": {
+ "id": "Unique identifier for the attendee.",
+ "event_id": "Identifier of the event this attendee belongs to (added by PostHog during fan-out).",
+ "bar_code": "Barcode encoded on the attendee's ticket.",
+ "transaction_ref": "Order reference of the transaction that created this attendee.",
+ "transaction_date": "Timestamp the purchasing transaction was made.",
+ "event_date": "Date of the event the attendee registered for.",
+ },
+ },
+ "transactions": {
+ "description": "Ticket purchase transactions for each event. Fetched per event.",
+ "docs_url": "https://developer.eventzilla.net/docs/",
+ "columns": {
+ "checkout_id": "Unique identifier for the transaction.",
+ "event_id": "Identifier of the event this transaction belongs to.",
+ "transaction_ref": "Order reference for the transaction.",
+ "transaction_date": "Timestamp the transaction was made.",
+ "transaction_amount": "Total amount of the transaction.",
+ "tickets_in_transaction": "Number of tickets (attendees) in the transaction.",
+ "transaction_status": "Status of the transaction (e.g. Confirmed, Pending, Cancelled, Incomplete).",
+ "event_date": "Date of the event the transaction is for.",
+ "user_id": "Identifier of the buyer.",
+ "email": "Buyer's email address.",
+ "buyer_first_name": "Buyer's first name.",
+ "buyer_last_name": "Buyer's last name.",
+ "promo_code": "Promo code applied to the transaction, if any.",
+ "payment_type": "Payment method used.",
+ },
+ },
+ "tickets": {
+ "description": "Ticket types configured for each event. Fetched per event.",
+ "docs_url": "https://developer.eventzilla.net/docs/",
+ "columns": {
+ "id": "Unique identifier for the ticket type.",
+ "event_id": "Identifier of the event this ticket type belongs to (added by PostHog during fan-out).",
+ "sales_start_date": "Date ticket sales start.",
+ "sales_end_date": "Date ticket sales end.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/eventzilla.py b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/eventzilla.py
new file mode 100644
index 000000000000..a6f82906a8fe
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/eventzilla.py
@@ -0,0 +1,254 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+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.batcher import Batcher
+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.eventzilla.settings import (
+ EVENTZILLA_ENDPOINTS,
+ EventzillaEndpointConfig,
+)
+
+EVENTZILLA_BASE_URL = "https://www.eventzillaapi.net/api/v2"
+
+# Documented default limit is 20; we request a larger page to cut request count. We advance the
+# offset by the number of rows actually returned (never a fixed step), so a server that silently
+# clamps the page size can't cause us to skip rows.
+PAGE_SIZE = 100
+
+# Safety ceiling on pages per list to bound a runaway paginator (e.g. an endpoint that ignores
+# offset). Real lists terminate far below this on an empty page.
+MAX_PAGES = 10_000
+
+
+class EventzillaRetryableError(Exception):
+ pass
+
+
+class EventzillaResumeConfig:
+ # Offset of the next page to fetch within the current list.
+ offset: int = 0
+ # For fan-out endpoints, the event whose child list we're currently paging. A stable event-id
+ # bookmark (not a positional index) so events added/removed between a crash and the retry can't
+ # resume us into the wrong event. None for top-level (non-fan-out) endpoints.
+ event_id: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {"x-api-key": api_key, "Accept": "application/json"}
+
+
+def _build_url(path: str, offset: int) -> str:
+ query = urlencode({"offset": offset, "limit": PAGE_SIZE})
+ return f"{EVENTZILLA_BASE_URL}{path}?{query}"
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ EventzillaRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise EventzillaRetryableError(f"Eventzilla API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Eventzilla API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> bool:
+ # A single cheap probe against the events list confirms the key is genuine without touching
+ # any per-event resource (the user may not have events yet).
+ url = _build_url("/events", offset=0)
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _iter_pages(
+ session: requests.Session,
+ path: str,
+ data_key: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ start_offset: int = 0,
+) -> Iterator[tuple[list[dict[str, Any]], int]]:
+ """Page through a limit/offset list, yielding (items, next_offset) per page.
+
+ The response's `pagination` object is the paginate signal: the list endpoints that support
+ offset/limit paging (events, users, transactions) return it, so we advance until its `total` is
+ reached (or an empty page). Endpoints that return their full result set in one response
+ (categories, tickets, and the per-event attendees/tickets samples) omit it, so we stop after the
+ first page rather than blindly re-requesting — which could loop forever on an offset-ignoring
+ endpoint. Advancing by the real returned count keeps us correct even if the server clamps the
+ requested page size.
+ """
+ offset = start_offset
+ for _ in range(MAX_PAGES):
+ data = _fetch_page(session, _build_url(path, offset), headers, logger)
+ items = data.get(data_key) or []
+ if not items:
+ return
+
+ offset += len(items)
+ yield items, offset
+
+ pagination = data.get("pagination")
+ if not isinstance(pagination, dict):
+ return
+ total = pagination.get("total")
+ if total is not None and offset >= total:
+ return
+
+ logger.warning(f"Eventzilla: hit MAX_PAGES paging {path}; stopping to avoid a runaway scan")
+
+
+def _iter_event_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:
+ event_ids: list[str] = []
+ for items, _ in _iter_pages(session, "/events", "events", headers, logger):
+ # `id` is the event primary key; a response missing it is malformed, so fail loudly
+ # (KeyError) rather than silently dropping the event and its entire fan-out subtree.
+ event_ids.extend(str(item["id"]) for item in items)
+ return event_ids
+
+
+def _get_top_level_rows(
+ session: requests.Session,
+ config: EventzillaEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[EventzillaResumeConfig],
+) -> Iterator[Any]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_offset = resume.offset if resume is not None and resume.event_id is None else 0
+ if start_offset:
+ logger.debug(f"Eventzilla: resuming {config.name} from offset={start_offset}")
+
+ for items, next_offset in _iter_pages(session, config.path, config.data_key, headers, logger, start_offset):
+ for item in items:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —
+ # merge dedupes on the primary key.
+ resumable_source_manager.save_state(EventzillaResumeConfig(offset=next_offset))
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ config: EventzillaEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[EventzillaResumeConfig],
+) -> Iterator[Any]:
+ event_ids = _iter_event_ids(session, headers, logger)
+
+ # Resolve the saved event-id bookmark to the slice of events still to process. If the bookmarked
+ # event no longer exists (deleted between runs), start over — merge dedupes the re-pulled rows.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = event_ids
+ resume_offset = 0
+ if resume is not None and resume.event_id is not None and resume.event_id in event_ids:
+ remaining = event_ids[event_ids.index(resume.event_id) :]
+ resume_offset = resume.offset
+ logger.debug(f"Eventzilla: resuming {config.name} from event_id={resume.event_id}, offset={resume_offset}")
+
+ for index, event_id in enumerate(remaining):
+ path = config.path.replace("{event_id}", event_id)
+ start_offset = resume_offset if index == 0 else 0
+
+ try:
+ for items, next_offset in _iter_pages(session, path, config.data_key, headers, logger, start_offset):
+ for item in items:
+ item["event_id"] = event_id
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ resumable_source_manager.save_state(
+ EventzillaResumeConfig(offset=next_offset, event_id=event_id)
+ )
+ except requests.HTTPError as exc:
+ # An event deleted between enumeration and this fetch 404s. Skip it rather than failing
+ # the whole sync — the child rows are genuinely gone. Any other HTTP error is re-raised.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Eventzilla: event {event_id} not found while fetching {config.name}, skipping")
+ else:
+ raise
+
+ # Advance the bookmark to the next event so a crash between events resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(EventzillaResumeConfig(offset=0, event_id=remaining[index + 1]))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EventzillaResumeConfig],
+) -> Iterator[Any]:
+ config = EVENTZILLA_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # One session reused across every page (and, for fan-out, every event) so urllib3 keeps the
+ # connection alive instead of re-handshaking per request.
+ session = make_tracked_session()
+
+ if config.fan_out_over_events:
+ yield from _get_fan_out_rows(session, config, headers, logger, batcher, resumable_source_manager)
+ else:
+ yield from _get_top_level_rows(session, config, headers, logger, batcher, resumable_source_manager)
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def eventzilla_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EventzillaResumeConfig],
+) -> SourceResponse:
+ endpoint_config = EVENTZILLA_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=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/eventzilla/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/settings.py
new file mode 100644
index 000000000000..30df3adf5749
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/settings.py
@@ -0,0 +1,75 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class EventzillaEndpointConfig:
+ name: str
+ path: str # May contain an `{event_id}` placeholder for fan-out endpoints.
+ data_key: str # Key wrapping the results array in the JSON response (e.g. "events").
+ primary_keys: list[str]
+ # Stable (never-updated) datetime field to partition by. Eventzilla exposes no `created_at`
+ # on events/users, so only the purchase-time endpoints (attendees/transactions) get one.
+ partition_key: Optional[str] = None
+ # When True, `path` carries an `{event_id}` placeholder resolved by walking every event and
+ # querying the child endpoint once per event. Child rows are stamped with `event_id`.
+ fan_out_over_events: bool = False
+ should_sync_default: bool = True
+ # Eventzilla exposes no server-side updated-since / date-range filter on any endpoint — only
+ # limit/offset paging (and status/category filters on /events) — so every table is full refresh.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+EVENTZILLA_ENDPOINTS: dict[str, EventzillaEndpointConfig] = {
+ "events": EventzillaEndpointConfig(
+ name="events",
+ path="/events",
+ data_key="events",
+ primary_keys=["id"],
+ ),
+ "categories": EventzillaEndpointConfig(
+ name="categories",
+ path="/categories",
+ data_key="categories",
+ # Categories are a static reference list; each item is only a `category` string.
+ primary_keys=["category"],
+ ),
+ "users": EventzillaEndpointConfig(
+ name="users",
+ path="/users",
+ data_key="users",
+ primary_keys=["id"],
+ ),
+ "attendees": EventzillaEndpointConfig(
+ name="attendees",
+ path="/events/{event_id}/attendees",
+ data_key="attendees",
+ # Attendee `id` is unique per event, so include the parent event id to stay unique table-wide.
+ primary_keys=["event_id", "id"],
+ partition_key="transaction_date",
+ fan_out_over_events=True,
+ ),
+ "transactions": EventzillaEndpointConfig(
+ name="transactions",
+ path="/events/{event_id}/transactions",
+ data_key="transactions",
+ primary_keys=["event_id", "checkout_id"],
+ partition_key="transaction_date",
+ fan_out_over_events=True,
+ ),
+ "tickets": EventzillaEndpointConfig(
+ name="tickets",
+ path="/events/{event_id}/tickets",
+ data_key="tickets",
+ primary_keys=["event_id", "id"],
+ fan_out_over_events=True,
+ ),
+}
+
+ENDPOINTS = tuple(EVENTZILLA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in EVENTZILLA_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/source.py
index ac7b5f1fa999..677be044da08 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/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.eventzilla.eventzilla import (
+ EventzillaResumeConfig,
+ eventzilla_source,
+ validate_credentials as validate_eventzilla_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.eventzilla.settings import (
+ ENDPOINTS,
+ EVENTZILLA_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import EventzillaSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class EventzillaSource(SimpleSource[EventzillaSourceConfig]):
+class EventzillaSource(ResumableSource[EventzillaSourceConfig, EventzillaResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.EVENTZILLA
@@ -24,7 +48,96 @@ class EventzillaSource(SimpleSource[EventzillaSourceConfig]):
name=SchemaExternalDataSourceType.EVENTZILLA,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Eventzilla",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Eventzilla API key to automatically pull your Eventzilla data into the PostHog Data warehouse.
+
+You can generate an API key in your Eventzilla account under **Settings > App Management**.""",
iconPath="/static/services/eventzilla.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/eventzilla",
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.eventzilla.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Eventzilla returns 401/403 for an invalid, revoked, or unauthorized API key. 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://www.eventzillaapi.net": "Your Eventzilla API key is invalid or has been revoked. Generate a new key under Settings > App Management, then reconnect.",
+ "403 Client Error: Forbidden for url: https://www.eventzillaapi.net": "Your Eventzilla API key is not authorized to access this data. Check the key under Settings > App Management, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: EventzillaSourceConfig,
+ 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 EVENTZILLA_ENDPOINTS[endpoint].fan_out_over_events:
+ return "Fetched per event by walking every event. Full refresh only"
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = EVENTZILLA_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ # Eventzilla exposes no server-side updated-since filter, so every table is full
+ # refresh only — no incremental or append modes.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.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: EventzillaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_eventzilla_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Eventzilla API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EventzillaResumeConfig]:
+ return ResumableSourceManager[EventzillaResumeConfig](inputs, EventzillaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: EventzillaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[EventzillaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return eventzilla_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/eventzilla/tests/test_eventzilla.py b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/tests/test_eventzilla.py
new file mode 100644
index 000000000000..364d5bb15cc7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/tests/test_eventzilla.py
@@ -0,0 +1,326 @@
+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.eventzilla import eventzilla
+from products.warehouse_sources.backend.temporal.data_imports.sources.eventzilla.eventzilla import (
+ PAGE_SIZE,
+ EventzillaResumeConfig,
+ EventzillaRetryableError,
+ _build_url,
+ _iter_pages,
+ eventzilla_source,
+ get_rows,
+ validate_credentials,
+)
+
+
+def _response_with_status(status_code: int) -> requests.Response:
+ response = requests.Response()
+ response.status_code = status_code
+ return response
+
+
+class _FakeResumableManager:
+ def __init__(self, state: EventzillaResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[EventzillaResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> EventzillaResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: EventzillaResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, pages: dict[str, Any]) -> list[dict]:
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(eventzilla, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for table in get_rows(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestIterPages:
+ def test_stops_on_empty_first_page(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(eventzilla, "_fetch_page", lambda *a, **k: {"events": []})
+ assert list(_iter_pages(MagicMock(), "/events", "events", {}, MagicMock())) == []
+
+ def test_single_short_page_without_pagination_stops(self, monkeypatch: Any) -> None:
+ # A page shorter than PAGE_SIZE and no `pagination` object means the list is exhausted;
+ # a second request (which would return the same rows for a non-paging endpoint) is a bug.
+ calls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ calls.append(url)
+ return {"tickets": [{"id": 1}, {"id": 2}]}
+
+ monkeypatch.setattr(eventzilla, "_fetch_page", fake_fetch)
+ pages = list(_iter_pages(MagicMock(), "/events/9/tickets", "tickets", {}, MagicMock()))
+
+ assert [items for items, _ in pages] == [[{"id": 1}, {"id": 2}]]
+ assert len(calls) == 1
+
+ def test_pagination_total_terminates_even_on_a_full_page(self, monkeypatch: Any) -> None:
+ # When `total` is reached we must stop, even though the page came back full (== PAGE_SIZE),
+ # otherwise we'd issue an unnecessary extra request and risk re-reading rows.
+ full_page = [{"id": i} for i in range(PAGE_SIZE)]
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ fetched.append(url)
+ return {"events": full_page, "pagination": {"offset": 0, "limit": PAGE_SIZE, "total": PAGE_SIZE}}
+
+ monkeypatch.setattr(eventzilla, "_fetch_page", fake_fetch)
+ pages = list(_iter_pages(MagicMock(), "/events", "events", {}, MagicMock()))
+
+ assert len(pages) == 1
+ assert len(fetched) == 1
+
+ def test_follows_multiple_pages_until_total_reached(self, monkeypatch: Any) -> None:
+ responses = [
+ {"events": [{"id": i} for i in range(PAGE_SIZE)], "pagination": {"total": PAGE_SIZE + 1}},
+ {"events": [{"id": 999}], "pagination": {"total": PAGE_SIZE + 1}},
+ ]
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ return responses.pop(0)
+
+ monkeypatch.setattr(eventzilla, "_fetch_page", fake_fetch)
+ pages = list(_iter_pages(MagicMock(), "/events", "events", {}, MagicMock()))
+
+ assert [len(items) for items, _ in pages] == [PAGE_SIZE, 1]
+ # next_offset advances by the real returned count, not a fixed step.
+ assert [next_offset for _, next_offset in pages] == [PAGE_SIZE, PAGE_SIZE + 1]
+
+ def test_offset_advances_by_actual_count_when_server_clamps_page_size(self, monkeypatch: Any) -> None:
+ # If the server clamps `limit` below PAGE_SIZE we must advance by rows returned, not PAGE_SIZE,
+ # or we'd skip rows. Two clamped-to-20 pages then an empty page.
+ responses = [
+ {"events": [{"id": i} for i in range(20)], "pagination": {"offset": 0, "limit": 20, "total": 25}},
+ {"events": [{"id": i} for i in range(20, 25)], "pagination": {"offset": 20, "limit": 20, "total": 25}},
+ ]
+ seen_offsets: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ seen_offsets.append(int(url.split("offset=")[1].split("&")[0]))
+ return responses.pop(0)
+
+ monkeypatch.setattr(eventzilla, "_fetch_page", fake_fetch)
+ list(_iter_pages(MagicMock(), "/events", "events", {}, MagicMock()))
+
+ assert seen_offsets == [0, 20]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_bool(self, _name: str, status: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(status)
+ with patch.object(eventzilla, "make_tracked_session", return_value=session):
+ assert validate_credentials("key") is expected
+
+ def test_transport_error_is_false(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(eventzilla, "make_tracked_session", return_value=session):
+ assert validate_credentials("key") is False
+
+
+class TestFetchPageRetries:
+ @parameterized.expand(
+ [
+ ("read_timeout", requests.ReadTimeout("slow")),
+ ("connection_error", requests.ConnectionError("down")),
+ ]
+ )
+ def test_transient_errors_are_retried(self, _name: str, transient: Exception) -> None:
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = {"events": []}
+ session = MagicMock()
+ session.get.side_effect = [transient, good]
+
+ with patch.object(eventzilla._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = eventzilla._fetch_page(session, "https://www.eventzillaapi.net/api/v2/events", {}, MagicMock())
+
+ assert result == {"events": []}
+ assert session.get.call_count == 2
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_5xx_and_429_are_retryable(self, _name: str, status: int) -> None:
+ resp = MagicMock()
+ resp.status_code = status
+ session = MagicMock()
+ session.get.return_value = resp
+
+ with patch.object(eventzilla._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(EventzillaRetryableError):
+ eventzilla._fetch_page(session, "https://www.eventzillaapi.net/api/v2/events", {}, MagicMock())
+
+ def test_4xx_raises_for_status(self) -> None:
+ resp = MagicMock()
+ resp.status_code = 401
+ resp.ok = False
+ resp.raise_for_status.side_effect = requests.HTTPError("401", response=_response_with_status(401))
+ session = MagicMock()
+ session.get.return_value = resp
+
+ with pytest.raises(requests.HTTPError):
+ eventzilla._fetch_page(session, "https://www.eventzillaapi.net/api/v2/events", {}, MagicMock())
+
+
+class TestFanOut:
+ def _pages_for_two_events(self) -> dict[str, Any]:
+ return {
+ _build_url("/events", 0): {"events": [{"id": 1}, {"id": 2}], "pagination": {"total": 2}},
+ _build_url("/events/1/attendees", 0): {"attendees": [{"id": "A1"}, {"id": "A2"}]},
+ _build_url("/events/2/attendees", 0): {"attendees": [{"id": "A3"}]},
+ }
+
+ def test_stamps_event_id_and_aggregates_across_events(self, monkeypatch: Any) -> None:
+ rows = _collect(_FakeResumableManager(), monkeypatch, "attendees", self._pages_for_two_events())
+ assert rows == [
+ {"id": "A1", "event_id": "1"},
+ {"id": "A2", "event_id": "1"},
+ {"id": "A3", "event_id": "2"},
+ ]
+
+ def test_resume_from_saved_event_and_offset(self, monkeypatch: Any) -> None:
+ # Resuming into event 2 at offset 0 must skip event 1 entirely, and enumeration always
+ # re-walks /events first.
+ pages = {
+ _build_url("/events", 0): {"events": [{"id": 1}, {"id": 2}], "pagination": {"total": 2}},
+ _build_url("/events/2/attendees", 0): {"attendees": [{"id": "A3"}]},
+ }
+ manager = _FakeResumableManager(EventzillaResumeConfig(offset=0, event_id="2"))
+ rows = _collect(manager, monkeypatch, "attendees", pages)
+ assert rows == [{"id": "A3", "event_id": "2"}]
+
+ def test_resume_from_deleted_event_restarts_from_first(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(EventzillaResumeConfig(offset=5, event_id="999"))
+ rows = _collect(manager, monkeypatch, "attendees", self._pages_for_two_events())
+ assert [r["event_id"] for r in rows] == ["1", "1", "2"]
+
+ def test_event_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:
+ not_found = requests.HTTPError(response=_response_with_status(404))
+ pages = {
+ _build_url("/events", 0): {"events": [{"id": 1}, {"id": 2}], "pagination": {"total": 2}},
+ _build_url("/events/1/attendees", 0): not_found,
+ _build_url("/events/2/attendees", 0): {"attendees": [{"id": "A3"}]},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, "attendees", pages)
+ assert rows == [{"id": "A3", "event_id": "2"}]
+
+ def test_non_404_http_error_propagates(self, monkeypatch: Any) -> None:
+ server_error = requests.HTTPError(response=_response_with_status(500))
+ pages = {
+ _build_url("/events", 0): {"events": [{"id": 1}], "pagination": {"total": 1}},
+ _build_url("/events/1/attendees", 0): server_error,
+ }
+ with pytest.raises(requests.HTTPError):
+ _collect(_FakeResumableManager(), monkeypatch, "attendees", pages)
+
+
+class TestTopLevelResume:
+ def test_resume_uses_saved_offset(self, monkeypatch: Any) -> None:
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ fetched.append(url)
+ return {"events": []}
+
+ monkeypatch.setattr(eventzilla, "_fetch_page", fake_fetch)
+ manager = _FakeResumableManager(EventzillaResumeConfig(offset=40))
+ list(
+ get_rows(
+ api_key="key",
+ endpoint="events",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ )
+ assert fetched == [_build_url("/events", 40)]
+
+
+class TestSaveStateAfterYield:
+ class _ImmediateBatcher:
+ # Yields after every batched item so we can observe save_state timing without 2000+ rows.
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ self._items: list[dict] = []
+
+ def batch(self, item: dict) -> None:
+ self._items.append(item)
+
+ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:
+ return bool(self._items)
+
+ def get_table(self) -> Any:
+ table = MagicMock()
+ table.to_pylist.return_value = list(self._items)
+ self._items = []
+ return table
+
+ def test_top_level_saves_next_offset_after_each_yield(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(eventzilla, "Batcher", self._ImmediateBatcher)
+ pages = {
+ _build_url("/events", 0): {"events": [{"id": 1}], "pagination": {"total": 2}},
+ _build_url("/events", 1): {"events": [{"id": 2}], "pagination": {"total": 2}},
+ }
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, "events", pages)
+
+ # State is saved AFTER each yielded batch carrying the NEXT offset, so a crash re-reads the
+ # last batch rather than skipping it. Top-level saves never carry an event_id.
+ assert [s.offset for s in manager.saved] == [1, 2]
+ assert all(s.event_id is None for s in manager.saved)
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("events", ["id"], None),
+ ("categories", ["category"], None),
+ ("users", ["id"], None),
+ ("attendees", ["event_id", "id"], "transaction_date"),
+ ("transactions", ["event_id", "checkout_id"], "transaction_date"),
+ ("tickets", ["event_id", "id"], None),
+ ]
+ )
+ def test_primary_keys_and_partitioning(
+ self, endpoint: str, primary_keys: list[str], partition_key: str | None
+ ) -> None:
+ response = eventzilla_source(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_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]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/tests/test_eventzilla_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/tests/test_eventzilla_source.py
new file mode 100644
index 000000000000..a3f84159cd5e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/eventzilla/tests/test_eventzilla_source.py
@@ -0,0 +1,100 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.eventzilla import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.eventzilla.eventzilla import (
+ EventzillaResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.eventzilla.source import EventzillaSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import EventzillaSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestEventzillaSourceClass:
+ def setup_method(self) -> None:
+ self.source = EventzillaSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.EVENTZILLA
+
+ def test_source_config_basics(self) -> None:
+ config = self.source.get_source_config
+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/eventzilla"
+
+ def test_source_config_has_single_secret_api_key_field(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert [f.name for f in fields] == ["api_key"]
+ api_key = fields[0]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.required is True
+ assert api_key.secret is True
+
+ def test_all_schemas_are_full_refresh_only(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == {"events", "categories", "users", "attendees", "transactions", "tickets"}
+ # Eventzilla has no server-side updated-since filter, so nothing supports incremental/append.
+ for schema in schemas:
+ assert schema.supports_incremental is False, schema.name
+ assert schema.supports_append is False, schema.name
+ assert schema.incremental_fields == [], schema.name
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["events", "attendees"])
+ assert {s.name for s in schemas} == {"events", "attendees"}
+
+ def test_fan_out_endpoints_carry_a_description(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=1)}
+ assert schemas["attendees"].description is not None
+ assert schemas["events"].description is None
+
+ @pytest.mark.parametrize("valid,expected", [(True, (True, None)), (False, (False, "Invalid Eventzilla API key"))])
+ def test_validate_credentials(self, valid: bool, expected: tuple[bool, str | None]) -> None:
+ config = EventzillaSourceConfig(api_key="key")
+ with patch.object(source_module, "validate_eventzilla_credentials", return_value=valid):
+ assert self.source.validate_credentials(config, team_id=1) == expected
+
+ @pytest.mark.parametrize("status", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors_cover_auth_failures(self, status: str) -> None:
+ keys = self.source.get_non_retryable_errors()
+ assert any(status in key for key in keys)
+
+ def test_resumable_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(MagicMock())
+ assert manager._data_class is EventzillaResumeConfig
+
+ def test_source_for_pipeline_plumbs_key_and_schema(self) -> None:
+ config = EventzillaSourceConfig(api_key="secret-key")
+ inputs = MagicMock()
+ inputs.schema_name = "transactions"
+ manager = MagicMock()
+ with patch.object(source_module, "eventzilla_source") as mock_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "secret-key"
+ assert kwargs["endpoint"] == "transactions"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # `lists_tables_without_credentials` is on, so public docs get the full static catalog.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == {
+ "events",
+ "categories",
+ "users",
+ "attendees",
+ "transactions",
+ "tickets",
+ }
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 284d0de16a49..b098a56295d1 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
@@ -1104,7 +1104,7 @@ class EventeeSourceConfig(config.Config):
@config.config
class EventzillaSourceConfig(config.Config):
- pass
+ api_key: str
@config.config