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 tenjin import source (#107246)

Tom Owerse811063b118e
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 d8c7105d39bf..a9d059a381d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -698,6 +698,7 @@ the row lists both.
| tempo | HTTP | requests | ✅ |
| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
| tenable_vulnerability_management | HTTP (async export flow) | requests | ✅ |
+| tenjin | HTTP | requests + `rest_source.RESTClient` | ✅ |
| terraform_cloud | HTTP | requests | ✅ |
| testrail | HTTP | requests | ✅ |
| thinkific | HTTP | requests | ✅ |
@@ -1424,7 +1425,6 @@ doesn't conflict with concurrent PRs.
- tebra
- telli
- tempo
-- tenjin
- terabox
- ternary
- terra_api
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tenjin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tenjin.py
index ea69a60d4bc0..0ae6a5830b18 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tenjin.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/tenjin.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class TenjinSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/canonical_descriptions.py
new file mode 100644
index 000000000000..cdc5b73ab9b8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/canonical_descriptions.py
@@ -0,0 +1,97 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://api-docs.tenjin.com/"
+
+_APP_COLUMNS = {
+ "date": "Date of the related data.",
+ "app_id": "The ID of the app in Tenjin.",
+ "platform": "The app's platform (ios, android, windows, or amazon).",
+ "bundle_id": "The Bundle ID of the app in the App Store.",
+ "store_id": "The Store ID of the app in the App Store.",
+}
+
+_SPEND_METRIC_COLUMNS = {
+ "spend": "Ad spend attributed to the row, in the account currency.",
+ "impressions": "Number of ad impressions.",
+ "clicks": "Number of ad clicks.",
+ "installs": "Number of attributed installs.",
+ "cpi": "Cost per install.",
+ "ctr": "Click-through rate.",
+ "cvr": "Click-to-install conversion rate.",
+ "tcpi": "Cost per tracked install.",
+ "tracked_installs": "Number of installs tracked by Tenjin.",
+}
+
+_CHANNEL_COLUMNS = {
+ "ad_network_id": "The ID of the channel in Tenjin.",
+ "ad_network_name": "The name of the channel.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "app_report": {
+ "description": "Daily user-acquisition performance per app from Tenjin's spend report.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_APP_COLUMNS,
+ "name": "The name of the app.",
+ "icon_url": "The icon of the app in the App Store.",
+ **_SPEND_METRIC_COLUMNS,
+ },
+ },
+ "campaign_report": {
+ "description": "Daily user-acquisition performance per campaign from Tenjin's spend report, including the campaign's app and channel.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_APP_COLUMNS,
+ "name": "The name of the campaign in Tenjin.",
+ "campaign_id": "The ID of the campaign in Tenjin.",
+ "app_name": "The name of the app in Tenjin.",
+ "app_icon_url": "The icon of the app in the App Store.",
+ **_CHANNEL_COLUMNS,
+ "icon_url": "The icon of the channel.",
+ "ad_network_icon_url": "The icon of the channel.",
+ **_SPEND_METRIC_COLUMNS,
+ },
+ },
+ "ad_revenue_report": {
+ "description": "Daily ad monetization revenue per app and channel from Tenjin's ad revenue report.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_APP_COLUMNS,
+ "app_name": "The name of the app in Tenjin.",
+ "app_icon_url": "The icon of the app in the App Store.",
+ **_CHANNEL_COLUMNS,
+ "ad_network_icon_url": "The icon of the channel.",
+ "ad_network_short_id": "Friendly URL slug used to identify the channel.",
+ "ad_network_custom": "Whether the channel is custom or natively supported by Tenjin.",
+ "ad_revenue": "Ad revenue attributed to the row, in the account currency.",
+ "impressions": "Number of ad impressions shown in the app.",
+ "clicks": "Number of clicks on ads shown in the app.",
+ "ecpm": "Effective cost per thousand impressions.",
+ "ecpc": "Effective cost per click.",
+ },
+ },
+ "sk_ad_network_report": {
+ "description": "Daily SKAdNetwork postback aggregates per app, channel, SKAN campaign, source app, and conversion value (iOS only).",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ **_APP_COLUMNS,
+ "app_name": "The name of the app in Tenjin.",
+ **_CHANNEL_COLUMNS,
+ "ad_network_short_id": "Friendly URL slug used to identify the channel.",
+ "campaign_id": "The ID of the campaign in Tenjin.",
+ "campaign_name": "The name of the campaign in Tenjin.",
+ "remote_campaign_id": "The campaign's ID on the ad network.",
+ "sk_ad_network_id": "SKAdNetwork ID for the ad network.",
+ "sk_campaign_id": "SKAdNetwork campaign ID, an integer from 0-99.",
+ "sk_source_app_id": "The Store ID of the app that showed the advertisement that led to a conversion.",
+ "fidelity_type": "1 for StoreKit-rendered ads, 0 for view-through ads.",
+ "conversion_value": "SKAdNetwork conversion value, an integer from 0-63.",
+ "conversion_value_count": "Count of occurrences of the conversion value.",
+ "conversion_value_total": "Sum of conversion values.",
+ "conversion_value_avg": "Average of conversion values.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/settings.py
new file mode 100644
index 000000000000..f4bedb877c23
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/settings.py
@@ -0,0 +1,96 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Every report is requested at daily granularity, so `date` is present on every row. It is the
+# only stable cursor the Reporting Metrics API exposes (it filters server-side via the required
+# start_date/end_date params).
+_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+]
+
+# Tenjin's documented default metric set per report endpoint. Pinned here instead of relying on
+# the server default so the table schema stays stable if Tenjin changes its defaults.
+_SPEND_METRICS = "spend,impressions,clicks,installs,cpi,ctr,cvr,tcpi,tracked_installs"
+_AD_REVENUE_METRICS = "ad_revenue,clicks,impressions,ecpm,ecpc"
+_SK_AD_NETWORK_METRICS = "conversion_value_avg,conversion_value_count,conversion_value_total"
+
+
+@frozen
+class TenjinReportConfig:
+ name: str
+ path: str
+ # Sent verbatim as the `group_by` / `metrics` query params. Together they define the report's
+ # column set, so changing either changes the table schema for every connected team.
+ group_by: str
+ metrics: str
+ # Aggregated report rows have no row ids; the date plus the grouping dimensions are the
+ # natural key. Every key column must be a field the chosen group_by returns.
+ primary_keys: list[str]
+ description: str
+
+
+# One entry per report shape we expose. Each Reporting Metrics endpoint is a single report whose
+# response schema is defined by the requested group_by and metrics, so each "table" here is a
+# fixed dimension/metric selection rather than a distinct collection.
+TENJIN_REPORTS: dict[str, TenjinReportConfig] = {
+ "app_report": TenjinReportConfig(
+ name="app_report",
+ path="/reports/spend",
+ group_by="app",
+ metrics=_SPEND_METRICS,
+ primary_keys=["date", "app_id"],
+ description="Daily user-acquisition performance per app: spend, impressions, clicks, installs, and conversion metrics.",
+ ),
+ "campaign_report": TenjinReportConfig(
+ name="campaign_report",
+ path="/reports/spend",
+ group_by="campaign",
+ metrics=_SPEND_METRICS,
+ # Grouping by campaign includes the app and channel in the response, so campaign_id is
+ # the only grouping dimension needed alongside the date.
+ primary_keys=["date", "campaign_id"],
+ description="Daily user-acquisition performance per campaign, including the campaign's app and channel.",
+ ),
+ "ad_revenue_report": TenjinReportConfig(
+ name="ad_revenue_report",
+ path="/reports/ad_revenue",
+ group_by="channel,app",
+ metrics=_AD_REVENUE_METRICS,
+ primary_keys=["date", "app_id", "ad_network_id"],
+ description="Daily ad monetization revenue per app broken down by channel: ad revenue, impressions, clicks, eCPM, and eCPC.",
+ ),
+ "sk_ad_network_report": TenjinReportConfig(
+ name="sk_ad_network_report",
+ path="/reports/sk_ad_network",
+ # Tenjin's documented example grouping for SKAN pulls. The response also carries the
+ # campaign, SKAdNetwork id, and fidelity type for these rows, which is why they are part
+ # of the key below.
+ group_by="app,channel,sk_campaign,sk_source_app,conversion_value",
+ metrics=_SK_AD_NETWORK_METRICS,
+ primary_keys=[
+ "date",
+ "app_id",
+ "ad_network_id",
+ "sk_ad_network_id",
+ "sk_campaign_id",
+ "sk_source_app_id",
+ "fidelity_type",
+ "conversion_value",
+ ],
+ description="Daily SKAdNetwork postback aggregates per app, channel, SKAN campaign, source app, and conversion value (iOS only).",
+ ),
+}
+
+ENDPOINTS = tuple(TENJIN_REPORTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: list(_DATE_INCREMENTAL_FIELDS) for name in TENJIN_REPORTS
+}
+
+DESCRIPTIONS: dict[str, str] = {name: config.description for name, config in TENJIN_REPORTS.items()}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/source.py
index 28e48e432d9a..f06e48a4cf0c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/source.py
@@ -1,28 +1,147 @@
-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
+import requests
+
+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.tenjin import TenjinSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.settings import (
+ DESCRIPTIONS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.tenjin import (
+ TenjinCredentialsError,
+ TenjinResumeConfig,
+ TenjinRetryableError,
+ tenjin_source,
+ validate_credentials as validate_tenjin_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TenjinSource(SimpleSource[TenjinSourceConfig]):
- api_docs_url = "https://tenjin.com/docs/api-access-tokens/"
+class TenjinSource(ResumableSource[TenjinSourceConfig, TenjinResumeConfig]):
+ lists_tables_without_credentials = True # static report catalog — safe for public docs
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://api-docs.tenjin.com/"
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TENJIN
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.tenjin.com": "Tenjin rejected your access token. Generate a new token under Automate > API Access Tokens in the Tenjin dashboard and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.tenjin.com": "Tenjin denied access. Check that your access token is valid and has the Reporting Metrics API permission.",
+ # A 400 means the report request itself is invalid (unknown metric or group_by). The
+ # request shape is fixed per table, so retrying it identically can never succeed.
+ "400 Client Error: Bad Request for url: https://api.tenjin.com": "Tenjin rejected the report request. Check that your account has access to the requested report and metrics.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: TenjinSourceConfig,
+ 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, descriptions=DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: TenjinSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ try:
+ # validate_credentials returns True or raises — it never returns False — so an
+ # unexpected status surfaces its real cause instead of a conflated credential error.
+ validate_tenjin_credentials(config.api_key)
+ return True, None
+ except TenjinCredentialsError as e:
+ return False, str(e)
+ except (TenjinRetryableError, requests.RequestException):
+ # A rate-limit, 5xx, or network blip isn't a bad credential. Don't mislabel it.
+ return (
+ False,
+ "Could not reach Tenjin to validate credentials. This may be a temporary rate-limit or network issue. Please try again.",
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TenjinResumeConfig]:
+ return ResumableSourceManager[TenjinResumeConfig](inputs, TenjinResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TenjinSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TenjinResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return tenjin_source(
+ api_key=config.api_key,
+ 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.TENJIN,
category=DataWarehouseSourceCategory.ADVERTISING,
- keywords=["mobile attribution", "user acquisition"],
label="Tenjin",
+ caption="""Enter your Tenjin API access token to pull daily user-acquisition spend, ad revenue, and SKAdNetwork reports into the PostHog Data warehouse.
+
+Generate a token in the Tenjin dashboard under Automate > API Access Tokens. The token must have the Reporting Metrics API permission.
+
+Tenjin's Reporting Metrics API returns metrics aggregated per day, so these tables are daily time series rather than user-level events.""",
iconPath="/static/services/tenjin.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/tenjin",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["mobile attribution", "user acquisition", "mmp"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tenjin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tenjin.py
new file mode 100644
index 000000000000..4d8e02f846e1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tenjin.py
@@ -0,0 +1,226 @@
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+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 (
+ JSONResponsePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.settings import TENJIN_REPORTS
+
+TENJIN_BASE_URL = "https://api.tenjin.com/v2"
+# First sync backfill depth. Attribution platforms rarely keep report data useful beyond this.
+MAX_HISTORY_DAYS = 730
+# Tenjin keeps restating recent days (late SKAN postbacks, ad network cost corrections), so an
+# incremental run re-reads a trailing window; the merge dedupes on the dimension key.
+LOOKBACK_DAYS = 7
+# The documented maximum, to keep the request count low on long backfills.
+PER_PAGE = 1000
+VALIDATE_TIMEOUT_SECONDS = 30
+
+
+class TenjinRetryableError(Exception):
+ """Transient upstream failure (429 / 5xx) that survived the tracked session's own retries."""
+
+ pass
+
+
+class TenjinCredentialsError(Exception):
+ """A credential check failed for a reason we can explain to the user."""
+
+ pass
+
+
+@frozen
+class TenjinResumeConfig:
+ # Absolute next-page URL from the response's `links.next`. It carries the full original query
+ # (dates, group_by, metrics), so resuming from it continues the exact same report pull.
+ next_url: Optional[str] = None
+
+
+def _today() -> date:
+ return datetime.now(UTC).date()
+
+
+def _to_date(value: Any) -> Optional[date]:
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return (value if value.tzinfo else value.replace(tzinfo=UTC)).astimezone(UTC).date()
+ if isinstance(value, date):
+ return value
+ try:
+ return datetime.fromisoformat(str(value)[:19].replace("Z", "")).date()
+ except ValueError:
+ try:
+ return date.fromisoformat(str(value)[:10])
+ except ValueError:
+ return None
+
+
+def resolve_start_date(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ today: date,
+) -> date:
+ earliest = today - timedelta(days=MAX_HISTORY_DAYS)
+ if should_use_incremental_field:
+ watermark = _to_date(db_incremental_field_last_value)
+ if watermark is not None:
+ return min(max(watermark - timedelta(days=LOOKBACK_DAYS), earliest), today)
+ return earliest
+
+
+def tenjin_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[TenjinResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+) -> SourceResponse:
+ report = TENJIN_REPORTS.get(endpoint)
+ if report is None:
+ raise ValueError(f"Unknown Tenjin report: {endpoint}")
+
+ today = _today()
+ start = resolve_start_date(should_use_incremental_field, db_incremental_field_last_value, today)
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": TENJIN_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": api_key,
+ },
+ "paginator": JSONResponsePaginator(next_url_path="links.next"),
+ # `links.next` is response-controlled; pin every paginated/resumed request to the
+ # Tenjin API host and refuse redirects, so a tampered next link can't carry the
+ # bearer token off-host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ },
+ "resource_defaults": {
+ "write_disposition": {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if should_use_incremental_field
+ else "replace",
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "table_name": endpoint,
+ "endpoint": {
+ # Rows come wrapped JSON:API style ({"type": "report", "attributes": {...}});
+ # the attributes object is the flat row with dimensions and metrics.
+ "data_selector": "data[*].attributes",
+ "path": report.path,
+ "params": {
+ "start_date": start.isoformat(),
+ "end_date": today.isoformat(),
+ # Always daily: rows carry no `date` at totals-daily granularity, which
+ # would break both the primary key and the incremental cursor.
+ "granularity": "daily",
+ "group_by": report.group_by,
+ "metrics": report.metrics,
+ "per_page": PER_PAGE,
+ },
+ },
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ 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 and resume.next_url:
+ initial_paginator_state = {"next_url": resume.next_url}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
+ # completion.
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(TenjinResumeConfig(next_url=str(state["next_url"])))
+
+ resource = rest_api_resource(
+ 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(report.primary_keys),
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=["date"],
+ # Tenjin documents no row order for report responses and offers no sort param, so rows
+ # are not guaranteed to arrive ascending by `date`. desc mode persists the incremental
+ # watermark only at successful job end instead of checkpointing a misleading per-batch
+ # max; the resume checkpoint above covers mid-run interruptions.
+ sort_mode="desc",
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the access token works with a one-day, one-row report probe.
+
+ Returns ``True`` on success. Raises ``TenjinCredentialsError`` with a user-facing message when
+ Tenjin rejects the token, ``TenjinRetryableError`` on rate-limit / 5xx responses, and lets
+ transport errors propagate so a transient failure isn't mislabelled as a bad credential.
+ Never returns ``False``.
+ """
+ today = _today().isoformat()
+ params = {
+ "start_date": today,
+ "end_date": today,
+ "group_by": "app",
+ "metrics": "spend",
+ "per_page": 1,
+ }
+ session = make_tracked_session(
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ redact_values=(api_key,),
+ # The Bearer token rides in every request's default headers, so pin the session off
+ # redirects; an upstream redirect must not carry the credential to another host.
+ allow_redirects=False,
+ )
+ response = session.get(
+ f"{TENJIN_BASE_URL}/reports/spend?{urlencode(params)}",
+ timeout=VALIDATE_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise TenjinRetryableError(f"Tenjin API error (retryable): status={response.status_code}")
+ if response.status_code == 200:
+ return True
+ if response.status_code in (401, 403):
+ # Verified against the live API: a missing or unrecognized token returns 401, a token
+ # Tenjin can't decode (or one lacking the Reporting Metrics permission) returns 403.
+ raise TenjinCredentialsError(
+ "Tenjin rejected the access token. Check that you pasted a valid token from "
+ "Automate > API Access Tokens in the Tenjin dashboard and that it has the "
+ "Reporting Metrics API permission."
+ )
+ raise TenjinCredentialsError(
+ f"Tenjin returned an unexpected response (HTTP {response.status_code}) while validating "
+ "credentials. If your access token looks correct, please try again shortly."
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tests/test_tenjin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tests/test_tenjin.py
new file mode 100644
index 000000000000..96c7185c5921
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tests/test_tenjin.py
@@ -0,0 +1,305 @@
+import json
+from collections.abc import Iterable
+from datetime import date, timedelta
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import validate_incremental_sync
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin import tenjin
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.settings import TENJIN_REPORTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.tenjin import (
+ LOOKBACK_DAYS,
+ MAX_HISTORY_DAYS,
+ TENJIN_BASE_URL,
+ TenjinCredentialsError,
+ TenjinResumeConfig,
+ TenjinRetryableError,
+ resolve_start_date,
+ tenjin_source,
+ validate_credentials,
+)
+
+TODAY = date(2026, 6, 30)
+
+_TRACKED_SESSION_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client"
+ ".make_tracked_session"
+)
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _report_page(rows: list[dict[str, Any]], next_url: str | None = None) -> Response:
+ links: dict[str, str] = {"self": f"{TENJIN_BASE_URL}/reports/spend"}
+ if next_url:
+ links["next"] = next_url
+ return _make_http_response(
+ {
+ "data": [{"type": "report", "attributes": row} for row in rows],
+ "links": links,
+ "meta": {"count": len(rows)},
+ }
+ )
+
+
+def _params(url: str, params: dict[str, Any]) -> dict[str, str]:
+ from_url = {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}
+ return {**from_url, **{key: str(value) for key, value in params.items()}}
+
+
+def _drive(
+ responses: list[Response],
+ endpoint: str = "app_report",
+ manager: Any = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> tuple[Any, list[dict[str, str]], list[list[dict[str, Any]]]]:
+ """Drive ``tenjin_source`` with a mocked HTTP session.
+
+ Returns ``(manager, sent, batches)`` where ``sent`` holds the effective query params of each
+ request (merged from the request URL and params, since the paginator moves them between the
+ two), captured at send-time because the Request object is mutated in place between pages.
+ """
+ if manager is None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ sent: list[dict[str, str]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent.append(_params(request.url, dict(request.params or {})))
+ return next(response_iter)
+
+ with (
+ patch(_TRACKED_SESSION_PATH) as MockSession,
+ mock.patch.object(tenjin, "_today", return_value=TODAY),
+ ):
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ response = tenjin_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ batches = list(cast(Iterable[Any], response.items()))
+ return manager, sent, batches
+
+
+class TestResolveStartDate:
+ def test_full_refresh_starts_at_the_history_cap(self) -> None:
+ assert resolve_start_date(False, None, TODAY) == TODAY - timedelta(days=MAX_HISTORY_DAYS)
+
+ def test_incremental_rewinds_the_watermark_by_the_lookback(self) -> None:
+ # Tenjin restates recent days (late SKAN postbacks, cost corrections), so an incremental
+ # run must re-read a trailing window.
+ assert resolve_start_date(True, "2026-06-20", TODAY) == date(2026, 6, 20) - timedelta(days=LOOKBACK_DAYS)
+
+ def test_incremental_without_watermark_falls_back_to_full_history(self) -> None:
+ assert resolve_start_date(True, None, TODAY) == TODAY - timedelta(days=MAX_HISTORY_DAYS)
+
+ def test_unparseable_watermark_falls_back_to_full_history(self) -> None:
+ assert resolve_start_date(True, "not-a-date", TODAY) == TODAY - timedelta(days=MAX_HISTORY_DAYS)
+
+ def test_watermark_older_than_the_history_cap_is_clamped(self) -> None:
+ assert resolve_start_date(True, "2010-01-01", TODAY) == TODAY - timedelta(days=MAX_HISTORY_DAYS)
+
+ def test_future_watermark_is_clamped_to_today(self) -> None:
+ # A watermark ahead of today would otherwise produce an inverted date range.
+ assert resolve_start_date(True, "2030-01-01", TODAY) == TODAY
+
+
+class TestRequestShaping:
+ def test_full_refresh_requests_full_history(self) -> None:
+ _, sent, _ = _drive([_report_page([{"date": "2026-06-30", "app_id": "a1"}])])
+
+ assert sent[0]["start_date"] == (TODAY - timedelta(days=MAX_HISTORY_DAYS)).isoformat()
+ assert sent[0]["end_date"] == TODAY.isoformat()
+
+ def test_incremental_requests_only_the_watermark_range(self) -> None:
+ _, sent, _ = _drive(
+ [_report_page([{"date": "2026-06-28", "app_id": "a1"}])],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-06-28",
+ )
+
+ assert sent[0]["start_date"] == "2026-06-21"
+ assert sent[0]["end_date"] == "2026-06-30"
+
+ @parameterized.expand([(name,) for name in TENJIN_REPORTS])
+ def test_every_report_is_requested_at_daily_granularity(self, endpoint: str) -> None:
+ # Rows carry no `date` at totals-daily granularity, which would break the primary key,
+ # the partition key, and the incremental cursor at once.
+ _, sent, _ = _drive([_report_page([{"date": "2026-06-30"}])], endpoint=endpoint)
+
+ assert sent[0]["granularity"] == "daily"
+ assert sent[0]["group_by"] == TENJIN_REPORTS[endpoint].group_by
+ assert sent[0]["metrics"] == TENJIN_REPORTS[endpoint].metrics
+
+
+class TestPaginationAndResume:
+ def test_rows_are_flattened_report_attributes(self) -> None:
+ # The pipeline must receive the flat attributes dict, not the JSON:API wrapper, so the
+ # primary key columns (`date`, `app_id`, ...) exist at the row root for the Delta merge.
+ row = {"date": "2026-06-30", "app_id": "a1", "spend": 12.5}
+ _, _, batches = _drive([_report_page([row])])
+
+ assert batches == [[row]]
+
+ def test_follows_next_link_then_terminates(self) -> None:
+ next_url = f"{TENJIN_BASE_URL}/reports/spend?group_by=app&page=2&per_page=1000"
+ _, sent, batches = _drive(
+ [
+ _report_page([{"date": "2026-06-29", "app_id": "a1"}], next_url=next_url),
+ _report_page([{"date": "2026-06-30", "app_id": "a1"}]),
+ ]
+ )
+
+ assert len(batches) == 2
+ assert len(sent) == 2
+ assert sent[1]["page"] == "2"
+
+ def test_saves_next_url_after_each_non_terminal_page(self) -> None:
+ next_url = f"{TENJIN_BASE_URL}/reports/spend?group_by=app&page=2&per_page=1000"
+ manager, _, _ = _drive(
+ [
+ _report_page([{"date": "2026-06-29", "app_id": "a1"}], next_url=next_url),
+ _report_page([{"date": "2026-06-30", "app_id": "a1"}]),
+ ]
+ )
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [TenjinResumeConfig(next_url=next_url)]
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager, _, _ = _drive([_report_page([{"date": "2026-06-30", "app_id": "a1"}])])
+
+ manager.save_state.assert_not_called()
+
+ def test_resume_starts_at_the_saved_next_url(self) -> None:
+ saved_url = f"{TENJIN_BASE_URL}/reports/spend?group_by=app&page=7&per_page=1000"
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = TenjinResumeConfig(next_url=saved_url)
+
+ _, sent, _ = _drive([_report_page([{"date": "2026-06-30", "app_id": "a1"}])], manager=manager)
+
+ assert len(sent) == 1
+ assert sent[0]["page"] == "7"
+
+
+class TestTenjinSourceResponse:
+ def test_unknown_report_raises(self) -> None:
+ with pytest.raises(ValueError):
+ tenjin_source(
+ api_key="test-key",
+ endpoint="nope",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),
+ db_incremental_field_last_value=None,
+ )
+
+ @parameterized.expand([(name,) for name in TENJIN_REPORTS])
+ def test_source_response_supports_incremental_sync(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ with mock.patch.object(tenjin, "_today", return_value=TODAY):
+ response = tenjin_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=None,
+ )
+
+ # Tenjin documents no row order for report responses, so the watermark must only be
+ # persisted at successful job end; asc mode would checkpoint a misleading per-batch max.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["date"]
+ assert not response.has_duplicate_primary_keys
+ validate_incremental_sync(True, response)
+
+
+class TestValidateCredentials:
+ def _validate(self, response: Response) -> bool:
+ session = MagicMock()
+ session.get.return_value = response
+ with (
+ mock.patch.object(tenjin, "make_tracked_session", return_value=session),
+ mock.patch.object(tenjin, "_today", return_value=TODAY),
+ ):
+ return validate_credentials("token")
+
+ def test_success(self) -> None:
+ assert self._validate(_make_http_response({"data": []})) is True
+
+ def test_probe_is_one_day_and_one_row(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _make_http_response({"data": []})
+ with (
+ mock.patch.object(tenjin, "make_tracked_session", return_value=session),
+ mock.patch.object(tenjin, "_today", return_value=TODAY),
+ ):
+ validate_credentials("token")
+
+ params = {key: values[0] for key, values in parse_qs(urlparse(session.get.call_args.args[0]).query).items()}
+ assert params["start_date"] == params["end_date"] == TODAY.isoformat()
+ assert params["per_page"] == "1"
+
+ @parameterized.expand([(429,), (500,), (503,)])
+ def test_throttle_and_5xx_are_retryable(self, status: int) -> None:
+ with pytest.raises(TenjinRetryableError):
+ self._validate(_make_http_response({}, status_code=status))
+
+ @parameterized.expand(
+ [
+ # Verified against the live API: a missing/unrecognized token returns 401 with
+ # {"error":"Unauthorized. Invalid access token provided."}; a token Tenjin can't
+ # decode returns 403 with {"error":"AuthHandler::DecodeError"}.
+ (401, {"error": "Unauthorized. Invalid access token provided."}),
+ (403, {"error": "AuthHandler::DecodeError"}),
+ ]
+ )
+ def test_rejections_are_credential_errors_naming_the_required_permission(
+ self, status: int, body: dict[str, Any]
+ ) -> None:
+ with pytest.raises(TenjinCredentialsError) as exc:
+ self._validate(_make_http_response(body, status_code=status))
+ assert "Reporting Metrics API permission" in str(exc.value)
+
+ def test_unexpected_status_does_not_blame_the_token(self) -> None:
+ with pytest.raises(TenjinCredentialsError) as exc:
+ self._validate(_make_http_response({}, status_code=418))
+ assert "unexpected response (HTTP 418)" in str(exc.value)
+
+ def test_transport_errors_propagate(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with mock.patch.object(tenjin, "make_tracked_session", return_value=session):
+ with pytest.raises(requests.ConnectionError):
+ validate_credentials("token")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tests/test_tenjin_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tests/test_tenjin_source.py
new file mode 100644
index 000000000000..3eaf9a216209
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tenjin/tests/test_tenjin_source.py
@@ -0,0 +1,109 @@
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tenjin import TenjinSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.settings import TENJIN_REPORTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.source import TenjinSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.tenjin import (
+ TenjinCredentialsError,
+ TenjinRetryableError,
+)
+
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.tenjin.source"
+
+
+class TestTenjinSource:
+ def setup_method(self) -> None:
+ self.source = TenjinSource()
+ self.team_id = 123
+ self.config = TenjinSourceConfig(api_key="tenjin-token")
+
+ def test_source_is_released(self) -> None:
+ # A truthy unreleasedSource hides the connector from users entirely.
+ assert not self.source.get_source_config.unreleasedSource
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas iterates a static report catalog with no I/O — safe for public docs.
+ assert self.source.lists_tables_without_credentials is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.tenjin.com/v2/reports/spend?start_date=2026-06-01",
+ "403 Client Error: Forbidden for url: https://api.tenjin.com/v2/reports/spend",
+ "400 Client Error: Bad Request for url: https://api.tenjin.com/v2/reports/ad_revenue",
+ ],
+ )
+ def test_permanent_failures_are_non_retryable(self, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.tenjin.com/v2/reports/spend",
+ "Tenjin API error (retryable): status=503",
+ ],
+ )
+ def test_throttles_and_5xx_stay_retryable(self, observed_error: str) -> None:
+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ def test_every_report_is_incremental_on_date(self) -> None:
+ # start_date/end_date is a real server-side filter, so every report can sync
+ # incrementally on date.
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert len(schemas) == len(TENJIN_REPORTS)
+ for schema in schemas:
+ assert schema.supports_incremental is True
+ assert [field["field"] for field in schema.incremental_fields] == ["date"]
+
+ @mock.patch(f"{_SOURCE_MODULE}.validate_tenjin_credentials")
+ def test_validate_credentials_success(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = True
+
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+ mock_validate.assert_called_once_with("tenjin-token")
+
+ @mock.patch(f"{_SOURCE_MODULE}.validate_tenjin_credentials")
+ def test_validate_credentials_surfaces_the_specific_rejection(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.side_effect = TenjinCredentialsError("Tenjin rejected the access token.")
+
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert message == "Tenjin rejected the access token."
+
+ @pytest.mark.parametrize(
+ "raised",
+ [TenjinRetryableError("status=503"), requests.ConnectionError("boom"), requests.ReadTimeout("slow")],
+ )
+ @mock.patch(f"{_SOURCE_MODULE}.validate_tenjin_credentials")
+ def test_transient_failures_are_not_reported_as_bad_credentials(
+ self, mock_validate: mock.MagicMock, raised: Exception
+ ) -> None:
+ mock_validate.side_effect = raised
+
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert message is not None
+ assert "temporary rate-limit or network issue" in message
+
+ @mock.patch(f"{_SOURCE_MODULE}.tenjin_source")
+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "app_report"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-06-01"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ # A full refresh must not inherit a stale watermark and silently skip history.
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ @pytest.mark.parametrize("report", sorted(TENJIN_REPORTS))
+ def test_canonical_descriptions_document_the_primary_key_columns(self, report: str) -> None:
+ # The key columns are what a user joins on, so they must not fall through to LLM guessing.
+ columns = self.source.get_canonical_descriptions()[report]["columns"]
+ assert set(TENJIN_REPORTS[report].primary_keys) <= set(columns)