: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 fullstory import source (#62947)
Tom Owers1ec3fb37a455
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 49636d19fdd0..2faab42d9676 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -84,6 +84,7 @@ the row lists both.| elasticsearch | HTTP | requests | ✅ || eventbrite | HTTP | requests | ✅ || front | HTTP | requests | ✅ |+| fullstory | HTTP | requests | ✅ || github | HTTP | requests | ✅ || gitlab | HTTP | requests | ✅ || gocardless | HTTP | requests | ✅ |@@ -250,7 +251,6 @@ doesn't conflict with concurrent PRs.- facebook_pages- firebase- freshbooks-- fullstory- gladly- google_ad_manager- google_analyticsdiff --git a/posthog/temporal/data_imports/sources/fullstory/fullstory.py b/posthog/temporal/data_imports/sources/fullstory/fullstory.pynew file mode 100644index 000000000000..80dfc543f30b--- /dev/null+++ b/posthog/temporal/data_imports/sources/fullstory/fullstory.py@@ -0,0 +1,119 @@+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.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++FULLSTORY_BASE_URL = "https://api.fullstory.com"+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5++# Session/event data only exists behind Fullstory's async Data Export jobs;+# the v2 users listing is the one directly listable surface.+ENDPOINTS = ("users",)+++class FullStoryRetryableError(Exception):+ pass+++class FullStoryResumeConfig:+ # v2 listings paginate with an opaque next_page_token.+ next_page_token: str+++def _get_session(api_key: str) -> requests.Session:+ # Fullstory's scheme is the raw API key after "Basic" (not base64 creds).+ return make_tracked_session(headers={"Authorization": f"Basic {api_key}"}, redact_values=(api_key,))+++def validate_credentials(api_key: str) -> bool:+ """Confirm the API key is valid with a cheap one-user listing probe."""+ try:+ response = _get_session(api_key).get(+ f"{FULLSTORY_BASE_URL}/v2/users",+ timeout=10,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FullStoryResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ session = _get_session(api_key)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page_token: Optional[str] = resume_config.next_page_token if resume_config is not None else None+ if page_token is not None:+ logger.debug(f"Fullstory: resuming {endpoint} from page token")++ @retry(+ retry=retry_if_exception_type((FullStoryRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(token: Optional[str]) -> dict[str, Any]:+ url = f"{FULLSTORY_BASE_URL}/v2/{endpoint}"+ if token:+ url = f"{url}?{urlencode({'page_token': token})}"+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise FullStoryRetryableError(f"Fullstory API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Fullstory API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()++ while True:+ data = fetch_page(page_token)+ items = data.get("results", []) or []++ if items:+ yield items++ next_token = data.get("next_page_token")+ if not next_token or not items:+ break++ page_token = next_token+ # Save state AFTER yielding the page so a crash re-yields the last page+ # (merge dedupes on primary key) rather than skipping it.+ resumable_source_manager.save_state(FullStoryResumeConfig(next_page_token=page_token))+++def fullstory_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FullStoryResumeConfig],+) -> SourceResponse:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=["id"],+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/fullstory/source.py b/posthog/temporal/data_imports/sources/fullstory/source.pyindex e50a2cad9d81..545063021347 100644--- a/posthog/temporal/data_imports/sources/fullstory/source.py+++ b/posthog/temporal/data_imports/sources/fullstory/source.py@@ -1,29 +1,113 @@-from typing import cast+from typing import Optional, castfrom 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, ResumableSourcefrom 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.fullstory.fullstory import (+ ENDPOINTS,+ FullStoryResumeConfig,+ fullstory_source,+ validate_credentials as validate_fullstory_credentials,+)from posthog.temporal.data_imports.sources.generated_configs import FullStorySourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class FullStorySource(SimpleSource[FullStorySourceConfig]):+class FullStorySource(ResumableSource[FullStorySourceConfig, FullStoryResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FULLSTORY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.fullstory.com": "Fullstory authentication failed. Please check your API key.",+ "403 Client Error: Forbidden for url: https://api.fullstory.com": "Fullstory denied access. Please check that your API key has the required permissions.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FULL_STORY,- label="FullStory",+ label="Fullstory",+ caption="""Enter your Fullstory API key to pull your Fullstory user data into the PostHog Data warehouse.++You can create an API key in Fullstory under Settings > Integrations & API Keys > API Keys. A key with at least the Viewer permission level is sufficient for syncing.""",iconPath="/static/services/fullstory.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/fullstory",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: FullStorySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # The users listing has no updated-since filter; session/event data+ # only exists behind async Data Export jobs (a follow-up).+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: FullStorySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_fullstory_credentials(config.api_key):+ return True, None++ return False, "Invalid Fullstory API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FullStoryResumeConfig]:+ return ResumableSourceManager[FullStoryResumeConfig](inputs, FullStoryResumeConfig)++ def source_for_pipeline(+ self,+ config: FullStorySourceConfig,+ resumable_source_manager: ResumableSourceManager[FullStoryResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return fullstory_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/fullstory/tests/test_fullstory.py b/posthog/temporal/data_imports/sources/fullstory/tests/test_fullstory.pynew file mode 100644index 000000000000..abf3632db925--- /dev/null+++ b/posthog/temporal/data_imports/sources/fullstory/tests/test_fullstory.py@@ -0,0 +1,117 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.fullstory.fullstory import (+ FullStoryResumeConfig,+ fullstory_source,+ get_rows,+ validate_credentials,+)++_MODULE = "posthog.temporal.data_imports.sources.fullstory.fullstory"+++def _make_manager(resume_state: FullStoryResumeConfig | 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 _response(items: list[dict[str, Any]], next_token: str | None = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ body: dict[str, Any] = {"results": items}+ if next_token:+ body["next_page_token"] = next_token+ resp.json.return_value = body+ resp.status_code = 200+ resp.ok = True+ return resp+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ @mock.patch(f"{_MODULE}.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("key") is expected++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_credentials_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key") is False++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_auth_header_uses_raw_key_after_basic(self, mock_session):+ response = mock.MagicMock()+ response.status_code = 200+ mock_session.return_value.get.return_value = response++ validate_credentials("key123")++ headers = mock_session.call_args.kwargs["headers"]+ assert headers["Authorization"] == "Basic key123"+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_via_page_token(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response([{"id": "u1"}], next_token="tok1"),+ _response([{"id": "u2"}]),+ ]++ manager = _make_manager()+ batches = list(get_rows("key", "users", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["u1", "u2"]+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].next_page_token == "tok1"+ second_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert parse_qs(urlparse(second_url).query)["page_token"] == ["tok1"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_token(self, mock_session):+ mock_session.return_value.get.return_value = _response([])++ manager = _make_manager(FullStoryResumeConfig(next_page_token="tok_resume"))+ list(get_rows("key", "users", mock.MagicMock(), manager))++ url = mock_session.return_value.get.call_args.args[0]+ assert parse_qs(urlparse(url).query)["page_token"] == ["tok_resume"]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_response_stops_without_saving_state(self, mock_session):+ mock_session.return_value.get.return_value = _response([], next_token="tok_loop")++ manager = _make_manager()+ batches = list(get_rows("key", "users", mock.MagicMock(), manager))++ assert batches == []+ assert mock_session.return_value.get.call_count == 1+ manager.save_state.assert_not_called()+++class TestFullStorySourceResponse:+ def test_response_metadata(self):+ response = fullstory_source("key", "users", mock.MagicMock(), _make_manager())++ assert response.name == "users"+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/fullstory/tests/test_fullstory_source.py b/posthog/temporal/data_imports/sources/fullstory/tests/test_fullstory_source.pynew file mode 100644index 000000000000..3ee485376e6d--- /dev/null+++ b/posthog/temporal/data_imports/sources/fullstory/tests/test_fullstory_source.py@@ -0,0 +1,116 @@+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.fullstory.fullstory import ENDPOINTS, FullStoryResumeConfig+from posthog.temporal.data_imports.sources.fullstory.source import FullStorySource+from posthog.temporal.data_imports.sources.generated_configs import FullStorySourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestFullStorySource:+ def setup_method(self):+ self.source = FullStorySource()+ self.team_id = 123+ self.config = FullStorySourceConfig(api_key="api-key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.FULLSTORY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "FullStory"+ assert config.label == "Fullstory"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/fullstory.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.fullstory.com/v2/users",+ "403 Client Error: Forbidden for url: https://api.fullstory.com/v2/users",+ ],+ )+ 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.fullstory.com/v2/users",+ ],+ )+ 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_are_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ assert all(not schema.supports_incremental for schema in schemas)+ assert all(not schema.supports_append for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["users"])+ assert len(schemas) == 1+ assert schemas[0].name == "users"++ 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, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Fullstory API key"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.fullstory.source.validate_fullstory_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ 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 == expected_message+ mock_validate.assert_called_once_with(self.config.api_key)++ 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 FullStoryResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.fullstory.source.fullstory_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_fs_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_fs_source.assert_called_once()+ kwargs = mock_fs_source.call_args.kwargs+ assert kwargs["api_key"] == "api-key"+ assert kwargs["endpoint"] == "users"+ assert kwargs["resumable_source_manager"] is managerdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex f0b30c59e8be..c00b3dc5a785 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -593,7 +593,7 @@ class FrontSourceConfig(config.Config):@config.configclass FullStorySourceConfig(config.Config):- pass+ api_key: str@config.config