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.

20.0 KB
Raw Blame
from collections.abc import AsyncIterable, Iterable
from typing import TYPE_CHECKING, Any, Optional, cast

import orjson
import pyarrow as pa
from asgiref.sync import async_to_sync

from products.warehouse_sources.sources.revenuecat import revenuecat as api_client
from products.warehouse_sources.sources.revenuecat._config import RevenueCatSourceConfig
from products.warehouse_sources.sources.revenuecat.constants import (
    EVENT_RESOURCE_NAME,
    RESOURCE_TO_REVENUECAT_EVENT_TYPE,
)
from products.warehouse_sources.sources.revenuecat.revenuecat import RevenueCatResumeConfig
from products.warehouse_sources.sources.revenuecat.settings import (
    REVENUECAT_API_SCHEMA_NAMES,
    REVENUECAT_WEBHOOK_SCHEMA_NAMES,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    ExternalWebhookInfo,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    WebhookCreationResult,
    WebhookDeletionResult,
    WebhookSource,
    WebhookSourceManager,
    detect,
)
from products.warehouse_sources.sources.sdk.internals import table_from_py_list

if TYPE_CHECKING:
    from products.warehouse_sources.sources.sdk import HogFunctionTemplateDC


REVENUECAT_API_KEYS_URL = "https://app.revenuecat.com/projects/_/api-keys"


# Event-payload fields RevenueCat documents as doubles. JSON drops the decimal point on
# whole values (`0`, `20`), so they parse as Python ints, and events like TRANSFER carry
# them as nulls. If the batch that creates the Delta table holds only whole values, the
# column gets locked to int64 and the first fractional price (e.g. 19.99) fails every
# subsequent sync with an Arrow truncation error; if it holds only nulls, the column is
# stored as string (Delta has no null type) and later prices are silently stringified.
# Force these columns to double so neither can happen.
_EVENT_DOUBLE_FIELDS = (
    "price",
    "price_in_purchased_currency",
    "takehome_percentage",
    "tax_percentage",
    "commission_percentage",
    "discount_percentage",
    "discount_amount",
)


def _webhook_table_transformer(table: pa.Table) -> pa.Table:
    """Unwrap RevenueCat's ``{"event": {...}, "api_version": "1.0"}`` envelope.

    Webhook deliveries land in S3 as raw POST bodies. RevenueCat nests the
    interesting payload under ``event`` — we hoist it so the warehouse table
    columns match the documented event field names directly. ``api_version`` is
    kept as a sibling column so consumers can detect upstream schema changes.

    We also derive a ``created_at`` field (Unix seconds) from RevenueCat's
    ``event_timestamp_ms`` so this table can share the same datetime partition
    convention as the API endpoints. The original ``event_timestamp_ms`` is
    preserved unchanged for callers that need sub-second precision. Columns
    documented as doubles are forced to float64 so whole-valued or all-null
    batches can't pin them to an integer or string type (see
    ``_EVENT_DOUBLE_FIELDS``).
    """
    if "event" not in table.column_names:
        return table_from_py_list([])

    event_col = table.column("event").to_pylist()
    api_version_col = (
        table.column("api_version").to_pylist() if "api_version" in table.column_names else [None] * table.num_rows
    )

    rows: list[dict[str, Any]] = []
    for event, api_version in zip(event_col, api_version_col):
        if event is None:
            continue
        # Defensive: `event` typically arrives as a nested dict (pyarrow struct),
        # but we accept a JSON-serialized string too in case the upstream
        # buffering layer flattens nested structures.
        row = orjson.loads(event) if isinstance(event, (str, bytes)) else dict(event)
        row["api_version"] = api_version
        event_ts_ms = row.get("event_timestamp_ms")
        if isinstance(event_ts_ms, int) and not isinstance(event_ts_ms, bool):
            row["created_at"] = event_ts_ms // 1000
        rows.append(row)

    result = table_from_py_list(rows)

    # Cast at the table level rather than per value: an all-null column carries no values
    # to coerce, yet still needs the float64 type or it infers `null` (stored as string).
    for field_name in _EVENT_DOUBLE_FIELDS:
        if field_name not in result.column_names:
            continue
        field_index = result.schema.get_field_index(field_name)
        column_type = result.schema.field(field_index).type
        if pa.types.is_null(column_type) or pa.types.is_integer(column_type):
            result = result.set_column(
                field_index,
                pa.field(field_name, pa.float64()),
                result.column(field_name).cast(pa.float64()),
            )

    return result


@SourceRegistry.register
class RevenueCatSource(
    ResumableSource[RevenueCatSourceConfig, RevenueCatResumeConfig],
    WebhookSource[RevenueCatSourceConfig],
):
    codebase_detection = detect(
        env=("^REVENUE_?CAT_", "^EXPO_PUBLIC_REVENUE_?CAT_"),
        script_hosts=("sdk.revenuecat-static.com",),
        npm=(
            "@revenuecat/purchases-js",
            "react-native-purchases",
            "@revenuecat/purchases-capacitor",
            "react-native-purchases-ui",
            "@revenuecat/purchases-capacitor-ui",
            "@revenuecat/purchases-ui-js",
            "@revenuecat/purchases-js-vega",
            "@revenuecat/workflow-web-components-sdk",
            "@revenuecat/cli",
            "cordova-plugin-purchases",
            "react-native-purchases-store-galaxy",
            "@awesome-cordova-plugins/purchases",
            "@ionic-native/purchases",
        ),
        cocoapods=(
            "RevenueCat",
            "Purchases",
            "RevenueCatUI",
            "PurchasesHybridCommon",
            "PurchasesHybridCommonUI",
            "PurchasesCoreSwift",
        ),
        maven=(
            "com.revenuecat.purchases:purchases",
            "com.revenuecat.purchases:purchases-ui",
            "com.revenuecat.purchases:purchases-store-amazon",
            "com.revenuecat.purchases:purchases-store-galaxy",
            "com.revenuecat.purchases:purchases-debug-view",
            "com.revenuecat.purchases:purchases-debug-view-noop",
            "com.revenuecat.purchases:purchases-admob",
            "com.revenuecat.purchases:purchases-admob-next-gen",
            "com.revenuecat.purchases:purchases-bom",
            "com.revenuecat.purchases:purchases-custom-entitlement-computation",
            "com.revenuecat.purchases:purchases-bc7",
            "com.revenuecat.purchases:purchases-ui-bc7",
            "com.revenuecat.purchases:purchases-store-amazon-bc7",
            "com.revenuecat.purchases:purchases-store-galaxy-bc7",
            "com.revenuecat.purchases:purchases-kmp-core",
            "com.revenuecat.purchases:purchases-kmp-ui",
            "com.revenuecat.purchases:purchases-kmp-either",
            "com.revenuecat.purchases:purchases-kmp-result",
            "com.revenuecat.purchases:purchases-kmp-datetime",
            "com.revenuecat.purchases:purchases-hybrid-common",
            "com.revenuecat.purchases:purchases-hybrid-common-ui",
        ),
        pub=("purchases_flutter", "purchases_ui_flutter"),
        swiftpm=(
            "github.com/revenuecat/purchases-ios",
            "github.com/revenuecat/purchases-ios-spm",
            "github.com/revenuecat/purchases-ios-admob",
            "github.com/revenuecat/purchases-hybrid-common",
        ),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    supported_versions = ("v2",)
    default_version = "v2"
    api_docs_url = "https://www.revenuecat.com/docs/api-v2"

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.REVENUECAT

    @property
    def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
        from products.warehouse_sources.sources.revenuecat.webhook_template import template

        return template

    @property
    def webhook_resource_map(self) -> dict[str, str]:
        return RESOURCE_TO_REVENUECAT_EVENT_TYPE

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.REVENUECAT,
            category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
            label="RevenueCat",
            caption=(
                "Connect your RevenueCat project using a "
                f"[v2 secret API key]({REVENUECAT_API_KEYS_URL}). PostHog uses the key to pull "
                "customers, products, entitlements, offerings, and apps, and to register a webhook "
                "integration for realtime subscription and purchase events."
            ),
            iconPath="/static/services/revenuecat.png",
            docsUrl="https://posthog.com/docs/cdp/sources/revenuecat",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="secret_api_key",
                        label="Secret API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="sk_...",
                        caption=(
                            f"Generate a [v2 secret API key]({REVENUECAT_API_KEYS_URL}) "
                            "with read access to customers, products, entitlements, offerings, "
                            "apps, and integrations (read/write for automatic webhook setup)."
                        ),
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="project_id",
                        label="Project ID",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="proj1a2b3c4d5e",
                        caption=(
                            "The id that starts with `proj`, found in your RevenueCat dashboard URL: "
                            "`app.revenuecat.com/projects/<project_id>`. You can paste either the id "
                            "or the full URL."
                        ),
                        secret=False,
                    ),
                ],
            ),
            releaseStatus=ReleaseStatus.GA,
            webhookSetupCaption=(
                "PostHog tries to register a webhook integration in RevenueCat using your "
                "secret API key. The integration authenticates itself by sending a custom "
                "**Authorization** header on every request, whose value you set below. "
                "PostHog rejects deliveries whose header does not match.\n\n"
                "**Manual setup** (only needed if auto-registration failed):\n\n"
                "1. Go to your **RevenueCat project** > **Integrations** > **+ New** > **Webhook**\n"
                "2. Paste the webhook URL shown below into the **Webhook URL** field\n"
                "3. Set the **Authorization header** to a secret value you generate locally — "
                "paste the same value into the field below so PostHog can verify deliveries\n"
                "4. Select **All events** under **Send events**\n"
                "5. Click **Save**"
            ),
            webhookFields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="authorization_header",
                        label="Authorization header value",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="Bearer my-secret",
                        caption=(
                            "The exact value RevenueCat will send in the Authorization header. "
                            "Must match what's configured in the RevenueCat webhook integration."
                        ),
                        secret=True,
                    ),
                ],
            ),
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.revenuecat.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized": (
                "RevenueCat rejected the API key. Generate a new v2 secret API key and reconnect."
            ),
            "403 Client Error: Forbidden": (
                "The API key doesn't have permission for this endpoint. Check that the key has "
                "read access to the resources you're syncing."
            ),
            "404 Client Error: Not Found": (
                "RevenueCat could not find the project. Double-check the project id and that the API key belongs to it."
            ),
            "Source column type changed": (
                "A column in this table started receiving values that don't fit the type stored from "
                "earlier syncs (for example a price column created from whole-number values now "
                "receiving a decimal price). We can't widen an existing column in place — reset and "
                "fully re-sync this table to adopt the new type."
            ),
        }

    def validate_credentials(
        self,
        config: RevenueCatSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return api_client.validate_credentials(config.secret_api_key, config.project_id)

    def get_schemas(
        self,
        config: RevenueCatSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # `events` is webhook-only — the v2 API doesn't expose a historical
        # backfill endpoint for webhook events, so the only way to populate
        # this table is via realtime webhook deliveries.
        webhook_schemas = [
            SourceSchema(
                name=name,
                supports_incremental=False,
                supports_append=False,
                supports_webhooks=True,
                incremental_fields=[],
            )
            for name in REVENUECAT_WEBHOOK_SCHEMA_NAMES
        ]
        # API endpoints don't expose a server-side `created_at >= X` filter, so
        # "incremental" syncs would still scan every page. Default to full
        # refresh and let the partitioning column (`created_at`) keep delta
        # writes cheap.
        api_schemas = [
            SourceSchema(
                name=name,
                supports_incremental=False,
                supports_append=False,
                supports_webhooks=False,
                incremental_fields=[],
            )
            for name in REVENUECAT_API_SCHEMA_NAMES
        ]
        schemas = [*webhook_schemas, *api_schemas]
        if names is not None:
            names_set = set(names)
            schemas = [s for s in schemas if s.name in names_set]
        return schemas

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RevenueCatResumeConfig]:
        return ResumableSourceManager[RevenueCatResumeConfig](inputs, RevenueCatResumeConfig)

    def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
        return WebhookSourceManager(inputs, inputs.logger)

    def create_webhook(
        self, config: RevenueCatSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> WebhookCreationResult:
        # The user hasn't entered the auth-header value yet on the warehouse
        # side. Skip passing one and the surrounding flow will collect it via
        # `webhookFields`, then bind it to the integration in place.
        return api_client.create_webhook(
            api_key=config.secret_api_key,
            project_id=config.project_id,
            webhook_url=webhook_url,
        )

    def webhook_inputs_updated(
        self,
        config: RevenueCatSourceConfig,
        webhook_url: str,
        team_id: int,
        inputs: dict[str, Any],
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        # Once the user provides the authorization header value, bind it to the
        # integration so RevenueCat starts sending the header on every
        # delivery. `create_webhook` updates the existing integration in place
        # (or creates it fresh if auto-registration failed earlier).
        header_value = inputs.get("authorization_header")
        if not header_value:
            return True, None

        creation = api_client.create_webhook(
            api_key=config.secret_api_key,
            project_id=config.project_id,
            webhook_url=webhook_url,
            authorization_header_value=header_value,
        )
        if not creation.success:
            return False, creation.error or "Failed to bind the new authorization header."
        return True, None

    def get_external_webhook_info(
        self, config: RevenueCatSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> ExternalWebhookInfo | None:
        return api_client.get_external_webhook_info(config.secret_api_key, config.project_id, webhook_url)

    def delete_webhook(
        self, config: RevenueCatSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
    ) -> WebhookDeletionResult:
        return api_client.delete_webhook(config.secret_api_key, config.project_id, webhook_url)

    def source_for_pipeline(
        self,
        config: RevenueCatSourceConfig,
        resumable_source_manager: ResumableSourceManager[RevenueCatResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        if inputs.schema_name == EVENT_RESOURCE_NAME:
            return self._webhook_source_response(inputs)
        return self._api_source_response(config, resumable_source_manager, inputs)

    def _webhook_source_response(self, inputs: SourceInputs) -> SourceResponse:
        webhook_source_manager = self.get_webhook_source_manager(inputs)
        webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=True)

        def items() -> Iterable[Any] | AsyncIterable[Any]:
            if webhook_enabled:
                return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)
            return iter([])

        return SourceResponse(
            items=items,
            primary_keys=["id"],
            name=inputs.schema_name,
            sort_mode="asc",
            partition_count=1,
            partition_size=1,
            partition_mode="datetime",
            partition_format="week",
            # `created_at` is derived in the webhook transformer from
            # `event_timestamp_ms / 1000` so it lands here as Unix seconds —
            # the partition layer treats bare ints as seconds, so this gives
            # us correctly-bucketed weekly partitions.
            partition_keys=["created_at"],
            webhook_only=True,
        )

    def _api_source_response(
        self,
        config: RevenueCatSourceConfig,
        resumable_source_manager: ResumableSourceManager[RevenueCatResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        # Datetime partitioning on the endpoint's timestamp field (`created_at`, or
        # `first_seen_at` for customers) — the transport normalizes RevenueCat's ms-epoch value
        # down to Unix seconds so the partition layer (which treats bare ints as seconds) produces
        # sane bucket dates.
        return api_client.revenuecat_api_source(
            api_key=config.secret_api_key,
            project_id=config.project_id,
            schema_name=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
        )