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 easypromos import source (#66747)

Tom Owers61a9551bfdec
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 4f1b34531c59..4a1d53160b95 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -105,6 +105,7 @@ the row lists both.
| doit | HTTP | requests | ✅ |
| drip | HTTP | requests | ✅ |
| easypost | HTTP | requests | ✅ |
+| easypromos | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
| freshsales | HTTP | requests | ✅ |
| elasticemail | HTTP | requests | ✅ |
@@ -379,7 +380,6 @@ doesn't conflict with concurrent PRs.
- dynamics365
- dynamodb
- e_conomic
-- easypromos
- ebay
- eloqua
- employment_hero
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/canonical_descriptions.py
new file mode 100644
index 000000000000..c27269fe6e2f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/canonical_descriptions.py
@@ -0,0 +1,85 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Curated from the Easypromos REST API v2 reference (https://easypromos-apiref.redoc.ly/). Keyed by
+# the endpoint/schema name from `get_schemas`. Partial coverage is fine — anything omitted falls
+# back to LLM enrichment. Fan-out tables carry an injected `promotion_id` column not in the API.
+DOCS_BASE = "https://easypromos-apiref.redoc.ly/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "promotions": {
+ "description": "A promotion in an Easypromos account. Always belongs to an organizing brand.",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "id": "Unique identifier of the promotion.",
+ "name": "Name of the promotion.",
+ "created": "Date and time the promotion was created. ISO-8601 in UTC.",
+ "organizing_brand_id": "Identifier of the organizing brand the promotion belongs to.",
+ },
+ },
+ "organizing_brands": {
+ "description": "A brand that organizes promotions. Every promotion belongs to one organizing brand.",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "id": "Unique identifier of the organizing brand.",
+ "name": "Name of the organizing brand.",
+ },
+ },
+ "stages": {
+ "description": "Definition of a participation stage in a promotion (a quiz, game, wheel, etc). Always belongs to a promotion.",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "id": "Unique identifier of the stage within its promotion.",
+ "promotion_id": "Identifier of the promotion this stage belongs to (added by PostHog during sync).",
+ },
+ },
+ "users": {
+ "description": "A participant registered in a promotion. Always belongs to a promotion.",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "id": "Unique identifier of the user within its promotion.",
+ "promotion_id": "Identifier of the promotion this user registered in (added by PostHog during sync).",
+ "created": "Date and time the user registered. ISO-8601 in UTC.",
+ },
+ },
+ "participations": {
+ "description": "A participation of a user in a participation stage (e.g. a single game play with points, IP and timestamp). Belongs to a user and a stage.",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "id": "Unique identifier of the participation within its promotion.",
+ "promotion_id": "Identifier of the promotion this participation belongs to (added by PostHog during sync).",
+ "created": "Date and time of the participation. ISO-8601 in UTC.",
+ },
+ },
+ "prizes": {
+ "description": "Assigned prizes and their winners in a promotion. A prize belongs to the user who won it and a prize type.",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "id": "Unique identifier of the assigned prize within its promotion.",
+ "promotion_id": "Identifier of the promotion this prize belongs to (added by PostHog during sync).",
+ "created": "Date and time the prize was assigned. ISO-8601 in UTC.",
+ },
+ },
+ "coin_transactions": {
+ "description": "Virtual coin transactions in a promotion — each records an amount, timestamp, coin type and the user performing the transaction.",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "promotion_id": "Identifier of the promotion this transaction belongs to (added by PostHog during sync).",
+ },
+ },
+ "rankings": {
+ "description": "Leaderboard of a promotion: users with their scores in a game-based stage.",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "promotion_id": "Identifier of the promotion this ranking belongs to (added by PostHog during sync).",
+ },
+ },
+ "points_of_sale": {
+ "description": "Points of sale configured in a promotion (e.g. for in-store prize redemption).",
+ "docs_url": DOCS_BASE,
+ "columns": {
+ "promotion_id": "Identifier of the promotion this point of sale belongs to (added by PostHog during sync).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/easypromos.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/easypromos.py
new file mode 100644
index 000000000000..f2c927489e3a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/easypromos.py
@@ -0,0 +1,271 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.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.easypromos.settings import (
+ EASYPROMOS_ENDPOINTS,
+ EasypromosEndpointConfig,
+)
+
+EASYPROMOS_BASE_URL = "https://api.easypromosapp.com/v2"
+
+# Bounded retries for the 200 req/min rate limit (429) and transient 5xx. Tuning kept near the top.
+_MAX_RETRY_ATTEMPTS = 6
+_REQUEST_TIMEOUT_SECONDS = 60
+
+
+class EasypromosRetryableError(Exception):
+ """A 429 or 5xx that a fresh request can recover from."""
+
+
+class EasypromosResumeConfig:
+ # Cursor that fetched the list page currently being processed. For top-level endpoints this is
+ # the endpoint's own page cursor; for fan-out endpoints it's the `/promotions` page cursor.
+ # None means the first page. On resume we re-fetch this page and the delta loader dedupes the
+ # re-delivered chunk, so no rows are lost or doubled.
+ cursor: int | None = None
+ # Fan-out only: the promotion whose child rows are currently being emitted, plus the child-list
+ # cursor within that promotion. Lets a fan-out sync resume mid-promotion instead of re-walking
+ # the whole parent page, so a single huge promotion can't livelock the resume.
+ promotion_id: int | None = None
+ child_cursor: int | None = None
+
+
+def _get_headers(access_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {access_token}",
+ "Accept": "application/json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (EasypromosRetryableError, requests.ReadTimeout, requests.ConnectionError),
+ ),
+ stop=stop_after_attempt(_MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(url, params=params, headers=headers, timeout=_REQUEST_TIMEOUT_SECONDS)
+
+ # 429 (rate limit) and 5xx are transient — retry with backoff. Easypromos allows 200 req/min
+ # per account, so a busy fan-out can legitimately hit the limit.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise EasypromosRetryableError(f"Easypromos API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Fan-out error bodies can echo PII from the API, so log only a short, truncated prefix
+ # rather than the full body.
+ body_prefix = response.text[:200]
+ logger.error(f"Easypromos API error: status={response.status_code}, body_prefix={body_prefix!r}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ return data if isinstance(data, dict) else {"items": data}
+
+
+def _next_cursor(data: dict[str, Any]) -> int | None:
+ """Read the cursor for the next page. Easypromos wraps lists as
+ `{"items": [...], "paging": {"next_cursor": <int|null>, "items_page": 100}}`; a null
+ `next_cursor` marks the last page."""
+ paging = data.get("paging")
+ if not isinstance(paging, dict):
+ return None
+ return paging.get("next_cursor")
+
+
+def _iter_list_pages(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ start_cursor: int | None = None,
+) -> Iterator[tuple[list[dict[str, Any]], int | None]]:
+ """Yield (items, request_cursor) for each page of an Easypromos list, following `next_cursor`.
+
+ `request_cursor` is the cursor used to FETCH the yielded page (None for the first page), so a
+ caller can checkpoint it and, on resume, re-fetch exactly that page.
+ """
+ cursor = start_cursor
+ while True:
+ params: dict[str, Any] = {}
+ if cursor is not None:
+ params["next_cursor"] = cursor
+ data = _fetch_page(session, url, params, headers, logger)
+
+ items = data.get("items")
+ items = items if isinstance(items, list) else []
+ yield items, cursor
+
+ next_cursor = _next_cursor(data)
+ if next_cursor is None:
+ return
+ cursor = next_cursor
+
+
+def validate_credentials(access_token: str) -> tuple[bool, str | None]:
+ """One cheap probe of the account-wide Bearer token against `/promotions`."""
+ try:
+ with make_tracked_session() as session:
+ response = session.get(
+ f"{EASYPROMOS_BASE_URL}/promotions",
+ headers=_get_headers(access_token),
+ timeout=10,
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Easypromos access token"
+ if response.status_code == 403:
+ # Valid token, but the account plan can't reach the REST API (Basic/Premium) or lacks
+ # access to this resource. Surface it rather than silently failing.
+ return False, "Your Easypromos plan does not have access to the REST API (requires White Label or Corporate)"
+ return False, f"Easypromos API returned status {response.status_code}"
+
+
+def _get_top_level_rows(
+ session: requests.Session,
+ endpoint_config: EasypromosEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[EasypromosResumeConfig],
+) -> Iterator[Any]:
+ """Page through a top-level list endpoint (`/promotions`, `/organizing_brands`)."""
+ url = f"{EASYPROMOS_BASE_URL}{endpoint_config.path}"
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_cursor = resume.cursor if resume is not None else None
+
+ for items, request_cursor in _iter_list_pages(session, url, headers, logger, start_cursor=start_cursor):
+ for item in items:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save AFTER yielding so a crash re-fetches the current page rather than skipping it.
+ resumable_source_manager.save_state(EasypromosResumeConfig(cursor=request_cursor))
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ endpoint_config: EasypromosEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[EasypromosResumeConfig],
+) -> Iterator[Any]:
+ """Walk `/promotions` and emit child rows for each promotion, injecting `promotion_id` so the
+ composite primary key is unique across promotions."""
+ promotions_url = f"{EASYPROMOS_BASE_URL}{EASYPROMOS_ENDPOINTS['promotions'].path}"
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ parent_start_cursor = resume.cursor if resume is not None else None
+ resume_promotion_id = resume.promotion_id if resume is not None else None
+ resume_child_cursor = resume.child_cursor if resume is not None else None
+
+ for promotions, parent_cursor in _iter_list_pages(
+ session, promotions_url, headers, logger, start_cursor=parent_start_cursor
+ ):
+ # When resuming into a parent page, skip the promotions already fully processed before the
+ # crash; pick up at the one we were mid-way through.
+ skipping = resume_promotion_id is not None
+ for promotion in promotions:
+ promotion_id = promotion["id"]
+ if skipping:
+ if promotion_id != resume_promotion_id:
+ continue
+ skipping = False
+
+ child_start_cursor = resume_child_cursor if promotion_id == resume_promotion_id else None
+ # Consume the saved child cursor only for the promotion it belongs to.
+ resume_child_cursor = None
+
+ child_path = endpoint_config.path.format(promotion_id=promotion_id)
+ child_url = f"{EASYPROMOS_BASE_URL}{child_path}"
+
+ for items, child_cursor in _iter_list_pages(
+ session, child_url, headers, logger, start_cursor=child_start_cursor
+ ):
+ for item in items:
+ item["promotion_id"] = promotion_id
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Checkpoint at promotion + child-page granularity so resume makes forward
+ # progress instead of re-fanning the whole parent page.
+ resumable_source_manager.save_state(
+ EasypromosResumeConfig(
+ cursor=parent_cursor,
+ promotion_id=promotion_id,
+ child_cursor=child_cursor,
+ )
+ )
+ # A parent page whose promotions we processed without ever resuming has consumed the resume
+ # bookmark; clear it so later pages aren't skipped.
+ resume_promotion_id = None
+
+
+def get_rows(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EasypromosResumeConfig],
+) -> Iterator[Any]:
+ endpoint_config = EASYPROMOS_ENDPOINTS[endpoint]
+ headers = _get_headers(access_token)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # One session reused across every page (and, for fan-out, every promotion) so urllib3 keeps the
+ # connection alive instead of re-handshaking per request. The context manager tears down the
+ # connection pool even when a request raises mid-stream.
+ with make_tracked_session() as session:
+ if endpoint_config.fan_out_over_promotions:
+ yield from _get_fan_out_rows(session, endpoint_config, headers, logger, batcher, resumable_source_manager)
+ else:
+ yield from _get_top_level_rows(session, endpoint_config, headers, logger, batcher, resumable_source_manager)
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def easypromos_source(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EasypromosResumeConfig],
+) -> SourceResponse:
+ endpoint_config = EASYPROMOS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ 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="month" 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/easypromos/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/settings.py
new file mode 100644
index 000000000000..918ce0ddf9cf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/settings.py
@@ -0,0 +1,110 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class EasypromosEndpointConfig:
+ name: str
+ # Path under /v2. Fan-out children use a `{promotion_id}` placeholder filled per parent
+ # promotion (e.g. "/users/{promotion_id}").
+ path: str
+ # Columns that uniquely identify a row table-wide. Fan-out children aggregate rows from every
+ # promotion, so the parent `promotion_id` is part of the key — Easypromos ids (user, stage,
+ # participation, ...) are only documented as unique within their promotion.
+ primary_keys: list[str]
+ # Stable creation-timestamp field to partition by, or None to skip partitioning. Only set where
+ # the API docs reliably show a `created` field on every row; never an `updated`/`last_*` field
+ # (those move and rewrite partitions every sync).
+ partition_key: Optional[str] = None
+ # When set, the endpoint is fetched by walking `/promotions` and calling this path once per
+ # promotion, substituting the promotion id into the `{promotion_id}` placeholder. Each emitted
+ # row gets `promotion_id` injected so the composite primary key is unique across promotions.
+ fan_out_over_promotions: bool = False
+ # Whether the table is selected for sync by default in the wizard.
+ should_sync_default: bool = True
+ # Easypromos exposes no server-side updated-since filter — only `order=created_asc|created_desc`
+ # with no `created_gte`-style cutoff — so every endpoint is full refresh and advertises no
+ # incremental fields. Kept as an explicit (empty) field for parity with other sources.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+# The Easypromos REST API v2 (https://api.easypromosapp.com/v2) is hierarchical: a handful of
+# account-level list endpoints, with the rest scoped to a single promotion. We model the
+# promotion-scoped resources as a single-hop fan-out over `/promotions`.
+#
+# None of these endpoints expose a server-side timestamp filter, so all are full refresh. The
+# `order` param (created_asc/created_desc) is honored but cannot bound the result set, so it only
+# fixes a stable pagination order (see easypromos.py).
+EASYPROMOS_ENDPOINTS: dict[str, EasypromosEndpointConfig] = {
+ "promotions": EasypromosEndpointConfig(
+ name="promotions",
+ path="/promotions",
+ primary_keys=["id"],
+ partition_key="created",
+ ),
+ "organizing_brands": EasypromosEndpointConfig(
+ name="organizing_brands",
+ path="/organizing_brands",
+ primary_keys=["id"],
+ ),
+ "stages": EasypromosEndpointConfig(
+ name="stages",
+ path="/stages/{promotion_id}",
+ primary_keys=["promotion_id", "id"],
+ fan_out_over_promotions=True,
+ ),
+ "users": EasypromosEndpointConfig(
+ name="users",
+ path="/users/{promotion_id}",
+ primary_keys=["promotion_id", "id"],
+ partition_key="created",
+ fan_out_over_promotions=True,
+ ),
+ "participations": EasypromosEndpointConfig(
+ name="participations",
+ path="/participations/{promotion_id}",
+ primary_keys=["promotion_id", "id"],
+ partition_key="created",
+ fan_out_over_promotions=True,
+ ),
+ "prizes": EasypromosEndpointConfig(
+ name="prizes",
+ path="/prizes/{promotion_id}",
+ primary_keys=["promotion_id", "id"],
+ partition_key="created",
+ fan_out_over_promotions=True,
+ ),
+ # GetPromotionVirtualCoinTransactions. The transaction object carries an `id`; its timestamp
+ # field name isn't confirmed against a live account, so no partition key until verified.
+ "coin_transactions": EasypromosEndpointConfig(
+ name="coin_transactions",
+ path="/coins/{promotion_id}",
+ primary_keys=["promotion_id", "id"],
+ fan_out_over_promotions=True,
+ should_sync_default=False,
+ ),
+ # A ranking is a leaderboard of users with scores. Keyed on the user within the promotion; the
+ # exact id field isn't confirmed against a live White Label account, so this may need adjusting.
+ "rankings": EasypromosEndpointConfig(
+ name="rankings",
+ path="/rankings/{promotion_id}",
+ primary_keys=["promotion_id", "user_id"],
+ fan_out_over_promotions=True,
+ should_sync_default=False,
+ ),
+ "points_of_sale": EasypromosEndpointConfig(
+ name="points_of_sale",
+ path="/points_of_sale/{promotion_id}",
+ primary_keys=["promotion_id", "id"],
+ fan_out_over_promotions=True,
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(EASYPROMOS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in EASYPROMOS_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/source.py
index d2ca03baaa69..39d0034532f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/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.easypromos.easypromos import (
+ EasypromosResumeConfig,
+ easypromos_source,
+ validate_credentials as validate_easypromos_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos.settings import (
+ EASYPROMOS_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import EasypromosSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class EasypromosSource(SimpleSource[EasypromosSourceConfig]):
+class EasypromosSource(ResumableSource[EasypromosSourceConfig, EasypromosResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.EASYPROMOS
@@ -24,7 +48,92 @@ class EasypromosSource(SimpleSource[EasypromosSourceConfig]):
name=SchemaExternalDataSourceType.EASYPROMOS,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="Easypromos",
- iconPath="/static/services/easypromos.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ keywords=["promotions", "contests", "giveaways"],
+ caption="""Enter your Easypromos access token to sync your promotions data into the PostHog Data warehouse.
+
+Get the token from the **Utilities** menu of your Easypromos account. The REST API is only available on **White Label** and **Corporate** plans, and it does not export data from Basic or Premium promotions.""",
+ iconPath="/static/services/easypromos.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/easypromos",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked access token surfaces as an HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can't satisfy a credential problem, so stop the sync.
+ "401 Client Error: Unauthorized for url: https://api.easypromosapp.com": "Your Easypromos access token is invalid or has been revoked. Generate a new token from the Utilities menu of your Easypromos account, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.easypromosapp.com": "Your Easypromos plan does not have access to the REST API (requires White Label or Corporate), or the token lacks access to this resource.",
+ }
+
+ def get_schemas(
+ self,
+ config: EasypromosSourceConfig,
+ 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 EASYPROMOS_ENDPOINTS[endpoint].fan_out_over_promotions:
+ return "Synced per promotion. Full refresh only — the API has no updated-since filter."
+ return "Full refresh only — the API has no updated-since filter."
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ return SourceSchema(
+ name=endpoint,
+ # Easypromos exposes no server-side timestamp filter, so every endpoint is full
+ # refresh (incremental would re-fetch every page anyway — identical API cost).
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=EASYPROMOS_ENDPOINTS[endpoint].should_sync_default,
+ description=_description(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: EasypromosSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_easypromos_credentials(config.access_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EasypromosResumeConfig]:
+ return ResumableSourceManager[EasypromosResumeConfig](inputs, EasypromosResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: EasypromosSourceConfig,
+ resumable_source_manager: ResumableSourceManager[EasypromosResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return easypromos_source(
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/tests/test_easypromos.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/tests/test_easypromos.py
new file mode 100644
index 000000000000..97467294d17e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/tests/test_easypromos.py
@@ -0,0 +1,238 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos import easypromos
+from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos.easypromos import (
+ EASYPROMOS_BASE_URL,
+ EasypromosResumeConfig,
+ _next_cursor,
+ easypromos_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos.settings import EASYPROMOS_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: EasypromosResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[EasypromosResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> EasypromosResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: EasypromosResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(items: list[dict], next_cursor: int | None) -> dict:
+ return {"items": items, "paging": {"next_cursor": next_cursor, "items_page": 100}}
+
+
+def _install_fake_fetch(monkeypatch: Any, pages: dict[tuple[str, int | None], dict]) -> list[tuple[str, int | None]]:
+ """Patch `_fetch_page` to serve canned pages keyed by (url, next_cursor request param)."""
+ fetched: list[tuple[str, int | None]] = []
+
+ def fake_fetch(session: Any, url: str, params: dict[str, Any], headers: dict[str, str], logger: Any) -> dict:
+ key = (url, params.get("next_cursor"))
+ fetched.append(key)
+ return pages[key]
+
+ monkeypatch.setattr(easypromos, "_fetch_page", fake_fetch)
+ return fetched
+
+
+def _collect(endpoint: str, manager: _FakeResumableManager, monkeypatch: Any) -> list[dict]:
+ rows: list[dict] = []
+ for table in get_rows(
+ access_token="tok",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestNextCursor:
+ @parameterized.expand(
+ [
+ ("has_next", {"items": [], "paging": {"next_cursor": 42, "items_page": 100}}, 42),
+ ("null_next", {"items": [], "paging": {"next_cursor": None, "items_page": 100}}, None),
+ ("no_paging", {"items": []}, None),
+ ("paging_not_dict", {"items": [], "paging": None}, None),
+ ]
+ )
+ def test_next_cursor(self, _name: str, data: dict, expected: int | None) -> None:
+ assert _next_cursor(data) == expected
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden_plan", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ session = MagicMock()
+ session.__enter__.return_value = session
+ session.get.return_value = response
+ with patch.object(easypromos, "make_tracked_session", return_value=session):
+ ok, error = validate_credentials("tok")
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_request_exception_is_invalid(self) -> None:
+ session = MagicMock()
+ session.__enter__.return_value = session
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(easypromos, "make_tracked_session", return_value=session):
+ ok, error = validate_credentials("tok")
+ assert ok is False
+ assert error is not None
+
+
+class TestTopLevelPagination:
+ def test_follows_cursor_until_null(self, monkeypatch: Any) -> None:
+ url = f"{EASYPROMOS_BASE_URL}/promotions"
+ pages = {
+ (url, None): _page([{"id": 1}, {"id": 2}], 100),
+ (url, 100): _page([{"id": 3}], None),
+ }
+ _install_fake_fetch(monkeypatch, pages)
+ rows = _collect("promotions", _FakeResumableManager(), monkeypatch)
+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]
+
+ def test_does_not_inject_promotion_id_for_top_level(self, monkeypatch: Any) -> None:
+ url = f"{EASYPROMOS_BASE_URL}/organizing_brands"
+ pages: dict[tuple[str, int | None], dict] = {(url, None): _page([{"id": 7, "name": "Acme"}], None)}
+ _install_fake_fetch(monkeypatch, pages)
+ rows = _collect("organizing_brands", _FakeResumableManager(), monkeypatch)
+ assert rows == [{"id": 7, "name": "Acme"}]
+ assert "promotion_id" not in rows[0]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ url = f"{EASYPROMOS_BASE_URL}/promotions"
+ # Only the resumed page is served; if the loop started at the first page this would KeyError.
+ pages: dict[tuple[str, int | None], dict] = {(url, 100): _page([{"id": 3}], None)}
+ fetched = _install_fake_fetch(monkeypatch, pages)
+ rows = _collect("promotions", _FakeResumableManager(EasypromosResumeConfig(cursor=100)), monkeypatch)
+ assert rows == [{"id": 3}]
+ assert fetched == [(url, 100)]
+
+ def test_saves_current_page_cursor_after_yield(self, monkeypatch: Any) -> None:
+ # Force a yield per row so we can observe the checkpoint cursor.
+ monkeypatch.setattr(
+ easypromos,
+ "Batcher",
+ lambda **kw: Batcher(logger=kw["logger"], chunk_size=1, chunk_size_bytes=kw["chunk_size_bytes"]),
+ )
+ url = f"{EASYPROMOS_BASE_URL}/promotions"
+ pages = {
+ (url, None): _page([{"id": 1}], 100),
+ (url, 100): _page([{"id": 2}], None),
+ }
+ _install_fake_fetch(monkeypatch, pages)
+ manager = _FakeResumableManager()
+ _collect("promotions", manager, monkeypatch)
+ # Checkpoints record the cursor that fetched the page being processed (None then 100).
+ assert [s.cursor for s in manager.saved] == [None, 100]
+
+
+class TestFanOut:
+ def _promotions_url(self) -> str:
+ return f"{EASYPROMOS_BASE_URL}/promotions"
+
+ def test_fans_out_over_promotions_and_injects_promotion_id(self, monkeypatch: Any) -> None:
+ promos_url = self._promotions_url()
+ pages: dict[tuple[str, int | None], dict] = {
+ (promos_url, None): _page([{"id": 10}, {"id": 20}], None),
+ (f"{EASYPROMOS_BASE_URL}/users/10", None): _page([{"id": 1}, {"id": 2}], None),
+ (f"{EASYPROMOS_BASE_URL}/users/20", None): _page([{"id": 1}], None),
+ }
+ _install_fake_fetch(monkeypatch, pages)
+ rows = _collect("users", _FakeResumableManager(), monkeypatch)
+ assert rows == [
+ {"id": 1, "promotion_id": 10},
+ {"id": 2, "promotion_id": 10},
+ {"id": 1, "promotion_id": 20},
+ ]
+
+ def test_follows_child_pagination(self, monkeypatch: Any) -> None:
+ promos_url = self._promotions_url()
+ pages = {
+ (promos_url, None): _page([{"id": 10}], None),
+ (f"{EASYPROMOS_BASE_URL}/participations/10", None): _page([{"id": 1}], 5),
+ (f"{EASYPROMOS_BASE_URL}/participations/10", 5): _page([{"id": 2}], None),
+ }
+ _install_fake_fetch(monkeypatch, pages)
+ rows = _collect("participations", _FakeResumableManager(), monkeypatch)
+ assert rows == [{"id": 1, "promotion_id": 10}, {"id": 2, "promotion_id": 10}]
+
+ def test_resume_skips_completed_promotions_and_uses_child_cursor(self, monkeypatch: Any) -> None:
+ promos_url = self._promotions_url()
+ # Saved state: mid-way through promotion 20, child cursor 5. Promotion 10 must be skipped and
+ # promotion 20's children must resume at cursor 5 (the un-served cursor None pages would KeyError).
+ pages = {
+ (promos_url, None): _page([{"id": 10}, {"id": 20}, {"id": 30}], None),
+ (f"{EASYPROMOS_BASE_URL}/users/20", 5): _page([{"id": 9}], None),
+ (f"{EASYPROMOS_BASE_URL}/users/30", None): _page([{"id": 1}], None),
+ }
+ _install_fake_fetch(monkeypatch, pages)
+ manager = _FakeResumableManager(EasypromosResumeConfig(cursor=None, promotion_id=20, child_cursor=5))
+ rows = _collect("users", manager, monkeypatch)
+ assert rows == [{"id": 9, "promotion_id": 20}, {"id": 1, "promotion_id": 30}]
+
+ def test_checkpoint_records_promotion_and_child_cursor(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(
+ easypromos,
+ "Batcher",
+ lambda **kw: Batcher(logger=kw["logger"], chunk_size=1, chunk_size_bytes=kw["chunk_size_bytes"]),
+ )
+ promos_url = self._promotions_url()
+ pages: dict[tuple[str, int | None], dict] = {
+ (promos_url, None): _page([{"id": 10}], None),
+ (f"{EASYPROMOS_BASE_URL}/prizes/10", None): _page([{"id": 1}], None),
+ }
+ _install_fake_fetch(monkeypatch, pages)
+ manager = _FakeResumableManager()
+ _collect("prizes", manager, monkeypatch)
+ assert manager.saved == [EasypromosResumeConfig(cursor=None, promotion_id=10, child_cursor=None)]
+
+
+class TestSourceResponse:
+ @parameterized.expand(list(EASYPROMOS_ENDPOINTS.keys()))
+ def test_primary_keys_and_partitioning_match_settings(self, endpoint: str) -> None:
+ config = EASYPROMOS_ENDPOINTS[endpoint]
+ response = easypromos_source(
+ access_token="tok",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_fan_out_children_carry_promotion_id_in_primary_key(self) -> None:
+ for endpoint, config in EASYPROMOS_ENDPOINTS.items():
+ if config.fan_out_over_promotions:
+ assert "promotion_id" in config.primary_keys, endpoint
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/tests/test_easypromos_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/tests/test_easypromos_source.py
new file mode 100644
index 000000000000..e689fa4fa4b8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/tests/test_easypromos_source.py
@@ -0,0 +1,142 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos.easypromos import (
+ EasypromosResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos.settings import (
+ EASYPROMOS_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.easypromos.source import EasypromosSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import EasypromosSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert EasypromosSource().source_type == ExternalDataSourceType.EASYPROMOS
+
+ def test_config_basics(self) -> None:
+ config = EasypromosSource().get_source_config
+ assert config.label == "Easypromos"
+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Stays hidden until it has synced end-to-end against a live White Label account.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/easypromos"
+
+ def test_single_secret_access_token_field(self) -> None:
+ fields = EasypromosSource().get_source_config.fields
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "access_token"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog, so the public docs can render the table list.
+ assert EasypromosSource.lists_tables_without_credentials is True
+
+
+class TestGetSchemas:
+ def test_returns_every_endpoint(self) -> None:
+ schemas = EasypromosSource().get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_all_full_refresh_only(self) -> None:
+ for schema in EasypromosSource().get_schemas(MagicMock(), team_id=1):
+ assert schema.supports_incremental is False, schema.name
+ assert schema.supports_append is False, schema.name
+
+ def test_should_sync_default_mirrors_settings(self) -> None:
+ schemas = {s.name: s for s in EasypromosSource().get_schemas(MagicMock(), team_id=1)}
+ for name, config in EASYPROMOS_ENDPOINTS.items():
+ assert schemas[name].should_sync_default is config.should_sync_default
+
+ def test_names_filter(self) -> None:
+ schemas = EasypromosSource().get_schemas(MagicMock(), team_id=1, names=["promotions", "users"])
+ assert {s.name for s in schemas} == {"promotions", "users"}
+
+ def test_fan_out_description_mentions_per_promotion(self) -> None:
+ schemas = {s.name: s for s in EasypromosSource().get_schemas(MagicMock(), team_id=1)}
+ assert "per promotion" in (schemas["users"].description or "")
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", True, None), ("invalid", False, "Invalid Easypromos access token")])
+ def test_delegates_to_transport(self, _name: str, ok: bool, error: str | None) -> None:
+ config = EasypromosSourceConfig(access_token="tok")
+ with patch.object(source_module, "validate_easypromos_credentials", return_value=(ok, error)) as mock:
+ result = EasypromosSource().validate_credentials(config, team_id=1)
+ assert result == (ok, error)
+ mock.assert_called_once_with("tok")
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.easypromosapp.com/v2/promotions"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.easypromosapp.com/v2/users/1"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ errors = EasypromosSource().get_non_retryable_errors()
+ assert any(key in observed for key in errors)
+
+ @parameterized.expand(
+ [
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://api.easypromosapp.com/v2/promotions",
+ ),
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.easypromosapp.com/v2/users/1",
+ ),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:
+ errors = EasypromosSource().get_non_retryable_errors()
+ assert not any(key in observed for key in errors)
+
+
+class TestResumableManager:
+ def test_returns_manager_bound_to_resume_config(self) -> None:
+ manager = EasypromosSource().get_resumable_source_manager(MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is EasypromosResumeConfig
+
+
+class TestSourceForPipeline:
+ def test_plumbs_endpoint_and_keys(self) -> None:
+ config = EasypromosSourceConfig(access_token="tok")
+ inputs = MagicMock()
+ inputs.schema_name = "participations"
+ inputs.logger = MagicMock()
+ response = EasypromosSource().source_for_pipeline(config, MagicMock(), inputs)
+ assert response.name == "participations"
+ assert response.primary_keys == EASYPROMOS_ENDPOINTS["participations"].primary_keys
+
+
+class TestCanonicalDescriptions:
+ def test_promotions_documented(self) -> None:
+ descriptions = EasypromosSource().get_canonical_descriptions()
+ assert "promotions" in descriptions
+ assert descriptions["promotions"]["description"]
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = EasypromosSource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
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 d6203361883e..65e256030b3a 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
@@ -1016,7 +1016,7 @@ class EasypostSourceConfig(config.Config):
@config.config
class EasypromosSourceConfig(config.Config):
- pass
+ access_token: str
@config.config