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(warehouse): implement schematic source (#118138)

Daniel RCc608a40b56b4
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 ae190d9166ae..95ac6061045a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -731,6 +731,7 @@ the row lists both.
| scale_ai | HTTP | requests | ✅ |
| scaleway | HTTP | requests | ✅ |
| scalr | HTTP | requests | ✅ |
+| schematic | HTTP | requests + `rest_source.RESTClient` | ✅ |
| scrunch | HTTP | requests | ✅ |
| secoda | HTTP | requests | ✅ |
| secureframe | HTTP | requests | ✅ |
@@ -1416,7 +1417,6 @@ doesn't conflict with concurrent PRs.
- savvycal
- scale_ai
- scaleway
-- schematic
- search_ads_360
- sec_edgar
- secureframe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/schematic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/schematic.py
index be7da4c22079..da01ddcd560a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/schematic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/schematic.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SchematicSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/canonical_descriptions.py
new file mode 100644
index 000000000000..cd61c528df56
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/canonical_descriptions.py
@@ -0,0 +1,242 @@
+"""Canonical, documentation-sourced descriptions for Schematic endpoints and columns.
+
+Sourced from the Schematic API reference (https://docs.schematichq.com/api-reference).
+Keyed by the endpoint names in `settings.py`, which match the `ExternalDataSchema.name` of a synced
+table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://docs.schematichq.com/api-reference"
+
+_COMMON_COLUMNS = {
+ "id": "Unique identifier for the object.",
+ "created_at": "Time at which the object was created.",
+ "updated_at": "Time at which the object was last updated.",
+}
+
+
+_ENVIRONMENT_ID = "Identifier of the Schematic environment the object belongs to."
+
+
+def _columns(*, with_id: bool = True, **overrides: str) -> dict[str, str]:
+ common = _COMMON_COLUMNS if with_id else {k: v for k, v in _COMMON_COLUMNS.items() if k != "id"}
+ return {**common, **overrides}
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "companies": {
+ "description": "A customer account in Schematic, with its lookup keys, traits, assigned plans and billing subscription.",
+ "docs_url": f"{_DOCS}/companies/list-companies",
+ "columns": _columns(
+ environment_id=_ENVIRONMENT_ID,
+ name="Display name of the company.",
+ last_seen_at="Time Schematic last received an event or check for this company.",
+ logo_url="URL of the company logo.",
+ keys="Lookup keys that identify the company, such as an external id or a billing customer id.",
+ traits="Trait values set on the company.",
+ entity_traits="Trait definitions and values set on the company.",
+ plans="Plans currently assigned to the company.",
+ add_ons="Add-on plans currently assigned to the company.",
+ billing_subscription="The company's billing subscription, when one is linked.",
+ user_count="Number of users that belong to the company.",
+ metrics="Usage metrics recorded for the company.",
+ ),
+ },
+ "users": {
+ "description": "An end user tracked by Schematic, with its lookup keys, traits and company memberships.",
+ "docs_url": f"{_DOCS}/companies/list-users",
+ "columns": _columns(
+ environment_id=_ENVIRONMENT_ID,
+ name="Display name of the user.",
+ last_seen_at="Time Schematic last received an event or check for this user.",
+ keys="Lookup keys that identify the user.",
+ traits="Trait values set on the user.",
+ entity_traits="Trait definitions and values set on the user.",
+ company_memberships="Companies the user belongs to.",
+ ),
+ },
+ "company_memberships": {
+ "description": "A link between a user and a company.",
+ "docs_url": f"{_DOCS}/companies/list-company-memberships",
+ "columns": _columns(
+ company_id="Identifier of the company.",
+ user_id="Identifier of the user.",
+ company="The company the membership belongs to.",
+ ),
+ },
+ "features": {
+ "description": "A feature defined in Schematic that plans and companies can be entitled to.",
+ "docs_url": f"{_DOCS}/features/list-features",
+ "columns": _columns(
+ name="Display name of the feature.",
+ description="Description of the feature.",
+ feature_type="How the feature is metered: boolean, event or trait.",
+ lifecycle_phase="Lifecycle phase of the feature, such as alpha, beta or GA.",
+ event_subtype="Event subtype that counts toward an event-metered feature.",
+ trait_id="Identifier of the trait that measures a trait-metered feature.",
+ icon="Icon shown for the feature in Schematic.",
+ flags="Flags attached to the feature.",
+ plans="Plans that entitle companies to the feature.",
+ maintainer="Account member who maintains the feature.",
+ ),
+ },
+ "flags": {
+ "description": "A feature flag evaluated by the Schematic SDKs.",
+ "docs_url": f"{_DOCS}/features/list-flags",
+ "columns": _columns(
+ key="Key used to check the flag from an SDK.",
+ name="Display name of the flag.",
+ description="Description of the flag.",
+ flag_type="Type of the flag.",
+ default_value="Value returned when no rule matches.",
+ feature_id="Identifier of the feature the flag belongs to.",
+ feature="The feature the flag belongs to.",
+ rules="Targeting rules evaluated for the flag.",
+ last_checked_at="Time the flag was last checked by an SDK.",
+ ),
+ },
+ "plans": {
+ "description": "A plan or add-on that bundles feature entitlements and billing products.",
+ "docs_url": f"{_DOCS}/plans/list-plans",
+ "columns": _columns(
+ name="Display name of the plan.",
+ description="Description of the plan.",
+ plan_type="Whether the row is a plan or an add-on.",
+ audience_type="Audience the plan targets.",
+ is_default="Whether the plan is the default plan for new companies.",
+ is_free="Whether the plan is free.",
+ is_trialable="Whether the plan offers a trial.",
+ trial_days="Length of the trial in days.",
+ company_count="Number of companies on the plan.",
+ billing_product="Billing product linked to the plan.",
+ monthly_price="Monthly price of the plan.",
+ yearly_price="Yearly price of the plan.",
+ entitlements="Feature entitlements the plan grants.",
+ features="Features included in the plan.",
+ ),
+ },
+ "plan_entitlements": {
+ "description": "A feature entitlement granted by a plan, with its limit and metering period.",
+ "docs_url": f"{_DOCS}/entitlements/list-plan-entitlements",
+ "columns": _columns(
+ environment_id=_ENVIRONMENT_ID,
+ plan_id="Identifier of the plan that grants the entitlement.",
+ feature_id="Identifier of the entitled feature.",
+ plan="The plan that grants the entitlement.",
+ feature="The entitled feature.",
+ value_type="How the entitlement value is expressed: boolean, numeric, trait or unlimited.",
+ value_bool="Boolean entitlement value.",
+ value_numeric="Numeric limit of the entitlement.",
+ value_trait_id="Identifier of the trait that sets the limit.",
+ metric_period="Period over which usage is measured.",
+ soft_limit="Whether usage may exceed the limit.",
+ price_behavior="How overage is priced.",
+ ),
+ },
+ "company_overrides": {
+ "description": "A per-company entitlement override that replaces the plan entitlement for one feature.",
+ "docs_url": f"{_DOCS}/entitlements/list-company-overrides",
+ "columns": _columns(
+ environment_id=_ENVIRONMENT_ID,
+ company_id="Identifier of the company the override applies to.",
+ feature_id="Identifier of the overridden feature.",
+ company="The company the override applies to.",
+ feature="The overridden feature.",
+ value_type="How the override value is expressed: boolean, numeric, trait or unlimited.",
+ value_bool="Boolean override value.",
+ value_numeric="Numeric limit set by the override.",
+ metric_period="Period over which usage is measured.",
+ expiration_date="Time the override stops applying.",
+ notes="Free-text notes on the override.",
+ ),
+ },
+ "billing_customers": {
+ "description": "A customer synced from the billing provider, with its subscriptions.",
+ "docs_url": f"{_DOCS}/billing/list-customers-with-subscriptions",
+ "columns": {
+ "id": "Unique identifier for the billing customer.",
+ "company_id": "Identifier of the Schematic company linked to the customer.",
+ "external_id": "Identifier of the customer in the billing provider.",
+ "provider_type": "Billing provider the customer comes from, such as Stripe.",
+ "name": "Name of the customer.",
+ "email": "Email address of the customer.",
+ "subscriptions": "Subscriptions held by the customer.",
+ "deleted_at": "Time the customer was deleted in the billing provider.",
+ "updated_at": "Time at which the customer was last updated.",
+ },
+ },
+ "billing_products": {
+ "description": "A product synced from the billing provider.",
+ "docs_url": f"{_DOCS}/billing/list-billing-products",
+ "columns": _columns(
+ with_id=False,
+ environment_id=_ENVIRONMENT_ID,
+ product_id="Unique identifier for the billing product.",
+ external_id="Identifier of the product in the billing provider.",
+ provider_type="Billing provider the product comes from, such as Stripe.",
+ name="Name of the product.",
+ currency="Currency of the product's default price.",
+ price="Default price in the smallest currency unit.",
+ price_decimal="Default price as a decimal string.",
+ is_active="Whether the product is active in the billing provider.",
+ prices="Prices defined for the product.",
+ subscription_count="Number of subscriptions that include the product.",
+ ),
+ },
+ "billing_prices": {
+ "description": "A price synced from the billing provider.",
+ "docs_url": f"{_DOCS}/billing/list-billing-prices",
+ "columns": _columns(
+ price_id="Identifier of the price.",
+ price_external_id="Identifier of the price in the billing provider.",
+ product_id="Identifier of the billing product the price belongs to.",
+ product_external_id="Identifier of the product in the billing provider.",
+ product_name="Name of the billing product.",
+ provider_type="Billing provider the price comes from, such as Stripe.",
+ currency="Currency of the price.",
+ price="Amount in the smallest currency unit.",
+ price_decimal="Amount as a decimal string.",
+ interval="Billing interval, such as month or year.",
+ interval_count="Number of intervals between charges.",
+ usage_type="Whether the price is licensed or metered.",
+ billing_scheme="Whether the price is per unit or tiered.",
+ tiers_mode="How tiers apply when the price is tiered.",
+ is_active="Whether the price is active in the billing provider.",
+ meter_id="Identifier of the meter for a metered price.",
+ ),
+ },
+ "billing_coupons": {
+ "description": "A coupon synced from the billing provider.",
+ "docs_url": f"{_DOCS}/billing/list-coupons",
+ "columns": {
+ "id": "Unique identifier for the coupon.",
+ "external_id": "Identifier of the coupon in the billing provider.",
+ "provider_type": "Billing provider the coupon comes from, such as Stripe.",
+ "name": "Name of the coupon.",
+ "amount_off": "Fixed discount in the smallest currency unit.",
+ "percent_off": "Percentage discount.",
+ "currency": "Currency of a fixed discount.",
+ "duration": "How long the coupon applies: once, repeating or forever.",
+ "duration_in_months": "Number of months a repeating coupon applies.",
+ "max_redemptions": "Maximum number of times the coupon can be redeemed.",
+ "times_redeemed": "Number of times the coupon has been redeemed.",
+ "is_active": "Whether the coupon is active.",
+ "valid_from": "Time the coupon becomes valid.",
+ "valid_until": "Time the coupon expires.",
+ },
+ },
+ "billing_meters": {
+ "description": "A usage meter synced from the billing provider.",
+ "docs_url": f"{_DOCS}/billing/list-meters",
+ "columns": {
+ "id": "Unique identifier for the meter.",
+ "provider_type": "Billing provider the meter comes from, such as Stripe.",
+ "event_name": "Name of the billing event the meter counts.",
+ "event_payload_key": "Payload key the meter aggregates.",
+ "external_price_id": "Identifier of the billing price attached to the meter.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/schematic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/schematic.py
new file mode 100644
index 000000000000..4ba06f142fc9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/schematic.py
@@ -0,0 +1,156 @@
+from collections.abc import Callable, Iterator
+from dataclasses import dataclass
+from functools import partial
+from typing import Any
+
+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.resource import Resource
+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.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.schematic.settings import (
+ PAGE_SIZE,
+ SCHEMATIC_BASE_URL,
+ SCHEMATIC_ENDPOINTS,
+ SchematicEndpointConfig,
+)
+
+API_KEY_HEADER = "X-Schematic-Api-Key"
+
+
+@dataclass(frozen=True)
+class SchematicResumeConfig:
+ offset: int
+ # Which `is_active` pass the offset belongs to, for endpoints read in an active and an inactive pass.
+ is_active: bool | None = None
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": SCHEMATIC_BASE_URL,
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "api_key", "api_key": api_key, "name": API_KEY_HEADER, "location": "header"},
+ # `requests` keeps a custom header on a cross-origin redirect, so a redirect would replay the key.
+ "allow_redirects": False,
+ "allowed_hosts": [],
+ }
+
+
+def _resource(
+ api_key: str,
+ config: SchematicEndpointConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[SchematicResumeConfig],
+ is_active: bool | None,
+ initial_offset: int | None,
+) -> Resource:
+ params: dict[str, Any] = dict(config.extra_params)
+ if is_active is not None:
+ params["is_active"] = "true" if is_active else "false"
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ # The response carries no total, so the walk ends on the first short page.
+ "data_selector": "data",
+ "data_selector_required": True,
+ "paginator": {"type": "offset", "limit": PAGE_SIZE, "total_path": None},
+ },
+ }
+ ],
+ }
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(SchematicResumeConfig(offset=int(state["offset"]), is_active=is_active))
+
+ return rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=None if initial_offset is None else {"offset": initial_offset},
+ )
+
+
+def _active_then_inactive(
+ build: Callable[[bool, int | None], Resource],
+ resumable_source_manager: ResumableSourceManager[SchematicResumeConfig],
+ resume: SchematicResumeConfig | None,
+) -> Iterator[Any]:
+ if resume is None or resume.is_active is not False:
+ yield from build(True, resume.offset if resume is not None else None)
+ # Every active row is handed on, so a resume from here starts the inactive pass.
+ resumable_source_manager.save_state(SchematicResumeConfig(offset=0, is_active=False))
+ yield from build(False, None)
+ else:
+ yield from build(False, resume.offset)
+
+
+def schematic_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[SchematicResumeConfig],
+) -> SourceResponse:
+ config = SCHEMATIC_ENDPOINTS[endpoint]
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.include_inactive:
+ build = partial(_resource, api_key, config, team_id, job_id, resumable_source_manager)
+ first = build(True, None)
+ # The chain hands each page on unchanged and holds no rows, so as a `Resource` it keeps the
+ # framework's checkpoints.
+ resource = Resource(
+ partial(_active_then_inactive, build, resumable_source_manager, resume),
+ name=endpoint,
+ hints=first._hints,
+ )
+ else:
+ resource = _resource(
+ api_key,
+ config,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ None,
+ resume.offset if resume is not None else None,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=list(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,
+ column_hints=resource.column_hints,
+ )
+
+
+def validate_credentials(api_key: str) -> tuple[bool, int | None]:
+ return validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{SCHEMATIC_BASE_URL}/companies?limit=1",
+ headers={API_KEY_HEADER: api_key, "Accept": "application/json"},
+ timeout=15,
+ allow_redirects=False,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/settings.py
new file mode 100644
index 000000000000..a1a7d1614ffe
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/settings.py
@@ -0,0 +1,55 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+SCHEMATIC_BASE_URL = "https://api.schematichq.com"
+
+PAGE_SIZE = 100
+
+
+@dataclass(frozen=True)
+class SchematicEndpointConfig:
+ name: str
+ path: str
+ primary_keys: tuple[str, ...] = ("id",)
+ # Billing customers, coupons and meters have no creation timestamp, so they stay unpartitioned.
+ partition_key: str | None = "created_at"
+ # Read once with `is_active=true` and once with `is_active=false`. Products and prices list only
+ # active records by default, and the coupons default is undocumented.
+ include_inactive: bool = False
+ extra_params: dict[str, str] = field(default_factory=dict)
+
+
+# No list endpoint takes a server-side `updated_after` style filter, so every table is full refresh.
+# `/events` is left out on purpose: it has no time filter either, and a full re-read of every usage
+# event each sync is unbounded.
+SCHEMATIC_ENDPOINTS: dict[str, SchematicEndpointConfig] = {
+ # Companies change on every event, so pin a stable order for the offset walk and its resume.
+ "companies": SchematicEndpointConfig(
+ name="companies",
+ path="/companies",
+ extra_params={"sort_order_column": "created_at", "sort_order_direction": "asc"},
+ ),
+ "users": SchematicEndpointConfig(name="users", path="/users"),
+ "company_memberships": SchematicEndpointConfig(name="company_memberships", path="/company-memberships"),
+ "features": SchematicEndpointConfig(name="features", path="/features"),
+ "flags": SchematicEndpointConfig(name="flags", path="/flags"),
+ "plans": SchematicEndpointConfig(name="plans", path="/plans"),
+ "plan_entitlements": SchematicEndpointConfig(name="plan_entitlements", path="/plan-entitlements"),
+ "company_overrides": SchematicEndpointConfig(name="company_overrides", path="/company-overrides"),
+ "billing_customers": SchematicEndpointConfig(
+ name="billing_customers", path="/billing/customers", partition_key=None
+ ),
+ "billing_products": SchematicEndpointConfig(
+ name="billing_products", path="/billing/products", primary_keys=("product_id",), include_inactive=True
+ ),
+ "billing_prices": SchematicEndpointConfig(name="billing_prices", path="/billing/price", include_inactive=True),
+ "billing_coupons": SchematicEndpointConfig(
+ name="billing_coupons", path="/billing/coupons", partition_key=None, include_inactive=True
+ ),
+ "billing_meters": SchematicEndpointConfig(name="billing_meters", path="/billing/meter", partition_key=None),
+}
+
+ENDPOINTS = tuple(SCHEMATIC_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/source.py
index a50ce54b6ccd..6a3b1c33ab0d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/source.py
@@ -1,16 +1,58 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.codebase_detection import detect
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+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.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.schematic import (
SchematicSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.schematic.schematic import (
+ SchematicResumeConfig,
+ schematic_source,
+ validate_credentials as validate_schematic_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.schematic.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SchematicSource(SimpleSource[SchematicSourceConfig]):
+class SchematicSource(ResumableSource[SchematicSourceConfig, SchematicResumeConfig]):
+ codebase_detection = detect(
+ env=("^SCHEMATIC_",),
+ npm=(
+ "@schematichq/schematic-js",
+ "@schematichq/schematic-react",
+ "@schematichq/schematic-components",
+ "@schematichq/schematic-typescript-node",
+ ),
+ pypi=("schematichq",),
+ go=("github.com/SchematicHQ/schematic-go",),
+ rubygems=("schematic",),
+ composer=("schematichq/schematic-php",),
+ )
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.schematichq.com/api-reference"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SCHEMATIC
@@ -22,7 +64,78 @@ class SchematicSource(SimpleSource[SchematicSourceConfig]):
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Schematic",
keywords=["schematichq", "entitlements"],
+ caption="""Sync your Schematic companies, users, features, flags, plans, entitlements and billing catalog into the PostHog Data warehouse.
+
+Use a secret API key for the environment you want to sync, created under **Settings > API keys** in Schematic. Publishable keys can't list data.""",
iconPath="/static/services/schematic.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/schematic",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Secret API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="sch_prod_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.schematic.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.schematichq.com": "Schematic rejected your API key. Create a new secret key under Settings > API keys, then reconnect the source.",
+ "403 Client Error: Forbidden for url: https://api.schematichq.com": "Your Schematic API key can't read this data. Use a secret key for the environment you want to sync, then reconnect the source.",
+ }
+
+ def get_schemas(
+ self,
+ config: SchematicSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: SchematicSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ is_valid, status = validate_schematic_credentials(config.api_key)
+ if is_valid:
+ return True, None
+ if status in (401, 403):
+ return False, "Schematic rejected the API key. Use a secret key for the environment you want to sync."
+ return False, "Could not reach the Schematic API with that key. Check the key and try again."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SchematicResumeConfig]:
+ return ResumableSourceManager[SchematicResumeConfig](inputs, SchematicResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SchematicSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SchematicResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return schematic_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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/tests/test_schematic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/tests/test_schematic.py
new file mode 100644
index 000000000000..2830a68d69ad
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/schematic/tests/test_schematic.py
@@ -0,0 +1,146 @@
+from typing import Any
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.schematic import (
+ SchematicSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.schematic.schematic import SchematicResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.schematic.source import SchematicSource
+
+
+def _driver() -> SourceDriver:
+ return SourceDriver(SchematicSource(), SchematicSourceConfig(api_key="sch_test_key"))
+
+
+PAGE_SIZE = 100
+
+
+def _page(rows: list[dict[str, Any]]) -> ScriptedResponse:
+ return ScriptedResponse(json={"data": rows, "params": {"limit": PAGE_SIZE}})
+
+
+def _rows(prefix: str, count: int) -> list[dict[str, Any]]:
+ return [{"id": f"{prefix}_{index}", "product_id": f"{prefix}_{index}"} for index in range(count)]
+
+
+_COMPANIES_ORDER = {"sort_order_column": "created_at", "sort_order_direction": "asc"}
+
+# Paths as the Schematic SDK calls them, so a typo in the endpoint table fails here.
+_SINGLE_PASS = [
+ ("companies", "/companies", _COMPANIES_ORDER),
+ ("users", "/users", {}),
+ ("company_memberships", "/company-memberships", {}),
+ ("features", "/features", {}),
+ ("flags", "/flags", {}),
+ ("plans", "/plans", {}),
+ ("plan_entitlements", "/plan-entitlements", {}),
+ ("company_overrides", "/company-overrides", {}),
+ ("billing_customers", "/billing/customers", {}),
+ ("billing_meters", "/billing/meter", {}),
+]
+_TWO_PASS = [
+ ("billing_products", "/billing/products"),
+ ("billing_prices", "/billing/price"),
+ ("billing_coupons", "/billing/coupons"),
+]
+
+
+class TestSchematicPagination:
+ @pytest.mark.parametrize(("endpoint", "path", "order"), _SINGLE_PASS)
+ def test_walks_offset_pages_until_a_short_page(self, endpoint: str, path: str, order: dict[str, str]) -> None:
+ result = _driver().run(endpoint, [_page(_rows("a", PAGE_SIZE)), _page(_rows("b", 3))])
+
+ assert result.raised is None
+ assert result.paths == [path] * 2
+ assert result.params("offset") == ["0", "100"]
+ assert result.params("limit") == ["100", "100"]
+ assert {name: result.requests[1].param(name) for name in _COMPANIES_ORDER} == {
+ name: order.get(name) for name in _COMPANIES_ORDER
+ }
+ assert [request.headers["x-schematic-api-key"] for request in result.requests] == ["sch_test_key"] * 2
+ assert result.saved_states == [SchematicResumeConfig(offset=PAGE_SIZE)]
+ assert len(result.rows) == PAGE_SIZE + 3
+
+ def test_empty_first_page_yields_nothing_and_saves_no_state(self) -> None:
+ result = _driver().run("companies", [_page([])])
+
+ assert result.raised is None
+ assert result.rows == []
+ assert result.saved_states == []
+
+ def test_resume_starts_from_the_saved_offset(self) -> None:
+ result = _driver().run("companies", [_page(_rows("c", 1))], resume_state=SchematicResumeConfig(offset=300))
+
+ assert result.raised is None
+ assert result.params("offset") == ["300"]
+
+ @pytest.mark.parametrize(("endpoint", "path"), _TWO_PASS)
+ def test_reads_active_then_inactive_records(self, endpoint: str, path: str) -> None:
+ result = _driver().run(
+ endpoint, [_page(_rows("a", PAGE_SIZE)), _page(_rows("b", 1)), _page(_rows("inactive", 2))]
+ )
+
+ assert result.raised is None
+ assert result.paths == [path] * 3
+ assert result.params("is_active") == ["true", "true", "false"]
+ assert result.params("offset") == ["0", str(PAGE_SIZE), "0"]
+ assert result.saved_states == [
+ SchematicResumeConfig(offset=PAGE_SIZE, is_active=True),
+ SchematicResumeConfig(offset=0, is_active=False),
+ ]
+ assert len(result.rows) == PAGE_SIZE + 3
+
+ @pytest.mark.parametrize(
+ ("resume", "expected_requests"),
+ [
+ (SchematicResumeConfig(offset=200, is_active=True), [("true", "200"), ("false", "0")]),
+ (SchematicResumeConfig(offset=100, is_active=False), [("false", "100")]),
+ ],
+ )
+ def test_resume_continues_the_pass_it_stopped_in(
+ self, resume: SchematicResumeConfig, expected_requests: list[tuple[str, str]]
+ ) -> None:
+ result = _driver().run(
+ "billing_products", [_page(_rows("r", 1)) for _ in expected_requests], resume_state=resume
+ )
+
+ assert result.raised is None
+ assert [(r.param("is_active"), r.param("offset")) for r in result.requests] == expected_requests
+
+ def test_does_not_follow_a_redirect_with_the_api_key(self) -> None:
+ result = _driver().run(
+ "companies", [ScriptedResponse(status=302, headers={"Location": "https://elsewhere.example.com/x"})]
+ )
+
+ assert result.raised is not None
+ assert {request.origin for request in result.requests} == {"https://api.schematichq.com"}
+
+
+class TestSchematicValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status", "body", "expected_valid", "expected_fragment"),
+ [
+ (200, {"data": [], "params": {}}, True, None),
+ (401, {"error": "Unauthorized", "message": "invalid api key"}, False, "rejected the API key"),
+ (500, {"error": "internal"}, False, "Could not reach"),
+ ],
+ )
+ def test_maps_the_probe_status_to_a_message(
+ self, status: int, body: dict[str, Any], expected_valid: bool, expected_fragment: str | None
+ ) -> None:
+ config = SchematicSourceConfig(api_key="sch_test_key")
+ # `always` because the transport retries a 5xx; assert the set of URLs, not the count.
+ with scripted_network(always(ScriptedResponse(status=status, json=body))) as network:
+ is_valid, message = SchematicSource().validate_credentials(config, team_id=1)
+
+ assert is_valid is expected_valid
+ assert (message is None) if expected_fragment is None else (expected_fragment in (message or ""))
+ assert {request.url for request in network.requests_log} == {"https://api.schematichq.com/companies?limit=1"}
+ assert network.requests_log[0].headers["x-schematic-api-key"] == "sch_test_key"