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(warehouse): implement rewardful source (#118154)

Daniel RCcc075655e8d9
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 171920f529d0..f8c5aa06be2d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -711,6 +711,7 @@ the row lists both.
| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| reverb | HTTP | requests + `rest_source.RESTClient` | ✅ |
| revolut_merchant | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| rewardful | HTTP | requests + `rest_source.RESTClient` | ✅ |
| rippling | HTTP | requests | ✅ |
| rki_covid | HTTP | requests | ✅ |
| roark | HTTP | requests | ✅ |
@@ -1400,7 +1401,6 @@ doesn't conflict with concurrent PRs.
- reply_io
- retail_express
- retently
-- rewardful
- ringcentral
- rocket_chat
- rocket_matter
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rewardful.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rewardful.py
index 5fd87ebd1f52..32497fabbdd8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rewardful.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rewardful.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class RewardfulSourceConfig(config.Config):
- pass
+ api_secret: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/canonical_descriptions.py
new file mode 100644
index 000000000000..06b247617622
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/canonical_descriptions.py
@@ -0,0 +1,138 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://developers.rewardful.com/rest-api"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "affiliates": {
+ "description": "A person or company that promotes your product in exchange for commissions.",
+ "docs_url": f"{_DOCS}/affiliates/object",
+ "columns": {
+ "id": "Unique identifier of the affiliate (UUID).",
+ "created_at": "When the affiliate was created.",
+ "updated_at": "When the affiliate was last updated.",
+ "first_name": "Affiliate's first name.",
+ "last_name": "Affiliate's last name.",
+ "email": "Affiliate's email address.",
+ "paypal_email": "PayPal email the affiliate is paid to, if PayPal payouts are enabled.",
+ "wise_email": "Wise email the affiliate is paid to, if Wise payouts are enabled.",
+ "state": "Affiliate status: active, disabled or suspicious.",
+ "stripe_customer_id": "Stripe customer the affiliate is linked to, if any.",
+ "stripe_account_id": "Stripe account the affiliate is linked to, if any.",
+ "visitors": "Number of unique visitors the affiliate has referred.",
+ "leads": "Number of leads the affiliate has referred.",
+ "conversions": "Number of paying customers the affiliate has referred.",
+ "campaign": "The campaign the affiliate belongs to.",
+ "links": "The affiliate's referral links.",
+ "coupon": "The coupon assigned to the affiliate, if any.",
+ },
+ },
+ "referrals": {
+ "description": "A visitor, lead or customer attributed to an affiliate.",
+ "docs_url": f"{_DOCS}/referrals/object",
+ "columns": {
+ "id": "Unique identifier of the referral (UUID).",
+ "created_at": "When the referral was first tracked.",
+ "updated_at": "When the referral was last updated.",
+ "became_lead_at": "When the referral became a lead.",
+ "became_conversion_at": "When the referral became a paying customer.",
+ "expires_at": "When the referral attribution expires.",
+ "deactivated_at": "When the referral was deactivated, if it was.",
+ "conversion_state": "Stage of the referral: visitor, lead or conversion.",
+ "visits": "Number of visits recorded for the referral.",
+ "link": "The affiliate link the referral came through.",
+ "customer": "The customer record in the payment processor: id, name, email and platform.",
+ "affiliate": "The affiliate the referral is attributed to.",
+ "stripe_account_id": "Stripe account the referral belongs to.",
+ "stripe_customer_id": "Stripe customer created for the referral, if any.",
+ },
+ },
+ "commissions": {
+ "description": "A commission earned by an affiliate on a sale.",
+ "docs_url": f"{_DOCS}/commissions/object",
+ "columns": {
+ "id": "Unique identifier of the commission (UUID).",
+ "created_at": "When the commission was created.",
+ "updated_at": "When the commission was last updated.",
+ "amount": "Commission amount in the smallest currency unit (for example cents).",
+ "currency": "Three-letter currency code of the commission.",
+ "state": "Commission status: due, pending, paid or voided.",
+ "due_at": "When the commission becomes due for payout.",
+ "paid_at": "When the commission was paid, if it was.",
+ "voided_at": "When the commission was voided, if it was.",
+ "campaign": "The campaign whose reward terms produced the commission.",
+ "sale": "The sale the commission was computed from, with charge, refund and tax amounts.",
+ },
+ },
+ "payouts": {
+ "description": "A payment of due commissions to an affiliate.",
+ "docs_url": f"{_DOCS}/payouts/the-payout-object",
+ "columns": {
+ "id": "Unique identifier of the payout (UUID).",
+ "created_at": "When the payout was created.",
+ "updated_at": "When the payout was last updated.",
+ "amount": "Payout amount in the smallest currency unit (for example cents).",
+ "currency": "Three-letter currency code of the payout.",
+ "state": "Payout status: pending, due, processing or paid.",
+ "paid_at": "When the payout was paid, if it was.",
+ "paid_by_id": "Identifier of the user who marked the payout as paid.",
+ "affiliate": "The affiliate the payout goes to.",
+ "commissions": "The commissions included in the payout.",
+ },
+ },
+ "campaigns": {
+ "description": "An affiliate program with its reward terms and the affiliates enrolled in it.",
+ "docs_url": f"{_DOCS}/campaigns/the-campaign-object",
+ "columns": {
+ "id": "Unique identifier of the campaign (UUID).",
+ "created_at": "When the campaign was created.",
+ "updated_at": "When the campaign was last updated.",
+ "name": "Campaign name.",
+ "url": "Destination URL affiliate links point to.",
+ "private": "Whether affiliates need an invitation token to join.",
+ "reward_type": "How commissions are computed: percent or amount.",
+ "commission_percent": "Commission percentage, when the reward type is percent.",
+ "commission_amount_cents": "Fixed commission amount in cents, when the reward type is amount.",
+ "commission_amount_currency": "Currency of the fixed commission amount.",
+ "minimum_payout_cents": "Minimum balance, in cents, before an affiliate is paid.",
+ "max_commission_period_months": "Number of months commissions keep accruing per referral.",
+ "max_commissions": "Maximum number of commissions per referral.",
+ "days_before_referrals_expire": "Days before an unconverted referral expires.",
+ "days_until_commissions_are_due": "Days after a sale before its commission becomes due.",
+ "default": "Whether new affiliates join this campaign by default.",
+ "stripe_coupon_id": "Stripe coupon applied to referred customers, if any.",
+ "visitors": "Number of unique visitors referred through the campaign.",
+ "leads": "Number of leads referred through the campaign.",
+ "conversions": "Number of paying customers referred through the campaign.",
+ "affiliates": "Number of affiliates enrolled in the campaign.",
+ },
+ },
+ "affiliate_links": {
+ "description": "A referral link that attributes visits to an affiliate.",
+ "docs_url": f"{_DOCS}/affiliate-links/the-affiliate-link-object",
+ "columns": {
+ "id": "Unique identifier of the link (UUID).",
+ "url": "Full referral URL.",
+ "token": "Referral token carried in the URL.",
+ "visitors": "Number of unique visitors through the link.",
+ "leads": "Number of leads through the link.",
+ "conversions": "Number of paying customers through the link.",
+ "affiliate_id": "The affiliate the link belongs to.",
+ },
+ },
+ "affiliate_coupons": {
+ "description": "A payment-processor coupon code assigned to an affiliate for offline attribution.",
+ "docs_url": f"{_DOCS}/affiliate-coupons/the-affiliate-coupon-object",
+ "columns": {
+ "id": "Unique identifier of the coupon (UUID).",
+ "external_id": "Identifier of the coupon in the payment processor (for example a Stripe promotion code).",
+ "token": "Coupon code the customer enters.",
+ "archived": "Whether the coupon is archived.",
+ "archived_at": "When the coupon was archived, if it was.",
+ "leads": "Number of leads attributed through the coupon.",
+ "conversions": "Number of paying customers attributed through the coupon.",
+ "affiliate_id": "The affiliate the coupon belongs to.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/rewardful.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/rewardful.py
new file mode 100644
index 000000000000..c7d76bb137e5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/rewardful.py
@@ -0,0 +1,159 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from requests.auth import HTTPBasicAuth
+from urllib3.util.retry import Retry
+
+from posthog.dataclasses import frozen
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.rewardful.settings import (
+ PAGE_LIMIT,
+ REWARDFUL_BASE_URL,
+ REWARDFUL_ENDPOINTS,
+)
+
+REQUEST_TIMEOUT = (10, 60)
+# Setup waits on the probe, so it gets one short attempt.
+PROBE_TIMEOUT_SECONDS = 30
+
+CAMPAIGNS_PAGED_ERROR = "Rewardful returned more than one page of campaigns"
+
+
+@frozen
+class RewardfulResumeConfig:
+ next_page: int
+
+
+def format_updated_since(value: Any) -> str:
+ """Format the watermark as the ISO 8601 UTC timestamp `updated_since` expects."""
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).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 unwrap_envelope(item: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]:
+ """Return the rows of a `{"pagination", "data"}` envelope, or the item itself when it is a row.
+
+ An unpaged endpoint is read without a selector, so a bare array arrives as rows and an envelope
+ arrives as one item holding them.
+ """
+ data = item.get("data")
+ if "pagination" in item and isinstance(data, list):
+ # One request reads only the first page, so a paged answer would sync a partial table.
+ if (item.get("pagination") or {}).get("next_page"):
+ raise ValueError(CAMPAIGNS_PAGED_ERROR)
+ return data
+ return item
+
+
+def rewardful_source(
+ api_secret: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[RewardfulResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = REWARDFUL_ENDPOINTS[endpoint]
+ is_incremental = should_use_incremental_field and bool(config.incremental_fields)
+
+ params: dict[str, Any] = {"limit": PAGE_LIMIT, **dict(config.params)}
+ if is_incremental and db_incremental_field_last_value is not None:
+ params["updated_since"] = {
+ "type": "incremental",
+ "cursor_path": "updated_at",
+ "initial_value": None,
+ "convert": format_updated_since,
+ }
+
+ endpoint_config: Endpoint = {"path": config.path, "params": params}
+ if config.paginated:
+ endpoint_config["data_selector"] = "data"
+ endpoint_config["data_selector_required"] = True
+ else:
+ endpoint_config["paginator"] = "single_page"
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": REWARDFUL_BASE_URL,
+ # The API secret is the username; the password is empty.
+ "auth": {"type": "http_basic", "username": api_secret, "password": ""},
+ "paginator": PageNumberPaginator(base_page=1, page_param="page", total_path="pagination.total_pages"),
+ "request_timeout": REQUEST_TIMEOUT,
+ },
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": endpoint,
+ "table_name": endpoint,
+ "primary_key": list(config.primary_keys),
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ **({} if config.paginated else {"data_map": unwrap_envelope}),
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"page": resume.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("page"):
+ resumable_source_manager.save_state(RewardfulResumeConfig(next_page=int(state["page"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=list(config.primary_keys),
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # Rows arrive newest-first by creation date and `updated_since` is the only filter, so the
+ # watermark can only be taken once the whole run has been read.
+ sort_mode="desc",
+ )
+
+
+def validate_credentials(api_secret: str) -> tuple[bool, str | None]:
+ is_valid, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_secret,), retry=Retry(total=0)),
+ f"{REWARDFUL_BASE_URL}/affiliates?limit=1",
+ auth=HTTPBasicAuth(api_secret, ""),
+ timeout=PROBE_TIMEOUT_SECONDS,
+ )
+ if is_valid:
+ return True, None
+ if status == 401:
+ return False, "Rewardful rejected the API secret. Copy it again from Company settings in Rewardful."
+ return False, "Could not connect to Rewardful. Check the API secret and try again."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/settings.py
new file mode 100644
index 000000000000..ee64b721d7aa
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/settings.py
@@ -0,0 +1,57 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+REWARDFUL_BASE_URL = "https://api.getrewardful.com/v1"
+
+# The documented maximum; the default is 25.
+PAGE_LIMIT = 100
+
+
+@frozen
+class RewardfulEndpointConfig:
+ name: str
+ path: str
+ primary_keys: tuple[str, ...] = ("id",)
+ # Rewardful only filters `referrals` by `updated_since` server-side, so that is the one
+ # incremental table. Every other list endpoint has no time filter and no sort parameter.
+ incremental_fields: tuple[IncrementalField, ...] = ()
+ partition_key: str | None = "created_at"
+ params: tuple[tuple[str, str], ...] = ()
+ paginated: bool = True
+
+
+_UPDATED_AT: IncrementalField = {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+REWARDFUL_ENDPOINTS: dict[str, RewardfulEndpointConfig] = {
+ "affiliates": RewardfulEndpointConfig(name="affiliates", path="/affiliates"),
+ "referrals": RewardfulEndpointConfig(
+ name="referrals",
+ path="/referrals",
+ incremental_fields=(_UPDATED_AT,),
+ ),
+ "commissions": RewardfulEndpointConfig(
+ name="commissions",
+ path="/commissions",
+ # The sale carries the charge, refund and tax amounts the commission was computed from.
+ params=(("expand[]", "sale"),),
+ ),
+ "payouts": RewardfulEndpointConfig(name="payouts", path="/payouts"),
+ # Rewardful documents no paging for campaigns and describes the response as a bare array.
+ "campaigns": RewardfulEndpointConfig(name="campaigns", path="/campaigns", paginated=False),
+ "affiliate_links": RewardfulEndpointConfig(name="affiliate_links", path="/affiliate_links", partition_key=None),
+ "affiliate_coupons": RewardfulEndpointConfig(
+ name="affiliate_coupons", path="/affiliate_coupons", partition_key=None
+ ),
+}
+
+ENDPOINTS = tuple(REWARDFUL_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: list(config.incremental_fields) for name, config in REWARDFUL_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/source.py
index b15d89c5854e..e85e9356c58b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/source.py
@@ -1,27 +1,126 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.codebase_detection import detect
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.rewardful import (
RewardfulSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rewardful.rewardful import (
+ RewardfulResumeConfig,
+ rewardful_source,
+ validate_credentials as validate_rewardful_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rewardful.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class RewardfulSource(SimpleSource[RewardfulSourceConfig]):
+class RewardfulSource(ResumableSource[RewardfulSourceConfig, RewardfulResumeConfig]):
+ codebase_detection = detect(env=("^REWARDFUL_",), script_hosts=("r.wdfl.co",))
+
+ lists_tables_without_credentials = True
+ api_docs_url = "https://developers.rewardful.com/rest-api/overview"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.REWARDFUL
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Rewardful rejected the API secret. Copy it again from Company settings in Rewardful, then reconnect the source.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.rewardful.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: RewardfulSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: RewardfulSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_rewardful_credentials(config.api_secret)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RewardfulResumeConfig]:
+ return ResumableSourceManager[RewardfulResumeConfig](inputs, RewardfulResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: RewardfulSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RewardfulResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return rewardful_source(
+ api_secret=config.api_secret,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.REWARDFUL,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
+ keywords=["affiliate", "referral"],
label="Rewardful",
+ caption="Sync affiliates, referrals, commissions and payouts from your Rewardful affiliate program.",
+ docsUrl="https://posthog.com/docs/cdp/sources/rewardful",
iconPath="/static/services/rewardful.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_secret",
+ label="API secret",
+ caption="Found under Company settings in Rewardful. The secret can also change data, but PostHog only reads with it.",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/tests/test_rewardful.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/tests/test_rewardful.py
new file mode 100644
index 000000000000..65164485be8f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rewardful/tests/test_rewardful.py
@@ -0,0 +1,174 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.rewardful import (
+ RewardfulSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rewardful.rewardful import (
+ RewardfulResumeConfig,
+ format_updated_since,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rewardful.source import RewardfulSource
+
+
+def _driver() -> SourceDriver:
+ return SourceDriver(RewardfulSource(), RewardfulSourceConfig(api_secret="rw_secret"))
+
+
+def _page(rows: list[dict[str, Any]], current_page: int, total_pages: int) -> ScriptedResponse:
+ return ScriptedResponse(
+ json={
+ "pagination": {
+ "previous_page": current_page - 1 or None,
+ "current_page": current_page,
+ "next_page": current_page + 1 if current_page < total_pages else None,
+ "count": len(rows),
+ "limit": 100,
+ "total_pages": total_pages,
+ "total_count": 0,
+ },
+ "data": rows,
+ }
+ )
+
+
+class TestPagination:
+ def test_walks_pages_until_total_pages_and_saves_the_next_page_before_each_yield(self) -> None:
+ result = _driver().run(
+ "affiliates",
+ [
+ _page([{"id": "a1"}], 1, 3),
+ _page([{"id": "a2"}], 2, 3),
+ _page([{"id": "a3"}], 3, 3),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.params("page") == ["1", "2", "3"]
+ assert result.params("limit") == ["100", "100", "100"]
+ assert result.requests[0].headers["authorization"] == "Basic cndfc2VjcmV0Og=="
+ assert [row["id"] for row in result.rows] == ["a1", "a2", "a3"]
+ # The third page is the last one, so no cursor is saved past it.
+ assert result.saved_states == [RewardfulResumeConfig(next_page=2), RewardfulResumeConfig(next_page=3)]
+ assert result.committed_states == [RewardfulResumeConfig(next_page=2), RewardfulResumeConfig(next_page=3)]
+
+ def test_resumes_from_the_saved_page(self) -> None:
+ result = _driver().run(
+ "commissions",
+ [_page([{"id": "c9"}], 3, 3)],
+ resume_state=RewardfulResumeConfig(next_page=3),
+ )
+
+ assert result.raised is None
+ assert result.params("page") == ["3"]
+ assert result.params("expand[]") == ["sale"]
+
+ def test_a_bare_array_body_on_a_paged_table_fails_loud_instead_of_syncing_zero_rows(self) -> None:
+ result = _driver().run("affiliates", [ScriptedResponse(json=[{"id": "a1"}])])
+
+ assert result.rows == []
+ assert isinstance(result.raised, ValueError)
+ assert "data" in str(result.raised)
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ [{"id": "camp_1"}, {"id": "camp_2"}],
+ {"pagination": {"next_page": None}, "data": [{"id": "camp_1"}, {"id": "camp_2"}]},
+ ],
+ )
+ def test_campaigns_read_one_page_in_either_documented_shape(self, body: Any) -> None:
+ result = _driver().run("campaigns", [ScriptedResponse(json=body)])
+
+ assert result.raised is None
+ assert result.paths == ["/v1/campaigns"]
+ assert result.params("page") == [None]
+ assert [row["id"] for row in result.rows] == ["camp_1", "camp_2"]
+
+ def test_a_paged_campaigns_answer_fails_instead_of_syncing_a_partial_table(self) -> None:
+ body = {"pagination": {"next_page": 2}, "data": [{"id": "camp_1"}]}
+ result = _driver().run("campaigns", [ScriptedResponse(json=body)])
+
+ assert result.raised is not None
+ assert "more than one page of campaigns" in str(result.raised)
+
+
+class TestIncrementalRequestShaping:
+ @pytest.mark.parametrize(
+ ("incremental_field", "last_value", "expected_updated_since"),
+ [
+ ("updated_at", datetime(2026, 3, 4, 5, 6, 7, tzinfo=UTC), "2026-03-04T05:06:07Z"),
+ ("updated_at", None, None),
+ (None, datetime(2026, 3, 4, 5, 6, 7, tzinfo=UTC), None),
+ ],
+ )
+ def test_referrals_send_updated_since_only_with_a_watermark(
+ self, incremental_field: str | None, last_value: Any, expected_updated_since: str | None
+ ) -> None:
+ kwargs: dict[str, Any] = {"db_incremental_field_last_value": last_value}
+ if incremental_field is not None:
+ kwargs["incremental_field"] = incremental_field
+ result = _driver().run("referrals", [_page([{"id": "r1"}], 1, 1)], **kwargs)
+
+ assert result.raised is None
+ assert result.params("updated_since") == [expected_updated_since]
+ assert result.response is not None and result.response.sort_mode == "desc"
+
+ def test_tables_without_a_server_filter_ignore_the_watermark(self) -> None:
+ result = _driver().run(
+ "commissions",
+ [_page([{"id": "c1"}], 1, 1)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert result.params("updated_since") == [None]
+
+
+class TestFormatUpdatedSince:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05Z"),
+ (datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05Z"),
+ (date(2026, 1, 2), "2026-01-02T00:00:00Z"),
+ ("2026-01-02T03:04:05Z", "2026-01-02T03:04:05Z"),
+ ],
+ )
+ def test_formats_as_utc_iso_8601(self, value: Any, expected: str) -> None:
+ assert format_updated_since(value) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("response", "expected_valid", "expected_message_fragment"),
+ [
+ (ScriptedResponse(json={"pagination": {}, "data": []}), True, None),
+ (ScriptedResponse(status=401, json={"error": "Invalid API Secret."}), False, "rejected the API secret"),
+ (ScriptedResponse(status=500, json={}), False, "Could not connect"),
+ (ConnectionError("boom"), False, "Could not connect"),
+ ],
+ )
+ def test_maps_the_probe_result_to_a_message(
+ self, response: Any, expected_valid: bool, expected_message_fragment: str | None
+ ) -> None:
+ with scripted_network(always(response)) as network:
+ is_valid, message = validate_credentials("rw_secret")
+
+ assert is_valid is expected_valid
+ if expected_message_fragment is None:
+ assert message is None
+ else:
+ assert message is not None and expected_message_fragment in message
+ # Setup waits on the probe, so a failed request gets no retry.
+ assert [request.path for request in network.requests_log] == ["/v1/affiliates"]