: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 usersnap import source (#71160)
Tom Owersae7269e3172e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7748c6dc052a..89f84fec744e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -527,6 +527,7 @@ the row lists both.| unstructured | HTTP | requests | ✅ || upstash | HTTP | requests | ✅ || uptimerobot | HTTP | requests | ✅ |+| usersnap | HTTP | requests + PyJWT | ✅ || uservoice | HTTP | requests | ✅ || vantage | HTTP | requests | ✅ || vapi | HTTP | requests | ✅ |@@ -967,7 +968,6 @@ doesn't conflict with concurrent PRs.- uppromote- uptick- us_census-- usersnap- uservoice- veeqo- vespadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 80ebceda7a3c..555da3c044fc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -4578,7 +4578,8 @@ class UptimerobotSourceConfig(config.Config):@config.configclass UsersnapSourceConfig(config.Config):- pass+ jwt_secret: str+ jwt_id: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/canonical_descriptions.pynew file mode 100644index 000000000000..f3905730825a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/canonical_descriptions.py@@ -0,0 +1,61 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Sourced from Usersnap's REST API v0.1 OpenAPI spec+# (https://app.swaggerhub.com/apis/usersnap6/usersnap-api/0.1).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "A Usersnap project: a feedback widget/board that collects feedback items.",+ "docs_url": "https://help.usersnap.com/reference/rest-api",+ "columns": {+ "project_id": "Unique identifier of the project.",+ "api_key": "The project's widget API key (used by widget-facing endpoints).",+ "company_id": "Identifier of the company the project belongs to.",+ "space_id": "Identifier of the space the project belongs to.",+ "created_at": "When the project was created.",+ "updated_at": "When the project was last updated.",+ "archived_at": "When the project was archived, if it has been.",+ "owner_id": "Identifier of the user who owns the project.",+ "default_assignee_id": "Identifier of the user new feedback items are assigned to by default.",+ "name": "Display name of the project.",+ "is_live": "Whether the project is live.",+ "feedback_count": "Total number of feedback items in the project.",+ "open_feedback_count": "Number of feedback items still open in the project.",+ },+ },+ "feedbacks": {+ "description": "A feedback item (bug report, rating, or comment) submitted to a project, including its screenshot, labels, and custom data.",+ "docs_url": "https://help.usersnap.com/reference/rest-api",+ "columns": {+ "feedback_id": "Unique identifier of the feedback item.",+ "feedback_number": "Sequential number of the feedback item within its project.",+ "public_link": "Public URL of the feedback item in Usersnap.",+ "project_id": "Identifier of the project the feedback item belongs to.",+ "created_at": "When the feedback item was created.",+ "updated_at": "When the feedback item was last updated.",+ "status_type": "Workflow state of the feedback item (e.g. open, in_progress, done).",+ "priority": "Priority assigned to the feedback item.",+ "assignee_id": "Identifier of the user the feedback item is assigned to.",+ "is_demo": "Whether this is a demo feedback item.",+ "email": "Email address of the person who submitted the feedback.",+ "client": "Client context captured at submission: page URL, browser, OS, screen size, and geolocation.",+ "custom_data": "Custom JSON data attached to the feedback item by the widget.",+ "screenshot": "Annotated screenshot attached to the feedback item, with its comments.",+ "screen_recording": "Screen recording attached to the feedback item.",+ "ordered_inputs": "The form field values submitted with the feedback item, in display order.",+ "labels": "Labels applied to the feedback item.",+ },+ },+ "project_assignees": {+ "description": "Users available as assignees on a project, one row per project/user pair.",+ "docs_url": "https://help.usersnap.com/reference/rest-api",+ "columns": {+ "project_id": "Identifier of the project (added by PostHog during the per-project fan-out).",+ "user_id": "Unique identifier of the user.",+ "first_name": "First name of the user.",+ "last_name": "Last name of the user.",+ "gravatar_url": "URL of the user's Gravatar image.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/settings.pynew file mode 100644index 000000000000..d4493a039b09--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/settings.py@@ -0,0 +1,55 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++USERSNAP_BASE_URL = "https://platform.usersnap.com/v0.1"+# Feedback list pages accept limit 1-100 (default 10).+PAGE_SIZE = 100+++@dataclass+class UsersnapEndpointConfig:+ name: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style+ # field, which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+++# The Usersnap REST API (v0.1) exposes projects and per-project feedback items. Only the+# feedbacks/filter endpoint supports a server-side timestamp filter (`filter_type: created_at`+# with gte), so `feedbacks` is the only incremental table; `updated_at` is orderable but not+# filterable, so changes to existing feedback items are only picked up on a full refresh.+USERSNAP_ENDPOINTS: dict[str, UsersnapEndpointConfig] = {+ "projects": UsersnapEndpointConfig(+ name="projects",+ primary_keys=["project_id"],+ ),+ "feedbacks": UsersnapEndpointConfig(+ name="feedbacks",+ primary_keys=["feedback_id"],+ partition_key="created_at",+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "project_assignees": UsersnapEndpointConfig(+ name="project_assignees",+ # user_id is only unique per project (the same user can be an assignee on many+ # projects), so the fan-out key must include the parent project.+ primary_keys=["project_id", "user_id"],+ ),+}++ENDPOINTS = tuple(USERSNAP_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in USERSNAP_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/source.pyindex a06d153aa402..de9118b203e1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UsersnapSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap import (+ UsersnapResumeConfig,+ usersnap_source,+ validate_credentials as validate_usersnap_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class UsersnapSource(SimpleSource[UsersnapSourceConfig]):+class UsersnapSource(ResumableSource[UsersnapSourceConfig, UsersnapResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.USERSNAP@@ -24,7 +47,114 @@ class UsersnapSource(SimpleSource[UsersnapSourceConfig]):name=SchemaExternalDataSourceType.USERSNAP,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Usersnap",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Usersnap REST API credentials to pull your Usersnap projects and feedback items into the PostHog Data warehouse.++The Usersnap REST API is a gated feature: it must be enabled on your plan by Usersnap (contact their customer success team). Once enabled, generate a JWT secret under **Settings → REST API** in Usersnap and copy both the secret and its JWT ID here — PostHog signs the short-lived bearer tokens for you.""",iconPath="/static/services/usersnap.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/usersnap",+ keywords=["feedback", "bug reporting"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="jwt_secret",+ label="JWT secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="jwt_id",+ label="JWT ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://platform.usersnap.com": "Usersnap authentication failed. Check that the JWT secret and JWT ID match a secret generated under Settings → REST API in Usersnap, then reconnect.",+ "403 Client Error: Forbidden for url: https://platform.usersnap.com": "Usersnap denied access. The REST API is a gated feature — make sure it is enabled on your Usersnap plan.",+ }++ def get_schemas(+ self,+ config: UsersnapSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "feedbacks":+ return (+ "Feedback items across all projects. Incremental syncs pick up newly created "+ "feedback; changes to existing items (status, assignee) are only reflected on a full refresh"+ )+ if endpoint == "project_assignees":+ return "Maps which users are available as assignees on each project"+ return None++ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ # The incremental filter uses gte, which re-pulls the watermark row; only merge+ # dedupes it on the primary key, append would materialize it as a duplicate.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description=_description(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: UsersnapSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_usersnap_credentials(config.jwt_secret, config.jwt_id):+ return True, None++ return (+ False,+ "Invalid Usersnap credentials. Check your JWT secret and JWT ID, and that the REST API is enabled on your Usersnap plan.",+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[UsersnapResumeConfig]:+ return ResumableSourceManager[UsersnapResumeConfig](inputs, UsersnapResumeConfig)++ def source_for_pipeline(+ self,+ config: UsersnapSourceConfig,+ resumable_source_manager: ResumableSourceManager[UsersnapResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return usersnap_source(+ jwt_secret=config.jwt_secret,+ jwt_id=config.jwt_id,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/tests/test_usersnap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/tests/test_usersnap.pynew file mode 100644index 000000000000..ea0532325040--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/tests/test_usersnap.py@@ -0,0 +1,325 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import jwt+import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.settings import (+ ENDPOINTS,+ USERSNAP_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap import (+ JWT_TTL_SECONDS,+ UsersnapResumeConfig,+ _format_datetime,+ get_rows,+ mint_jwt,+ usersnap_source,+ validate_credentials,+)+++def _make_manager(resume_state: UsersnapResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _resp(payload: dict[str, Any]) -> mock.MagicMock:+ response = mock.MagicMock(status_code=200, ok=True)+ response.json.return_value = payload+ return response+++def _resp_404() -> mock.MagicMock:+ response = mock.MagicMock(status_code=404, ok=False, text="not found")+ response.raise_for_status.side_effect = requests.HTTPError(response=response)+ return response+++def _projects_page(projects: list[dict[str, Any]], has_more: bool = False) -> dict[str, Any]:+ return {"status": True, "data": {"has_more": has_more, "count": len(projects), "projects": projects}}+++def _feedbacks_page(+ items: list[dict[str, Any]], has_more: bool = False, next_after: str | None = None+) -> dict[str, Any]:+ data: dict[str, Any] = {"has_more": has_more, "count": len(items), "feedbacks": items}+ if next_after is not None:+ data["next"] = {"after": next_after, "limit": 100}+ return {"status": True, "data": data}+++class TestMintJwt:+ def test_token_uses_hs256_with_kid_header_and_expiry(self):+ token = mint_jwt("shared-secret", "jwt-id-123")++ header = jwt.get_unverified_header(token)+ assert header["alg"] == "HS256"+ assert header["kid"] == "jwt-id-123"++ claims = jwt.decode(token, "shared-secret", algorithms=["HS256"])+ assert claims["exp"] - claims["iat"] == JWT_TTL_SECONDS+++class TestFormatDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05Z"),+ (datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05Z"),+ (date(2026, 1, 2), "2026-01-02T00:00:00Z"),+ ("2026-01-02T03:04:05Z", "2026-01-02T03:04:05Z"),+ ],+ )+ def test_format_datetime_values(self, value, expected):+ assert _format_datetime(value) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ response = mock.MagicMock()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response++ assert validate_credentials("secret", "jwt-id") is expected++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_validate_credentials_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("secret", "jwt-id") is False++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_validate_credentials_disables_http_sample_capture(self, mock_session):+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("secret", "jwt-id")+ assert mock_session.call_args.kwargs["capture"] is False+++class TestGetRows:+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_projects_yields_single_batch(self, mock_session):+ projects = [{"project_id": "p1", "api_key": "k1"}, {"project_id": "p2", "api_key": "k2"}]+ mock_session.return_value.request.return_value = _resp(_projects_page(projects))++ batches = list(get_rows("secret", "jwt-id", "projects", mock.MagicMock(), _make_manager()))++ assert batches == [projects]+ assert mock_session.return_value.request.call_count == 1++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_disables_http_sample_capture(self, mock_session):+ mock_session.return_value.request.return_value = _resp(_projects_page([{"project_id": "p1"}]))+ list(get_rows("secret", "jwt-id", "projects", mock.MagicMock(), _make_manager()))+ assert mock_session.call_args.kwargs["capture"] is False++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_projects_truncation_is_surfaced(self, mock_session):+ mock_session.return_value.request.return_value = _resp(_projects_page([{"project_id": "p1"}], has_more=True))+ logger = mock.MagicMock()++ list(get_rows("secret", "jwt-id", "projects", logger, _make_manager()))++ logger.warning.assert_called_once()++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_feedbacks_paginates_with_after_cursor_and_saves_state_after_yield(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _resp(_projects_page([{"project_id": "p1", "api_key": "k1"}])),+ _resp(_feedbacks_page([{"feedback_id": "f1"}, {"feedback_id": "f2"}], has_more=True, next_after="f2")),+ _resp(_feedbacks_page([{"feedback_id": "f3"}], has_more=False)),+ ]++ manager = _make_manager()+ batches = list(get_rows("secret", "jwt-id", "feedbacks", mock.MagicMock(), manager))++ assert [item["feedback_id"] for batch in batches for item in batch] == ["f1", "f2", "f3"]+ second_page_url = mock_session.return_value.request.call_args_list[2].args[1]+ assert "after=f2" in second_page_url+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == UsersnapResumeConfig(project_id="p1", after="f2")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_feedbacks_falls_back_to_last_item_cursor_when_next_missing(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _resp(_projects_page([{"project_id": "p1", "api_key": "k1"}])),+ _resp(_feedbacks_page([{"feedback_id": "f1"}], has_more=True)),+ _resp(_feedbacks_page([{"feedback_id": "f2"}], has_more=False)),+ ]++ batches = list(get_rows("secret", "jwt-id", "feedbacks", mock.MagicMock(), _make_manager()))++ assert [item["feedback_id"] for batch in batches for item in batch] == ["f1", "f2"]+ assert "after=f1" in mock_session.return_value.request.call_args_list[2].args[1]++ @pytest.mark.parametrize(+ "should_use_incremental_field, last_value, expected_query",+ [+ (+ True,+ datetime(2026, 1, 1, tzinfo=UTC),+ [{"filter_type": "created_at", "operator": "gte", "value": "2026-01-01T00:00:00Z"}],+ ),+ (False, None, None),+ (True, None, None),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_feedbacks_filter_body(self, mock_session, should_use_incremental_field, last_value, expected_query):+ mock_session.return_value.request.side_effect = [+ _resp(_projects_page([{"project_id": "p1", "api_key": "k1"}])),+ _resp(_feedbacks_page([{"feedback_id": "f1"}], has_more=False)),+ ]++ list(+ get_rows(+ "secret",+ "jwt-id",+ "feedbacks",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ )+ )++ body = mock_session.return_value.request.call_args_list[1].kwargs["json"]+ assert body["order_by"] == {"direction": "asc", "order_by_type": "created_at"}+ assert body.get("query") == expected_query++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_feedbacks_fans_out_over_projects_and_bookmarks_the_next_one(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _resp(_projects_page([{"project_id": "p1", "api_key": "k1"}, {"project_id": "p2", "api_key": "k2"}])),+ _resp(_feedbacks_page([{"feedback_id": "f1"}], has_more=False)),+ _resp(_feedbacks_page([{"feedback_id": "f2"}], has_more=False)),+ ]++ manager = _make_manager()+ batches = list(get_rows("secret", "jwt-id", "feedbacks", mock.MagicMock(), manager))++ assert [item["feedback_id"] for batch in batches for item in batch] == ["f1", "f2"]+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == UsersnapResumeConfig(project_id="p2", after=None)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_feedbacks_resumes_from_bookmarked_project_and_cursor(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _resp(_projects_page([{"project_id": "p1", "api_key": "k1"}, {"project_id": "p2", "api_key": "k2"}])),+ _resp(_feedbacks_page([{"feedback_id": "f9"}], has_more=False)),+ ]++ manager = _make_manager(UsersnapResumeConfig(project_id="p2", after="f8"))+ batches = list(get_rows("secret", "jwt-id", "feedbacks", mock.MagicMock(), manager))++ assert [item["feedback_id"] for batch in batches for item in batch] == ["f9"]+ resumed_url = mock_session.return_value.request.call_args_list[1].args[1]+ assert "/projects/p2/feedbacks/filter" in resumed_url+ assert "after=f8" in resumed_url++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_feedbacks_restarts_when_bookmarked_project_no_longer_exists(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _resp(_projects_page([{"project_id": "p1", "api_key": "k1"}])),+ _resp(_feedbacks_page([{"feedback_id": "f1"}], has_more=False)),+ ]++ manager = _make_manager(UsersnapResumeConfig(project_id="gone", after="f8"))+ batches = list(get_rows("secret", "jwt-id", "feedbacks", mock.MagicMock(), manager))++ assert [item["feedback_id"] for batch in batches for item in batch] == ["f1"]+ assert "after=" not in mock_session.return_value.request.call_args_list[1].args[1]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_feedbacks_skips_project_deleted_mid_sync(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _resp(_projects_page([{"project_id": "p1", "api_key": "k1"}, {"project_id": "p2", "api_key": "k2"}])),+ _resp_404(),+ _resp(_feedbacks_page([{"feedback_id": "f2"}], has_more=False)),+ ]++ batches = list(get_rows("secret", "jwt-id", "feedbacks", mock.MagicMock(), _make_manager()))++ assert [item["feedback_id"] for batch in batches for item in batch] == ["f2"]++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap.make_tracked_session"+ )+ def test_assignees_fan_out_rows_carry_project_id(self, mock_session):+ mock_session.return_value.request.side_effect = [+ _resp(_projects_page([{"project_id": "p1", "api_key": "k1"}, {"project_id": "p2", "api_key": "k2"}])),+ _resp({"status": True, "data": {"users": [{"user_id": "u1"}]}}),+ _resp({"status": True, "data": {"users": [{"user_id": "u1"}, {"user_id": "u2"}]}}),+ ]++ batches = list(get_rows("secret", "jwt-id", "project_assignees", mock.MagicMock(), _make_manager()))++ rows = [row for batch in batches for row in batch]+ assert [(row["project_id"], row["user_id"]) for row in rows] == [("p1", "u1"), ("p2", "u1"), ("p2", "u2")]+ # The assignees endpoint is keyed on the project's api_key, not its project_id.+ assert "/projects/k1/assignees" in mock_session.return_value.request.call_args_list[1].args[1]+ assert "/projects/k2/assignees" in mock_session.return_value.request.call_args_list[2].args[1]+++class TestUsersnapSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = USERSNAP_ENDPOINTS[endpoint]+ response = usersnap_source("secret", "jwt-id", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ # The feedbacks fan-out concatenates per-project streams, so it must not checkpoint+ # the incremental watermark per batch.+ assert response.sort_mode == ("desc" if endpoint == "feedbacks" else "asc")+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(USERSNAP_ENDPOINTS.values()))+ def test_partition_keys_are_stable_creation_fields(self, config):+ if config.partition_key:+ assert config.partition_key == "created_at"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/tests/test_usersnap_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/tests/test_usersnap_source.pynew file mode 100644index 000000000000..3268f0030444--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/tests/test_usersnap_source.py@@ -0,0 +1,148 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import UsersnapSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.source import UsersnapSource+from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.usersnap import UsersnapResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestUsersnapSource:+ def setup_method(self):+ self.source = UsersnapSource()+ self.team_id = 123+ self.config = UsersnapSourceConfig(jwt_secret="shared-secret", jwt_id="jwt-id-123")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.USERSNAP++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Usersnap"+ assert config.label == "Usersnap"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/usersnap.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/usersnap"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["jwt_secret", "jwt_id"]++ def test_jwt_secret_field_is_secret_password(self):+ config = self.source.get_source_config+ secret_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "jwt_secret"+ )+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://platform.usersnap.com/v0.1/projects",+ "403 Client Error: Forbidden for url: https://platform.usersnap.com/v0.1/projects/p1/feedbacks/filter?limit=100",+ ],+ )+ 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://platform.usersnap.com/v0.1/projects",+ ],+ )+ 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(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ # Only the feedbacks/filter endpoint exposes a server-side created_at filter.+ assert incremental == {"feedbacks"}+ # The gte filter re-pulls the watermark row, so every table is merge/full-refresh only.+ assert all(schema.supports_append is False for schema in schemas)++ def test_incremental_schema_advertises_created_at(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["feedbacks"].incremental_fields == INCREMENTAL_FIELDS["feedbacks"]+ assert schemas["projects"].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["feedbacks"])+ assert len(schemas) == 1+ assert schemas[0].name == "feedbacks"++ 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(+ "mock_return, expected_valid",+ [+ (True, True),+ (False, False),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.source.validate_usersnap_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert (error_message is None) is expected_valid+ mock_validate.assert_called_once_with(self.config.jwt_secret, self.config.jwt_id)++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is UsersnapResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.source.usersnap_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_usersnap_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "feedbacks"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_usersnap_source.assert_called_once()+ kwargs = mock_usersnap_source.call_args.kwargs+ assert kwargs["jwt_secret"] == "shared-secret"+ assert kwargs["jwt_id"] == "jwt-id-123"+ assert kwargs["endpoint"] == "feedbacks"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.source.usersnap_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_usersnap_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "projects"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_usersnap_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/usersnap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/usersnap.pynew file mode 100644index 000000000000..944d38902953--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/usersnap/usersnap.py@@ -0,0 +1,339 @@+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import jwt+import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.usersnap.settings import (+ PAGE_SIZE,+ USERSNAP_BASE_URL,+ USERSNAP_ENDPOINTS,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# Tokens are minted per request, so the TTL only needs to outlive a single call.+JWT_TTL_SECONDS = 600+++class UsersnapRetryableError(Exception):+ pass+++class UsersnapResumeConfig:+ # The project currently being processed in the feedbacks fan-out. A stable project-ID+ # bookmark (not a positional index) so projects added/removed between a crash and the+ # retry can't resume us into the wrong project.+ project_id: str+ # `after` cursor (a feedback_id) within that project. None means "start the project at+ # its first page".+ after: str | None = None+++def mint_jwt(jwt_secret: str, jwt_id: str) -> str:+ """Mint a short-lived HS256 bearer token for the Usersnap REST API.++ Usersnap verifies tokens with the shared JWT secret and requires the `kid` header to be+ the JWT ID shown alongside it (and explicitly requires HS256, not HS512). The docs don't+ specify required claims, so we keep the payload to the standard iat/exp pair.+ """+ now = int(time.time())+ return jwt.encode(+ {"iat": now, "exp": now + JWT_TTL_SECONDS},+ jwt_secret,+ algorithm="HS256",+ headers={"kid": jwt_id},+ )+++def _get_headers(jwt_secret: str, jwt_id: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {mint_jwt(jwt_secret, jwt_id)}",+ "Accept": "application/json",+ }+++def _format_datetime(value: Any) -> str:+ """Format an incremental cursor value as ISO 8601 with a Z suffix (the format the+ filter examples in Usersnap's API docs use)."""+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def validate_credentials(jwt_secret: str, jwt_id: str) -> bool:+ """Confirm the JWT secret pair is valid. GET /projects is a cheap authenticated probe."""+ try:+ # `capture=False` for the same reason as in `get_rows`: project responses carry+ # user-authored content that the name-based scrubbers can't reliably sanitize.+ response = make_tracked_session(capture=False).get(+ f"{USERSNAP_BASE_URL}/projects",+ headers=_get_headers(jwt_secret, jwt_id),+ timeout=10,+ )+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ retry=retry_if_exception_type(+ (+ UsersnapRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ method: str,+ url: str,+ jwt_secret: str,+ jwt_id: str,+ logger: FilteringBoundLogger,+ json_body: dict[str, Any] | None = None,+) -> dict[str, Any]:+ # Headers are rebuilt per request so long syncs never outlive the minted token.+ response = session.request(+ method,+ url,+ headers=_get_headers(jwt_secret, jwt_id),+ json=json_body,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ # Usersnap doesn't publish rate limits; exponential backoff on 429/5xx is sufficient.+ if response.status_code == 429 or response.status_code >= 500:+ raise UsersnapRetryableError(f"Usersnap API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404 is expected and handled during the per-project fan-out (a project deleted mid-sync).+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Usersnap API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _get_projects(+ session: requests.Session,+ jwt_secret: str,+ jwt_id: str,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ payload = _fetch(session, "GET", f"{USERSNAP_BASE_URL}/projects", jwt_secret, jwt_id, logger)+ data = payload.get("data") or {}+ projects = data.get("projects") or []+ # The spec exposes has_more on the projects list but documents no cursor params for it,+ # so we can't page past the first response. Surface truncation instead of hiding it.+ if data.get("has_more"):+ logger.warning(+ f"Usersnap: /projects returned has_more=true; only the first {len(projects)} projects were fetched"+ )+ return projects+++def _get_feedback_rows(+ session: requests.Session,+ jwt_secret: str,+ jwt_id: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[UsersnapResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every project, paging each project's feedback via the filter endpoint.++ Ordering by created_at ascending plus a server-side `created_at gte` filter gives real+ incremental sync; the filter rides in the POST body on every page, so pagination stays+ windowed and never walks back through history. `gte` re-pulls the watermark row itself,+ which merge dedupes on feedback_id — the table is therefore merge-only (no append).+ """+ body: dict[str, Any] = {"order_by": {"direction": "asc", "order_by_type": "created_at"}}+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ body["query"] = [+ {+ "filter_type": "created_at",+ "operator": "gte",+ "value": _format_datetime(db_incremental_field_last_value),+ }+ ]++ project_ids = [project["project_id"] for project in _get_projects(session, jwt_secret, jwt_id, logger)]++ # Resolve the saved project-ID bookmark to the slice of projects still to process. If the+ # bookmarked project no longer exists, start over from the first project — merge dedupes+ # the re-pulled rows on the primary key. `resume_after` is consumed by the first project only.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = project_ids+ resume_after: str | None = None+ if resume is not None and resume.project_id in project_ids:+ remaining = project_ids[project_ids.index(resume.project_id) :]+ resume_after = resume.after+ logger.debug(f"Usersnap: resuming feedbacks from project_id={resume.project_id}, after={resume_after}")++ for index, project_id in enumerate(remaining):+ after = resume_after+ resume_after = None++ try:+ while True:+ params: dict[str, Any] = {"limit": PAGE_SIZE}+ if after:+ params["after"] = after+ url = f"{USERSNAP_BASE_URL}/projects/{project_id}/feedbacks/filter?{urlencode(params)}"+ payload = _fetch(session, "POST", url, jwt_secret, jwt_id, logger, json_body=body)++ data = payload.get("data") or {}+ items = data.get("feedbacks") or []+ has_more = bool(data.get("has_more"))+ # Prefer the server-provided cursor; fall back to the documented cursor+ # semantics (the feedback_id of the last item on the page).+ next_after = (data.get("next") or {}).get("after") or (items[-1]["feedback_id"] if items else None)++ if items:+ yield items+ # Save AFTER yielding (and only when more pages remain) so a crash+ # re-yields the last page rather than skipping it.+ if has_more and next_after:+ resumable_source_manager.save_state(+ UsersnapResumeConfig(project_id=project_id, after=next_after)+ )++ if not has_more or not next_after:+ break+ after = next_after+ except requests.HTTPError as exc:+ # A project deleted between enumeration and this fetch 404s. Skip it rather than+ # failing the whole sync. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Usersnap: project {project_id} not found while fetching feedbacks, skipping")+ else:+ raise++ # Advance the bookmark to the next project so a crash between projects resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(UsersnapResumeConfig(project_id=remaining[index + 1], after=None))+++def _get_assignee_rows(+ session: requests.Session,+ jwt_secret: str,+ jwt_id: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ # The assignees endpoint is keyed on the project's widget api_key (not project_id), so+ # both come from the projects listing. Rows carry project_id so the fan-out key is unique+ # table-wide and assignee_id on feedbacks can be joined per project.+ for project in _get_projects(session, jwt_secret, jwt_id, logger):+ api_key = project.get("api_key")+ project_id = project.get("project_id")+ if not api_key or not project_id:+ continue+ try:+ payload = _fetch(+ session, "GET", f"{USERSNAP_BASE_URL}/projects/{api_key}/assignees", jwt_secret, jwt_id, logger+ )+ except requests.HTTPError as exc:+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Usersnap: project {project_id} not found while fetching assignees, skipping")+ continue+ raise+ users = (payload.get("data") or {}).get("users") or []+ if users:+ yield [{"project_id": project_id, **user} for user in users]+++def get_rows(+ jwt_secret: str,+ jwt_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[UsersnapResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ # One session reused across every page (and every project in the fan-out) so urllib3+ # keeps the connection alive instead of re-handshaking per request.+ # `capture=False`: feedback responses carry end-user emails, arbitrary submitted/custom+ # text, screenshots, and recording URLs — user-authored content the name-based scrubbers+ # can't reliably sanitize, so we exclude these requests from HTTP sample capture (they're+ # still metered and logged).+ session = make_tracked_session(capture=False)++ if endpoint == "projects":+ projects = _get_projects(session, jwt_secret, jwt_id, logger)+ if projects:+ yield projects+ return++ if endpoint == "project_assignees":+ yield from _get_assignee_rows(session, jwt_secret, jwt_id, logger)+ return++ if endpoint == "feedbacks":+ yield from _get_feedback_rows(+ session,+ jwt_secret,+ jwt_id,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ return++ raise ValueError(f"Unknown Usersnap endpoint: {endpoint}")+++def usersnap_source(+ jwt_secret: str,+ jwt_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[UsersnapResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = USERSNAP_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ jwt_secret=jwt_secret,+ jwt_id=jwt_id,+ 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,+ ),+ primary_keys=config.primary_keys,+ # Feedbacks are ascending within each project but the fan-out concatenates projects,+ # so the stream isn't globally monotonic: desc mode persists the incremental+ # watermark only at successful job end instead of checkpointing per batch.+ sort_mode="desc" if endpoint == "feedbacks" else "asc",+ 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,+ )