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 productboard import source (#61663)

Tom Owers071760a72fe8
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 1fc51557a34b..919cc0933784 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -103,6 +103,7 @@ the row lists both.
| polar | HTTP | requests | ✅ |
| postgres | DB protocol | psycopg | ➖ |
| postmark | HTTP | requests | ✅ |
+| productboard | HTTP | requests | ✅ |
| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |
| recharge | HTTP | requests | ✅ |
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -211,7 +212,6 @@ doesn't conflict with concurrent PRs.
- paypal
- pendo
- plaid
-- productboard
- quickbooks
- ringcentral
- salesloft
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index c5f5533f3ee1..ded7043acfb8 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -696,7 +696,7 @@ class PostmarkSourceConfig(config.Config):
@config.config
class ProductboardSourceConfig(config.Config):
- pass
+ access_token: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/productboard/productboard.py b/posthog/temporal/data_imports/sources/productboard/productboard.py
new file mode 100644
index 000000000000..1cb13e4f4ae2
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/productboard/productboard.py
@@ -0,0 +1,215 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import quote
+
+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.productboard.settings import PRODUCTBOARD_ENDPOINTS
+
+PRODUCTBOARD_BASE_URL = "https://api.productboard.com/v2"
+
+
+class ProductboardRetryableError(Exception):
+ pass
+
+
+class ProductboardResumeConfig:
+ next_url: str
+
+
+def _get_headers(access_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {access_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_incremental_value(value: Any) -> str:
+ """Format an incremental cursor value as ISO 8601 with a `Z` suffix.
+
+ Productboard's date/time filters expect ISO 8601 date-time strings; we normalise
+ to UTC so naive watermarks from the DB compare correctly against tz-aware values.
+ """
+ if isinstance(value, datetime):
+ dt = value
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time())
+ else:
+ return str(value)
+
+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ """Build a URL, percent-encoding values but keeping literal param keys.
+
+ Productboard's entity filter uses the bracket key `type[]`, which we preserve
+ verbatim while still encoding values (e.g. ISO timestamps containing `:`).
+ """
+ if not params:
+ return base_url
+ parts = [f"{key}={quote(str(value), safe='')}" for key, value in params.items()]
+ return f"{base_url}?{'&'.join(parts)}"
+
+
+def _build_initial_params(
+ endpoint: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ config = PRODUCTBOARD_ENDPOINTS[endpoint]
+ params: dict[str, Any] = {}
+
+ if config.entity_type:
+ params["type[]"] = config.entity_type
+
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:
+ field = incremental_field or config.default_incremental_field
+ filter_param = config.incremental_param_map.get(field) if field else None
+ if filter_param:
+ params[filter_param] = _format_incremental_value(db_incremental_field_last_value)
+
+ return params
+
+
+def validate_credentials(access_token: str, path: str) -> tuple[bool, int | None, str | None]:
+ """Probe a single Productboard endpoint. Returns (ok, status_code, message)."""
+ try:
+ response = make_tracked_session().get(
+ f"{PRODUCTBOARD_BASE_URL}{path}",
+ headers=_get_headers(access_token),
+ timeout=10,
+ )
+ except requests.exceptions.RequestException as e:
+ return False, None, str(e)
+
+ if response.ok:
+ return True, response.status_code, None
+
+ try:
+ message = response.json().get("message")
+ except Exception:
+ message = response.text or None
+
+ return False, response.status_code, message
+
+
+def get_rows(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ProductboardResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = PRODUCTBOARD_ENDPOINTS[endpoint]
+ headers = _get_headers(access_token)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+
+ params = _build_initial_params(
+ endpoint, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url = resume_config.next_url
+ logger.debug(f"Productboard: resuming from URL: {url}")
+ else:
+ url = _build_url(f"{PRODUCTBOARD_BASE_URL}{config.path}", params)
+
+ @retry(
+ retry=retry_if_exception_type((ProductboardRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ProductboardRetryableError(
+ f"Productboard API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Productboard API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+
+ items = data.get("data", [])
+ if not items:
+ break
+
+ next_url = data.get("links", {}).get("next")
+
+ # Checkpoint the CURRENT page URL, not the next one: the batcher buffers across
+ # page boundaries, so a yield can flush rows from several pages at once. On
+ # resume we re-fetch this page and rely on primary-key merge to dedupe the rows
+ # already yielded. Advancing the checkpoint to next_url here would strand any
+ # current-page rows still buffered (not yet yielded) if we crashed mid-page.
+ checkpoint_url = url
+
+ for item in items:
+ batcher.batch(item)
+
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save state after yielding (not before) so a crash re-yields the last
+ # batch rather than skipping it.
+ resumable_source_manager.save_state(ProductboardResumeConfig(next_url=checkpoint_url))
+
+ if not next_url:
+ break
+
+ url = next_url
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def productboard_source(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ProductboardResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = PRODUCTBOARD_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ endpoint=endpoint,
+ 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=[config.primary_key],
+ sort_mode=config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/productboard/settings.py b/posthog/temporal/data_imports/sources/productboard/settings.py
new file mode 100644
index 000000000000..53c72febd4ca
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/productboard/settings.py
@@ -0,0 +1,86 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SortMode
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class ProductboardEndpointConfig:
+ name: str
+ path: str
+ # Set for endpoints served by the generic `/entities` resource; the value is the
+ # `type[]` query param Productboard expects (e.g. "feature", "component").
+ entity_type: Optional[str] = None
+ primary_key: str = "id"
+ # Stable, immutable datetime field used for partitioning. Never use `updatedAt`.
+ partition_key: Optional[str] = None
+ sort_mode: SortMode = "asc"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Maps an incremental field name to the server-side filter query param that
+ # actually filters on it (only the notes endpoint exposes such filters).
+ incremental_param_map: dict[str, str] = field(default_factory=dict)
+ default_incremental_field: Optional[str] = None
+
+ @property
+ def supports_incremental(self) -> bool:
+ return bool(self.incremental_param_map)
+
+
+_DATETIME = IncrementalFieldType.DateTime
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {"label": name, "type": _DATETIME, "field": name, "field_type": _DATETIME}
+
+
+# Notes are the only Productboard resource exposing server-side timestamp filters
+# (`createdFrom` / `updatedFrom`). The list is sorted by creation date newest-first
+# and there is no sort parameter, so we read it descending.
+_NOTES = ProductboardEndpointConfig(
+ name="notes",
+ path="/notes",
+ partition_key="createdAt",
+ sort_mode="desc",
+ incremental_fields=[_datetime_field("createdAt"), _datetime_field("updatedAt")],
+ incremental_param_map={"createdAt": "createdFrom", "updatedAt": "updatedFrom"},
+ default_incremental_field="updatedAt",
+)
+
+
+def _entity_endpoint(name: str, entity_type: str) -> ProductboardEndpointConfig:
+ # Entity responses carry top-level `id`, `createdAt` and `updatedAt`, but the
+ # `/entities` list endpoint exposes no timestamp filter, so these are full-refresh
+ # only. `createdAt` is immutable, so it's a safe partition key.
+ return ProductboardEndpointConfig(
+ name=name,
+ path="/entities",
+ entity_type=entity_type,
+ partition_key="createdAt",
+ )
+
+
+PRODUCTBOARD_ENDPOINTS: dict[str, ProductboardEndpointConfig] = {
+ "features": _entity_endpoint("features", "feature"),
+ "subfeatures": _entity_endpoint("subfeatures", "subfeature"),
+ "components": _entity_endpoint("components", "component"),
+ "products": _entity_endpoint("products", "product"),
+ "initiatives": _entity_endpoint("initiatives", "initiative"),
+ "objectives": _entity_endpoint("objectives", "objective"),
+ "key_results": _entity_endpoint("key_results", "keyResult"),
+ "releases": _entity_endpoint("releases", "release"),
+ "release_groups": _entity_endpoint("release_groups", "releaseGroup"),
+ "companies": _entity_endpoint("companies", "company"),
+ "users": _entity_endpoint("users", "user"),
+ "notes": _NOTES,
+ # Members carry no documented top-level timestamp, so no partitioning.
+ "members": ProductboardEndpointConfig(name="members", path="/members"),
+ "teams": ProductboardEndpointConfig(name="teams", path="/teams", partition_key="createdAt"),
+}
+
+ENDPOINTS = tuple(PRODUCTBOARD_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PRODUCTBOARD_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/productboard/source.py b/posthog/temporal/data_imports/sources/productboard/source.py
index 35814d728fc6..b65777449425 100644
--- a/posthog/temporal/data_imports/sources/productboard/source.py
+++ b/posthog/temporal/data_imports/sources/productboard/source.py
@@ -1,29 +1,146 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
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.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import ProductboardSourceConfig
+from posthog.temporal.data_imports.sources.productboard.productboard import (
+ ProductboardResumeConfig,
+ productboard_source,
+ validate_credentials as validate_productboard_credentials,
+)
+from posthog.temporal.data_imports.sources.productboard.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PRODUCTBOARD_ENDPOINTS,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
+def _probe_path(schema_name: Optional[str]) -> str:
+ """Path used to validate credentials. With a schema, probe its endpoint to confirm
+ scope; otherwise hit a cheap workspace-scoped endpoint to confirm the token."""
+ if schema_name is None:
+ return "/members"
+
+ config = PRODUCTBOARD_ENDPOINTS[schema_name]
+ if config.entity_type:
+ return f"/entities?type[]={config.entity_type}"
+ return config.path
+
+
@SourceRegistry.register
-class ProductboardSource(SimpleSource[ProductboardSourceConfig]):
+class ProductboardSource(ResumableSource[ProductboardSourceConfig, ProductboardResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PRODUCTBOARD
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.productboard.com": "Your Productboard access token is invalid or expired. Please generate a new token and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.productboard.com": "Your Productboard access token is missing the required scope for this resource. Please grant access and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ProductboardSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=PRODUCTBOARD_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=PRODUCTBOARD_ENDPOINTS[endpoint].supports_incremental,
+ 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: ProductboardSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ ok, status, message = validate_productboard_credentials(config.access_token, _probe_path(schema_name))
+ if ok:
+ return True, None
+
+ if status == 401:
+ return False, "Invalid Productboard access token"
+
+ # A valid token may legitimately lack scope for endpoints the user isn't syncing,
+ # so accept 403 at source-create. Re-raise it only when validating a specific schema.
+ if status == 403:
+ if schema_name is None:
+ return True, None
+ return False, message or "Your access token is missing the required scope for this resource"
+
+ return False, message or "Failed to validate Productboard credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ProductboardResumeConfig]:
+ return ResumableSourceManager[ProductboardResumeConfig](inputs, ProductboardResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ProductboardSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ProductboardResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return productboard_source(
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ 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,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.PRODUCTBOARD,
label="Productboard",
+ caption="""Enter your Productboard public API access token to sync your Productboard data into the PostHog Data warehouse.
+
+You can create an access token in your Productboard [workspace settings](https://app.productboard.com/) under **Integrations → Public API**. A Pro plan or higher is required.
+
+Grant read access for the resources you want to sync — for example `entities:read`, `notes:read`, `members:read`, and `teams:read`.""",
iconPath="/static/services/productboard.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/productboard",
unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/posthog/temporal/data_imports/sources/productboard/tests/test_productboard.py b/posthog/temporal/data_imports/sources/productboard/tests/test_productboard.py
new file mode 100644
index 000000000000..237de2621d99
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/productboard/tests/test_productboard.py
@@ -0,0 +1,248 @@
+from collections.abc import Iterable
+from datetime import UTC, date, datetime, timedelta, timezone
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.temporal.data_imports.sources.productboard.productboard import (
+ ProductboardResumeConfig,
+ _build_initial_params,
+ _build_url,
+ _format_incremental_value,
+ get_rows,
+ productboard_source,
+ validate_credentials,
+)
+
+
+def _make_response(json_body: Any, status_code: int = 200) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = json_body
+ response.text = ""
+ return response
+
+
+def _session_returning(responses: list[mock.MagicMock]) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ return session
+
+
+class _FakeBatcher:
+ """Yields every batched item immediately so each page boundary exercises the
+ save_state-after-yield path that the real (5000-row) batcher only hits at scale."""
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ self._items: list[Any] = []
+
+ def batch(self, item: Any) -> None:
+ self._items.append(item)
+
+ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:
+ return len(self._items) > 0
+
+ def get_table(self) -> list[Any]:
+ items = self._items
+ self._items = []
+ return items
+
+
+class TestFormatIncrementalValue:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2023, 10, 1, 10, 0, 0, tzinfo=UTC), "2023-10-01T10:00:00Z"),
+ (datetime(2023, 10, 1, 10, 0, 0), "2023-10-01T10:00:00Z"),
+ (date(2023, 10, 1), "2023-10-01T00:00:00Z"),
+ ("2023-10-01T10:00:00Z", "2023-10-01T10:00:00Z"),
+ (123, "123"),
+ ],
+ )
+ def test_format(self, value, expected):
+ assert _format_incremental_value(value) == expected
+
+ def test_naive_local_offset_is_normalised_to_utc(self):
+ # An aware non-UTC datetime is converted to UTC before formatting.
+ value = datetime(2023, 10, 1, 12, 0, 0, tzinfo=timezone(timedelta(hours=2)))
+ assert _format_incremental_value(value) == "2023-10-01T10:00:00Z"
+
+
+class TestBuildUrl:
+ @pytest.mark.parametrize(
+ "base_url, params, expected",
+ [
+ # No params returns the bare URL.
+ ("https://api.productboard.com/v2/notes", {}, "https://api.productboard.com/v2/notes"),
+ # The bracket entity-filter key is kept literal.
+ (
+ "https://api.productboard.com/v2/entities",
+ {"type[]": "feature"},
+ "https://api.productboard.com/v2/entities?type[]=feature",
+ ),
+ # Values (e.g. ISO timestamps) are percent-encoded.
+ (
+ "https://api.productboard.com/v2/notes",
+ {"updatedFrom": "2023-10-01T10:00:00Z"},
+ "https://api.productboard.com/v2/notes?updatedFrom=2023-10-01T10%3A00%3A00Z",
+ ),
+ ],
+ )
+ def test_build_url(self, base_url, params, expected):
+ assert _build_url(base_url, params) == expected
+
+
+class TestBuildInitialParams:
+ def test_entity_endpoint_adds_type_filter(self):
+ assert _build_initial_params("features", False, None, None) == {"type[]": "feature"}
+
+ def test_entity_endpoint_ignores_incremental(self):
+ # Entities have no server-side timestamp filter, so a last value never becomes a param.
+ params = _build_initial_params("features", True, datetime(2023, 1, 1, tzinfo=UTC), "createdAt")
+ assert params == {"type[]": "feature"}
+
+ @pytest.mark.parametrize(
+ "incremental_field, expected_param",
+ [
+ ("updatedAt", "updatedFrom"),
+ ("createdAt", "createdFrom"),
+ ],
+ )
+ def test_notes_incremental_maps_to_server_filter(self, incremental_field, expected_param):
+ params = _build_initial_params("notes", True, datetime(2023, 10, 1, 10, 0, 0, tzinfo=UTC), incremental_field)
+ assert params == {expected_param: "2023-10-01T10:00:00Z"}
+
+ def test_notes_default_incremental_field(self):
+ params = _build_initial_params("notes", True, datetime(2023, 10, 1, 10, 0, 0, tzinfo=UTC), None)
+ assert params == {"updatedFrom": "2023-10-01T10:00:00Z"}
+
+ def test_notes_full_refresh_has_no_filter(self):
+ assert _build_initial_params("notes", False, None, None) == {}
+
+ def test_notes_incremental_without_last_value_has_no_filter(self):
+ assert _build_initial_params("notes", True, None, "updatedAt") == {}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, json_body, expected",
+ [
+ (200, {"data": []}, (True, 200, None)),
+ (401, {"message": "Unauthorized"}, (False, 401, "Unauthorized")),
+ (403, {"message": "Forbidden"}, (False, 403, "Forbidden")),
+ (500, {"message": "Server error"}, (False, 500, "Server error")),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.productboard.make_tracked_session")
+ def test_status_mapping(self, mock_session, status_code, json_body, expected):
+ mock_session.return_value.get.return_value = _make_response(json_body, status_code)
+ assert validate_credentials("token", "/notes") == expected
+
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.productboard.make_tracked_session")
+ def test_request_exception_returns_message(self, mock_session):
+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")
+ ok, status, message = validate_credentials("token", "/notes")
+ assert ok is False
+ assert status is None
+ assert "boom" in (message or "")
+
+
+class TestGetRows:
+ def _collect(self, iterator: Iterable[Any]) -> list[Any]:
+ return list(iterator)
+
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.productboard.make_tracked_session")
+ def test_paginates_until_no_next_link(self, mock_session):
+ page1 = _make_response(
+ {
+ "data": [{"id": "1"}, {"id": "2"}],
+ "links": {"next": "https://api.productboard.com/v2/notes?pageCursor=c2"},
+ }
+ )
+ page2 = _make_response({"data": [{"id": "3"}], "links": {}})
+ mock_session.return_value = _session_returning([page1, page2])
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ rows: list[dict] = []
+ for table in get_rows("token", "notes", mock.MagicMock(), manager):
+ rows.extend(table.to_pylist())
+
+ assert [r["id"] for r in rows] == ["1", "2", "3"]
+ # First page uses the constructed URL, second follows links.next verbatim.
+ assert (
+ mock_session.return_value.get.call_args_list[0].args[0].startswith("https://api.productboard.com/v2/notes")
+ )
+ assert mock_session.return_value.get.call_args_list[1].args[0].endswith("pageCursor=c2")
+
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.productboard.Batcher", _FakeBatcher)
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.productboard.make_tracked_session")
+ def test_checkpoints_current_page_not_next(self, mock_session):
+ # The checkpoint must be the page we just processed, so resume re-fetches it and
+ # merge-dedupes — never the next page (which would strand still-buffered rows).
+ page1_url = "https://api.productboard.com/v2/notes"
+ page2_url = "https://api.productboard.com/v2/notes?pageCursor=c2"
+ page1 = _make_response({"data": [{"id": "1"}], "links": {"next": page2_url}})
+ page2 = _make_response({"data": [{"id": "2"}], "links": {}})
+ mock_session.return_value = _session_returning([page1, page2])
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ list(get_rows("token", "notes", mock.MagicMock(), manager))
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert all(isinstance(s, ProductboardResumeConfig) for s in saved)
+ # First page's yield checkpoints the first page URL (not page2_url), second the second.
+ assert [s.next_url for s in saved] == [page1_url, page2_url]
+
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.productboard.make_tracked_session")
+ def test_resumes_from_saved_state(self, mock_session):
+ resume_url = "https://api.productboard.com/v2/notes?pageCursor=resume"
+ page = _make_response({"data": [{"id": "9"}], "links": {}})
+ mock_session.return_value = _session_returning([page])
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ProductboardResumeConfig(next_url=resume_url)
+
+ list(get_rows("token", "notes", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.productboard.make_tracked_session")
+ def test_empty_first_page_yields_nothing(self, mock_session):
+ mock_session.return_value = _session_returning([_make_response({"data": [], "links": {}})])
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ assert list(get_rows("token", "notes", mock.MagicMock(), manager)) == []
+
+
+class TestProductboardSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, expected_sort, expected_partition_keys",
+ [
+ ("features", "asc", ["createdAt"]),
+ ("notes", "desc", ["createdAt"]),
+ ("teams", "asc", ["createdAt"]),
+ ("members", "asc", None),
+ ],
+ )
+ def test_source_response_metadata(self, endpoint, expected_sort, expected_partition_keys):
+ response = productboard_source("token", endpoint, mock.MagicMock(), mock.MagicMock())
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == expected_sort
+ assert response.partition_keys == expected_partition_keys
+ if expected_partition_keys is None:
+ assert response.partition_mode is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "week"
diff --git a/posthog/temporal/data_imports/sources/productboard/tests/test_productboard_source.py b/posthog/temporal/data_imports/sources/productboard/tests/test_productboard_source.py
new file mode 100644
index 000000000000..29347de2848a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/productboard/tests/test_productboard_source.py
@@ -0,0 +1,163 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import ProductboardSourceConfig
+from posthog.temporal.data_imports.sources.productboard.productboard import ProductboardResumeConfig
+from posthog.temporal.data_imports.sources.productboard.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.productboard.source import ProductboardSource, _probe_path
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestProductboardSource:
+ def setup_method(self):
+ self.source = ProductboardSource()
+ self.team_id = 123
+ self.config = ProductboardSourceConfig(access_token="pb-token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.PRODUCTBOARD
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Productboard"
+ assert config.label == "Productboard"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Kept unreleased while the source is still in alpha.
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/productboard.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["access_token"]
+
+ def test_access_token_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token"
+ )
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.productboard.com/v2/notes",
+ "403 Client Error: Forbidden for url: https://api.productboard.com/v2/entities?type[]=feature",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.productboard.com/v2/notes",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_notes_supports_incremental(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ assert incremental == {"notes"}
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["notes"].incremental_fields == INCREMENTAL_FIELDS["notes"]
+ assert {f["field"] for f in schemas["notes"].incremental_fields} == {"createdAt", "updatedAt"}
+ assert schemas["features"].incremental_fields == []
+ assert schemas["features"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["notes"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "notes"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "probe_return, schema_name, expected_valid, expected_message",
+ [
+ ((True, 200, None), None, True, None),
+ ((False, 401, "Unauthorized"), None, False, "Invalid Productboard access token"),
+ # 403 at source-create means a valid token that just lacks scope for the probe endpoint.
+ ((False, 403, "Forbidden"), None, True, None),
+ # 403 on a specific schema means the user can't sync that endpoint.
+ ((False, 403, "Forbidden"), "notes", False, "Forbidden"),
+ ((False, 500, "Server error"), None, False, "Server error"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.source.validate_productboard_credentials")
+ def test_validate_credentials(self, mock_validate, probe_return, schema_name, expected_valid, expected_message):
+ mock_validate.return_value = probe_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, schema_name)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+
+ @pytest.mark.parametrize(
+ "schema_name, expected_path",
+ [
+ (None, "/members"),
+ ("features", "/entities?type[]=feature"),
+ ("key_results", "/entities?type[]=keyResult"),
+ ("notes", "/notes"),
+ ("members", "/members"),
+ ("teams", "/teams"),
+ ],
+ )
+ def test_probe_path(self, schema_name, expected_path):
+ assert _probe_path(schema_name) == expected_path
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ProductboardResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.source.productboard_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_productboard_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "notes"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2023-10-01T00:00:00Z"
+ inputs.incremental_field = "updatedAt"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_productboard_source.assert_called_once()
+ kwargs = mock_productboard_source.call_args.kwargs
+ assert kwargs["access_token"] == "pb-token"
+ assert kwargs["endpoint"] == "notes"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2023-10-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "updatedAt"
+
+ @mock.patch("posthog.temporal.data_imports.sources.productboard.source.productboard_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_productboard_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "features"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2023-10-01T00:00:00Z"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_productboard_source.call_args.kwargs["db_incremental_field_last_value"] is None