: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 thinkific import source (#65638)
Tom Owersca6cdffa61a4
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex ec6b0be069f9..0508332ffdba 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -194,6 +194,7 @@ the row lists both.| taboola | HTTP | requests | ✅ || teamwork | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |+| thinkific | HTTP | requests | ✅ || tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || todoist | HTTP | requests | ✅ || trello | HTTP | requests | ✅ |@@ -653,7 +654,6 @@ doesn't conflict with concurrent PRs.- teamtailor- tempo- testrail-- thinkific- thinkific_courses- thrive_learning- ticketmasterdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 74f37a729b0f..5741b33b04df 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -3093,7 +3093,8 @@ class ThinkificCoursesSourceConfig(config.Config):@config.configclass ThinkificSourceConfig(config.Config):- pass+ api_key: str+ subdomain: str@config.configdiff --git a/posthog/temporal/data_imports/sources/thinkific/canonical_descriptions.py b/posthog/temporal/data_imports/sources/thinkific/canonical_descriptions.pynew file mode 100644index 000000000000..6a2eb741aabb--- /dev/null+++ b/posthog/temporal/data_imports/sources/thinkific/canonical_descriptions.py@@ -0,0 +1,114 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Curated from the Thinkific public Admin API docs (https://developers.thinkific.com/api/api-documentation/).+# Partial coverage is fine - any endpoint/column not described here falls back to LLM enrichment.+_DOCS = "https://developers.thinkific.com/api/api-documentation/"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "courses": {+ "description": "Courses available in your Thinkific school.",+ "docs_url": f"{_DOCS}Courses",+ "columns": {+ "id": "Unique identifier for the course.",+ "name": "Name of the course.",+ "slug": "URL slug used to access the course.",+ "product_id": "Identifier of the product this course belongs to.",+ "instructor_id": "Identifier of the course's primary instructor.",+ },+ },+ "collections": {+ "description": "Course collections (groupings of courses shown on the storefront).",+ "docs_url": f"{_DOCS}Collections",+ "columns": {+ "id": "Unique identifier for the collection.",+ "name": "Name of the collection.",+ "slug": "URL slug for the collection.",+ "course_ids": "Identifiers of the courses contained in this collection.",+ },+ },+ "enrollments": {+ "description": "A user's enrollment in a course, including progress and completion state.",+ "docs_url": f"{_DOCS}Enrollments",+ "columns": {+ "id": "Unique identifier for the enrollment.",+ "user_id": "Identifier of the enrolled user.",+ "user_email": "Email address of the enrolled user.",+ "course_id": "Identifier of the course the user is enrolled in.",+ "course_name": "Name of the course the user is enrolled in.",+ "percentage_completed": "Fraction of the course the user has completed (0.0–1.0).",+ "completed": "Whether the user has completed the course.",+ "is_free_trial": "Whether the enrollment is part of a free trial.",+ "started_at": "Timestamp when the user started the course.",+ "activated_at": "Timestamp when the enrollment became active.",+ "completed_at": "Timestamp when the user completed the course.",+ "expiry_date": "Timestamp when the enrollment expires, if applicable.",+ "created_at": "Timestamp when the enrollment was created.",+ "updated_at": "Timestamp when the enrollment was last updated.",+ },+ },+ "users": {+ "description": "Users (students, instructors, admins) in your Thinkific school.",+ "docs_url": f"{_DOCS}Users",+ "columns": {+ "id": "Unique identifier for the user.",+ "first_name": "User's first name.",+ "last_name": "User's last name.",+ "email": "User's email address.",+ "roles": "Roles assigned to the user (e.g. student, instructor, admin).",+ "created_at": "Timestamp when the user was created.",+ },+ },+ "instructors": {+ "description": "Instructors who can be assigned to courses.",+ "docs_url": f"{_DOCS}Instructors",+ "columns": {+ "id": "Unique identifier for the instructor.",+ "first_name": "Instructor's first name.",+ "last_name": "Instructor's last name.",+ "email": "Instructor's email address.",+ "user_id": "Identifier of the underlying user record.",+ },+ },+ "orders": {+ "description": "Orders placed for products in your Thinkific school.",+ "docs_url": f"{_DOCS}Orders",+ "columns": {+ "id": "Unique identifier for the order.",+ "user_id": "Identifier of the user who placed the order.",+ "user_email": "Email address of the purchasing user.",+ "product_id": "Identifier of the purchased product.",+ "product_name": "Name of the purchased product.",+ "amount_dollars": "Order total in dollars.",+ "status": "Status of the order (e.g. complete, refunded).",+ "created_at": "Timestamp when the order was placed.",+ },+ },+ "products": {+ "description": "Products that can be sold (courses, bundles, memberships).",+ "docs_url": f"{_DOCS}Products",+ "columns": {+ "id": "Unique identifier for the product.",+ "name": "Name of the product.",+ "price": "List price of the product.",+ "productable_type": "Type of object the product wraps (e.g. Course, Bundle).",+ },+ },+ "promotions": {+ "description": "Promotions (discount campaigns) configured in your school.",+ "docs_url": f"{_DOCS}Promotions",+ "columns": {+ "id": "Unique identifier for the promotion.",+ "name": "Name of the promotion.",+ "description": "Description of the promotion.",+ },+ },+ "groups": {+ "description": "Groups used to organize and bulk-enroll users.",+ "docs_url": f"{_DOCS}Groups",+ "columns": {+ "id": "Unique identifier for the group.",+ "name": "Name of the group.",+ "token": "Invite/join token for the group.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/thinkific/settings.py b/posthog/temporal/data_imports/sources/thinkific/settings.pynew file mode 100644index 000000000000..fe1449bd49a3--- /dev/null+++ b/posthog/temporal/data_imports/sources/thinkific/settings.py@@ -0,0 +1,63 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class ThinkificEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Thinkific only exposes server-side date filters (query[updated_*]) on a subset of its list+ # endpoints. When False the endpoint is full refresh regardless of any advertised incremental+ # fields, so we never pretend to filter server-side when the API would silently ignore it.+ supports_incremental: bool = False+ # Stable creation timestamp used for datetime partitioning. Only set where the field is+ # confirmed to exist in the response payload (verified against the Thinkific API docs); leaving+ # it None disables partitioning rather than risk partitioning on an absent column.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Default page size is 25; the API accepts a larger limit. 100 divides evenly into the+ # pipeline's batch thresholds, keeping resume checkpoints on clean page boundaries.+ page_size: int = 100+++_UPDATED_AT_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++# Top-level (account-scoped) list endpoints of the Thinkific public Admin API. Every object carries a+# numeric `id` that is unique within its own collection, so `id` is a safe table-wide primary key+# (these are not fan-out children that aggregate rows across parents).+THINKIFIC_ENDPOINTS: dict[str, ThinkificEndpointConfig] = {+ "courses": ThinkificEndpointConfig(name="courses", path="/courses"),+ "collections": ThinkificEndpointConfig(name="collections", path="/collections"),+ # Enrollments is the one endpoint the API documents server-side date filtering for+ # (query[updated_after] / query[updated_on_or_after] / ...), so it's the only incremental one.+ "enrollments": ThinkificEndpointConfig(+ name="enrollments",+ path="/enrollments",+ supports_incremental=True,+ partition_key="created_at",+ incremental_fields=_UPDATED_AT_INCREMENTAL,+ ),+ "users": ThinkificEndpointConfig(name="users", path="/users", partition_key="created_at"),+ "instructors": ThinkificEndpointConfig(name="instructors", path="/instructors"),+ "orders": ThinkificEndpointConfig(name="orders", path="/orders"),+ "products": ThinkificEndpointConfig(name="products", path="/products"),+ "promotions": ThinkificEndpointConfig(name="promotions", path="/promotions"),+ "groups": ThinkificEndpointConfig(name="groups", path="/groups"),+}++ENDPOINTS = tuple(THINKIFIC_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in THINKIFIC_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/thinkific/source.py b/posthog/temporal/data_imports/sources/thinkific/source.pyindex 8f74a5e5a65f..e79944eca44b 100644--- a/posthog/temporal/data_imports/sources/thinkific/source.py+++ b/posthog/temporal/data_imports/sources/thinkific/source.py@@ -1,20 +1,34 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import ThinkificSourceConfig+from posthog.temporal.data_imports.sources.thinkific.settings import ENDPOINTS, THINKIFIC_ENDPOINTS+from posthog.temporal.data_imports.sources.thinkific.thinkific import (+ ThinkificResumeConfig,+ is_valid_subdomain,+ thinkific_source,+ validate_credentials as validate_thinkific_credentials,+)from products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class ThinkificSource(SimpleSource[ThinkificSourceConfig]):+class ThinkificSource(ResumableSource[ThinkificSourceConfig, ThinkificResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.THINKIFIC@@ -23,9 +37,110 @@ class ThinkificSource(SimpleSource[ThinkificSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.THINKIFIC,- category=DataWarehouseSourceCategory.PRODUCTIVITY,+ category=DataWarehouseSourceCategory.E_COMMERCE,label="Thinkific",+ caption="""Enter your Thinkific API key and account subdomain to pull your Thinkific course, enrollment, and order data into the PostHog Data warehouse.++You can create an API key under **Settings → Code & analytics → API** in your Thinkific admin. The subdomain is the `<subdomain>` part of your `<subdomain>.thinkific.com` admin URL.""",iconPath="/static/services/thinkific.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/thinkific",+ keywords=["lms", "elearning", "e-learning", "courses"],+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="subdomain",+ label="Subdomain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="mycompany",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid/revoked API key or wrong subdomain surfaces as an HTTPError when `_fetch_page`+ # calls `raise_for_status()`. Retrying can never fix a credential problem, so stop the sync.+ "401 Client Error: Unauthorized for url: https://api.thinkific.com": "Your Thinkific API key or subdomain is invalid. Create a new API key in your Thinkific admin (Settings → Code & analytics → API) and confirm the subdomain, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.thinkific.com": "Your Thinkific API key does not have permission to access this data. Check the key in your Thinkific admin, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.thinkific.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: ThinkificSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=THINKIFIC_ENDPOINTS[endpoint].supports_incremental,+ supports_append=THINKIFIC_ENDPOINTS[endpoint].supports_incremental,+ incremental_fields=THINKIFIC_ENDPOINTS[endpoint].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: ThinkificSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not is_valid_subdomain(config.subdomain):+ return False, "Thinkific subdomain is invalid"++ endpoint_path = THINKIFIC_ENDPOINTS[schema_name].path if schema_name in THINKIFIC_ENDPOINTS else "/courses"+ is_valid, status_code = validate_thinkific_credentials(config.api_key, config.subdomain, endpoint_path)+ if is_valid:+ return True, None++ # Accept a 403 at source-create (schema_name is None): the key is genuine but lacks access to+ # the probed endpoint, which is fine when the user only wants to sync endpoints they can read.+ # Per-schema checks (schema_name set) still surface the 403.+ if status_code == 403 and schema_name is None:+ return True, None++ return False, "Invalid Thinkific API key or subdomain"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ThinkificResumeConfig]:+ return ResumableSourceManager[ThinkificResumeConfig](inputs, ThinkificResumeConfig)++ def source_for_pipeline(+ self,+ config: ThinkificSourceConfig,+ resumable_source_manager: ResumableSourceManager[ThinkificResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return thinkific_source(+ api_key=config.api_key,+ subdomain=config.subdomain,+ 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/posthog/temporal/data_imports/sources/thinkific/tests/test_thinkific.py b/posthog/temporal/data_imports/sources/thinkific/tests/test_thinkific.pynew file mode 100644index 000000000000..2097f82ec927--- /dev/null+++ b/posthog/temporal/data_imports/sources/thinkific/tests/test_thinkific.py@@ -0,0 +1,276 @@+from datetime import UTC, date, datetime+from typing import Any++from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.thinkific.settings import THINKIFIC_ENDPOINTS+from posthog.temporal.data_imports.sources.thinkific.thinkific import (+ ThinkificResumeConfig,+ ThinkificRetryableError,+ _build_base_params,+ _fetch_page,+ _format_incremental_date,+ get_rows,+ is_valid_subdomain,+ thinkific_source,+ validate_credentials,+)++PATCH_SESSION = "posthog.temporal.data_imports.sources.thinkific.thinkific.make_tracked_session"+++def _page(items: list[dict[str, Any]], next_page: int | None) -> dict[str, Any]:+ return {"items": items, "meta": {"pagination": {"next_page": next_page}}}+++def _mock_response(body: dict[str, Any], status_code: int = 200) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body+ response.text = str(body)+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError+ return response+++def _drive(endpoint: str, manager: MagicMock, responses: list[MagicMock], **kwargs: Any) -> tuple[MagicMock, list[Any]]:+ """Run get_rows with a mocked session, returning (session, yielded_batches)."""+ session = MagicMock()+ session.get.side_effect = responses+ logger = MagicMock()+ with patch(PATCH_SESSION, return_value=session):+ batches = list(+ get_rows(+ api_key="key",+ subdomain="sub",+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=manager,+ **kwargs,+ )+ )+ return session, batches+++class TestFormatIncrementalDate:+ @parameterized.expand(+ [+ ("aware_datetime", datetime(2026, 3, 4, 23, 58, tzinfo=UTC), "2026-03-04"),+ ("naive_datetime", datetime(2026, 3, 4, 1, 0), "2026-03-04"),+ ("date", date(2026, 3, 4), "2026-03-04"),+ ("iso_string", "2026-03-04T10:00:00Z", "2026-03-04"),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str) -> None:+ assert _format_incremental_date(value) == expected+++class TestBuildBaseParams:+ @parameterized.expand(+ [+ # The server-side filter is added only when all three hold: the endpoint supports it, the+ # incremental flag is on, and a cursor value is present. Any other combination is limit-only.+ (+ "incremental_adds_inclusive_filter",+ True,+ True,+ datetime(2026, 3, 4, tzinfo=UTC),+ {"limit": 100, "query[updated_on_or_after]": "2026-03-04"},+ ),+ ("full_refresh_endpoint_never_filters", False, True, datetime(2026, 3, 4, tzinfo=UTC), {"limit": 100}),+ ("cursor_value_missing", True, True, None, {"limit": 100}),+ ("incremental_flag_off", True, False, datetime(2026, 3, 4, tzinfo=UTC), {"limit": 100}),+ ]+ )+ def test_filter_only_added_when_all_conditions_hold(+ self, _name: str, supports_incremental: bool, should_use: bool, value: Any, expected: dict[str, Any]+ ) -> None:+ assert _build_base_params(100, supports_incremental, should_use, value) == expected+++class TestIsValidSubdomain:+ @parameterized.expand(+ [+ ("simple", "mycompany", True),+ ("hyphenated", "my-company", True),+ ("alnum", "abc123", True),+ ("with_space", "my company", False),+ ("with_dot", "my.company", False),+ ("with_protocol", "https://x", False),+ ("empty", "", False),+ ]+ )+ def test_subdomain(self, _name: str, value: str, expected: bool) -> None:+ assert is_valid_subdomain(value) is expected+++class TestFetchPage:+ # Call the undecorated function so a single status maps straight to its raise, bypassing tenacity's+ # retry/backoff (which would otherwise loop and slow the test).+ _raw = _fetch_page.__wrapped__ # type: ignore[attr-defined]++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("gateway", 503)])+ def test_retryable_status_raises_retryable_error(self, _name: str, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response({}, status_code=status)+ try:+ TestFetchPage._raw(session, "https://x", {}, MagicMock())+ raise AssertionError("expected ThinkificRetryableError")+ except ThinkificRetryableError:+ pass++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_4xx_raises_http_error(self, _name: str, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response({"error": "Authentication Error"}, status_code=status)+ try:+ TestFetchPage._raw(session, "https://x", {}, MagicMock())+ raise AssertionError("expected HTTPError")+ except requests.HTTPError:+ pass++ def test_success_returns_json(self) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(_page([{"id": 1}], None))+ result = TestFetchPage._raw(session, "https://x", {}, MagicMock())+ assert result["items"] == [{"id": 1}]+++class TestGetRowsPagination:+ def test_fresh_run_paginates_and_saves_after_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [+ _mock_response(_page([{"id": 1}], 2)),+ _mock_response(_page([{"id": 2}], 3)),+ _mock_response(_page([{"id": 3}], None)),+ ]+ session, batches = _drive("courses", manager, responses)++ # Each page is yielded as a list[dict] (no source-level batcher).+ assert batches == [[{"id": 1}], [{"id": 2}], [{"id": 3}]]++ # First page request starts at page=1; subsequent requests advance to the saved next_page.+ sent_pages = [call.args[0] for call in session.get.call_args_list]+ assert "page=1" in sent_pages[0]+ assert "page=2" in sent_pages[1]+ assert "page=3" in sent_pages[2]++ # State saved after each non-terminal page; the terminal page saves nothing.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [ThinkificResumeConfig(next_page=2), ThinkificResumeConfig(next_page=3)]++ def test_resume_starts_from_saved_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = ThinkificResumeConfig(next_page=5)+ responses = [_mock_response(_page([{"id": 99}], None))]+ session, batches = _drive("courses", manager, responses)++ assert batches == [[{"id": 99}]]+ assert "page=5" in session.get.call_args_list[0].args[0]+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [_mock_response(_page([{"id": 1}], None))]+ _drive("courses", manager, responses)+ manager.save_state.assert_not_called()++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [_mock_response(_page([], None))]+ _, batches = _drive("courses", manager, responses)+ assert batches == []++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [_mock_response(_page([{"id": 1}], None))]+ _drive("courses", manager, responses)+ manager.load_state.assert_not_called()++ def test_incremental_filter_applied_for_enrollments(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [_mock_response(_page([{"id": 1}], None))]+ session, _ = _drive(+ "enrollments",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ url = session.get.call_args_list[0].args[0]+ assert "updated_on_or_after" in url++ def test_no_incremental_filter_for_full_refresh_endpoint(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ responses = [_mock_response(_page([{"id": 1}], None))]+ session, _ = _drive(+ "courses",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ url = session.get.call_args_list[0].args[0]+ assert "updated_on_or_after" not in url+++class TestThinkificSourceResponse:+ def test_full_refresh_endpoint_has_no_partitioning(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ resp = thinkific_source("k", "s", "courses", MagicMock(), manager)+ assert resp.name == "courses"+ assert resp.primary_keys == ["id"]+ assert resp.partition_mode is None+ assert resp.partition_keys is None+ assert resp.sort_mode == "asc"++ def test_enrollments_partitions_by_created_at(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ resp = thinkific_source("k", "s", "enrollments", MagicMock(), manager)+ assert resp.partition_mode == "datetime"+ assert resp.partition_keys == ["created_at"]+ assert resp.partition_format == "month"++ @parameterized.expand(list(THINKIFIC_ENDPOINTS.keys()))+ def test_every_endpoint_builds_a_response(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ resp = thinkific_source("k", "s", endpoint, MagicMock(), manager)+ assert resp.primary_keys == ["id"]+ assert callable(resp.items)+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True, 200),+ ("unauthorized", 401, False, 401),+ ("forbidden", 403, False, 403),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, expected_valid: bool, expected_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response({}, status_code=status)+ with patch(PATCH_SESSION, return_value=session):+ is_valid, code = validate_credentials("key", "sub")+ assert is_valid is expected_valid+ assert code == expected_code++ def test_exception_returns_none_status(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch(PATCH_SESSION, return_value=session):+ is_valid, code = validate_credentials("key", "sub")+ assert is_valid is False+ assert code is Nonediff --git a/posthog/temporal/data_imports/sources/thinkific/tests/test_thinkific_source.py b/posthog/temporal/data_imports/sources/thinkific/tests/test_thinkific_source.pynew file mode 100644index 000000000000..afb6e29ed099--- /dev/null+++ b/posthog/temporal/data_imports/sources/thinkific/tests/test_thinkific_source.py@@ -0,0 +1,149 @@+from typing import Any, Optional++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import ThinkificSourceConfig+from posthog.temporal.data_imports.sources.thinkific.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.thinkific.source import ThinkificSource+from posthog.temporal.data_imports.sources.thinkific.thinkific import ThinkificResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType++PATCH_VALIDATE = "posthog.temporal.data_imports.sources.thinkific.source.validate_thinkific_credentials"+++def _config(api_key: str = "key", subdomain: str = "mycompany") -> ThinkificSourceConfig:+ return ThinkificSourceConfig(api_key=api_key, subdomain=subdomain)+++def _inputs(schema_name: str = "courses", **overrides: Any) -> MagicMock:+ inputs = MagicMock()+ inputs.schema_name = schema_name+ inputs.team_id = 1+ inputs.job_id = "job"+ inputs.logger = MagicMock()+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)+ inputs.incremental_field = overrides.get("incremental_field", None)+ return inputs+++class TestThinkificSourceConfig:+ def test_source_type(self) -> None:+ assert ThinkificSource().source_type == ExternalDataSourceType.THINKIFIC++ def test_source_config_basics(self) -> None:+ cfg = ThinkificSource().get_source_config+ assert cfg.label == "Thinkific"+ assert cfg.category == DataWarehouseSourceCategory.E_COMMERCE+ assert cfg.releaseStatus == ReleaseStatus.ALPHA+ assert cfg.unreleasedSource is True++ def test_source_config_fields(self) -> None:+ cfg = ThinkificSource().get_source_config+ fields = {f.name: f for f in cfg.fields}+ assert set(fields) == {"api_key", "subdomain"}+ api_key, subdomain = fields["api_key"], fields["subdomain"]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert isinstance(subdomain, SourceFieldInputConfig)+ # The secret must be a password field; the subdomain is a plain text identifier.+ assert api_key.type == "password"+ assert api_key.secret is True+ assert subdomain.type == "text"+ assert subdomain.secret is False++ def test_non_retryable_errors_cover_auth(self) -> None:+ keys = ThinkificSource().get_non_retryable_errors()+ assert any("401" in k for k in keys)+ assert any("403" in k for k in keys)+++class TestThinkificGetSchemas:+ def test_returns_all_endpoints(self) -> None:+ schemas = ThinkificSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_enrollments_is_incremental(self) -> None:+ schemas = {s.name: s for s in ThinkificSource().get_schemas(_config(), team_id=1)}+ assert schemas["enrollments"].supports_incremental is True+ assert schemas["enrollments"].incremental_fields[0]["field"] == "updated_at"+ for name in ("courses", "users", "orders", "products"):+ assert schemas[name].supports_incremental is False++ def test_names_filter(self) -> None:+ schemas = ThinkificSource().get_schemas(_config(), team_id=1, names=["courses", "users"])+ assert {s.name for s in schemas} == {"courses", "users"}+++class TestThinkificValidateCredentials:+ def test_rejects_invalid_subdomain_without_calling_api(self) -> None:+ with patch(PATCH_VALIDATE) as mock_validate:+ ok, err = ThinkificSource().validate_credentials(_config(subdomain="bad domain"), team_id=1)+ assert ok is False+ assert err is not None+ mock_validate.assert_not_called()++ def test_valid_credentials(self) -> None:+ with patch(PATCH_VALIDATE, return_value=(True, 200)):+ ok, err = ThinkificSource().validate_credentials(_config(), team_id=1)+ assert ok is True+ assert err is None++ @parameterized.expand(+ [+ # (status, schema_name, expected_ok) - 403 at source-create (schema None) is accepted, but a+ # per-schema 403 is surfaced as a failure.+ ("forbidden_at_create", 403, None, True),+ ("forbidden_for_schema", 403, "courses", False),+ ("unauthorized_at_create", 401, None, False),+ ]+ )+ def test_status_handling(self, _name: str, status: int, schema_name: Optional[str], expected_ok: bool) -> None:+ with patch(PATCH_VALIDATE, return_value=(False, status)):+ ok, _err = ThinkificSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)+ assert ok is expected_ok+++class TestThinkificPipelinePlumbing:+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = ThinkificSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ThinkificResumeConfig++ def test_source_for_pipeline_passes_incremental_value_only_when_enabled(self) -> None:+ source = ThinkificSource()+ manager = MagicMock(spec=ResumableSourceManager)+ with patch("posthog.temporal.data_imports.sources.thinkific.source.thinkific_source") as mock_source:+ source.source_for_pipeline(+ _config(),+ manager,+ _inputs("enrollments", should_use_incremental_field=True, db_incremental_field_last_value="2026-03-04"),+ )+ kwargs = mock_source.call_args.kwargs+ assert kwargs["endpoint"] == "enrollments"+ assert kwargs["subdomain"] == "mycompany"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-03-04"++ def test_source_for_pipeline_drops_incremental_value_when_disabled(self) -> None:+ source = ThinkificSource()+ manager = MagicMock(spec=ResumableSourceManager)+ with patch("posthog.temporal.data_imports.sources.thinkific.source.thinkific_source") as mock_source:+ source.source_for_pipeline(+ _config(),+ manager,+ _inputs("courses", should_use_incremental_field=False, db_incremental_field_last_value="2026-03-04"),+ )+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestThinkificCanonicalDescriptions:+ def test_keys_are_valid_endpoint_names(self) -> None:+ descriptions = ThinkificSource().get_canonical_descriptions()+ assert descriptions+ assert set(descriptions).issubset(set(ENDPOINTS))diff --git a/posthog/temporal/data_imports/sources/thinkific/thinkific.py b/posthog/temporal/data_imports/sources/thinkific/thinkific.pynew file mode 100644index 000000000000..c7599ab958bf--- /dev/null+++ b/posthog/temporal/data_imports/sources/thinkific/thinkific.py@@ -0,0 +1,199 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+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+from posthog.temporal.data_imports.sources.thinkific.settings import THINKIFIC_ENDPOINTS++THINKIFIC_BASE_URL = "https://api.thinkific.com/api/public/v1"++# Thinkific subdomains are the `<subdomain>.thinkific.com` slug, sent as the X-Auth-Subdomain header.+_SUBDOMAIN_RE = re.compile(r"^[a-zA-Z0-9-]+$")+++class ThinkificRetryableError(Exception):+ pass+++class ThinkificResumeConfig:+ # 1-based page number to fetch next. Thinkific paginates by page number (meta.pagination), so the+ # page index is the only state needed to resume an endpoint mid-sync.+ next_page: int+++def is_valid_subdomain(subdomain: str) -> bool:+ return bool(_SUBDOMAIN_RE.match(subdomain))+++def _get_headers(api_key: str, subdomain: str) -> dict[str, str]:+ return {+ "X-Auth-API-Key": api_key,+ "X-Auth-Subdomain": subdomain,+ "Accept": "application/json",+ }+++def _format_incremental_date(value: Any) -> str:+ """Thinkific's query[updated_*] filters take an ISO 8601 *date* (day granularity), so we reduce+ the stored cursor (a datetime watermark) to its UTC date."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ # Already a string cursor (e.g. an ISO timestamp) - keep the leading date portion.+ return str(value)[:10]+++def _build_base_params(+ page_size: int,+ supports_incremental: bool,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": page_size}++ if supports_incremental and should_use_incremental_field and db_incremental_field_last_value is not None:+ # Inclusive, day-granularity filter on `updated_at`: re-fetch the whole boundary day so+ # updates that landed after the watermark within the same day aren't skipped. Re-pulled rows+ # are deduped by the primary key on merge. We deliberately use `updated_on_or_after` rather+ # than the exclusive `updated_after` to avoid that same-day gap.+ params["query[updated_on_or_after]"] = _format_incremental_date(db_incremental_field_last_value)++ return params+++@retry(+ retry=retry_if_exception_type((ThinkificRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ # allow_redirects=False so a server-side 3xx can never forward the X-Auth-API-Key/Subdomain+ # credential headers to another host. Pagination already targets the fixed THINKIFIC_BASE_URL+ # (by page number, never a response-supplied URL), so legitimate responses are always 2xx.+ response = session.get(url, headers=headers, timeout=60, allow_redirects=False)++ # 429 carries a RateLimit-Reset epoch header; tenacity's exponential backoff is a safe fallback+ # without parsing it. Transient 5xx are likewise retried.+ if response.status_code == 429 or response.status_code >= 500:+ raise ThinkificRetryableError(f"Thinkific API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Thinkific API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ThinkificResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = THINKIFIC_ENDPOINTS[endpoint]+ headers = _get_headers(api_key, subdomain)+ # One session reused across every page so urllib3 keeps the connection alive instead of+ # re-handshaking per request. `redact_values` masks the API key wherever it lands (the+ # X-Auth-API-Key header isn't on the name-based scrub denylist) in logs and sample capture.+ session = make_tracked_session(redact_values=(api_key,))++ base_params = _build_base_params(+ config.page_size,+ config.supports_incremental,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume else 1+ if resume is not None:+ logger.debug(f"Thinkific: resuming {endpoint} from page {page}")++ while True:+ url = f"{THINKIFIC_BASE_URL}{config.path}?{urlencode({**base_params, 'page': page})}"+ data = _fetch_page(session, url, headers, logger)++ # Thinkific wraps every list response as {"items": [...], "meta": {"pagination": {...}}};+ # records carry their fields at the top level (no JSON:API attributes envelope).+ items = data.get("items", [])+ if not items:+ break++ next_page = data.get("meta", {}).get("pagination", {}).get("next_page")++ # Yield the page's rows directly - the pipeline batches/buffers for us, so we don't run our+ # own Batcher here. One yield per page keeps resume checkpoints page-aligned.+ yield items++ if not next_page:+ break++ # Save AFTER yielding the page so a crash re-yields starting at next_page (merge dedupes on+ # the primary key) rather than skipping it.+ resumable_source_manager.save_state(ThinkificResumeConfig(next_page=next_page))+ page = next_page+++def thinkific_source(+ api_key: str,+ subdomain: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ThinkificResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = THINKIFIC_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ subdomain=subdomain,+ 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,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # The public API exposes no sort parameter; list endpoints return id-ascending (≈ creation+ # order). Incremental enrollments sync stays correct regardless of exact ordering because the+ # day-granularity filter is inclusive and merge dedupes on the primary key.+ sort_mode="asc",+ )+++def validate_credentials(api_key: str, subdomain: str, endpoint_path: str = "/courses") -> tuple[bool, int | None]:+ """Cheap probe to confirm the API key + subdomain are genuine. Returns (is_valid, status_code);+ status_code is None when the request never completed."""+ url = f"{THINKIFIC_BASE_URL}{endpoint_path}?{urlencode({'page': 1, 'limit': 1})}"+ try:+ session = make_tracked_session(redact_values=(api_key,))+ response = session.get(url, headers=_get_headers(api_key, subdomain), timeout=10, allow_redirects=False)+ return response.status_code == 200, response.status_code+ except Exception:+ return False, None