: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement vercel import source (#65656)
Tom Owersd41442db4d11
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex fd581d713572..ae0f3278f94e 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -212,6 +212,7 @@ the row lists both.| trello | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |+| vercel | HTTP | requests | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ || webflow | HTTP | requests | ✅ || woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -680,7 +681,6 @@ doesn't conflict with concurrent PRs.- uservoice- vantage- veeqo-- vercel- visma_economic- vwo- waiteraiddiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 1604d0c50e3c..65ba64d9125e 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -3266,7 +3266,8 @@ class VeeqoSourceConfig(config.Config):@config.configclass VercelSourceConfig(config.Config):- pass+ access_token: str+ team_id: str | None = None@config.configdiff --git a/posthog/temporal/data_imports/sources/vercel/canonical_descriptions.py b/posthog/temporal/data_imports/sources/vercel/canonical_descriptions.pynew file mode 100644index 000000000000..07f0413701f1--- /dev/null+++ b/posthog/temporal/data_imports/sources/vercel/canonical_descriptions.py@@ -0,0 +1,69 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Sourced from Vercel's public REST API reference (https://vercel.com/docs/rest-api/reference).+# Partial coverage is fine — any column not listed here falls back to LLM enrichment, which is+# given the source name, endpoint, docs_url, and column types.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "deployments": {+ "description": "A Vercel deployment: a single build and release of a project, with its state, target environment, and URL.",+ "docs_url": "https://vercel.com/docs/rest-api/reference/endpoints/deployments/list-deployments",+ "columns": {+ "uid": "Unique identifier for the deployment.",+ "name": "Name of the project the deployment belongs to.",+ "url": "The deployment's unique URL (without the scheme).",+ "created": "Time the deployment was created, as a Unix timestamp in milliseconds.",+ "createdAt": "Time the deployment was created, as a Unix timestamp in milliseconds.",+ "state": "Current state of the deployment (e.g. BUILDING, READY, ERROR, CANCELED).",+ "readyState": "Readiness state of the deployment.",+ "type": "Deployment type (e.g. LAMBDAS).",+ "target": "Deployment target environment (e.g. production, staging, or null for preview).",+ "creator": "The user or team member who created the deployment.",+ "inspectorUrl": "URL of the deployment's inspector page in the Vercel dashboard.",+ },+ },+ "projects": {+ "description": "A Vercel project: a codebase connected to Vercel with its build, environment, and deployment configuration.",+ "docs_url": "https://vercel.com/docs/rest-api/reference/endpoints/projects/retrieve-a-list-of-projects",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "Name of the project.",+ "accountId": "Identifier of the user or team that owns the project.",+ "createdAt": "Time the project was created, as a Unix timestamp in milliseconds.",+ "updatedAt": "Time the project was last updated, as a Unix timestamp in milliseconds.",+ "framework": "Framework preset configured for the project (e.g. nextjs).",+ },+ },+ "teams": {+ "description": "A Vercel team the access token can access.",+ "docs_url": "https://vercel.com/docs/rest-api/reference/endpoints/teams/list-all-teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "slug": "URL-friendly unique slug for the team.",+ "name": "Display name of the team.",+ "createdAt": "Time the team was created, as a Unix timestamp in milliseconds.",+ },+ },+ "domains": {+ "description": "A domain registered with or added to Vercel.",+ "docs_url": "https://vercel.com/docs/rest-api/reference/endpoints/domains/list-all-the-domains",+ "columns": {+ "id": "Unique identifier for the domain.",+ "name": "The domain name.",+ "createdAt": "Time the domain was added, as a Unix timestamp in milliseconds.",+ "verified": "Whether the domain has been verified.",+ "serviceType": "How the domain's DNS is served (e.g. zeit.world, external).",+ },+ },+ "aliases": {+ "description": "An alias mapping a custom or vercel.app URL to a specific deployment.",+ "docs_url": "https://vercel.com/docs/rest-api/reference/endpoints/aliases/list-aliases",+ "columns": {+ "uid": "Unique identifier for the alias.",+ "alias": "The aliased URL (without the scheme).",+ "created": "Time the alias was created, as a Unix timestamp in milliseconds.",+ "createdAt": "Time the alias was created, as a Unix timestamp in milliseconds.",+ "deployment": "The deployment the alias points to.",+ "deploymentId": "Identifier of the deployment the alias points to.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/vercel/settings.py b/posthog/temporal/data_imports/sources/vercel/settings.pynew file mode 100644index 000000000000..b432cada63b0--- /dev/null+++ b/posthog/temporal/data_imports/sources/vercel/settings.py@@ -0,0 +1,83 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class VercelEndpointConfig:+ name: str+ # Versioned path on https://api.vercel.com (Vercel pins each resource to its own API version).+ path: str+ # Key in the JSON response body that holds the list of rows (e.g. {"deployments": [...]}).+ response_data_key: str+ primary_key: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Query param that lower-bounds results by creation time (Unix ms). Only set where Vercel+ # documents a genuine server-side time filter — None means full refresh for this endpoint.+ since_param: Optional[str] = None+ # Team-owned resources require ?teamId=<id> on each request. Endpoints that list resources+ # visible to the token itself (e.g. /v2/teams) are not team-scoped.+ team_scoped: bool = True+++# Vercel list endpoints share one pagination model: the response carries a `pagination` object+# with `count`, `next`, and `prev` Unix-ms timestamps; the next page is requested by passing the+# `next` value back as the `until` query param. Rows arrive newest-first (descending by creation+# time), so every SourceResponse here is sort_mode="desc".+VERCEL_ENDPOINTS: dict[str, VercelEndpointConfig] = {+ "deployments": VercelEndpointConfig(+ name="deployments",+ path="/v6/deployments",+ response_data_key="deployments",+ primary_key="uid",+ # /v6/deployments documents `since`/`until` (Unix ms) as a server-side filter on the+ # deployment creation time. `created` is an immutable epoch-ms integer, so it is both the+ # incremental cursor and a stable ordering key.+ since_param="since",+ incremental_fields=[+ {+ "label": "created",+ "type": IncrementalFieldType.Integer,+ "field": "created",+ "field_type": IncrementalFieldType.Integer,+ },+ ],+ ),+ # The endpoints below are full refresh only: Vercel's public docs describe the `pagination`+ # cursor for them but do not document a server-side creation-time filter, and we have no API+ # credentials to curl-verify one. Marking them incremental would re-page the whole resource+ # every sync at the same API cost as a full refresh, so we ship full refresh until a filter is+ # confirmed against the live API.+ "projects": VercelEndpointConfig(+ name="projects",+ path="/v9/projects",+ response_data_key="projects",+ primary_key="id",+ ),+ "teams": VercelEndpointConfig(+ name="teams",+ path="/v2/teams",+ response_data_key="teams",+ primary_key="id",+ team_scoped=False,+ ),+ "domains": VercelEndpointConfig(+ name="domains",+ path="/v5/domains",+ response_data_key="domains",+ primary_key="id",+ ),+ "aliases": VercelEndpointConfig(+ name="aliases",+ path="/v4/aliases",+ response_data_key="aliases",+ primary_key="uid",+ ),+}++ENDPOINTS = tuple(VERCEL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in VERCEL_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/vercel/source.py b/posthog/temporal/data_imports/sources/vercel/source.pyindex 0cb9d4e90f5a..a9c0702f3771 100644--- a/posthog/temporal/data_imports/sources/vercel/source.py+++ b/posthog/temporal/data_imports/sources/vercel/source.py@@ -1,31 +1,141 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import VercelSourceConfig+from posthog.temporal.data_imports.sources.vercel.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.vercel.vercel import (+ VercelResumeConfig,+ validate_credentials as validate_vercel_credentials,+ vercel_source,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class VercelSource(SimpleSource[VercelSourceConfig]):+class VercelSource(ResumableSource[VercelSourceConfig, VercelResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.VERCEL+ @property+ def connection_host_fields(self) -> list[str]:+ # `team_id` selects which Vercel team the stored access token is used against. Editing it+ # on an existing source must force the token to be re-entered — otherwise an editor could+ # retarget the preserved token at another Vercel team it can access.+ return ["team_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.VERCEL,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Vercel",- iconPath="/static/services/vercel.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter a Vercel access token to pull your Vercel deployments, projects, teams, domains, and aliases into the PostHog Data warehouse.++Create an access token in your [Vercel account settings](https://vercel.com/account/tokens). A read-only token is sufficient.++To sync resources owned by a team, also enter the team's ID (found under **Team Settings**). Leave it blank to sync resources owned by the token's user.""",+ iconPath="/static/services/vercel.png",+ docsUrl="https://posthog.com/docs/cdp/sources/vercel",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="team_id",+ label="Team ID (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="team_...",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.vercel.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls raise_for_status().+ # Retrying never satisfies a credential/permission problem, so stop the sync. Match the+ # stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.vercel.com": "Your Vercel access token is invalid or has been revoked. Create a new token in your Vercel account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.vercel.com": "Your Vercel access token is not authorized for this resource. Check the token's scope (and team access), then reconnect.",+ }++ def get_schemas(+ self,+ config: VercelSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: VercelSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_vercel_credentials(config.access_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[VercelResumeConfig]:+ return ResumableSourceManager[VercelResumeConfig](inputs, VercelResumeConfig)++ def source_for_pipeline(+ self,+ config: VercelSourceConfig,+ resumable_source_manager: ResumableSourceManager[VercelResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return vercel_source(+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ team_id=config.team_id,+ logger=inputs.logger,+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/vercel/tests/test_vercel.py b/posthog/temporal/data_imports/sources/vercel/tests/test_vercel.pynew file mode 100644index 000000000000..0a75ae7524c9--- /dev/null+++ b/posthog/temporal/data_imports/sources/vercel/tests/test_vercel.py@@ -0,0 +1,229 @@+from typing import Any++from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.vercel import vercel+from posthog.temporal.data_imports.sources.vercel.settings import VERCEL_ENDPOINTS+from posthog.temporal.data_imports.sources.vercel.vercel import (+ PAGE_SIZE,+ VercelResumeConfig,+ _build_params,+ _should_stop_desc,+ get_rows,+ validate_credentials,+ vercel_source,+)+++class _FakeResumableManager:+ def __init__(self, state: VercelResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[VercelResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> VercelResumeConfig | None:+ return self._state++ def save_state(self, data: VercelResumeConfig) -> None:+ self.saved.append(data)+++def _patch_fetch(monkeypatch: Any, responses: list[dict]) -> list[str]:+ """Replace _fetch_page with a queue that returns canned pages in order, recording each URL."""+ calls: list[str] = []+ queue = list(responses)++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ calls.append(url)+ return queue.pop(0)++ monkeypatch.setattr(vercel, "_fetch_page", fake_fetch)+ return calls+++def _collect(endpoint: str, manager: _FakeResumableManager, monkeypatch: Any, responses: list[dict], **kwargs: Any):+ calls = _patch_fetch(monkeypatch, responses)+ rows: list[dict] = []+ for table in get_rows(+ access_token="t",+ endpoint=endpoint,+ team_id=kwargs.get("team_id"),+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=kwargs.get("should_use_incremental_field", False),+ db_incremental_field_last_value=kwargs.get("db_incremental_field_last_value"),+ incremental_field=kwargs.get("incremental_field"),+ ):+ rows.extend(table.to_pylist())+ return rows, calls+++class TestBuildParams:+ @parameterized.expand(+ [+ ("default", "deployments", None, None, None, {"limit": PAGE_SIZE}),+ ("team_scoped_with_team", "deployments", "team_1", None, None, {"limit": PAGE_SIZE, "teamId": "team_1"}),+ # /v2/teams lists resources visible to the token itself, so teamId must not be appended.+ ("not_team_scoped_ignores_team", "teams", "team_1", None, None, {"limit": PAGE_SIZE}),+ ("since_and_until", "deployments", None, 123, 456, {"limit": PAGE_SIZE, "since": 123, "until": 456}),+ # projects has no since_param, so a cursor value must not become a query filter.+ ("no_since_param_drops_since", "projects", None, 123, None, {"limit": PAGE_SIZE}),+ ]+ )+ def test_build_params(+ self,+ _name: str,+ endpoint: str,+ team_id: str | None,+ since_value: Any,+ until: int | None,+ expected: dict[str, Any],+ ) -> None:+ assert _build_params(VERCEL_ENDPOINTS[endpoint], team_id, since_value, until) == expected+++class TestShouldStopDesc:+ @parameterized.expand(+ [+ ("page_crosses_watermark", [{"created": 300}, {"created": 100}], "created", 150, True),+ ("equal_to_watermark_stops", [{"created": 150}], "created", 150, True),+ ("all_above_watermark", [{"created": 300}, {"created": 200}], "created", 150, False),+ ("no_cutoff", [{"created": 300}], "created", None, False),+ ("no_field", [{"created": 300}], None, 150, False),+ ("empty_items", [], "created", 150, False),+ ("missing_field_value_ignored", [{"other": 1}], "created", 150, False),+ ]+ )+ def test_should_stop_desc(+ self, _name: str, items: list[dict], field_name: str | None, cutoff: Any, expected: bool+ ) -> None:+ assert _should_stop_desc(items, field_name, cutoff) is expected+++class TestValidateCredentials:+ @parameterized.expand([(200, True), (401, False), (403, False), (500, False)])+ def test_status_mapping(self, status: int, expected_ok: bool) -> None:+ response = requests.Response()+ response.status_code = status+ session = MagicMock()+ session.get.return_value = response+ with patch.object(vercel, "make_tracked_session", lambda *a, **k: session):+ ok, error = validate_credentials("token")++ assert ok is expected_ok, f"status={status}"+ assert (error is None) is expected_ok, f"status={status}"++ def test_request_exception_is_handled(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(vercel, "make_tracked_session", lambda *a, **k: session)++ ok, error = validate_credentials("token")+ assert ok is False+ assert error == "boom"+++class TestGetRows:+ def test_full_refresh_follows_until_cursor_across_pages(self, monkeypatch: Any) -> None:+ responses = [+ {"deployments": [{"uid": "1", "created": 300}, {"uid": "2", "created": 200}], "pagination": {"next": 200}},+ {"deployments": [{"uid": "3", "created": 100}], "pagination": {"next": None}},+ ]+ rows, calls = _collect("deployments", _FakeResumableManager(), monkeypatch, responses)++ assert [r["uid"] for r in rows] == ["1", "2", "3"]+ assert "until=" not in calls[0]+ assert "until=200" in calls[1]++ def test_uses_response_data_key_per_endpoint(self, monkeypatch: Any) -> None:+ responses = [{"projects": [{"id": "p1"}, {"id": "p2"}], "pagination": {"next": None}}]+ rows, _ = _collect("projects", _FakeResumableManager(), monkeypatch, responses)+ assert [r["id"] for r in rows] == ["p1", "p2"]++ def test_incremental_sends_since_and_stops_at_watermark(self, monkeypatch: Any) -> None:+ responses = [+ {"deployments": [{"uid": "1", "created": 300}, {"uid": "2", "created": 200}], "pagination": {"next": 200}},+ # 120 <= watermark(150): stop after this page rather than walking older history.+ {"deployments": [{"uid": "3", "created": 120}], "pagination": {"next": 120}},+ {"deployments": [{"uid": "4", "created": 50}], "pagination": {"next": None}},+ ]+ rows, calls = _collect(+ "deployments",+ _FakeResumableManager(),+ monkeypatch,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=150,+ )++ assert [r["uid"] for r in rows] == ["1", "2", "3"]+ assert "since=150" in calls[0]+ assert len(calls) == 2++ def test_stops_when_cursor_does_not_advance(self, monkeypatch: Any) -> None:+ # An endpoint that ignores `until` re-serves the same cursor; stop instead of looping forever.+ responses = [+ {"deployments": [{"uid": "1", "created": 300}], "pagination": {"next": 300}},+ {"deployments": [{"uid": "9", "created": 300}], "pagination": {"next": 300}},+ ]+ rows, calls = _collect("deployments", _FakeResumableManager(), monkeypatch, responses)++ assert [r["uid"] for r in rows] == ["1", "9"]+ assert len(calls) == 2++ def test_resumes_from_saved_until_cursor(self, monkeypatch: Any) -> None:+ responses = [{"deployments": [{"uid": "1", "created": 400}], "pagination": {"next": None}}]+ manager = _FakeResumableManager(VercelResumeConfig(until=500))+ rows, calls = _collect("deployments", manager, monkeypatch, responses)++ assert [r["uid"] for r in rows] == ["1"]+ assert "until=500" in calls[0]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ responses = [{"deployments": [], "pagination": {"next": None}}]+ rows, calls = _collect("deployments", _FakeResumableManager(), monkeypatch, responses)+ assert rows == []+ assert len(calls) == 1++ def test_mid_page_yield_checkpoints_current_page_not_next(self, monkeypatch: Any) -> None:+ # Regression: a mid-page yield must checkpoint the cursor for the CURRENT page, not the+ # next one. Page two crosses the batcher's 2000-row chunk, so the batch yields while the+ # rest of page two is still unprocessed. Saving the next cursor (400) here would advance+ # the watermark past those rows and silently skip them after a crash/resume; the checkpoint+ # must stay at page two's own cursor (200) so resume re-fetches it (dedup handles the+ # already-yielded rows).+ responses: list[dict] = [+ {"deployments": [{"uid": "a", "created": 100}, {"uid": "b", "created": 99}], "pagination": {"next": 200}},+ {+ "deployments": [{"uid": str(i), "created": 100000 - i} for i in range(2500)],+ "pagination": {"next": 400},+ },+ {"deployments": [], "pagination": {"next": None}},+ ]+ manager = _FakeResumableManager()+ rows, _ = _collect("deployments", manager, monkeypatch, responses)++ assert len(rows) == 2502+ assert manager.saved == [VercelResumeConfig(until=200)]+++class TestVercelSource:+ @parameterized.expand(+ [("deployments", "uid"), ("projects", "id"), ("teams", "id"), ("domains", "id"), ("aliases", "uid")]+ )+ def test_source_response_primary_key_and_sort(self, endpoint: str, expected_pk: str) -> None:+ response = vercel_source(+ access_token="t",+ endpoint=endpoint,+ team_id=None,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == [expected_pk]+ assert response.sort_mode == "desc"diff --git a/posthog/temporal/data_imports/sources/vercel/tests/test_vercel_source.py b/posthog/temporal/data_imports/sources/vercel/tests/test_vercel_source.pynew file mode 100644index 000000000000..ee7f15d68066--- /dev/null+++ b/posthog/temporal/data_imports/sources/vercel/tests/test_vercel_source.py@@ -0,0 +1,158 @@+from typing import Any, cast++from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import VercelSourceConfig+from posthog.temporal.data_imports.sources.vercel import source as vercel_source_module+from posthog.temporal.data_imports.sources.vercel.source import VercelSource+from posthog.temporal.data_imports.sources.vercel.vercel import VercelResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalFieldType+++def _source_inputs(schema_name: str, **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "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 TestVercelSource:+ def setup_method(self) -> None:+ self.source = VercelSource()+ self.config = VercelSourceConfig(access_token="token", team_id=None)++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.VERCEL++ def test_connection_host_fields_includes_team_id(self) -> None:+ # team_id retargets the stored token at a different Vercel team, so editing it must force+ # the token to be re-entered.+ assert self.source.connection_host_fields == ["team_id"]++ def test_source_config_metadata(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Vercel"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Stays hidden until it's been exercised against the live API.+ assert config.unreleasedSource is True++ def test_source_config_fields(self) -> None:+ fields = {f.name: cast(SourceFieldInputConfig, f) for f in self.source.get_source_config.fields}+ assert set(fields) == {"access_token", "team_id"}+ assert fields["access_token"].required is True+ assert fields["access_token"].secret is True+ # Team scoping is optional — a personal token can sync its own resources.+ assert fields["team_id"].required is False+ assert fields["team_id"].secret is False++ def test_get_schemas_incremental_only_for_deployments(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}+ assert set(schemas) == {"deployments", "projects", "teams", "domains", "aliases"}++ deployments = schemas["deployments"]+ assert deployments.supports_incremental is True+ assert deployments.supports_append is True+ assert [f["field"] for f in deployments.incremental_fields] == ["created"]+ assert deployments.incremental_fields[0]["field_type"] == IncrementalFieldType.Integer++ for full_refresh in ("projects", "teams", "domains", "aliases"):+ assert schemas[full_refresh].supports_incremental is False+ assert schemas[full_refresh].incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["deployments"])+ assert [s.name for s in schemas] == ["deployments"]++ @parameterized.expand(+ [("valid", (True, None)), ("invalid", (False, "Invalid or unauthorized Vercel access token"))]+ )+ def test_validate_credentials_delegates(self, _name: str, result: tuple) -> None:+ with mock.patch.object(vercel_source_module, "validate_vercel_credentials", lambda token: result):+ assert self.source.validate_credentials(self.config, team_id=1) == result++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.vercel.com/v6/deployments?limit=100"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.vercel.com/v9/projects?limit=100"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limit", "429 Client Error: Too Many Requests for url: https://api.vercel.com/v6/deployments"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.vercel.com/v6/deployments"),+ ("read_timeout", "HTTPSConnectionPool(host='api.vercel.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs("deployments"))+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is VercelResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ config = VercelSourceConfig(access_token="token", team_id="team_42")+ captured: dict[str, Any] = {}++ def fake_vercel_source(**kwargs: Any):+ captured.update(kwargs)+ return MagicMock(name="source_response")++ manager = MagicMock()+ inputs = _source_inputs(+ "deployments",+ should_use_incremental_field=True,+ db_incremental_field_last_value=123,+ incremental_field="created",+ )++ with mock.patch.object(vercel_source_module, "vercel_source", fake_vercel_source):+ self.source.source_for_pipeline(config, manager, inputs)++ assert captured["access_token"] == "token"+ assert captured["team_id"] == "team_42"+ assert captured["endpoint"] == "deployments"+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == 123+ assert captured["incremental_field"] == "created"+ assert captured["resumable_source_manager"] is manager++ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:+ captured: dict[str, Any] = {}++ def fake_vercel_source(**kwargs: Any):+ captured.update(kwargs)+ return MagicMock()++ inputs = _source_inputs("projects", should_use_incremental_field=False, db_incremental_field_last_value=999)+ with mock.patch.object(vercel_source_module, "vercel_source", fake_vercel_source):+ self.source.source_for_pipeline(self.config, MagicMock(), inputs)++ assert captured["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/vercel/vercel.py b/posthog/temporal/data_imports/sources/vercel/vercel.pynew file mode 100644index 000000000000..d7230e8c0b83--- /dev/null+++ b/posthog/temporal/data_imports/sources/vercel/vercel.py@@ -0,0 +1,219 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.vercel.settings import VERCEL_ENDPOINTS, VercelEndpointConfig++VERCEL_BASE_URL = "https://api.vercel.com"++# Vercel caps the page size at 100 (default 20); request the max to minimize round-trips.+PAGE_SIZE = 100++# Backstop against an endpoint that silently ignores the `until` cursor (which would otherwise+# re-serve page one forever). Resumable state means an interrupted sync picks back up, so this is+# a runaway guard, not a coverage limit — at 100 rows/page it allows ~1M rows before warning.+MAX_PAGES = 10_000+++class VercelRetryableError(Exception):+ pass+++class VercelResumeConfig:+ # The `until` pagination cursor (Unix ms) for the next page. None means "start at page one".+ # The `since` lower bound is reconstructed from db_incremental_field_last_value on resume, so+ # only the cursor needs persisting.+ until: int | None = None+++def _get_headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {access_token}",+ "Accept": "application/json",+ }+++def _build_params(+ config: VercelEndpointConfig,+ team_id: str | None,+ since_value: Any,+ until: int | None,+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": PAGE_SIZE}++ if config.team_scoped and team_id:+ params["teamId"] = team_id++ if config.since_param and since_value is not None:+ params[config.since_param] = since_value++ if until is not None:+ params["until"] = until++ return params+++def _build_url(path: str, params: dict[str, Any]) -> str:+ return f"{VERCEL_BASE_URL}{path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type((VercelRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=60)++ # Vercel rate limits per-endpoint and returns 429 with a reset window; treat 429 and any 5xx+ # as transient and let tenacity back off. A bad/insufficient token (401/403) is raised below+ # via raise_for_status() and matched by get_non_retryable_errors() so the sync stops.+ if response.status_code == 429 or response.status_code >= 500:+ raise VercelRetryableError(f"Vercel API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Vercel API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _should_stop_desc(items: list[dict[str, Any]], field_name: str | None, cutoff: Any) -> bool:+ """For an incremental, newest-first endpoint, stop paginating once a page contains a row at or+ below the watermark. This is a client-side backstop: the `since` filter should already exclude+ older rows, but if Vercel silently ignored it the watermark check still terminates the walk and+ prevents re-fetching the full history every sync."""+ if not field_name or cutoff is None or not items:+ return False+ return any(item.get(field_name) is not None and item[field_name] <= cutoff for item in items)+++def validate_credentials(access_token: str) -> tuple[bool, str | None]:+ """Confirm the access token is genuine via GET /v2/user — the cheapest authenticated probe,+ available to any valid Vercel token regardless of team scope or resource permissions."""+ try:+ response = make_tracked_session().get(+ f"{VERCEL_BASE_URL}/v2/user", headers=_get_headers(access_token), timeout=10+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid or unauthorized Vercel access token"+ return False, f"Vercel API error: {response.status_code}"+++def get_rows(+ access_token: str,+ endpoint: str,+ team_id: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[VercelResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = VERCEL_ENDPOINTS[endpoint]+ headers = _get_headers(access_token)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page so urllib3 keeps the connection alive.+ session = make_tracked_session()++ field_name = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)+ # Only deployments has a documented server-side `since` filter; for everything else cutoff stays+ # None and we full-refresh the resource.+ cutoff = (+ db_incremental_field_last_value+ if (should_use_incremental_field and config.since_param and db_incremental_field_last_value is not None)+ else None+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ until = resume.until if resume else None+ if resume is not None:+ logger.debug(f"Vercel: resuming {endpoint} from until={until}")++ page_count = 0+ while True:+ url = _build_url(config.path, _build_params(config, team_id, cutoff, until))+ data = _fetch_page(session, url, headers, logger)++ items = data.get(config.response_data_key) or []+ if not items:+ break++ next_until = (data.get("pagination") or {}).get("next")+ stop_after_page = _should_stop_desc(items, field_name, cutoff)++ for item in items:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Checkpoint the cursor for the CURRENT page (not next_until): a yield can fire+ # mid-page, so the rest of this page may still be unprocessed. Saving next_until+ # here would advance the watermark past those rows and silently skip them on+ # resume. Re-fetching the current page instead re-yields its rows; the merge+ # dedupes on the primary key, so the already-yielded rows are harmless duplicates.+ if not stop_after_page:+ resumable_source_manager.save_state(VercelResumeConfig(until=until))++ page_count += 1+ if stop_after_page or next_until is None:+ break+ # If the cursor doesn't advance, the endpoint is ignoring `until`; stop rather than loop+ # forever on page one.+ if next_until == until:+ logger.warning(f"Vercel: {endpoint} pagination cursor did not advance (until={until}); stopping")+ break+ if page_count >= MAX_PAGES:+ logger.warning(f"Vercel: {endpoint} hit MAX_PAGES={MAX_PAGES}; remaining pages skipped")+ break+ until = next_until++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def vercel_source(+ access_token: str,+ endpoint: str,+ team_id: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[VercelResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = VERCEL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ endpoint=endpoint,+ team_id=team_id,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=[endpoint_config.primary_key],+ # Vercel returns rows newest-first; the watermark must checkpoint as descending.+ sort_mode="desc",+ )