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.

fix(warehouse): import Dub links filed into folders (#94022)

Adlet1b876cf8b364
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 07ef330cb85f..ae59d5834cd7 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -530,8 +530,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/drip/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/dropbox_sign.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/dropbox_sign/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/dynamodb.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/dynamodb/tests/test_dynamodb.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/dynatrace.py
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
index f0cda7ceada8..4264ea8d3366 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py
@@ -1,10 +1,11 @@
-import dataclasses
from datetime import date, datetime
from typing import Any, Optional
import requests
from requests import Request, Response
+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,
@@ -27,12 +28,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settin
)
REQUEST_TIMEOUT_SECONDS = 30
+# /folders rejects a larger page with a 422.
+FOLDERS_PAGE_SIZE = 50
+@frozen
class DubResumeConfig:
page: Optional[int] = None
starting_after: Optional[str] = None
+ # Which /links scope the cursor belongs to; see DubLinksScopePaginator.
+ scope_index: Optional[int] = None
class DubCursorPaginator(BasePaginator):
@@ -86,13 +91,119 @@ class DubCursorPaginator(BasePaginator):
self._has_next_page = True
+class DubLinksScopePaginator(BasePaginator):
+ """Cursor paginator that walks the unfiled links, then each folder in turn.
+
+ `GET /links` returns only the links that sit outside a folder unless `folderId` is passed,
+ so paging it once imports a workspace's filed links as nothing at all. Each scope carries
+ its own `startingAfter` cursor: a page shorter than `page_size` ends that scope, and the
+ walk finishes once the last folder is exhausted.
+ """
+
+ def __init__(self, page_size: int, folder_ids: list[str]) -> None:
+ super().__init__()
+ self._page_size = page_size
+ # `None` is the unfiled scope — what a request carrying no `folderId` returns.
+ self._scopes: list[Optional[str]] = [None, *folder_ids]
+ self._scope_index = 0
+ self._starting_after: Optional[str] = None
+
+ def _current_folder_id(self) -> Optional[str]:
+ if self._scope_index >= len(self._scopes):
+ return None
+ return self._scopes[self._scope_index]
+
+ def _inject(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+
+ if self._starting_after is None:
+ # A new scope restarts at its first page, so drop the previous scope's cursor.
+ request.params.pop("startingAfter", None)
+ else:
+ request.params["startingAfter"] = self._starting_after
+
+ folder_id = self._current_folder_id()
+ if folder_id is None:
+ request.params.pop("folderId", None)
+ else:
+ request.params["folderId"] = folder_id
+
+ def init_request(self, request: Request) -> None:
+ self._inject(request)
+
+ def update_request(self, request: Request) -> None:
+ self._inject(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ rows = data if data is not None else response.json()
+ is_full_page = isinstance(rows, list) and len(rows) >= self._page_size
+ last_id = rows[-1].get("id") if is_full_page and isinstance(rows[-1], dict) else None
+
+ if last_id is not None:
+ self._starting_after = str(last_id)
+ self._has_next_page = True
+ return
+
+ self._scope_index += 1
+ self._starting_after = None
+ self._has_next_page = self._scope_index < len(self._scopes)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ if not self._has_next_page:
+ return None
+ return {"scope_index": self._scope_index, "starting_after": self._starting_after}
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ scope_index = state.get("scope_index")
+ starting_after = state.get("starting_after")
+ if scope_index is None and starting_after is None:
+ return
+ if scope_index is not None:
+ # A folder can disappear between runs, which would leave the saved index past the end.
+ self._scope_index = min(int(scope_index), len(self._scopes) - 1)
+ self._starting_after = None if starting_after is None else str(starting_after)
+ self._has_next_page = True
+
+
+def _fetch_folder_ids(api_key: str) -> list[str]:
+ """Every folder in the workspace, so /links can be walked once per folder."""
+ session = _make_session(api_key)
+ folder_ids: list[str] = []
+ page = 1
+
+ while True:
+ res = session.get(
+ f"{DUB_BASE_URL}/folders",
+ params={"page": page, "pageSize": FOLDERS_PAGE_SIZE},
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if res.status_code in (401, 403, 404):
+ # Folders are plan-gated. A workspace without them keeps every link unfiled, so
+ # there is nothing for the extra passes to find.
+ return folder_ids
+ res.raise_for_status()
+
+ rows = res.json()
+ if not isinstance(rows, list) or not rows:
+ return folder_ids
+
+ folder_ids.extend(str(row["id"]) for row in rows if isinstance(row, dict) and row.get("id"))
+ if len(rows) < FOLDERS_PAGE_SIZE:
+ return folder_ids
+ page += 1
+
+
def _format_timestamp(value: Any) -> str:
if isinstance(value, datetime | date):
return value.isoformat()
return str(value)
-def _build_paginator(config: DubEndpointConfig) -> BasePaginator:
+def _build_paginator(config: DubEndpointConfig, folder_ids: list[str]) -> BasePaginator:
+ if config.folder_scoped:
+ return DubLinksScopePaginator(page_size=config.page_size, folder_ids=folder_ids)
if config.pagination == "cursor":
return DubCursorPaginator(page_size=config.page_size)
return PageNumberPaginator(base_page=1, page_param="page", total_path=None)
@@ -129,6 +240,7 @@ def get_resource(
endpoint: str,
should_use_incremental_field: bool,
db_incremental_field_last_value: Optional[Any],
+ folder_ids: Optional[list[str]] = None,
) -> EndpointResource:
config = DUB_ENDPOINTS[endpoint]
@@ -148,7 +260,7 @@ def get_resource(
endpoint_config: Endpoint = {
"path": config.path,
"params": params,
- "paginator": _build_paginator(config),
+ "paginator": _build_paginator(config, folder_ids or []),
}
return {
@@ -176,6 +288,7 @@ def dub_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
endpoint_config = DUB_ENDPOINTS[endpoint]
+ folder_ids = _fetch_folder_ids(api_key) if endpoint_config.folder_scoped else []
config: RESTAPIConfig = {
"client": {
@@ -187,7 +300,9 @@ def dub_source(
"headers": {"Accept": "application/json"},
"session": _make_session(api_key),
},
- "resources": [get_resource(endpoint, should_use_incremental_field, db_incremental_field_last_value)],
+ "resources": [
+ get_resource(endpoint, should_use_incremental_field, db_incremental_field_last_value, folder_ids)
+ ],
}
# For incremental event syncs the watermark itself is the resume cursor: the pipeline
@@ -202,6 +317,11 @@ def dub_source(
if resume_config is not None:
if resume_config.page is not None:
initial_paginator_state = {"page": resume_config.page}
+ elif resume_config.scope_index is not None:
+ initial_paginator_state = {
+ "scope_index": resume_config.scope_index,
+ "starting_after": resume_config.starting_after,
+ }
elif resume_config.starting_after is not None:
initial_paginator_state = {"starting_after": resume_config.starting_after}
@@ -212,6 +332,14 @@ def dub_source(
return
if state.get("page") is not None:
resumable_source_manager.save_state(DubResumeConfig(page=int(state["page"])))
+ elif state.get("scope_index") is not None:
+ starting_after = state.get("starting_after")
+ resumable_source_manager.save_state(
+ DubResumeConfig(
+ scope_index=int(state["scope_index"]),
+ starting_after=None if starting_after is None else str(starting_after),
+ )
+ )
elif state.get("starting_after") is not None:
resumable_source_manager.save_state(DubResumeConfig(starting_after=str(state["starting_after"])))
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
index 880d55b32cbc..ab56dff6a7fa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionFormat, SortMode
from products.warehouse_sources.backend.types import IncrementalField
@@ -8,7 +10,7 @@ from products.warehouse_sources.backend.types import IncrementalField
DUB_BASE_URL = "https://api.dub.co"
-@dataclass
+@frozen
class DubEndpointConfig:
name: str
path: str
@@ -23,6 +25,9 @@ class DubEndpointConfig:
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
+ # /links returns only the links sitting outside a folder unless `folderId` is passed, so
+ # this endpoint has to be walked once per folder as well to import the whole workspace.
+ folder_scoped: bool = False
def _event_endpoint(name: str, event_type: str, primary_key: str) -> DubEndpointConfig:
@@ -44,7 +49,7 @@ def _event_endpoint(name: str, event_type: str, primary_key: str) -> DubEndpoint
DUB_ENDPOINTS: dict[str, DubEndpointConfig] = {
- "links": DubEndpointConfig(name="links", path="/links", pagination="cursor"),
+ "links": DubEndpointConfig(name="links", path="/links", pagination="cursor", folder_scoped=True),
"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"),
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
index 595269739d43..dcac5c223813 100644
--- 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
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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,
+ DubLinksScopePaginator,
DubResumeConfig,
_make_session,
_scrub_link_password,
@@ -99,6 +100,77 @@ class TestDubCursorPaginator:
assert paginator.get_resume_state() is None
+class TestDubLinksScopePaginator:
+ def test_first_scope_sends_no_folder_id(self) -> None:
+ paginator = DubLinksScopePaginator(page_size=3, folder_ids=["fold_a"])
+ request = Request(method="GET", url="https://api.dub.co/links", params={})
+ paginator.init_request(request)
+
+ assert "folderId" not in request.params
+ assert "startingAfter" not in request.params
+
+ def test_full_page_advances_cursor_inside_the_scope(self) -> None:
+ paginator = DubLinksScopePaginator(page_size=3, folder_ids=["fold_a"])
+ 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"
+ assert "folderId" not in request.params
+
+ def test_exhausted_scope_moves_to_the_next_folder(self) -> None:
+ # /links hides folder contents unless folderId is sent, so a walk that stops after the
+ # unfiled scope imports none of a workspace's filed links.
+ paginator = DubLinksScopePaginator(page_size=3, folder_ids=["fold_a"])
+ paginator.update_state(MagicMock(), data=_rows(1))
+
+ assert paginator.has_next_page is True
+
+ request = Request(method="GET", url="https://api.dub.co/links", params={"startingAfter": "row-0"})
+ paginator.update_request(request)
+ assert request.params["folderId"] == "fold_a"
+ # The previous scope's cursor must not leak into the new one.
+ assert "startingAfter" not in request.params
+
+ def test_walk_ends_once_the_last_folder_is_exhausted(self) -> None:
+ paginator = DubLinksScopePaginator(page_size=3, folder_ids=["fold_a"])
+ paginator.update_state(MagicMock(), data=_rows(1))
+ paginator.update_state(MagicMock(), data=_rows(1))
+
+ assert paginator.has_next_page is False
+ assert paginator.get_resume_state() is None
+
+ def test_resume_state_round_trip_keeps_the_scope(self) -> None:
+ paginator = DubLinksScopePaginator(page_size=3, folder_ids=["fold_a", "fold_b"])
+ paginator.update_state(MagicMock(), data=_rows(1))
+ paginator.update_state(MagicMock(), data=_rows(3))
+
+ state = paginator.get_resume_state()
+ assert state == {"scope_index": 1, "starting_after": "row-2"}
+
+ resumed = DubLinksScopePaginator(page_size=3, folder_ids=["fold_a", "fold_b"])
+ resumed.set_resume_state(state or {})
+ request = Request(method="GET", url="https://api.dub.co/links", params={})
+ resumed.init_request(request)
+
+ assert request.params["folderId"] == "fold_a"
+ assert request.params["startingAfter"] == "row-2"
+
+ def test_resume_state_saved_before_folder_scoping_still_seeds_the_cursor(self) -> None:
+ # A sync interrupted across the deploy that added folder scoping resumes from a state
+ # with no scope_index; dropping it would silently restart the walk from the first page.
+ paginator = DubLinksScopePaginator(page_size=3, folder_ids=["fold_a"])
+ paginator.set_resume_state({"starting_after": "row-7"})
+
+ request = Request(method="GET", url="https://api.dub.co/links", params={})
+ paginator.init_request(request)
+
+ assert request.params["startingAfter"] == "row-7"
+ assert "folderId" not in request.params
+
+
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
@@ -209,7 +281,7 @@ class TestDubSourceResumeBehavior:
_make_http_response(_rows(100, "b")),
_make_http_response(_rows(1, "c")),
]
- sent_params = self._drive("links", manager, responses)
+ sent_params = self._drive("customers", 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]
@@ -218,12 +290,30 @@ class TestDubSourceResumeBehavior:
DubResumeConfig(starting_after="b-99"),
]
+ def test_links_walk_covers_unfiled_links_then_every_folder(self) -> None:
+ # Without the per-folder passes only the first request is made, and every link filed
+ # into a folder is missing from the table while the sync still reports success.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub._fetch_folder_ids",
+ return_value=["fold_a", "fold_b"],
+ ):
+ sent_params = self._drive(
+ "links",
+ manager,
+ [_make_http_response(_rows(1, p)) for p in ("unfiled", "a", "b")],
+ )
+
+ assert [p.get("folderId") for p in sent_params] == [None, "fold_a", "fold_b"]
+
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))])
+ sent_params = self._drive("customers", manager, [_make_http_response(_rows(1))])
assert [p.get("startingAfter") for p in sent_params] == ["a-42"]