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 dub import source (#72640)

Tom Owers4a1a4b2d4f1e
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 53dcc19c9996..f378e458b979 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -188,6 +188,7 @@ the row lists both.
| drata | HTTP | requests | ✅ |
| dropbox_sign | HTTP | requests | ✅ |
| drip | HTTP | requests | ✅ |
+| dub | HTTP | requests + `rest_source.RESTClient` | ✅ |
| dynatrace | HTTP | requests | ✅ |
| e2b | HTTP | requests | ✅ |
| e_conomic | HTTP | requests | ✅ |
@@ -726,7 +727,6 @@ doesn't conflict with concurrent PRs.
- drata
- dremio
- dropbox
-- dub
- dubsado
- dwolla
- dynamics365
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/canonical_descriptions.py
new file mode 100644
index 000000000000..93f789ec202f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/canonical_descriptions.py
@@ -0,0 +1,190 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "links": {
+ "description": "A short link in the workspace, with its destination, targeting rules, and lifetime analytics counters.",
+ "docs_url": "https://dub.co/docs/api-reference/links/list",
+ "columns": {
+ "id": "The unique ID of the short link.",
+ "domain": "The domain of the short link (e.g. dub.sh or a custom domain).",
+ "key": "The short link slug after the domain (e.g. 'github' for dub.sh/github).",
+ "url": "The destination URL of the short link.",
+ "shortLink": "The full short link, including https (e.g. https://dub.sh/github).",
+ "externalId": "The identifier of the link in your own database, prefixed with 'ext_' when queried.",
+ "tenantId": "The ID of the tenant that created the link inside your system.",
+ "programId": "The ID of the partner program the link is associated with.",
+ "partnerId": "The ID of the partner the link is associated with.",
+ "archived": "Whether the link is archived.",
+ "expiresAt": "The date and time when the link will expire.",
+ "trackConversion": "Whether conversion tracking is enabled for the link.",
+ "folderId": "The unique ID of the folder the link belongs to.",
+ "tags": "The tags assigned to the link.",
+ "utm_source": "The UTM source of the link.",
+ "utm_medium": "The UTM medium of the link.",
+ "utm_campaign": "The UTM campaign of the link.",
+ "clicks": "The number of clicks on the link.",
+ "leads": "The number of leads generated by the link.",
+ "conversions": "The number of unique customers who converted through the link.",
+ "sales": "The total number of sales (including recurring) generated by the link.",
+ "saleAmount": "The total dollar amount of sales generated by the link, in cents.",
+ "lastClicked": "The date and time when the link was last clicked.",
+ "userId": "The ID of the workspace user who created the link.",
+ "workspaceId": "The ID of the workspace the link belongs to.",
+ "createdAt": "The date and time when the link was created.",
+ "updatedAt": "The date and time when the link was last updated.",
+ },
+ },
+ "click_events": {
+ "description": "A click on one of the workspace's short links, with device, location, and referrer detail. Requires a Dub Business plan or higher.",
+ "docs_url": "https://dub.co/docs/api-reference/events/list",
+ "columns": {
+ "event": "The event type; always 'click' for this table.",
+ "timestamp": "When the click happened.",
+ "click": "The click detail object: click ID, URL, country, city, device, browser, OS, referer, and whether it came from a QR scan.",
+ "click_id": "The unique ID of the click.",
+ "link": "The short link that was clicked, embedded as an object.",
+ },
+ },
+ "lead_events": {
+ "description": "A lead conversion event attributed to a short link click. Requires a Dub Business plan or higher.",
+ "docs_url": "https://dub.co/docs/api-reference/events/list",
+ "columns": {
+ "event": "The event type; always 'lead' for this table.",
+ "timestamp": "When the lead event happened.",
+ "eventId": "The unique ID of the lead event.",
+ "eventName": "The name of the lead event (e.g. 'Sign up').",
+ "click": "The originating click, embedded as an object.",
+ "link": "The short link that drove the lead, embedded as an object.",
+ "customer": "The customer who converted, embedded as an object.",
+ "metadata": "Additional metadata attached to the event when it was tracked.",
+ },
+ },
+ "sale_events": {
+ "description": "A sale conversion event attributed to a short link click, with the sale amount and payment processor. Requires a Dub Business plan or higher.",
+ "docs_url": "https://dub.co/docs/api-reference/events/list",
+ "columns": {
+ "event": "The event type; always 'sale' for this table.",
+ "timestamp": "When the sale event happened.",
+ "eventId": "The unique ID of the sale event.",
+ "eventName": "The name of the sale event (e.g. 'Purchase').",
+ "sale": "The sale detail object: amount in cents, currency, invoice ID, and payment processor.",
+ "click": "The originating click, embedded as an object.",
+ "link": "The short link that drove the sale, embedded as an object.",
+ "customer": "The customer who made the purchase, embedded as an object.",
+ "metadata": "Additional metadata attached to the event when it was tracked.",
+ },
+ },
+ "customers": {
+ "description": "A customer tracked for conversion attribution in the workspace, with lifetime sales totals.",
+ "docs_url": "https://dub.co/docs/api-reference/customers/list",
+ "columns": {
+ "id": "The unique ID of the customer on Dub.",
+ "externalId": "The unique ID of the customer in your own database.",
+ "name": "The name of the customer.",
+ "email": "The email of the customer.",
+ "country": "The country of the customer.",
+ "stripeCustomerId": "The Stripe customer ID, used to attribute recurring sales.",
+ "sales": "The total number of sales made by the customer.",
+ "saleAmount": "The total dollar amount of sales made by the customer, in cents.",
+ "createdAt": "The date the customer was created (signup or trial start).",
+ "firstSaleAt": "The date of the customer's first sale.",
+ "subscriptionCanceledAt": "The date the customer's subscription was canceled.",
+ "programId": "The ID of the partner program the customer is attributed to.",
+ },
+ },
+ "tags": {
+ "description": "A tag used to organize short links in the workspace.",
+ "docs_url": "https://dub.co/docs/api-reference/tags/list",
+ "columns": {
+ "id": "The unique ID of the tag.",
+ "name": "The name of the tag.",
+ "color": "The color of the tag.",
+ },
+ },
+ "domains": {
+ "description": "A custom domain configured for short links in the workspace.",
+ "docs_url": "https://dub.co/docs/api-reference/introduction",
+ "columns": {
+ "id": "The unique identifier of the domain.",
+ "slug": "The domain name (e.g. acme.com).",
+ "verified": "Whether the domain is verified.",
+ "primary": "Whether the domain is the primary domain for the workspace.",
+ "archived": "Whether the domain is archived.",
+ "expiredUrl": "The URL to redirect to when a link under this domain has expired.",
+ "notFoundUrl": "The URL to redirect to when a link under this domain doesn't exist.",
+ "createdAt": "The date the domain was created.",
+ "updatedAt": "The date the domain was last updated.",
+ },
+ },
+ "folders": {
+ "description": "A folder used to group and access-control short links in the workspace.",
+ "docs_url": "https://dub.co/docs/api-reference/folders/list",
+ "columns": {
+ "id": "The unique ID of the folder.",
+ "name": "The name of the folder.",
+ "description": "The description of the folder.",
+ "type": "The type of the folder ('default' or 'mega').",
+ "accessLevel": "The workspace-wide access level of the folder ('write', 'read', or null for no access).",
+ "createdAt": "The date the folder was created.",
+ "updatedAt": "The date the folder was last updated.",
+ },
+ },
+ "partners": {
+ "description": "A partner enrolled in the workspace's partner program, with lifetime performance totals.",
+ "docs_url": "https://dub.co/docs/api-reference/partners/list",
+ "columns": {
+ "id": "The unique ID of the partner on Dub.",
+ "name": "The name of the partner.",
+ "email": "The email of the partner.",
+ "country": "The country of the partner.",
+ "status": "The enrollment status of the partner in the program (e.g. approved, pending, banned).",
+ "programId": "The ID of the partner program.",
+ "groupId": "The ID of the partner group the partner belongs to.",
+ "tenantId": "The ID of the partner in your own system.",
+ "payoutsEnabledAt": "The date payouts were enabled for the partner.",
+ "totalClicks": "The total number of clicks driven by the partner.",
+ "totalLeads": "The total number of leads driven by the partner.",
+ "totalConversions": "The total number of conversions driven by the partner.",
+ "totalSaleAmount": "The total dollar amount of sales driven by the partner, in cents.",
+ "totalCommissions": "The total commissions earned by the partner, in cents.",
+ "createdAt": "The date the partner was enrolled in the program.",
+ },
+ },
+ "commissions": {
+ "description": "A commission earned by a partner for a click, lead, sale, or custom event in the partner program.",
+ "docs_url": "https://dub.co/docs/api-reference/commissions/list",
+ "columns": {
+ "id": "The commission's unique ID on Dub.",
+ "type": "The type of commission (click, lead, sale, referral, or custom).",
+ "amount": "The amount of the underlying sale, in cents.",
+ "earnings": "The partner's earnings for the commission, in cents.",
+ "currency": "The currency of the commission.",
+ "status": "The status of the commission (e.g. pending, processed, paid, refunded, fraud, canceled).",
+ "invoiceId": "The ID of the invoice associated with the commission.",
+ "quantity": "The quantity of the items in the commission.",
+ "partner": "The partner who earned the commission, embedded as an object.",
+ "customer": "The customer whose activity generated the commission, embedded as an object.",
+ "createdAt": "The date the commission was created.",
+ "updatedAt": "The date the commission was last updated.",
+ },
+ },
+ "payouts": {
+ "description": "A payout of accrued commissions to a partner. Requires a Dub Business plan or higher.",
+ "docs_url": "https://dub.co/docs/api-reference/payouts/list",
+ "columns": {
+ "id": "The unique ID of the payout.",
+ "invoiceId": "The ID of the invoice associated with the payout.",
+ "amount": "The amount of the payout, in cents.",
+ "currency": "The currency of the payout.",
+ "status": "The status of the payout (pending, processing, processed, sent, completed, failed, or canceled).",
+ "periodStart": "The start of the period the payout covers.",
+ "periodEnd": "The end of the period the payout covers.",
+ "createdAt": "The date the payout was created.",
+ "initiatedAt": "The date the payout was initiated.",
+ "paidAt": "The date the payout was paid.",
+ "partner": "The partner receiving the payout, embedded as an object.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py
new file mode 100644
index 000000000000..b87480af5e8d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py
@@ -0,0 +1,293 @@
+import dataclasses
+from datetime import date, datetime
+from typing import Any, Optional
+
+import requests
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import (
+ DUB_BASE_URL,
+ DUB_ENDPOINTS,
+ DubEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 30
+
+
+class DubResumeConfig:
+ page: Optional[int] = None
+ starting_after: Optional[str] = None
+
+
+class DubCursorPaginator(BasePaginator):
+ """Paginator for Dub endpoints using `startingAfter` cursor pagination.
+
+ The cursor is the `id` of the last row on the current page; a page shorter than
+ `page_size` signals the end (the API returns a bare array with no next-page marker).
+ """
+
+ def __init__(self, page_size: int) -> None:
+ super().__init__()
+ self._page_size = page_size
+ self._starting_after: Optional[str] = None
+
+ def _inject_cursor(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["startingAfter"] = self._starting_after
+
+ def init_request(self, request: Request) -> None:
+ # Honour a seeded resume cursor on the first request.
+ if self._starting_after is not None:
+ self._inject_cursor(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ rows = data if data is not None else response.json()
+ if not isinstance(rows, list) or len(rows) < self._page_size:
+ self._has_next_page = False
+ return
+
+ last_id = rows[-1].get("id") if isinstance(rows[-1], dict) else None
+ if last_id is None:
+ self._has_next_page = False
+ return
+
+ self._starting_after = str(last_id)
+ self._has_next_page = True
+
+ def update_request(self, request: Request) -> None:
+ self._inject_cursor(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ if self._has_next_page and self._starting_after is not None:
+ return {"starting_after": self._starting_after}
+ return None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ starting_after = state.get("starting_after")
+ if starting_after is not None:
+ self._starting_after = str(starting_after)
+ self._has_next_page = True
+
+
+def _format_timestamp(value: Any) -> str:
+ if isinstance(value, datetime | date):
+ return value.isoformat()
+ return str(value)
+
+
+def _build_paginator(config: DubEndpointConfig) -> BasePaginator:
+ if config.pagination == "cursor":
+ return DubCursorPaginator(page_size=config.page_size)
+ return PageNumberPaginator(base_page=1, page_param="page", total_path=None)
+
+
+def _make_session(api_key: str) -> requests.Session:
+ """Session for all Dub traffic — imports and credential probes alike.
+
+ Response capture is disabled because Dub payloads carry imported customer data (emails,
+ click location/referrer, destination URLs, arbitrary event metadata) that the name-based
+ sample scrubbers can't reliably recognise, so sampling would leak it into the shared sample
+ bucket outside the warehouse table's access controls. The API key is still redacted from
+ logged URLs and metered telemetry."""
+ return make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=(api_key,),
+ capture=False,
+ )
+
+
+def _scrub_link_password(item: dict[str, Any]) -> dict[str, Any]:
+ # Dub returns the plaintext `password` of protected links — at the top level on /links records
+ # and nested under each event's `link` object on /events. It's a credential to the short link's
+ # destination, not analytics data, so drop it before it lands in a warehouse column readable by
+ # anyone with table access.
+ item.pop("password", None)
+ link = item.get("link")
+ if isinstance(link, dict):
+ link.pop("password", None)
+ return item
+
+
+def get_resource(
+ endpoint: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> EndpointResource:
+ config = DUB_ENDPOINTS[endpoint]
+
+ params: dict[str, Any] = {**config.params, config.page_size_param: config.page_size}
+
+ if config.event_type is not None:
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ # `start` takes precedence over `interval` and applies to every page, so
+ # pagination naturally terminates at the watermark. The boundary event is
+ # re-fetched and deduped by the merge on primary key.
+ params["start"] = _format_timestamp(db_incremental_field_last_value)
+ else:
+ # /events defaults to a 24h window — without this a first sync would silently
+ # import only the last day of history.
+ params["interval"] = "all"
+
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "params": params,
+ "paginator": _build_paginator(config),
+ }
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ "data_map": _scrub_link_password,
+ }
+
+
+def dub_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[DubResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = DUB_ENDPOINTS[endpoint]
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": DUB_BASE_URL,
+ "auth": {
+ "type": "bearer",
+ "token": api_key,
+ },
+ "headers": {"Accept": "application/json"},
+ "session": _make_session(api_key),
+ },
+ "resources": [get_resource(endpoint, should_use_incremental_field, db_incremental_field_last_value)],
+ }
+
+ # For incremental event syncs the watermark itself is the resume cursor: the pipeline
+ # checkpoints `timestamp` after each batch (sort_mode="asc"), and a restart re-derives
+ # `start` from it. Reusing a saved page number against that fresher `start` would skip
+ # rows, so paginator resume state is only used for non-incremental runs.
+ use_paginator_resume = not (endpoint_config.event_type is not None and should_use_incremental_field)
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if use_paginator_resume and resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ if resume_config.page is not None:
+ initial_paginator_state = {"page": resume_config.page}
+ elif resume_config.starting_after is not None:
+ initial_paginator_state = {"starting_after": resume_config.starting_after}
+
+ 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 not state:
+ return
+ if state.get("page") is not None:
+ resumable_source_manager.save_state(DubResumeConfig(page=int(state["page"])))
+ elif state.get("starting_after") is not None:
+ resumable_source_manager.save_state(DubResumeConfig(starting_after=str(state["starting_after"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint if use_paginator_resume else None,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=[endpoint_config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format=endpoint_config.partition_format if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ sort_mode=endpoint_config.sort_mode,
+ )
+
+
+def _probe_params(config: DubEndpointConfig) -> dict[str, Any]:
+ params: dict[str, Any] = {**config.params, config.page_size_param: 1}
+ if config.event_type is not None:
+ # Keep the probe cheap — a 24h window is enough to establish plan access.
+ params["interval"] = "24h"
+ return params
+
+
+def _error_message(res: Response) -> str:
+ try:
+ return str(res.json()["error"]["message"])
+ except Exception:
+ return f"HTTP {res.status_code}"
+
+
+def check_endpoint_access(api_key: str, endpoint: str) -> str | None:
+ """Probe one endpoint; return None when reachable, or a short reason when access is denied.
+
+ Only a real denial (401/403) counts as unreachable — throttles, 5xx, and network blips
+ are treated as reachable so a transient error never hides a table from the schema picker.
+ """
+ config = DUB_ENDPOINTS[endpoint]
+ try:
+ session = _make_session(api_key)
+ res = session.get(
+ f"{DUB_BASE_URL}{config.path}",
+ params=_probe_params(config),
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if res.status_code in (401, 403):
+ return _error_message(res)
+ return None
+ except Exception:
+ return None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ """Cheap token probe against /links, which every Dub workspace key can read."""
+ try:
+ session = _make_session(api_key)
+ res = session.get(
+ f"{DUB_BASE_URL}/links",
+ params={"pageSize": 1},
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if res.status_code == 200:
+ return True, None
+ if res.status_code == 401:
+ return False, "Invalid Dub API key. Please check your key and try again."
+ return False, _error_message(res)
+ except Exception as e:
+ return False, str(e)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py
new file mode 100644
index 000000000000..5d0d8883d8d0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py
@@ -0,0 +1,93 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ PartitionFormat,
+ SortMode,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+DUB_BASE_URL = "https://api.dub.co"
+
+
+@dataclass
+class DubEndpointConfig:
+ name: str
+ path: str
+ # "cursor" = startingAfter cursor pagination; "page" = 1-based page-number pagination.
+ pagination: Literal["cursor", "page"]
+ page_size: int = 100
+ page_size_param: str = "pageSize"
+ primary_key: str = "id"
+ partition_key: Optional[str] = "createdAt"
+ partition_format: PartitionFormat = "month"
+ sort_mode: SortMode = "desc"
+ params: dict[str, str] = field(default_factory=dict)
+ # Set for the /events streams; selects which event type the shared endpoint returns.
+ event_type: Optional[str] = None
+
+
+def _event_endpoint(name: str, event_type: str, primary_key: str) -> DubEndpointConfig:
+ return DubEndpointConfig(
+ name=name,
+ path="/events",
+ pagination="page",
+ # /events allows up to 1000 rows per page; larger pages keep us well inside
+ # Dub's stricter per-second analytics rate limits.
+ page_size=500,
+ page_size_param="limit",
+ primary_key=primary_key,
+ partition_key="timestamp",
+ partition_format="week",
+ sort_mode="asc",
+ params={"event": event_type, "sortBy": "timestamp", "sortOrder": "asc"},
+ event_type=event_type,
+ )
+
+
+DUB_ENDPOINTS: dict[str, DubEndpointConfig] = {
+ "links": DubEndpointConfig(name="links", path="/links", pagination="cursor"),
+ "click_events": _event_endpoint("click_events", "clicks", primary_key="click_id"),
+ "lead_events": _event_endpoint("lead_events", "leads", primary_key="eventId"),
+ "sale_events": _event_endpoint("sale_events", "sales", primary_key="eventId"),
+ "customers": DubEndpointConfig(name="customers", path="/customers", pagination="cursor"),
+ "tags": DubEndpointConfig(
+ name="tags",
+ path="/tags",
+ pagination="page",
+ partition_key=None,
+ # Explicit stable sort so rows don't shift across page boundaries mid-sync.
+ params={"sortBy": "createdAt", "sortOrder": "asc"},
+ sort_mode="asc",
+ ),
+ "domains": DubEndpointConfig(name="domains", path="/domains", pagination="page", page_size=50),
+ "folders": DubEndpointConfig(name="folders", path="/folders", pagination="page", page_size=50),
+ "partners": DubEndpointConfig(
+ name="partners",
+ path="/partners",
+ pagination="page",
+ params={"sortBy": "createdAt", "sortOrder": "asc"},
+ sort_mode="asc",
+ ),
+ "commissions": DubEndpointConfig(name="commissions", path="/commissions", pagination="cursor"),
+ "payouts": DubEndpointConfig(name="payouts", path="/payouts", pagination="page"),
+}
+
+ENDPOINTS = tuple(DUB_ENDPOINTS.keys())
+
+# Only the /events streams expose a genuine server-side timestamp filter (start/end) with a
+# stable ascending sort, so they're the only incremental candidates. Commissions document a
+# start/end filter too, but it keys on createdAt while commission status keeps mutating after
+# creation (pending -> processed -> paid), so an incremental sync would freeze stale statuses —
+# those stay full refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "click_events": [incremental_field("timestamp")],
+ "lead_events": [incremental_field("timestamp")],
+ "sale_events": [incremental_field("timestamp")],
+}
+
+# Endpoints gated by Dub plan or product setup: /events needs a Business plan or higher,
+# /payouts needs a Business partner-program plan, and /partners + /commissions require a
+# partner program. Used by get_endpoint_permissions to surface per-table reachability.
+PLAN_GATED_ENDPOINTS = ("click_events", "lead_events", "sale_events", "partners", "commissions", "payouts")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/source.py
index dcd925cb0f4b..d5cee9bb6c86 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/source.py
@@ -1,30 +1,149 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub import (
+ DubResumeConfig,
+ check_endpoint_access,
+ dub_source,
+ validate_credentials as validate_dub_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PLAN_GATED_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dub import DubSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DubSource(SimpleSource[DubSourceConfig]):
+class DubSource(ResumableSource[DubSourceConfig, DubResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://dub.co/docs/api-reference/introduction"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DUB
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Your Dub API key is invalid or has been revoked. Please create a new key in your Dub workspace settings and reconnect.",
+ "403 Client Error: Forbidden for url": "Your Dub API key doesn't have access to this resource. Events and payouts require a Dub Business plan or higher, and partner tables require a partner program.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.dub.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: DubSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self, config: DubSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Per-schema check (from the incremental_fields action): confirm the key's plan
+ # actually reaches that endpoint. At source-create, only probe the token itself.
+ if schema_name is not None and schema_name in ENDPOINTS:
+ reason = check_endpoint_access(config.api_key, schema_name)
+ if reason is not None:
+ return False, reason
+ return True, None
+
+ return validate_dub_credentials(config.api_key)
+
+ def get_endpoint_permissions(
+ self, config: DubSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ # Only probe the plan/program-gated endpoints; the rest are reachable with any
+ # workspace key, and /events access is shared by all three event tables.
+ permissions: dict[str, str | None] = dict.fromkeys(endpoints)
+ event_access: str | None | bool = False # False = not probed yet
+ for endpoint in endpoints:
+ if endpoint not in PLAN_GATED_ENDPOINTS:
+ continue
+ if endpoint.endswith("_events"):
+ if event_access is False:
+ event_access = check_endpoint_access(config.api_key, endpoint)
+ permissions[endpoint] = cast(str | None, event_access)
+ else:
+ permissions[endpoint] = check_endpoint_access(config.api_key, endpoint)
+ return permissions
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DubResumeConfig]:
+ return ResumableSourceManager[DubResumeConfig](inputs, DubResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DubSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DubResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return dub_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=SchemaExternalDataSourceType.DUB,
category=DataWarehouseSourceCategory.ADVERTISING,
label="Dub",
+ caption="Create a workspace API key in your Dub workspace under Settings > API Keys. Event tables (clicks, leads, sales) and payouts require a Dub Business plan or higher.",
+ docsUrl="https://posthog.com/docs/cdp/sources/dub",
iconPath="/static/services/dub.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["dub.co", "short links", "attribution", "affiliate"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Workspace API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="dub_xxxxxxxx",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub.py
new file mode 100644
index 000000000000..6715008d23e9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub.py
@@ -0,0 +1,330 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub import (
+ DubCursorPaginator,
+ DubResumeConfig,
+ _make_session,
+ _scrub_link_password,
+ check_endpoint_access,
+ dub_source,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import DUB_ENDPOINTS, ENDPOINTS
+
+
+def _rows(n: int, prefix: str = "row") -> list[dict[str, Any]]:
+ return [{"id": f"{prefix}-{i}", "createdAt": "2026-01-01T00:00:00.000Z"} for i in range(n)]
+
+
+def _params(resource: EndpointResource) -> dict[str, Any]:
+ endpoint = resource["endpoint"]
+ assert isinstance(endpoint, dict)
+ params = endpoint.get("params")
+ assert params is not None
+ return params
+
+
+def _make_http_response(body: 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
+
+
+class TestDubCursorPaginator:
+ def test_full_page_advances_cursor_to_last_row_id(self) -> None:
+ paginator = DubCursorPaginator(page_size=3)
+ paginator.update_state(MagicMock(), data=_rows(3))
+
+ assert paginator.has_next_page is True
+
+ request = Request(method="GET", url="https://api.dub.co/links", params={})
+ paginator.update_request(request)
+ assert request.params["startingAfter"] == "row-2"
+
+ @pytest.mark.parametrize(
+ ("label", "rows"),
+ [
+ ("short_page", _rows(2)),
+ ("empty_page", []),
+ ("non_list_body", cast(list[Any], None)),
+ ],
+ )
+ def test_terminal_pages_stop_pagination(self, label: str, rows: list[Any]) -> None:
+ paginator = DubCursorPaginator(page_size=3)
+ response = MagicMock()
+ response.json.return_value = rows
+ paginator.update_state(response, data=rows if isinstance(rows, list) else None)
+
+ assert paginator.has_next_page is False
+
+ def test_fresh_paginator_does_not_inject_cursor_on_first_request(self) -> None:
+ paginator = DubCursorPaginator(page_size=100)
+ request = Request(method="GET", url="https://api.dub.co/links", params={})
+ paginator.init_request(request)
+
+ assert "startingAfter" not in request.params
+
+ def test_resume_state_round_trip(self) -> None:
+ paginator = DubCursorPaginator(page_size=3)
+ paginator.update_state(MagicMock(), data=_rows(3))
+
+ state = paginator.get_resume_state()
+ assert state == {"starting_after": "row-2"}
+
+ resumed = DubCursorPaginator(page_size=3)
+ resumed.set_resume_state(state or {})
+ request = Request(method="GET", url="https://api.dub.co/links", params={})
+ resumed.init_request(request)
+
+ assert request.params["startingAfter"] == "row-2"
+ assert resumed.has_next_page is True
+
+ def test_no_resume_state_on_terminal_page(self) -> None:
+ paginator = DubCursorPaginator(page_size=3)
+ paginator.update_state(MagicMock(), data=_rows(1))
+
+ assert paginator.get_resume_state() is None
+
+
+class TestGetResource:
+ def test_event_endpoint_defaults_to_full_history(self) -> None:
+ # /events defaults to a 24h window server-side; without interval=all a first
+ # sync would silently import only the last day.
+ resource = get_resource("click_events", False, None)
+ params = _params(resource)
+
+ assert params["interval"] == "all"
+ assert "start" not in params
+ assert params["event"] == "clicks"
+ assert params["sortOrder"] == "asc"
+
+ def test_event_endpoint_uses_watermark_as_start(self) -> None:
+ watermark = datetime(2026, 5, 1, 12, 30, tzinfo=UTC)
+ resource = get_resource("lead_events", True, watermark)
+ params = _params(resource)
+
+ assert params["start"] == watermark.isoformat()
+ assert "interval" not in params
+
+ @pytest.mark.parametrize("endpoint", ENDPOINTS)
+ def test_every_endpoint_builds_a_resource(self, endpoint: str) -> None:
+ resource = get_resource(endpoint, False, None)
+
+ assert resource["name"] == endpoint
+ assert resource["write_disposition"] == "replace"
+ params = _params(resource)
+ config = DUB_ENDPOINTS[endpoint]
+ assert params[config.page_size_param] == config.page_size
+
+ def test_incremental_run_uses_merge_disposition(self) -> None:
+ resource = get_resource("sale_events", True, None)
+
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+
+ @pytest.mark.parametrize("endpoint", ENDPOINTS)
+ def test_every_resource_scrubs_link_passwords(self, endpoint: str) -> None:
+ # Link passwords are a credential to the short link's destination, not analytics data;
+ # without this map they'd land in a warehouse column any viewer could read.
+ assert get_resource(endpoint, False, None)["data_map"] is _scrub_link_password
+
+
+class TestScrubLinkPassword:
+ def test_strips_top_level_and_nested_link_password(self) -> None:
+ row = {
+ "id": "l1",
+ "password": "top-secret",
+ "url": "https://example.com",
+ "link": {"id": "l2", "password": "nested-secret", "domain": "dub.sh"},
+ }
+
+ scrubbed = _scrub_link_password(row)
+
+ assert "password" not in scrubbed
+ assert "password" not in scrubbed["link"]
+ assert scrubbed["url"] == "https://example.com"
+ assert scrubbed["link"]["domain"] == "dub.sh"
+
+ def test_leaves_rows_without_passwords_untouched(self) -> None:
+ row = {"id": "l1", "url": "https://example.com", "link": {"id": "l2"}}
+
+ assert _scrub_link_password(row) == row
+
+
+class TestDubSourceResumeBehavior:
+ def _drive(
+ self,
+ endpoint: str,
+ manager: MagicMock,
+ responses: list[Response],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ) -> list[dict[str, Any]]:
+ """Drive ``dub_source`` with a mocked HTTP session; returns per-request params."""
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source_response = dub_source(
+ api_key="dub_test",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ list(cast(Iterable[Any], source_response.items()))
+ return sent_params
+
+ def test_cursor_endpoint_saves_cursor_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(_rows(100, "a")),
+ _make_http_response(_rows(100, "b")),
+ _make_http_response(_rows(1, "c")),
+ ]
+ sent_params = self._drive("links", manager, responses)
+
+ assert [p.get("startingAfter") for p in sent_params] == [None, "a-99", "b-99"]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ DubResumeConfig(starting_after="a-99"),
+ DubResumeConfig(starting_after="b-99"),
+ ]
+
+ def test_cursor_endpoint_resumes_from_saved_cursor(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = DubResumeConfig(starting_after="a-42")
+
+ sent_params = self._drive("links", manager, [_make_http_response(_rows(1))])
+
+ assert [p.get("startingAfter") for p in sent_params] == ["a-42"]
+
+ def test_page_endpoint_saves_page_number(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(_rows(100, "a")),
+ _make_http_response([]),
+ ]
+ sent_params = self._drive("partners", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [1, 2]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [DubResumeConfig(page=2)]
+
+ def test_incremental_event_sync_ignores_saved_page_state(self) -> None:
+ # On incremental runs the timestamp watermark is the resume cursor; replaying a
+ # saved page number against a fresher `start` filter would skip rows.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = DubResumeConfig(page=7)
+
+ sent_params = self._drive(
+ "click_events",
+ manager,
+ [_make_http_response(_rows(1)), _make_http_response([])],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-05-01T00:00:00",
+ )
+
+ manager.load_state.assert_not_called()
+ manager.save_state.assert_not_called()
+ assert sent_params[0]["page"] == 1
+ assert sent_params[0]["start"] == "2026-05-01T00:00:00"
+
+ def test_full_refresh_event_sync_still_uses_page_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = DubResumeConfig(page=7)
+
+ sent_params = self._drive("click_events", manager, [_make_http_response(_rows(1)), _make_http_response([])])
+
+ assert sent_params[0]["page"] == 7
+
+
+class TestMakeSession:
+ def test_disables_sample_capture(self) -> None:
+ # Every Dub path (sync + both credential probes) builds its session here. Dub payloads
+ # carry imported customer data the name-based scrubbers can't recognise, so capture must
+ # stay off or sampling would leak it into the shared sample bucket.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session"
+ ) as make_session:
+ _make_session("secret-key")
+ assert make_session.call_args.kwargs["capture"] is False
+ assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)
+
+
+class TestCredentialValidation:
+ def _mock_session(self, response: Response) -> Any:
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid"),
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ ],
+ )
+ def test_validate_credentials_status_mapping(self, status_code: int, expected_valid: bool) -> None:
+ response = _make_http_response({"error": {"code": "forbidden", "message": "Nope"}}, status_code)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session",
+ return_value=self._mock_session(response),
+ ):
+ valid, message = validate_credentials("dub_test")
+
+ assert valid is expected_valid
+ assert (message is None) is expected_valid
+
+ def test_check_endpoint_access_surfaces_api_denial_message(self) -> None:
+ response = _make_http_response(
+ {"error": {"code": "forbidden", "message": "Requires a Business plan or higher."}}, 403
+ )
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session",
+ return_value=self._mock_session(response),
+ ):
+ assert check_endpoint_access("dub_test", "click_events") == "Requires a Business plan or higher."
+
+ @pytest.mark.parametrize("status_code", [200, 429, 500])
+ def test_check_endpoint_access_only_denials_block(self, status_code: int) -> None:
+ # A throttle or transient 5xx must never hide a table from the schema picker.
+ response = _make_http_response({"error": {"code": "x", "message": "x"}}, status_code)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session",
+ return_value=self._mock_session(response),
+ ):
+ assert check_endpoint_access("dub_test", "payouts") is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub_source.py
new file mode 100644
index 000000000000..a9cd7d02f6b9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub_source.py
@@ -0,0 +1,160 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub import DubResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.source import DubSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dub import DubSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+EVENT_ENDPOINTS = ("click_events", "lead_events", "sale_events")
+
+
+def _make_inputs(**overrides) -> SourceInputs:
+ defaults: dict = {
+ "schema_name": "links",
+ "schema_id": "schema-id",
+ "source_id": "source-id",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-id",
+ "logger": MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestDubSource:
+ def setup_method(self):
+ self.source = DubSource()
+ self.config = DubSourceConfig(api_key="dub_test_key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.DUB
+
+ def test_source_is_released(self) -> None:
+ # unreleasedSource=True hides the connector from every user; a finished source
+ # must never regain it.
+ assert not self.source.get_source_config.unreleasedSource
+
+ def test_source_config_has_secret_api_key_field(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert [f.name for f in fields] == ["api_key"]
+ assert isinstance(fields[0], SourceFieldInputConfig)
+ assert fields[0].secret is True
+
+ def test_get_schemas_only_event_streams_are_incremental(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1)
+
+ assert [s.name for s in schemas] == list(ENDPOINTS)
+ incremental = {s.name for s in schemas if s.supports_incremental}
+ assert incremental == set(EVENT_ENDPOINTS)
+ for schema in schemas:
+ if schema.name in EVENT_ENDPOINTS:
+ assert [f["field"] for f in schema.incremental_fields] == ["timestamp"]
+
+ def test_get_schemas_names_filter(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1, names=["links", "tags"])
+
+ assert [s.name for s in schemas] == ["links", "tags"]
+
+ @pytest.mark.parametrize(
+ ("valid", "message"),
+ [
+ (True, None),
+ (False, "Invalid Dub API key. Please check your key and try again."),
+ ],
+ )
+ def test_validate_credentials_probes_token(self, valid: bool, message: str | None) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.source.validate_dub_credentials",
+ return_value=(valid, message),
+ ) as mock_validate:
+ assert self.source.validate_credentials(self.config, team_id=1) == (valid, message)
+
+ mock_validate.assert_called_once_with("dub_test_key")
+
+ @pytest.mark.parametrize(
+ ("reason", "expected"),
+ [
+ (None, (True, None)),
+ ("Requires a Business plan or higher.", (False, "Requires a Business plan or higher.")),
+ ],
+ )
+ def test_validate_credentials_with_schema_name_checks_endpoint_access(
+ self, reason: str | None, expected: tuple[bool, str | None]
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.source.check_endpoint_access",
+ return_value=reason,
+ ) as mock_check:
+ assert self.source.validate_credentials(self.config, team_id=1, schema_name="click_events") == expected
+
+ mock_check.assert_called_once_with("dub_test_key", "click_events")
+
+ def test_get_endpoint_permissions_probes_events_once(self) -> None:
+ # All three event tables share /events, so one probe must cover them; ungated
+ # endpoints are reported reachable without any request.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.source.check_endpoint_access",
+ return_value="Business plan required",
+ ) as mock_check:
+ permissions = self.source.get_endpoint_permissions(self.config, team_id=1, endpoints=list(ENDPOINTS))
+
+ probed = [call.args[1] for call in mock_check.call_args_list]
+ assert len([e for e in probed if e in EVENT_ENDPOINTS]) == 1
+ assert set(probed) - set(EVENT_ENDPOINTS) == {"partners", "commissions", "payouts"}
+ for endpoint in EVENT_ENDPOINTS:
+ assert permissions[endpoint] == "Business plan required"
+ assert permissions["links"] is None
+ assert permissions["tags"] is None
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is DubResumeConfig
+
+ def test_source_for_pipeline_plumbs_inputs(self) -> None:
+ inputs = _make_inputs(
+ schema_name="click_events",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-05-01T00:00:00",
+ )
+ manager = MagicMock(spec=ResumableSourceManager)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.source.dub_source"
+ ) as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ api_key="dub_test_key",
+ endpoint="click_events",
+ team_id=1,
+ job_id="job-id",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-05-01T00:00:00",
+ )
+
+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:
+ inputs = _make_inputs(
+ schema_name="links",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="stale-watermark",
+ )
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.source.dub_source"
+ ) as mock_source:
+ self.source.source_for_pipeline(self.config, MagicMock(spec=ResumableSourceManager), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dub.py
index 09c4718ad6c4..a73f7485c3a8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dub.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class DubSourceConfig(config.Config):
- pass
+ api_key: str