Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement thinkific_courses import source (#72626)

Tom Owers58b4ada92e15
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ceb55ad4f5fa..53dcc19c9996 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -549,6 +549,7 @@ the row lists both.
| terraform_cloud | HTTP | requests | ✅ |
| testrail | HTTP | requests | ✅ |
| thinkific | HTTP | requests | ✅ |
+| thinkific_courses | HTTP | requests + `rest_source.RESTClient` | ✅ |
| tickettailor | HTTP | requests | ✅ |
| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| tinyemail | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -968,7 +969,6 @@ doesn't conflict with concurrent PRs.
- telli
- tempo
- terra_api
-- thinkific_courses
- thrive_learning
- ticketmaster
- ticktick
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/thinkificcourses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/thinkificcourses.py
index e68218e788e0..e327b4e3b8e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/thinkificcourses.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/thinkificcourses.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ThinkificCoursesSourceConfig(config.Config):
- pass
+ api_key: str
+ subdomain: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/canonical_descriptions.py
new file mode 100644
index 000000000000..1faf6c6667b3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/canonical_descriptions.py
@@ -0,0 +1,143 @@
+from products.warehouse_sources.backend.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.",
+ },
+ },
+ "course_reviews": {
+ "description": "Reviews students have left on courses, including rating and review text.",
+ "docs_url": f"{_DOCS}Course%20Reviews",
+ "columns": {
+ "id": "Unique identifier for the review.",
+ "course_id": "Identifier of the reviewed course.",
+ "user_id": "Identifier of the user who wrote the review.",
+ "rating": "Star rating the user gave the course.",
+ "title": "Title of the review.",
+ "review_text": "Body text of the review.",
+ "approved": "Whether the review has been approved for display.",
+ "created_at": "Timestamp when the review was created.",
+ },
+ },
+ "coupons": {
+ "description": "Coupon codes belonging to promotions in your school.",
+ "docs_url": f"{_DOCS}Coupons",
+ "columns": {
+ "id": "Unique identifier for the coupon.",
+ "promotion_id": "Identifier of the promotion this coupon belongs to.",
+ "code": "The coupon code users redeem.",
+ "note": "Internal note attached to the coupon.",
+ "quantity": "Total number of times the coupon can be used.",
+ "quantity_used": "Number of times the coupon has been used.",
+ "created_at": "Timestamp when the coupon was created.",
+ },
+ },
+ "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.",
+ },
+ },
+ "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.",
+ },
+ },
+ "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.",
+ },
+ },
+ "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.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/settings.py
new file mode 100644
index 000000000000..9f53d5112dfc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/settings.py
@@ -0,0 +1,98 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class ThinkificCoursesEndpointConfig:
+ name: str
+ path: str
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ # 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
+ # Set for child endpoints that iterate a parent list and query per parent (single-level fan-out).
+ fanout: Optional[DependentEndpointConfig] = None
+
+
+_UPDATED_AT_INCREMENTAL: list[IncrementalField] = [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+# List endpoints of the Thinkific public Admin API (https://api.thinkific.com/api/public/v1). Every
+# top-level object carries a numeric `id` unique within its own collection, so `id` is a safe
+# table-wide primary key there. Fan-out children aggregate rows across parents, so their key
+# includes the parent id — Thinkific doesn't document child ids as globally unique.
+THINKIFIC_COURSES_ENDPOINTS: dict[str, ThinkificCoursesEndpointConfig] = {
+ "courses": ThinkificCoursesEndpointConfig(name="courses", path="/courses"),
+ "collections": ThinkificCoursesEndpointConfig(name="collections", path="/collections"),
+ # The reviews endpoint requires a course_id query param, so it fans out over courses. The
+ # framework only binds resolve params in the path, hence the query string in the path template.
+ "course_reviews": ThinkificCoursesEndpointConfig(
+ name="course_reviews",
+ path="/course_reviews?course_id={course_id}",
+ primary_keys=["course_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="courses",
+ resolve_param="course_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "course_id"},
+ ),
+ ),
+ # Coupons require a promotion_id query param, so they fan out over promotions.
+ "coupons": ThinkificCoursesEndpointConfig(
+ name="coupons",
+ path="/coupons?promotion_id={promotion_id}",
+ primary_keys=["promotion_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="promotions",
+ resolve_param="promotion_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "promotion_id"},
+ ),
+ ),
+ # 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": ThinkificCoursesEndpointConfig(
+ name="enrollments",
+ path="/enrollments",
+ supports_incremental=True,
+ partition_key="created_at",
+ incremental_fields=_UPDATED_AT_INCREMENTAL,
+ default_incremental_field="updated_at",
+ ),
+ "groups": ThinkificCoursesEndpointConfig(name="groups", path="/groups"),
+ "instructors": ThinkificCoursesEndpointConfig(name="instructors", path="/instructors"),
+ "orders": ThinkificCoursesEndpointConfig(name="orders", path="/orders"),
+ "products": ThinkificCoursesEndpointConfig(name="products", path="/products"),
+ "promotions": ThinkificCoursesEndpointConfig(name="promotions", path="/promotions"),
+ "users": ThinkificCoursesEndpointConfig(name="users", path="/users", partition_key="created_at"),
+}
+
+ENDPOINTS = tuple(THINKIFIC_COURSES_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in THINKIFIC_COURSES_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/source.py
index 841d0326a30e..c7d024b5e99a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/source.py
@@ -1,21 +1,50 @@
-from typing import cast
+from typing import Optional, cast
from 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 (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.thinkificcourses import (
ThinkificCoursesSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ THINKIFIC_COURSES_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.thinkific_courses import (
+ ThinkificCoursesResumeConfig,
+ is_valid_subdomain,
+ thinkific_courses_source,
+ validate_credentials as validate_thinkific_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ThinkificCoursesSource(SimpleSource[ThinkificCoursesSourceConfig]):
+class ThinkificCoursesSource(ResumableSource[ThinkificCoursesSourceConfig, ThinkificCoursesResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://developers.thinkific.com/api/api-documentation"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.THINKIFICCOURSES
@@ -24,9 +53,112 @@ class ThinkificCoursesSource(SimpleSource[ThinkificCoursesSourceConfig]):
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.THINKIFIC_COURSES,
- category=DataWarehouseSourceCategory.PRODUCTIVITY,
+ category=DataWarehouseSourceCategory.E_COMMERCE,
label="Thinkific Courses",
+ caption="""Enter your Thinkific API key and account subdomain to pull your Thinkific course, review, 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_courses.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/thinkific-courses",
+ keywords=["lms", "elearning", "e-learning", "courses", "thinkific"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ 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 the client
+ # raises 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 products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.canonical_descriptions import ( # noqa: PLC0415 — lazy import of the sibling catalog, per the canonical-descriptions convention
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ThinkificCoursesSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self, config: ThinkificCoursesSourceConfig, 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 = "/courses"
+ if schema_name in THINKIFIC_COURSES_ENDPOINTS:
+ endpoint_config = THINKIFIC_COURSES_ENDPOINTS[schema_name]
+ # Fan-out endpoints need a parent id in their path, so probe the parent list instead —
+ # access to the parent is what the fan-out sync needs first anyway.
+ endpoint_path = (
+ THINKIFIC_COURSES_ENDPOINTS[endpoint_config.fanout.parent_name].path
+ if endpoint_config.fanout
+ else endpoint_config.path
+ )
+
+ 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[ThinkificCoursesResumeConfig]:
+ return ResumableSourceManager[ThinkificCoursesResumeConfig](inputs, ThinkificCoursesResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ThinkificCoursesSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ThinkificCoursesResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return thinkific_courses_source(
+ api_key=config.api_key,
+ subdomain=config.subdomain,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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/thinkific_courses/tests/test_thinkific_courses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/tests/test_thinkific_courses.py
new file mode 100644
index 000000000000..7306826ebe63
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/tests/test_thinkific_courses.py
@@ -0,0 +1,320 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, Optional, cast
+
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+from requests import HTTPError, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.settings import (
+ THINKIFIC_COURSES_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.thinkific_courses import (
+ THINKIFIC_BASE_URL,
+ ThinkificCoursesResumeConfig,
+ _client_config,
+ _format_incremental_date,
+ thinkific_courses_source,
+ validate_credentials,
+)
+
+# Both the pipeline client (via _client_config) and validate_credentials build their tracked session
+# through make_tracked_session imported into the thinkific_courses module, so patch it there.
+SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.thinkific_courses.make_tracked_session"
+# Retries sleep between attempts; patch the backoff clock so retry paths don't stall the suite.
+SLEEP_PATCH = "tenacity.nap.time.sleep"
+
+
+def _response(items: Optional[list[dict[str, Any]]], total_pages: int = 1) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp.url = f"{THINKIFIC_BASE_URL}/courses"
+ resp._content = json.dumps({"items": items or [], "meta": {"pagination": {"total_pages": total_pages}}}).encode()
+ return resp
+
+
+def _error_response(status: int, reason: str) -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp.reason = reason
+ resp.url = f"{THINKIFIC_BASE_URL}/courses"
+ resp._content = json.dumps({"error": "Authentication Error"}).encode()
+ return resp
+
+
+def _make_manager(resume_state: Optional[ThinkificCoursesResumeConfig] = 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 _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and capture each request's url + params AT SEND TIME.
+
+ ``request.params`` is one dict mutated in place across pages, so inspecting it after the run
+ shows only the final state — snapshot a copy when each request is prepared instead. The
+ prepared mock carries the request's real url so the client's allowed-hosts guard can parse it.
+ """
+ session.headers = {}
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ snapshots.append({"url": request.url, "params": dict(request.params or {})})
+ prepared = mock.MagicMock()
+ prepared.url = request.url
+ return prepared
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return snapshots
+
+
+def _run(
+ endpoint: str,
+ manager: mock.MagicMock,
+ responses: list[Response],
+ **kwargs: Any,
+) -> tuple[mock.MagicMock, list[dict[str, Any]], list[Any]]:
+ """Drive thinkific_courses_source with a mocked client session; return (session, snapshots, pages)."""
+ with mock.patch(SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ snapshots = _wire(session, responses)
+ resp = thinkific_courses_source(
+ "key", "sub", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs
+ )
+ pages = list(cast("Iterable[Any]", resp.items()))
+ return session, snapshots, pages
+
+
+def _rows(pages: list[Any]) -> list[dict[str, Any]]:
+ return [row for page in pages for row in page]
+
+
+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 TestPagination:
+ def test_fresh_run_paginates_and_saves_after_each_non_terminal_page(self) -> None:
+ manager = _make_manager()
+ responses = [
+ _response([{"id": 1}], total_pages=3),
+ _response([{"id": 2}], total_pages=3),
+ _response([{"id": 3}], total_pages=3),
+ ]
+ _session, snapshots, pages = _run("courses", manager, responses)
+
+ assert _rows(pages) == [{"id": 1}, {"id": 2}, {"id": 3}]
+
+ # First request starts at page=1 with the configured limit; later requests advance by page.
+ assert snapshots[0]["params"]["page"] == 1
+ assert snapshots[0]["params"]["limit"] == 100
+ assert snapshots[1]["params"]["page"] == 2
+ assert snapshots[2]["params"]["page"] == 3
+
+ # State saved after each non-terminal page (points at the next page); the last page saves nothing.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ ThinkificCoursesResumeConfig(next_page=2),
+ ThinkificCoursesResumeConfig(next_page=3),
+ ]
+
+ def test_resume_starts_from_saved_page(self) -> None:
+ manager = _make_manager(ThinkificCoursesResumeConfig(next_page=5))
+ _, snapshots, pages = _run("courses", manager, [_response([{"id": 99}], total_pages=5)])
+
+ assert _rows(pages) == [{"id": 99}]
+ assert snapshots[0]["params"]["page"] == 5
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = _make_manager()
+ session, _snapshots, pages = _run("courses", manager, [_response([{"id": 1}], total_pages=1)])
+
+ assert _rows(pages) == [{"id": 1}]
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+
+class TestIncrementalFilter:
+ @parameterized.expand(
+ [
+ # Filter added only when all three hold: endpoint supports it, flag on, cursor present.
+ ("enrollments_all_conditions", "enrollments", True, datetime(2026, 3, 4, tzinfo=UTC), True),
+ ("enrollments_flag_off", "enrollments", False, datetime(2026, 3, 4, tzinfo=UTC), False),
+ ("enrollments_cursor_missing", "enrollments", True, None, False),
+ # Full-refresh endpoints never get the filter, even with flag + cursor set.
+ ("courses_never", "courses", True, datetime(2026, 3, 4, tzinfo=UTC), False),
+ ]
+ )
+ def test_filter_only_when_all_conditions_hold(
+ self, _name: str, endpoint: str, should_use: bool, value: Any, expected_present: bool
+ ) -> None:
+ manager = _make_manager()
+ _, snapshots, _pages = _run(
+ endpoint,
+ manager,
+ [_response([{"id": 1}], total_pages=1)],
+ should_use_incremental_field=should_use,
+ db_incremental_field_last_value=value,
+ )
+ assert ("query[updated_on_or_after]" in snapshots[0]["params"]) is expected_present
+ if expected_present:
+ assert snapshots[0]["params"]["query[updated_on_or_after]"] == "2026-03-04"
+
+
+class TestFanout:
+ def test_child_requests_bound_per_parent_and_rows_carry_parent_id(self) -> None:
+ manager = _make_manager()
+ responses = [
+ _response([{"id": 11}, {"id": 22}], total_pages=1), # parent: courses
+ _response([{"id": 1, "rating": 5}], total_pages=1), # reviews for course 11
+ _response([{"id": 2, "rating": 4}], total_pages=1), # reviews for course 22
+ ]
+ session, snapshots, pages = _run("course_reviews", manager, responses)
+
+ # The parent id resolves into the child's query string (query-param resolve rides in the path).
+ assert snapshots[1]["url"] == f"{THINKIFIC_BASE_URL}/course_reviews?course_id=11"
+ assert snapshots[2]["url"] == f"{THINKIFIC_BASE_URL}/course_reviews?course_id=22"
+ # Child pagination starts fresh per parent and must not be mistaken for a single-entity fetch.
+ assert snapshots[1]["params"]["page"] == 1
+ assert snapshots[2]["params"]["page"] == 1
+
+ # Child rows aggregate across parents and carry the renamed parent id — the composite
+ # primary key (course_id, id) depends on it.
+ assert _rows(pages) == [
+ {"id": 1, "rating": 5, "course_id": 11},
+ {"id": 2, "rating": 4, "course_id": 22},
+ ]
+ assert session.send.call_count == 3
+
+ def test_fanout_resume_skips_completed_parents(self) -> None:
+ manager = _make_manager(
+ ThinkificCoursesResumeConfig(completed=["/course_reviews?course_id=11"], current=None, child_state=None)
+ )
+ responses = [
+ _response([{"id": 11}, {"id": 22}], total_pages=1), # parent: courses
+ _response([{"id": 2, "rating": 4}], total_pages=1), # reviews for course 22 only
+ ]
+ session, snapshots, pages = _run("course_reviews", manager, responses)
+
+ assert _rows(pages) == [{"id": 2, "rating": 4, "course_id": 22}]
+ assert snapshots[1]["url"] == f"{THINKIFIC_BASE_URL}/course_reviews?course_id=22"
+ assert session.send.call_count == 2
+
+ def test_fanout_checkpoints_completed_parents(self) -> None:
+ manager = _make_manager()
+ responses = [
+ _response([{"id": 11}], total_pages=1), # parent: promotions
+ _response([{"id": 7, "code": "SAVE"}], total_pages=1), # coupons for promotion 11
+ ]
+ _session, _snapshots, pages = _run("coupons", manager, responses)
+
+ assert _rows(pages) == [{"id": 7, "code": "SAVE", "promotion_id": 11}]
+ # After the parent's children are fully synced, the checkpoint records it as completed so a
+ # retry skips it instead of re-fetching every parent's children.
+ final_state = manager.save_state.call_args_list[-1].args[0]
+ assert final_state.completed == ["/coupons?promotion_id=11"]
+ assert final_state.current is None
+
+
+class TestErrorHandling:
+ @parameterized.expand([("unauthorized", 401, "Unauthorized"), ("forbidden", 403, "Forbidden")])
+ @mock.patch(SLEEP_PATCH)
+ def test_auth_error_raises_matchable_http_error(self, _name: str, status: int, reason: str, _sleep: Any) -> None:
+ # A 401/403 must surface as an HTTPError whose message carries the status and host, so
+ # get_non_retryable_errors can substring-match it and stop the sync loud.
+ manager = _make_manager()
+ with pytest.raises(HTTPError) as exc:
+ _run("courses", manager, [_error_response(status, reason)])
+ message = str(exc.value)
+ assert f"{status}" in message
+ assert "api.thinkific.com" in message
+
+
+class TestSourceResponse:
+ @parameterized.expand(list(THINKIFIC_COURSES_ENDPOINTS.keys()))
+ def test_every_endpoint_builds_a_response_with_its_declared_keys(self, endpoint: str) -> None:
+ config = THINKIFIC_COURSES_ENDPOINTS[endpoint]
+ manager = _make_manager()
+ resp = thinkific_courses_source("k", "s", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
+ assert resp.name == endpoint
+ assert resp.primary_keys == config.primary_keys
+ assert resp.sort_mode == "asc"
+ assert callable(resp.items)
+
+ @parameterized.expand([("enrollments",), ("users",)])
+ def test_partitioned_endpoint_partitions_by_created_at(self, endpoint: str) -> None:
+ manager = _make_manager()
+ resp = thinkific_courses_source("k", "s", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
+ assert resp.partition_mode == "datetime"
+ assert resp.partition_keys == ["created_at"]
+ assert resp.partition_format == "month"
+
+ def test_fanout_children_use_composite_primary_keys(self) -> None:
+ # Child ids aren't documented as globally unique, so the parent id must stay in the key —
+ # dropping it seeds duplicate rows and every later merge multi-matches them.
+ assert THINKIFIC_COURSES_ENDPOINTS["course_reviews"].primary_keys == ["course_id", "id"]
+ assert THINKIFIC_COURSES_ENDPOINTS["coupons"].primary_keys == ["promotion_id", "id"]
+
+
+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 = mock.MagicMock()
+ session.get.return_value = mock.MagicMock(status_code=status)
+ with mock.patch(SESSION_PATCH, 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 = mock.MagicMock()
+ session.get.side_effect = Exception("boom")
+ with mock.patch(SESSION_PATCH, return_value=session):
+ is_valid, code = validate_credentials("key", "sub")
+ assert is_valid is False
+ assert code is None
+
+ def test_probe_disables_redirects_and_sample_capture_to_protect_customer_data(self) -> None:
+ # The X-Auth-API-Key header rides on the probe, so redirects are pinned off to stop a redirect
+ # replaying the key off-host. A successful /courses probe also returns real customer data
+ # (student names, free-text notes), so capture is off to keep that body out of HTTP sample storage.
+ session = mock.MagicMock()
+ session.get.return_value = mock.MagicMock(status_code=200)
+ with mock.patch(SESSION_PATCH, return_value=session) as make_session:
+ validate_credentials("key", "sub")
+ assert make_session.call_args.kwargs["allow_redirects"] is False
+ assert make_session.call_args.kwargs["capture"] is False
+
+
+class TestPipelineSessionCapture:
+ def test_client_config_disables_sample_capture_and_pins_redirects(self) -> None:
+ # Thinkific rows carry student names/emails and free-text review and coupon notes the name-based
+ # scrubbers can't recognise, so the pipeline session must be built with capture off (bodies stay
+ # out of HTTP sample storage), redirects pinned off (the key can't be replayed off-host), and the
+ # key registered for log redaction.
+ with mock.patch(SESSION_PATCH) as make_session:
+ _client_config("key", "sub")
+ assert make_session.call_args.kwargs["capture"] is False
+ assert make_session.call_args.kwargs["allow_redirects"] is False
+ assert make_session.call_args.kwargs["redact_values"] == ("key",)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/tests/test_thinkific_courses_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/tests/test_thinkific_courses_source.py
new file mode 100644
index 000000000000..26cc90873de1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/tests/test_thinkific_courses_source.py
@@ -0,0 +1,173 @@
+from typing import Any, Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.thinkificcourses import (
+ ThinkificCoursesSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.source import (
+ ThinkificCoursesSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.thinkific_courses import (
+ ThinkificCoursesResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+PATCH_VALIDATE = "products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.source.validate_thinkific_credentials"
+
+
+def _config(api_key: str = "key", subdomain: str = "mycompany") -> ThinkificCoursesSourceConfig:
+ return ThinkificCoursesSourceConfig(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 TestThinkificCoursesSourceConfig:
+ def test_source_type(self) -> None:
+ assert ThinkificCoursesSource().source_type == ExternalDataSourceType.THINKIFICCOURSES
+
+ def test_source_config_is_released_alpha(self) -> None:
+ cfg = ThinkificCoursesSource().get_source_config
+ assert cfg.label == "Thinkific Courses"
+ assert cfg.category == DataWarehouseSourceCategory.E_COMMERCE
+ assert cfg.releaseStatus == ReleaseStatus.ALPHA
+ # unreleasedSource hides the connector from every user; a finished source must not carry it.
+ assert not cfg.unreleasedSource
+
+ def test_source_config_fields(self) -> None:
+ cfg = ThinkificCoursesSource().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 = ThinkificCoursesSource().get_non_retryable_errors()
+ assert any("401" in k for k in keys)
+ assert any("403" in k for k in keys)
+
+
+class TestThinkificCoursesGetSchemas:
+ def test_returns_all_endpoints(self) -> None:
+ schemas = ThinkificCoursesSource().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 ThinkificCoursesSource().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 set(ENDPOINTS) - {"enrollments"}:
+ assert schemas[name].supports_incremental is False
+
+ def test_names_filter(self) -> None:
+ schemas = ThinkificCoursesSource().get_schemas(_config(), team_id=1, names=["courses", "course_reviews"])
+ assert {s.name for s in schemas} == {"courses", "course_reviews"}
+
+
+class TestThinkificCoursesValidateCredentials:
+ def test_rejects_invalid_subdomain_without_calling_api(self) -> None:
+ with patch(PATCH_VALIDATE) as mock_validate:
+ ok, err = ThinkificCoursesSource().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 = ThinkificCoursesSource().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 = ThinkificCoursesSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
+ assert ok is expected_ok
+
+ @parameterized.expand(
+ [
+ # Fan-out schemas can't be probed directly (their path needs a parent id), so the check
+ # must probe the parent list endpoint instead of the templated child path.
+ ("fanout_probes_parent", "course_reviews", "/courses"),
+ ("fanout_probes_promotions_parent", "coupons", "/promotions"),
+ ("top_level_probes_itself", "enrollments", "/enrollments"),
+ ]
+ )
+ def test_schema_probe_path(self, _name: str, schema_name: str, expected_path: str) -> None:
+ with patch(PATCH_VALIDATE, return_value=(True, 200)) as mock_validate:
+ ThinkificCoursesSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
+ assert mock_validate.call_args.args[2] == expected_path
+
+
+class TestThinkificCoursesPipelinePlumbing:
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = ThinkificCoursesSource().get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ThinkificCoursesResumeConfig
+
+ def test_source_for_pipeline_passes_incremental_value_only_when_enabled(self) -> None:
+ source = ThinkificCoursesSource()
+ manager = MagicMock(spec=ResumableSourceManager)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.source.thinkific_courses_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 = ThinkificCoursesSource()
+ manager = MagicMock(spec=ResumableSourceManager)
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.source.thinkific_courses_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 TestThinkificCoursesCanonicalDescriptions:
+ def test_keys_are_valid_endpoint_names(self) -> None:
+ descriptions = ThinkificCoursesSource().get_canonical_descriptions()
+ assert descriptions
+ assert set(descriptions).issubset(set(ENDPOINTS))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/thinkific_courses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/thinkific_courses.py
new file mode 100644
index 000000000000..e662428b10b6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/thinkific_courses/thinkific_courses.py
@@ -0,0 +1,253 @@
+import re
+import dataclasses
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, Optional, cast
+from urllib.parse import urlencode
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.thinkific_courses.settings import (
+ THINKIFIC_COURSES_ENDPOINTS,
+ ThinkificCoursesEndpointConfig,
+)
+
+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 ThinkificCoursesResumeConfig:
+ # Top-level endpoints resume by page number: Thinkific paginates by page (meta.pagination), so
+ # the 1-based next page index is the only state needed.
+ next_page: Optional[int] = None
+ # Fan-out endpoints resume by parent: child paths already fully synced, the path in progress,
+ # and that path's paginator state (see rest_source._make_paginate_dependent_resource).
+ completed: Optional[list[str]] = None
+ current: Optional[str] = None
+ child_state: Optional[dict[str, Any]] = None
+
+
+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 _client_config(api_key: str, subdomain: str) -> ClientConfig:
+ # The API key travels via the framework `auth` config (X-Auth-API-Key) so it's redacted from logs
+ # and error messages; only the non-secret subdomain routing header and Accept go on the session.
+ # `capture=False`: Thinkific responses carry student names/emails and free-text review and coupon
+ # notes the name-based sample scrubbers can't recognise, so keep bodies out of HTTP sample storage
+ # entirely (requests are still metered and logged). `redact_values=(api_key,)` masks the key in
+ # logged URLs; `allow_redirects=False` never replays the X-Auth-API-Key header to a redirect target.
+ session = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False)
+ return {
+ "base_url": THINKIFIC_BASE_URL,
+ "headers": {"X-Auth-Subdomain": subdomain, "Accept": "application/json"},
+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-Auth-API-Key", "location": "header"},
+ "session": session,
+ # Pin every request (and the X-Auth-API-Key header) to the Thinkific host and refuse to
+ # follow a 3xx, so a server-side redirect can never forward the credential headers off-host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ }
+
+
+def _paginator() -> PageNumberPaginator:
+ # Page-number pagination; `meta.pagination.total_pages` is the total PAGE count, so the
+ # paginator stops after the last page without paying an extra empty-page request. The public
+ # API exposes no sort param; list endpoints return id-ascending (≈ creation order).
+ return PageNumberPaginator(base_page=1, page=1, total_path="meta.pagination.total_pages")
+
+
+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 _make_source_response(
+ config: ThinkificCoursesEndpointConfig, items: Any, column_hints: Optional[dict[str, Any]] = None
+) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=items,
+ 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,
+ # 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",
+ column_hints=column_hints,
+ )
+
+
+def _fanout_source(
+ config: ThinkificCoursesEndpointConfig,
+ api_key: str,
+ subdomain: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ThinkificCoursesResumeConfig],
+) -> SourceResponse:
+ assert config.fanout is not None
+
+ initial_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and (resume.completed or resume.current):
+ initial_state = {
+ "completed": resume.completed or [],
+ "current": resume.current,
+ "child_state": resume.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # The fan-out checkpoints after each child page and after each parent completes; saving the
+ # completed-parents list means a retry skips parents already fully synced (merge dedupes any
+ # re-yielded in-progress page).
+ if state is not None:
+ resumable_source_manager.save_state(
+ ThinkificCoursesResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=THINKIFIC_COURSES_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(api_key, subdomain),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ # Explicit paginator/data_selector on both levels: the child path embeds its resolve
+ # placeholder in a query string, which the single-entity heuristic would otherwise
+ # mistake for a fetch-one-record endpoint and stop after a single page.
+ parent_endpoint_extra={"paginator": _paginator(), "data_selector": "items"},
+ child_endpoint_extra={"paginator": _paginator(), "data_selector": "items"},
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ ),
+ )
+ return _make_source_response(config, lambda: dependent_resource)
+
+
+def thinkific_courses_source(
+ api_key: str,
+ subdomain: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ThinkificCoursesResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = THINKIFIC_COURSES_ENDPOINTS[endpoint]
+
+ if config.fanout is not None:
+ return _fanout_source(config, api_key, subdomain, endpoint, team_id, job_id, resumable_source_manager)
+
+ params: dict[str, Any] = {"limit": config.page_size}
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value is not None:
+ # Inclusive, day-granularity server-side 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)
+
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_key, subdomain),
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ # Thinkific wraps every list response as {"items": [...], "meta": {"pagination": {...}}};
+ # records carry their fields at the top level (no attributes envelope). A missing/empty
+ # `items` is a legit zero-row page (paginator stops), so this is not `_required`.
+ "data_selector": "items",
+ "paginator": _paginator(),
+ },
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.next_page is not None:
+ initial_paginator_state = {"page": resume.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields the
+ # last page (merge dedupes on the primary key) rather than skipping it.
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(ThinkificCoursesResumeConfig(next_page=int(state["page"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ # Incremental is expressed as a static server-side filter param above (day granularity), so the
+ # framework doesn't inject its own cursor param.
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return _make_source_response(config, lambda: resource, column_hints=resource.column_hints)
+
+
+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})}"
+ return validate_via_probe(
+ # The X-Auth-API-Key header rides on the probe; pin redirects off on the session so one can't
+ # replay it to a redirect target off the Thinkific host during validation. `capture=False`:
+ # a successful /courses probe response can contain Thinkific customer data (student names,
+ # free-text notes), so keep it out of HTTP sample storage just like the sync path's session.
+ lambda: make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False),
+ url,
+ headers=_get_headers(api_key, subdomain),
+ )
diff --git a/products/warehouse_sources/backend/tests/test_migration_0028.py b/products/warehouse_sources/backend/tests/test_migration_0028.py
index a95b6f279074..a07bc1c35b05 100644
--- a/products/warehouse_sources/backend/tests/test_migration_0028.py
+++ b/products/warehouse_sources/backend/tests/test_migration_0028.py
@@ -1,12 +1,17 @@
from typing import Any
-from posthog.test.base import TestMigrations
+from posthog.test.base import NonAtomicTestMigrations
-class BackfillDirectQueryEnabledMigrationTest(TestMigrations):
+class BackfillDirectQueryEnabledMigrationTest(NonAtomicTestMigrations):
"""0028 defaults every row to True. The backfill must opt existing synced (warehouse) sources out so
the direct-connect capability gate only lights up sources a user explicitly enables; direct sources
keep True.
+
+ NonAtomic: setUp's MigrationExecutor spends minutes CPU-bound building migration project state.
+ Under the atomic TestCase wrapper the connection sits idle in transaction for that whole stretch,
+ tripping the CI/dev Postgres idle_in_transaction_session_timeout (300s), which kills the session
+ mid-test with "the connection is closed".
"""
migrate_from = "0028_externaldatasource_direct_query_enabled"