: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 teachable import source (#72643)
Tom Owersafbdc872e5e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e4c95be13019..928eda0f9fb5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -534,6 +534,7 @@ the row lists both.| tailscale | HTTP | requests | ✅ || tavus | HTTP | requests | ✅ || tawk_to | HTTP | requests | ✅ |+| teachable | HTTP | requests + `rest_source.RESTClient` | ✅ || teamcity | HTTP | requests | ✅ || teamtailor | HTTP | requests | ✅ || teamwork | HTTP | requests | ✅ |@@ -961,7 +962,6 @@ doesn't conflict with concurrent PRs.- swonkie- synthesia- systeme-- teachable- telli- tempo- terra_apidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/teachable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/teachable.pyindex c20027ec772b..a4d46d595573 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/teachable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/teachable.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass TeachableSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/canonical_descriptions.pynew file mode 100644index 000000000000..c0f7572a5d96--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/canonical_descriptions.py@@ -0,0 +1,79 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "users": {+ "description": "A user account at your Teachable school (students, authors, and owners).",+ "docs_url": "https://docs.teachable.com/reference/listusers",+ "columns": {+ "id": "Unique identifier for the user.",+ "name": "The user's full name.",+ "email": "The user's email address.",+ },+ },+ "courses": {+ "description": "A course at your Teachable school.",+ "docs_url": "https://docs.teachable.com/reference/listcourses",+ "columns": {+ "id": "Unique identifier for the course.",+ "name": "The course name.",+ "heading": "The course subtitle, from the Information tab of the course admin.",+ "description": "Text from the Course Description block of the course sales page.",+ "is_published": "Whether the course is published and visible to students.",+ "image_url": "URL of the course image from the Information tab.",+ },+ },+ "course_enrollments": {+ "description": "A student's enrollment in a course, including completion progress.",+ "docs_url": "https://docs.teachable.com/reference/showcourseenrollments",+ "columns": {+ "course_id": "Unique identifier of the course the student is enrolled in.",+ "user_id": "Unique identifier of the enrolled student.",+ "enrolled_at": "When the student enrolled in the course, in ISO8601 format.",+ "expires_at": "When the enrollment expires, or null if it never expires.",+ "completed_at": "When the student completed the course, or null if not yet finished.",+ "percent_complete": "Percentage of the course the student has marked complete.",+ },+ },+ "transactions": {+ "description": "A sales transaction made in your school. Several transactions may belong to a single sale.",+ "docs_url": "https://docs.teachable.com/reference/listtransactions",+ "columns": {+ "id": "Unique identifier for the transaction.",+ "sale_id": "Identifier of the sale this transaction belongs to.",+ "user_id": "Unique identifier of the purchasing user.",+ "pricing_plan_id": "Identifier of the pricing plan the purchase was made under.",+ "created_at": "When the transaction was created, in ISO8601 format.",+ "purchased_at": "The purchase date, which can differ from the creation date for recurring pricing plans.",+ "charge": "Total amount the user paid, calculated in USD by default.",+ "final_price": "The listed price in the currency of choice, excluding fees and taxes.",+ "currency": "Currency of the transaction, in ISO4217 alphabetic code.",+ "tax_charge": "Taxes charged, in the currency of choice.",+ "revenue": "Total amount collected, calculated in USD by default.",+ "status": "Payment status: 'paid', or null when unpaid.",+ "has_chargeback": "Whether a chargeback flagged the transaction as fraudulent.",+ "chargeback_fee": "Fee charged for a chargeback, if any.",+ "affiliate_id": "Identifier of the affiliate credited for the sale, if any.",+ "affiliate_fees": "Fees paid to the affiliate.",+ "author_id": "Identifier of the course author credited for the sale, if any.",+ "author_fees": "Fees paid to the course author.",+ "coupon_id": "Identifier of the coupon applied to the purchase, if any.",+ "refunded_at": "When the transaction was refunded, or null if not refunded.",+ "amount_refunded": "Amount refunded to the user.",+ },+ },+ "pricing_plans": {+ "description": "A pricing plan for a course at your school.",+ "docs_url": "https://docs.teachable.com/reference/listpricingplans",+ "columns": {+ "id": "Unique identifier for the pricing plan.",+ "created_at": "When the pricing plan was created, in ISO8601 format.",+ "updated_at": "When the pricing plan was last updated, in ISO8601 format.",+ "name": "The pricing plan name.",+ "price": "Price as a positive integer in the smallest currency unit (e.g. 100 cents = $1.00 USD).",+ "currency": "Currency of the plan, in ISO4217 alphabetic code.",+ "course_id": "Identifier of the course this pricing plan belongs to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/settings.pynew file mode 100644index 000000000000..2bc6d1639a50--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/settings.py@@ -0,0 +1,96 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++TEACHABLE_BASE_URL = "https://developers.teachable.com"++# Teachable documents a 20-row default page size (5 for /pricing_plans). We request more via+# `per`; if the server clamps it, pagination still terminates correctly because the paginators+# stop on `meta.number_of_pages` / `meta.has_more_results` / an empty page, never on the+# requested page size.+DEFAULT_PAGE_SIZE = 100++# Teachable notes new transactions can take up to two minutes to appear via the API, and the+# `start` filter is exclusive of the given instant — re-read a trailing window on each+# incremental sync so late-arriving boundary rows aren't skipped (the merge dedupes on `id`).+TRANSACTIONS_INCREMENTAL_LOOKBACK_SECONDS = 300+++@dataclass+class TeachableEndpointConfig:+ name: str+ path: str+ data_selector: str+ primary_key: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ partition_key: str | None = None+ page_size: int = DEFAULT_PAGE_SIZE+ fanout: DependentEndpointConfig | None = None+++TEACHABLE_ENDPOINTS: dict[str, TeachableEndpointConfig] = {+ "users": TeachableEndpointConfig(+ name="users",+ path="/v1/users",+ data_selector="users",+ primary_key=["id"],+ # The list response only carries id/name/email — no timestamp to filter or partition+ # on, so full refresh with no partitioning.+ ),+ "courses": TeachableEndpointConfig(+ name="courses",+ path="/v1/courses",+ data_selector="courses",+ primary_key=["id"],+ # Course rows have no timestamp field and no server-side change filter — full refresh.+ ),+ "course_enrollments": TeachableEndpointConfig(+ name="course_enrollments",+ path="/v1/courses/{course_id}/enrollments",+ data_selector="enrollments",+ # user_id is only unique within a course, and this table aggregates enrollments across+ # every course, so the parent course id is part of the key to keep it unique table-wide.+ primary_key=["course_id", "user_id"],+ # enrolled_at never changes once a user is enrolled (unlike percent_complete /+ # completed_at, which move as the student progresses).+ partition_key="enrolled_at",+ # Full refresh only: the API does offer a server-side `enrolled_in_after` filter, but+ # enrollment rows mutate (percent_complete, completed_at), so an enrolled_at cursor+ # would freeze progress fields on already-synced rows.+ fanout=DependentEndpointConfig(+ parent_name="courses",+ resolve_param="course_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "course_id"},+ ),+ ),+ "transactions": TeachableEndpointConfig(+ name="transactions",+ path="/v1/transactions",+ data_selector="transactions",+ primary_key=["id"],+ incremental_fields=[incremental_field("created_at")],+ default_incremental_field="created_at",+ partition_key="created_at",+ ),+ "pricing_plans": TeachableEndpointConfig(+ name="pricing_plans",+ path="/v1/pricing_plans",+ data_selector="pricing_plans",+ primary_key=["id"],+ partition_key="created_at",+ # No server-side updated-since filter, so full refresh (the table is small).+ ),+}++ENDPOINTS = tuple(TEACHABLE_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in TEACHABLE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/source.pyindex 8a5bd7d26758..43716e813d03 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/source.py@@ -1,33 +1,138 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.teachable import (TeachableSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.teachable.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ TRANSACTIONS_INCREMENTAL_LOOKBACK_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.teachable.teachable import (+ TeachableResumeConfig,+ teachable_source,+ validate_credentials as validate_teachable_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TeachableSource(SimpleSource[TeachableSourceConfig]):+class TeachableSource(ResumableSource[TeachableSourceConfig, TeachableResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Teachable's API only exposes an unversioned `/v1/` path with no documented version+ # choice, so we leave the framework's unversioned default in place.+ api_docs_url = "https://docs.teachable.com/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TEACHABLE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Invalid Teachable API key. Please create a new key in your school admin under Settings > API and reconnect.",+ "403 Client Error: Forbidden for url": "Teachable rejected the API key. Check that the key is active and that your school is on the Growth plan or higher (required for API access).",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.teachable.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: TeachableSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ for schema in schemas:+ if schema.name == "transactions":+ # New transactions can take up to two minutes to appear via the API, and the+ # `start` filter is exclusive — re-read a trailing window each incremental sync.+ schema.default_incremental_lookback_seconds = TRANSACTIONS_INCREMENTAL_LOOKBACK_SECONDS+ return schemas++ def validate_credentials(+ self, config: TeachableSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_teachable_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TeachableResumeConfig]:+ return ResumableSourceManager[TeachableResumeConfig](inputs, TeachableResumeConfig)++ def source_for_pipeline(+ self,+ config: TeachableSourceConfig,+ resumable_source_manager: ResumableSourceManager[TeachableResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return teachable_source(+ api_key=config.api_key,+ 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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TEACHABLE,category=DataWarehouseSourceCategory.E_COMMERCE,label="Teachable",+ caption=(+ "Import users, courses, enrollments, sales transactions, and pricing plans from "+ "your Teachable school.\n\n"+ "Create an API key in your Teachable admin under Settings > API. "+ "The Teachable API requires a school on the Growth plan or higher."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/teachable",iconPath="/static/services/teachable.png",keywords=["lms", "courses", "e-learning"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/teachable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/teachable.pynew file mode 100644index 000000000000..5266cfc4ec41--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/teachable.py@@ -0,0 +1,325 @@+import dataclasses+from collections.abc import Callable, Iterable+from typing import Any, Optional, cast++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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 (+ BasePaginator,+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.teachable.settings import (+ TEACHABLE_BASE_URL,+ TEACHABLE_ENDPOINTS,+ TeachableEndpointConfig,+)+++class TeachableResumeConfig:+ """Paginator checkpoint: `page` for page-numbered endpoints, `search_after` for /users."""++ page: Optional[int] = None+ search_after: Optional[int] = None+++def _format_teachable_datetime(value: Any) -> str:+ """Format the incremental watermark for Teachable's `start` filter.++ Truncates to whole seconds, which rounds the lower bound *down* — combined with+ `start` being exclusive, a sync re-fetches at most a few boundary rows (the merge+ dedupes them) rather than skipping any.+ """+ normalized_value = coerce_datetime_to_utc(value)+ if normalized_value is None:+ return str(value)+ return normalized_value.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _teachable_incremental_window(cursor_path: str) -> IncrementalConfig:+ # `start` is a server-side time filter on /transactions, exclusive of the given instant.+ return {+ "cursor_path": cursor_path,+ "start_param": "start",+ "initial_value": "1970-01-01T00:00:00Z",+ "convert": _format_teachable_datetime,+ }+++def _rest_api_client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": TEACHABLE_BASE_URL,+ "auth": {"type": "api_key", "name": "apiKey", "api_key": api_key, "location": "header"},+ "headers": {"Accept": "application/json"},+ # Pin every request (and the apiKey header) to the Teachable host and refuse to follow a+ # 3xx, so a server-side redirect can never replay the credential header off-host.+ "allowed_hosts": [],+ "allow_redirects": False,+ }+++def _page_paginator() -> PageNumberPaginator:+ # Teachable pages are 1-based; `meta.number_of_pages` reports the total page count, so+ # pagination stops after the last page without paying an extra empty-page request.+ return PageNumberPaginator(base_page=1, page_param="page", total_path="meta.number_of_pages")+++class TeachableUsersPaginator(BasePaginator):+ """Cursor paginator for `/v1/users` using `search_after`.++ Plain `page` pagination stops working past the 10,000th user, so we walk the id-sorted+ list with `search_after` (the last user id of the previous page) from the start.+ Termination: `meta.has_more_results` when the API returns it, otherwise an empty page.+ A short page alone is only terminal when it's shorter than the server-reported+ `meta.per_page` — the server may clamp our requested `per`.+ """++ def __init__(self, per: int) -> None:+ super().__init__()+ self.per = per+ self._search_after: Optional[int] = None++ def _apply_params(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["per"] = self.per+ if self._search_after is not None:+ request.params["search_after"] = self._search_after++ def init_request(self, request: Request) -> None:+ self._apply_params(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ if not data:+ self._has_next_page = False+ return++ meta: dict[str, Any] = {}+ try:+ body = response.json()+ if isinstance(body, dict) and isinstance(body.get("meta"), dict):+ meta = body["meta"]+ except Exception:+ meta = {}++ # Prefer the server-provided next cursor; fall back to the last row's id.+ next_cursor: Optional[int] = None+ meta_search_after = meta.get("search_after")+ if isinstance(meta_search_after, list) and meta_search_after and isinstance(meta_search_after[0], int):+ next_cursor = meta_search_after[0]+ else:+ last_row = data[-1]+ if isinstance(last_row, dict) and isinstance(last_row.get("id"), int):+ next_cursor = last_row["id"]++ if next_cursor is None:+ self._has_next_page = False+ return+ self._search_after = next_cursor++ has_more = meta.get("has_more_results")+ if has_more is False:+ self._has_next_page = False+ return+ if has_more is None:+ per_page = meta.get("per_page")+ effective_per = per_page if isinstance(per_page, int) else self.per+ if len(data) < effective_per:+ self._has_next_page = False+ return++ self._has_next_page = True++ def update_request(self, request: Request) -> None:+ self._apply_params(request)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._has_next_page and self._search_after is not None:+ return {"search_after": self._search_after}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ search_after = state.get("search_after")+ if search_after is not None:+ self._search_after = int(search_after)+ self._has_next_page = True+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ response = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(+ f"{TEACHABLE_BASE_URL}/v1/courses",+ headers={"apiKey": api_key, "Accept": "application/json"},+ params={"per": 1},+ timeout=10,+ )+ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Teachable API key"+ if response.status_code == 403:+ return (+ False,+ "Teachable rejected the API key. Check that the key is active and that your school "+ "is on the Growth plan or higher (required for API access).",+ )+ return False, f"Teachable API returned an unexpected status code: {response.status_code}"+++def get_resource(+ endpoint: str,+ should_use_incremental_field: bool,+ incremental_field_name: str | None = None,+) -> EndpointResource:+ config = TEACHABLE_ENDPOINTS[endpoint]+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": {"per": config.page_size} if endpoint != "users" else {},+ "data_selector": config.data_selector,+ # The wrapper key is documented as required, so a response without it means the API+ # shape changed — fail loud rather than silently syncing 0 rows.+ "data_selector_required": True,+ "paginator": TeachableUsersPaginator(per=config.page_size) if endpoint == "users" else _page_paginator(),+ }++ use_incremental = should_use_incremental_field and bool(config.incremental_fields)+ if use_incremental:+ endpoint_config["incremental"] = _teachable_incremental_window(+ incremental_field_name or config.default_incremental_field or "created_at"+ )++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _make_source_response(+ endpoint_config: TeachableEndpointConfig,+ items_fn: Callable[[], Iterable[Any]],+ sort_mode: SortMode = "asc",+) -> SourceResponse:+ return SourceResponse(+ name=endpoint_config.name,+ items=items_fn,+ primary_keys=endpoint_config.primary_key,+ sort_mode=sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def teachable_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: Optional[ResumableSourceManager[TeachableResumeConfig]] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = TEACHABLE_ENDPOINTS[endpoint]++ if endpoint_config.fanout:+ # Dependent resources don't currently support resume in the rest_source framework;+ # the manager is intentionally not threaded into this path.+ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=TEACHABLE_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=endpoint_config.fanout,+ client_config=_rest_api_client_config(api_key),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field=incremental_field,+ incremental_config_factory=_teachable_incremental_window,+ page_size_param="per",+ parent_endpoint_extra={+ "paginator": _page_paginator(),+ "data_selector": TEACHABLE_ENDPOINTS[endpoint_config.fanout.parent_name].data_selector,+ },+ child_endpoint_extra={+ "paginator": _page_paginator(),+ "data_selector": endpoint_config.data_selector,+ },+ # Enrollments are sorted by enrolled_at; pin the direction so page boundaries+ # stay stable while rows are inserted mid-sync.+ child_params_extra={"sort_direction": "asc"},+ ),+ )+ return _make_source_response(endpoint_config, lambda: dependent_resource)++ config: RESTAPIConfig = {+ "client": _rest_api_client_config(api_key),+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None+ if resumable_source_manager is not None:+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ if resume_config.search_after is not None:+ initial_paginator_state = {"search_after": resume_config.search_after}+ elif resume_config.page is not None:+ initial_paginator_state = {"page": resume_config.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while there is another page to resume to; the Redis TTL cleans up+ # on completion.+ if resumable_source_manager is None or not state:+ return+ if state.get("page") is not None or state.get("search_after") is not None:+ resumable_source_manager.save_state(+ TeachableResumeConfig(page=state.get("page"), search_after=state.get("search_after"))+ )++ resume_hook = save_checkpoint++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=resume_hook,+ initial_paginator_state=initial_paginator_state,+ )++ # Teachable doesn't document /transactions ordering, so incremental syncs run with desc+ # semantics: the watermark is committed only once the sync completes, never mid-run.+ sort_mode: SortMode = "desc" if (should_use_incremental_field and endpoint_config.incremental_fields) else "asc"+ return _make_source_response(endpoint_config, lambda: resource, sort_mode=sort_mode)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/tests/test_teachable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/tests/test_teachable.pynew file mode 100644index 000000000000..fa2239c49ef9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/tests/test_teachable.py@@ -0,0 +1,281 @@+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, Mock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.teachable.teachable import (+ TeachableResumeConfig,+ TeachableUsersPaginator,+ _format_teachable_datetime,+ _rest_api_client_config,+ get_resource,+ teachable_source,+ validate_credentials,+)+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++def _users_response(meta: dict[str, Any]) -> Mock:+ response = Mock()+ response.json.return_value = {"users": [], "meta": meta}+ return response+++class TestTeachableTransport:+ @parameterized.expand(+ [+ # has_more_results=True from a search_after response — keep paging.+ ("has_more", {"per_page": 2, "has_more_results": True, "search_after": [20]}, 2, True),+ # has_more_results=False — stop even on a full page.+ ("no_more", {"per_page": 2, "has_more_results": False, "search_after": [20]}, 2, False),+ # Page-mode meta (no has_more_results): a page matching the server's per_page keeps going,+ # even when the server clamped our requested `per` below what we asked for.+ ("server_clamped_full_page", {"per_page": 2, "number_of_pages": 5}, 2, True),+ # Page-mode meta: a page shorter than the server's per_page is terminal.+ ("short_page", {"per_page": 2, "number_of_pages": 1}, 1, False),+ ]+ )+ def test_users_paginator_termination(self, _name, meta, row_count, expected_has_next) -> None:+ paginator = TeachableUsersPaginator(per=100)+ data = [{"id": i + 1, "name": "u", "email": "[email protected]"} for i in range(row_count)]+ paginator.update_state(_users_response(meta), data=data)+ assert paginator.has_next_page is expected_has_next++ def test_users_paginator_empty_page_is_terminal(self) -> None:+ paginator = TeachableUsersPaginator(per=100)+ paginator.update_state(_users_response({"per_page": 100}), data=[])+ assert paginator.has_next_page is False++ def test_users_paginator_advances_search_after_cursor(self) -> None:+ paginator = TeachableUsersPaginator(per=100)+ request = Mock()+ request.params = None+ paginator.init_request(request)+ assert request.params == {"per": 100}++ # No meta cursor — fall back to the last row's id.+ data = [{"id": 5}, {"id": 9}]+ paginator.update_state(_users_response({"per_page": 2}), data=data)+ paginator.update_request(request)+ assert request.params["search_after"] == 9++ # A server-provided meta cursor takes precedence over the last row id.+ paginator.update_state(+ _users_response({"per_page": 2, "has_more_results": True, "search_after": [42]}),+ data=[{"id": 30}, {"id": 41}],+ )+ paginator.update_request(request)+ assert request.params["search_after"] == 42++ def test_users_paginator_resume_state_round_trip(self) -> None:+ paginator = TeachableUsersPaginator(per=100)+ paginator.update_state(+ _users_response({"per_page": 1, "has_more_results": True, "search_after": [77]}),+ data=[{"id": 77}],+ )+ state = paginator.get_resume_state()+ assert state == {"search_after": 77}++ resumed = TeachableUsersPaginator(per=100)+ resumed.set_resume_state(cast(dict[str, Any], state))+ request = Mock()+ request.params = None+ resumed.init_request(request)+ assert request.params["search_after"] == 77++ @parameterized.expand(+ [+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "2026-03-01T12:30:45Z"),+ ("aware_datetime", datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC), "2026-03-01T12:30:45Z"),+ ("passthrough_string", "1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z"),+ ]+ )+ def test_format_teachable_datetime(self, _name, value, expected) -> None:+ assert _format_teachable_datetime(value) == expected++ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Invalid Teachable API key"),+ (403, False, "Growth plan"),+ (500, False, "unexpected status code"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.teachable.teachable.make_tracked_session")+ def test_validate_credentials_status_mapping(self, status, expected_valid, message_fragment, mock_session) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status)++ is_valid, message = validate_credentials("teachable-key")++ assert is_valid is expected_valid+ if message_fragment is None:+ assert message is None+ else:+ assert message is not None and message_fragment in message++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://developers.teachable.com/v1/courses"+ assert call.kwargs["headers"]["apiKey"] == "teachable-key"+ # The validation session must refuse redirects so a 3xx can't replay the apiKey off-host.+ assert mock_session.call_args.kwargs["allow_redirects"] is False++ def test_rest_client_config_pins_host_and_blocks_redirects(self) -> None:+ # A redirect off the Teachable host would otherwise replay the apiKey credential header.+ config = _rest_api_client_config("teachable-key")+ assert config["allowed_hosts"] == []+ assert config["allow_redirects"] is False++ def test_get_resource_transactions_incremental(self) -> None:+ resource = cast(dict[str, Any], get_resource("transactions", should_use_incremental_field=True))+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ incremental = resource["endpoint"]["incremental"]+ assert incremental["start_param"] == "start"+ assert incremental["cursor_path"] == "created_at"+ assert resource["endpoint"]["data_selector"] == "transactions"++ def test_get_resource_transactions_full_refresh(self) -> None:+ resource = cast(dict[str, Any], get_resource("transactions", should_use_incremental_field=False))+ assert resource["write_disposition"] == "replace"+ assert "incremental" not in resource["endpoint"]++ def test_get_resource_users_uses_search_after_paginator(self) -> None:+ resource = cast(dict[str, Any], get_resource("users", should_use_incremental_field=False))+ assert isinstance(resource["endpoint"]["paginator"], TeachableUsersPaginator)++ def test_get_resource_page_paginator_stops_on_number_of_pages(self) -> None:+ resource = cast(dict[str, Any], get_resource("courses", should_use_incremental_field=False))+ paginator = resource["endpoint"]["paginator"]+ assert isinstance(paginator, PageNumberPaginator)++ response = Mock()+ response.json.return_value = {"courses": [], "meta": {"number_of_pages": 1}}+ paginator.update_state(response, data=[{"id": 1}])+ assert paginator.has_next_page is False++ def test_get_resource_rejects_fanout_endpoint(self) -> None:+ with pytest.raises(ValueError, match="Fan-out endpoint"):+ get_resource("course_enrollments", should_use_incremental_field=False)++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_enrollments_fanout_row_format(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("courses", [{"id": 11, "name": "Course"}]),+ _FakeDltResource(+ "course_enrollments",+ [{"user_id": 7, "enrolled_at": "2026-01-01T00:00:00Z", "_courses_id": 11}],+ ),+ ]++ response = teachable_source(+ api_key="key",+ endpoint="course_enrollments",+ team_id=1,+ job_id="job-1",+ )++ rows = list(cast(Any, response.items()))+ assert rows == [{"user_id": 7, "enrolled_at": "2026-01-01T00:00:00Z", "course_id": 11}]+ # user_id is only unique per course, so the parent course id is part of the key.+ assert response.primary_keys == ["course_id", "user_id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["enrolled_at"]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.teachable.teachable.build_dependent_resource"+ )+ def test_enrollments_fanout_wiring(self, mock_build_dependent_resource) -> None:+ mock_build_dependent_resource.return_value = iter([])++ teachable_source(api_key="key", endpoint="course_enrollments", team_id=1, job_id="job-1")++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["page_size_param"] == "per"+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "courses"+ assert kwargs["child_endpoint_extra"]["data_selector"] == "enrollments"+ assert kwargs["child_params_extra"] == {"sort_direction": "asc"}++ @parameterized.expand(+ [+ ("page_endpoint", TeachableResumeConfig(page=5), {"page": 5}),+ ("users_endpoint", TeachableResumeConfig(search_after=99), {"search_after": 99}),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.teachable.teachable.rest_api_resource")+ def test_resume_state_seeds_paginator(self, _name, saved_state, expected_initial, mock_rest_api_resource) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = saved_state++ teachable_source(+ api_key="key",+ endpoint="users" if saved_state.search_after else "courses",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == expected_initial++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.teachable.teachable.rest_api_resource")+ def test_resume_hook_saves_state_only_when_resumable(self, mock_rest_api_resource) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False++ teachable_source(+ api_key="key",+ endpoint="courses",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]++ resume_hook({"page": 3})+ assert manager.save_state.call_args.args[0] == TeachableResumeConfig(page=3, search_after=None)++ manager.save_state.reset_mock()+ resume_hook(None)+ resume_hook({})+ manager.save_state.assert_not_called()++ @parameterized.expand(+ [+ ("incremental_desc", True, "desc"),+ ("full_refresh_asc", False, "asc"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.teachable.teachable.rest_api_resource")+ def test_transactions_sort_mode(+ self, _name, should_use_incremental_field, expected, mock_rest_api_resource+ ) -> None:+ response = teachable_source(+ api_key="key",+ endpoint="transactions",+ team_id=1,+ job_id="job-1",+ should_use_incremental_field=should_use_incremental_field,+ )+ assert response.sort_mode == expected+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["created_at"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/tests/test_teachable_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/tests/test_teachable_source.pynew file mode 100644index 000000000000..7c0393df7ab0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teachable/tests/test_teachable_source.py@@ -0,0 +1,132 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.teachable import (+ TeachableSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.teachable.settings import (+ ENDPOINTS,+ TRANSACTIONS_INCREMENTAL_LOOKBACK_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.teachable.source import TeachableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.teachable.teachable import TeachableResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestTeachableSource:+ def setup_method(self) -> None:+ self.source = TeachableSource()+ self.team_id = 123+ self.config = TeachableSourceConfig(api_key="teachable-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TEACHABLE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Teachable"+ assert config.label == "Teachable"+ assert config.category == DataWarehouseSourceCategory.E_COMMERCE+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/teachable.png"+ # The source ships visible — a truthy unreleasedSource hides it from every user.+ assert not config.unreleasedSource++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ assert [f.name for f in config.fields] == ["api_key"]+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_incremental_semantics(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ # Only /transactions has a server-side time filter (`start`); everything else is+ # full refresh.+ assert schemas["transactions"].supports_incremental is True+ assert [f["field"] for f in schemas["transactions"].incremental_fields] == ["created_at"]+ assert schemas["transactions"].default_incremental_lookback_seconds == TRANSACTIONS_INCREMENTAL_LOOKBACK_SECONDS++ for name in ("users", "courses", "course_enrollments", "pricing_plans"):+ assert schemas[name].supports_incremental is False, name+ assert schemas[name].incremental_fields == [], name++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["transactions"])+ assert [s.name for s in schemas] == ["transactions"]++ @pytest.mark.parametrize(+ "observed_error,expect_match",+ [+ ("401 Client Error: Unauthorized for url: https://developers.teachable.com/v1/users", True),+ ("403 Client Error: Forbidden for url: https://developers.teachable.com/v1/courses", True),+ ("500 Server Error: Internal Server Error for url: https://developers.teachable.com/v1/users", False),+ ],+ )+ def test_non_retryable_errors_match_auth_failures_only(self, observed_error: str, expect_match: bool) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable) is expect_match++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.teachable.source.validate_teachable_credentials"+ )+ def test_validate_credentials_plumbs_api_key(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_validate.call_args.args == ("teachable-key",)++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is TeachableResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.teachable.source.teachable_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_teachable_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "transactions"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.incremental_field = "created_at"+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_teachable_source.call_args.kwargs+ assert kwargs["api_key"] == "teachable-key"+ assert kwargs["endpoint"] == "transactions"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["incremental_field"] == "created_at"+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.teachable.source.teachable_source")+ def test_source_for_pipeline_omits_watermark_when_not_incremental(+ self, mock_teachable_source: mock.MagicMock+ ) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "transactions"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_teachable_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)