: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 skio import source (#107248)
Tom Owers06044ed2408f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex f054e7a7a5de..558a12a930c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -646,6 +646,7 @@ the row lists both.| simplecast | HTTP | requests | ✅ || simplesat | HTTP | requests | ✅ || singlestore | HTTP | requests + `rest_source.RESTClient` | ✅ |+| skio | HTTP (GraphQL) | requests | ✅ || skyvern | HTTP | requests | ✅ || slack | HTTP | requests + `rest_source.RESTClient` | ✅ || sleekplan | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1382,7 +1383,6 @@ doesn't conflict with concurrent PRs.- sinch- singular- site24x7-- skio- skyvern- slash- sleuthdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/skio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/skio.pyindex abee53e5e898..185ac2935bb1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/skio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/skio.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SkioSourceConfig(config.Config):- pass+ api_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skio/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/canonical_descriptions.pynew file mode 100644index 000000000000..78b7ad4e2f91--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/canonical_descriptions.py@@ -0,0 +1,123 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions follow the schema published at https://code.skio.com. Skio's data model mirrors+# Shopify's GraphQL objects; `platformId` is always the Shopify GID of the mirrored object+# (e.g. gid://shopify/SubscriptionContract/123).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "subscriptions": {+ "description": "A customer's subscription contract, mirroring a Shopify SubscriptionContract.",+ "docs_url": "https://code.skio.com",+ "columns": {+ "id": "Unique identifier of the subscription.",+ "platformId": "Shopify GID of the mirrored SubscriptionContract.",+ "status": "Current status of the subscription (e.g. active, cancelled, paused).",+ "statusContext": "Additional context for the current status, such as the pause or cancellation origin.",+ "createdAt": "When the subscription was created.",+ "updatedAt": "When the subscription was last updated.",+ "cancelledAt": "When the subscription was cancelled, if it has been.",+ "nextBillingDate": "When the subscription bills next.",+ "nextRenewalDate": "When a prepaid subscription renews next.",+ "lastBillingAttemptAt": "When the most recent billing attempt ran.",+ "currencyCode": "ISO currency code the subscription bills in.",+ "deliveryPrice": "Delivery price charged per order.",+ "cyclesCompleted": "Number of billing cycles completed so far.",+ "storefrontUserId": "Customer the subscription belongs to (joins to customers.id).",+ "originOrderId": "Order that started the subscription (joins to orders.id).",+ "shippingAddressId": "Address the subscription ships to (joins to addresses.id).",+ "churnScore": "Skio's predicted churn risk score for the subscription.",+ },+ },+ "subscription_lines": {+ "description": "A product line on a subscription, mirroring a Shopify SubscriptionLine.",+ "docs_url": "https://code.skio.com",+ "columns": {+ "id": "Unique identifier of the subscription line.",+ "platformId": "Shopify GID of the mirrored SubscriptionLine.",+ "subscriptionId": "Subscription the line belongs to (joins to subscriptions.id).",+ "productVariantId": "Product variant on the line (joins to product_variants.id).",+ "quantity": "Quantity of the variant per order.",+ "priceWithoutDiscount": "Line price before subscription discounts.",+ "removedAt": "When the line was removed from the subscription, if it has been.",+ },+ },+ "orders": {+ "description": (+ "An order generated by a subscription, mirroring a Shopify Order. To find the "+ "subscription behind an order, join through order_line_items.subscriptionLineId "+ "to subscription_lines.subscriptionId."+ ),+ "docs_url": "https://code.skio.com",+ "columns": {+ "id": "Unique identifier of the order.",+ "platformId": "Shopify GID of the mirrored Order.",+ "platformNumber": "Shopify order number.",+ "storefrontUserId": "Customer the order belongs to (joins to customers.id).",+ "totalPrice": "Total price of the order.",+ "currencyCode": "ISO currency code of the order.",+ "processedAt": "When the order was processed.",+ "cancelledAt": "When the order was cancelled, if it has been.",+ "createdAt": "When the order was created.",+ },+ },+ "order_line_items": {+ "description": "A line item on an order, mirroring a Shopify LineItem.",+ "docs_url": "https://code.skio.com",+ "columns": {+ "id": "Unique identifier of the order line item.",+ "platformId": "Shopify GID of the mirrored LineItem.",+ "orderId": "Order the line item belongs to (joins to orders.id).",+ "subscriptionLineId": "Subscription line that produced the item (joins to subscription_lines.id).",+ "productVariantId": "Product variant ordered (joins to product_variants.id).",+ "quantity": "Quantity ordered.",+ "priceWithoutDiscount": "Item price before discounts.",+ },+ },+ "customers": {+ "description": "A storefront customer, mirroring a Shopify Customer (Skio calls these StorefrontUsers).",+ "docs_url": "https://code.skio.com",+ "columns": {+ "id": "Unique identifier of the customer.",+ "platformId": "Shopify GID of the mirrored Customer.",+ "email": "Customer email address.",+ "emailLower": "Lowercased customer email, for case-insensitive joins.",+ "phoneNumber": "Customer phone number.",+ "shopifyTags": "Tags on the mirrored Shopify customer.",+ "redactedAt": "When the customer's data was redacted for a GDPR request, if it has been.",+ },+ },+ "addresses": {+ "description": "A shipping address attached to a customer or subscription.",+ "docs_url": "https://code.skio.com",+ "columns": {+ "id": "Unique identifier of the address.",+ "storefrontUserId": "Customer the address belongs to (joins to customers.id).",+ "province": "State or province of the address.",+ "zip": "Postal code of the address.",+ },+ },+ "products": {+ "description": "A product available on subscription, mirroring a Shopify Product.",+ "docs_url": "https://code.skio.com",+ "columns": {+ "id": "Unique identifier of the product.",+ "platformId": "Shopify GID of the mirrored Product.",+ "title": "Product title.",+ "status": "Status of the mirrored Shopify product.",+ "deletedAt": "When the product was deleted, if it has been.",+ },+ },+ "product_variants": {+ "description": "A product variant available on subscription, mirroring a Shopify ProductVariant.",+ "docs_url": "https://code.skio.com",+ "columns": {+ "id": "Unique identifier of the product variant.",+ "platformId": "Shopify GID of the mirrored ProductVariant.",+ "productId": "Product the variant belongs to (joins to products.id).",+ "sku": "Stock keeping unit of the variant.",+ "price": "Current price of the variant.",+ "outOfStockAt": "When the variant went out of stock, if it is.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skio/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/settings.pynew file mode 100644index 000000000000..e3029dd37c9e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/settings.py@@ -0,0 +1,288 @@+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++SKIO_GRAPHQL_URL = "https://graphql.skio.com/v1/graphql"++# Skio caps queries at 100 returned nodes per request (see the rate limits section at+# https://code.skio.com), so one flat page of rows sits exactly at that cap.+SKIO_PAGE_SIZE = 100+++@frozen+class SkioEndpointConfig:+ """One Skio GraphQL collection synced as a table.++ `graphql_type` is the Hasura object type behind `query_name`, which names the generated+ `<type>_bool_exp` / `<type>_order_by` input types the query document declares. `fields` is the+ flat scalar selection set, taken verbatim from the published schema at https://code.skio.com;+ Skio limits query depth to 4 nested levels, so every stream selects scalars only and+ relationships are joined in the warehouse via the *Id columns.+ """++ name: str+ query_name: str+ graphql_type: str+ fields: tuple[str, ...]+ description: str++ @property+ def query_document(self) -> str:+ """The stream's GraphQL document. Filtering, ordering, and page size ride in as variables+ so one document serves full refresh, incremental, and resumed pages alike."""+ field_lines = "\n".join(f" {field}" for field in self.fields)+ return f"""query {self.query_name}Page($limit: Int!, $where: {self.graphql_type}_bool_exp, $orderBy: [{self.graphql_type}_order_by!]) {{+ {self.query_name}(limit: $limit, where: $where, order_by: $orderBy) {{+{field_lines}+ }}+}}"""+++ENDPOINTS: dict[str, SkioEndpointConfig] = {+ "subscriptions": SkioEndpointConfig(+ name="subscriptions",+ query_name="Subscriptions",+ graphql_type="Subscription",+ fields=(+ "id",+ "platformId",+ "status",+ "statusContext",+ "createdAt",+ "updatedAt",+ "cancelledAt",+ "nextBillingDate",+ "nextRenewalDate",+ "lastBillingAttemptAt",+ "currencyCode",+ "deliveryPrice",+ "deliveryPriceOverride",+ "cyclesCompleted",+ "remainingCyclesUntilRenewal",+ "prepaidProductPricesPerDelivery",+ "isPickup",+ "note",+ "customAttributes",+ "metadata",+ "churnScore",+ "churnPredictedAt",+ "churnRiskReasons",+ "streakCount",+ "maxStreakCount",+ "streakExpiresAt",+ "migrationIndex",+ "billingPolicyId",+ "deliveryPolicyId",+ "prepaidDeliveryPolicyId",+ "originOrderId",+ "shippingAddressId",+ "storefrontUserId",+ "siteId",+ ),+ description="Subscription contracts, mirroring Shopify SubscriptionContract objects.",+ ),+ "subscription_lines": SkioEndpointConfig(+ name="subscription_lines",+ query_name="SubscriptionLines",+ graphql_type="SubscriptionLine",+ fields=(+ "id",+ "platformId",+ "subscriptionId",+ "productVariantId",+ "sellingPlanId",+ "quantity",+ "priceWithoutDiscount",+ "taxable",+ "titleOverride",+ "isPrepaid",+ "ordersRemaining",+ "prepaidSubscriptionId",+ "groupId",+ "reChargeId",+ "customAttributes",+ "createdAt",+ "updatedAt",+ "removedAt",+ ),+ description="Line items on a subscription, mirroring Shopify SubscriptionLine objects.",+ ),+ "orders": SkioEndpointConfig(+ name="orders",+ query_name="Orders",+ graphql_type="Order",+ # `subscriptionId` is deliberately not selected: Skio's schema documents it as never+ # written (always null). The real link from an order to its subscription runs through+ # order_line_items.subscriptionLineId -> subscription_lines.subscriptionId.+ fields=(+ "id",+ "platformId",+ "platformNumber",+ "name",+ "storefrontUserId",+ "shippingAddressId",+ "siteId",+ "currencyCode",+ "totalPrice",+ "totalPricePresentmentAmount",+ "taxExempt",+ "taxesIncluded",+ "note",+ "appId",+ "clientIp",+ "firstOrderInPrepaidSequence",+ "prepaidSubscriptionId",+ "fulfillAt",+ "fulfillmentOrderCredit",+ "processedAt",+ "deliveredAt",+ "cancelledAt",+ "deletedAt",+ "createdAt",+ "updatedAt",+ ),+ description="Orders generated by subscriptions, mirroring Shopify Order objects.",+ ),+ "order_line_items": SkioEndpointConfig(+ name="order_line_items",+ query_name="OrderLineItems",+ graphql_type="OrderLineItem",+ fields=(+ "id",+ "platformId",+ "orderId",+ "subscriptionLineId",+ "productVariantId",+ "quantity",+ "priceWithoutDiscount",+ "pricePresentmentAmount",+ "pricePresentmentCurrencyCode",+ "currencyCode",+ "attributionGroupId",+ "groupId",+ "customAttributes",+ "createdAt",+ "updatedAt",+ ),+ description="Line items on an order, mirroring Shopify LineItem objects.",+ ),+ "customers": SkioEndpointConfig(+ name="customers",+ query_name="StorefrontUsers",+ graphql_type="StorefrontUser",+ # `qaToken` is deliberately not selected: it is a login token, not customer data.+ fields=(+ "id",+ "platformId",+ "email",+ "emailLower",+ "firstName",+ "lastName",+ "phoneNumber",+ "shopifyTags",+ "smsTransactionalOptIn",+ "tempSmsTransactionalOptIn",+ "siteId",+ "redactedAt",+ "removedAt",+ "createdAt",+ "updatedAt",+ ),+ description="Storefront customers with subscriptions, mirroring Shopify Customer objects.",+ ),+ "addresses": SkioEndpointConfig(+ name="addresses",+ query_name="Addresses",+ graphql_type="Address",+ # `doorCode` is deliberately not selected: it is a physical-access code for delivery,+ # not shipping data, and warehouse access is granted at table/source scope with no+ # column-specific redaction for it.+ fields=(+ "id",+ "platformId",+ "storefrontUserId",+ "firstName",+ "lastName",+ "company",+ "address1",+ "address2",+ "city",+ "province",+ "zip",+ "country",+ "phoneNumber",+ "createdAt",+ "updatedAt",+ ),+ description="Shipping addresses attached to customers and subscriptions.",+ ),+ "products": SkioEndpointConfig(+ name="products",+ query_name="Products",+ graphql_type="Product",+ fields=(+ "id",+ "platformId",+ "title",+ "slug",+ "status",+ "description",+ "imageSrc",+ "images",+ "shopifyTags",+ "metafields",+ "canUpsell",+ "hideOn1TimeUpsells",+ "limitOneTimeUpsellQuantity",+ "oneTimeUpsellPercentageOff",+ "smsOrder",+ "siteId",+ "deletedAt",+ "createdAt",+ "updatedAt",+ ),+ description="Products available on subscription, mirroring Shopify Product objects.",+ ),+ "product_variants": SkioEndpointConfig(+ name="product_variants",+ query_name="ProductVariants",+ graphql_type="ProductVariant",+ fields=(+ "id",+ "platformId",+ "productId",+ "title",+ "sku",+ "price",+ "compareAtPrice",+ "position",+ "image",+ "marketPrices",+ "outOfStockAt",+ "deletedAt",+ "createdAt",+ "updatedAt",+ ),+ description="Product variants available on subscription, mirroring Shopify ProductVariant objects.",+ ),+}++# Every collection carries non-null createdAt/updatedAt timestamptz columns with server-side+# comparison filters in its Hasura bool_exp, so both are genuine incremental cursors.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ endpoint: [+ {+ "label": "updatedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "updatedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ {+ "label": "createdAt",+ "type": IncrementalFieldType.DateTime,+ "field": "createdAt",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+ for endpoint in ENDPOINTS+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skio/skio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/skio.pynew file mode 100644index 000000000000..23181d58b838--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/skio.py@@ -0,0 +1,231 @@+from collections.abc import Iterator+from datetime import date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger++from posthog.dataclasses import frozen++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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.skio.settings import (+ ENDPOINTS,+ SKIO_GRAPHQL_URL,+ SKIO_PAGE_SIZE,+ SkioEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60++# Skio's Hasura instance answers an invalid or revoked token with HTTP 200 and this message in the+# GraphQL errors body (verified against the live API), so credential failures are classified on the+# error text rather than the status code.+INVALID_TOKEN_ERROR = "Invalid response from authorization hook"+# A field the token's role can't see fails validation with this fragment (verified against the+# live API with no token); the query is the same on every retry, so it can never self-heal.+FIELD_NOT_FOUND_ERROR = "not found in type: 'query_root'"+++class SkioAPIError(Exception):+ """A GraphQL-level error from Skio. Hasura returns these with HTTP 200, so the tracked+ transport's status-code retries never see them; permanent ones are matched by message in+ `get_non_retryable_errors`."""+++@frozen+class SkioResumeConfig:+ """Keyset cursor: the last row already yielded. The next page filters strictly past it, so a+ resumed run continues exactly after the last committed batch. `last_value` is the incremental+ field's value on that row, unset on full refresh (which pages on `id` alone)."""++ last_id: str | None = None+ last_value: str | None = None+++def _headers(api_token: str) -> dict[str, str]:+ # Skio's documented header is `authorization: API <token>` (case sensitive).+ return {"authorization": f"API {api_token}"}+++def _format_timestamp(value: Any) -> str:+ if isinstance(value, datetime | date):+ return value.isoformat()+ return str(value)+++def _post_query(+ session: requests.Session,+ api_token: str,+ document: str,+ variables: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.post(+ SKIO_GRAPHQL_URL,+ json={"query": document, "variables": variables},+ headers=_headers(api_token),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()++ payload = response.json()+ errors = payload.get("errors")+ if errors:+ messages = "; ".join(str(error.get("message", error)) for error in errors if isinstance(error, dict))+ logger.error(f"Skio API error: {messages}")+ raise SkioAPIError(f"Skio API error: {messages or errors}")++ return payload.get("data") or {}+++def _build_order_by(incremental_field: str | None) -> list[dict[str, str]]:+ # `id` breaks ties between rows sharing a timestamp so the keyset cursor never skips or+ # revisits rows within one value.+ if incremental_field:+ return [{incremental_field: "asc"}, {"id": "asc"}]+ return [{"id": "asc"}]+++def _build_where(+ incremental_field: str | None,+ db_incremental_field_last_value: Any,+ cursor: SkioResumeConfig | None,+) -> dict[str, Any] | None:+ """Combine the incremental watermark with the keyset-continuation predicate.++ The watermark uses `_gte` rather than `_gt` so rows written at exactly the stored value after+ the previous run read it are re-pulled; merge dedupes them on `id`.+ """+ clauses: list[dict[str, Any]] = []++ if incremental_field and db_incremental_field_last_value is not None:+ clauses.append({incremental_field: {"_gte": _format_timestamp(db_incremental_field_last_value)}})++ if cursor is not None and cursor.last_id is not None:+ if incremental_field and cursor.last_value is not None:+ clauses.append(+ {+ "_or": [+ {incremental_field: {"_gt": cursor.last_value}},+ {+ "_and": [+ {incremental_field: {"_eq": cursor.last_value}},+ {"id": {"_gt": cursor.last_id}},+ ]+ },+ ]+ }+ )+ else:+ clauses.append({"id": {"_gt": cursor.last_id}})++ if not clauses:+ return None+ if len(clauses) == 1:+ return clauses[0]+ return {"_and": clauses}+++def validate_credentials(api_token: str) -> tuple[bool, str | None]:+ """One cheap authenticated probe. It must select a real collection: Skio's Hasura answers+ bare `{ __typename }` even with no token, so only a table read exercises the auth hook."""+ config = ENDPOINTS["subscriptions"]+ document = f"query ValidateCredentials {{ {config.query_name}(limit: 1) {{ id }} }}"+ session = make_tracked_session(redact_values=(api_token,))+ try:+ response = session.post(+ SKIO_GRAPHQL_URL,+ json={"query": document},+ headers=_headers(api_token),+ timeout=10,+ )+ response.raise_for_status()+ payload = response.json()+ except Exception:+ return False, "Could not connect to the Skio API"++ errors = payload.get("errors")+ if not errors:+ return True, None++ messages = "; ".join(str(error.get("message", "")) for error in errors if isinstance(error, dict))+ if INVALID_TOKEN_ERROR in messages or FIELD_NOT_FOUND_ERROR in messages:+ return False, "Invalid Skio API token"+ return False, f"Skio API error: {messages}"+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SkioResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config: SkioEndpointConfig = ENDPOINTS[endpoint]+ document = config.query_document+ # One session for every page so urllib3 keeps the connection alive; the token is redacted from+ # tracked-transport samples because it rides in a non-standard `authorization` header value.+ session = make_tracked_session(redact_values=(api_token,))++ field = incremental_field if should_use_incremental_field else None+ cursor = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ order_by = _build_order_by(field)++ while True:+ variables: dict[str, Any] = {"limit": SKIO_PAGE_SIZE, "orderBy": order_by}+ where = _build_where(field, db_incremental_field_last_value if field else None, cursor)+ if where is not None:+ variables["where"] = where++ data = _post_query(session, api_token, document, variables, logger)+ rows = data.get(config.query_name) or []+ if not rows:+ break++ last_row = rows[-1]+ cursor = SkioResumeConfig(+ last_id=str(last_row["id"]),+ last_value=str(last_row[field]) if field and last_row.get(field) is not None else None,+ )+ # Staged before the yield it covers: the pipeline commits right after it writes these rows,+ # so a resumed run picks up exactly after the last written batch.+ resumable_source_manager.save_state(cursor)+ yield rows++ if len(rows) < SKIO_PAGE_SIZE:+ break+++def skio_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SkioResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=["id"],+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ # The physical Delta column: the pipeline snake_cases API field names before partitioning.+ partition_keys=["created_at"],+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/source.pyindex 3e16c2557d18..826b8fdea80d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/skio/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/source.py@@ -1,14 +1,40 @@-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.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+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.skio import SkioSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.skio.settings import ENDPOINTS, INCREMENTAL_FIELDS+from products.warehouse_sources.backend.temporal.data_imports.sources.skio.skio import (+ FIELD_NOT_FOUND_ERROR,+ INVALID_TOKEN_ERROR,+ SkioResumeConfig,+ skio_source,+ validate_credentials as validate_skio_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SkioSource(SimpleSource[SkioSourceConfig]):+class SkioSource(ResumableSource[SkioSourceConfig, SkioResumeConfig]):+ # Skio's GraphQL API is served from Hasura's fixed /v1/graphql path and exposes no+ # vendor-chosen version token, so the unversioned framework default applies.+ api_docs_url = "https://code.skio.com"++ lists_tables_without_credentials = True # static endpoint catalog, so safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SKIO@@ -19,8 +45,99 @@ class SkioSource(SimpleSource[SkioSourceConfig]):name=ExternalDataSourceType.SKIO,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Skio",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Skio API token to pull your Skio subscription data into the PostHog Data warehouse.++You can generate an API token in your Skio dashboard: click **API** in the left navigation bar, set a name, and generate the token.+""",iconPath="/static/services/skio.png",+ docsUrl="https://posthog.com/docs/cdp/sources/skio",keywords=["subscriptions", "shopify"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.skio.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Skio's Hasura backend answers these with HTTP 200, so they surface as SkioAPIError+ # messages rather than HTTP status errors; both are verbatim live-API strings.+ return {+ INVALID_TOKEN_ERROR: "Your Skio API token is invalid or has been revoked. Generate a new token under API in your Skio dashboard, then reconnect.",+ FIELD_NOT_FOUND_ERROR: "Your Skio API token does not have access to this table. Generate a new token under API in your Skio dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: SkioSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint_config.name,+ supports_incremental=True,+ # Every collection is mutable (orders cancel, subscriptions change status), so only+ # merge keeps one row per id; append would materialize each update as a duplicate.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS[endpoint_config.name],+ description=endpoint_config.description,+ )+ for endpoint_config in ENDPOINTS.values()+ ]+ if names is not None:+ names_set = set(names)+ schemas = [schema for schema in schemas if schema.name in names_set]+ return schemas++ def validate_credentials(+ self,+ config: SkioSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_skio_credentials(config.api_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SkioResumeConfig]:+ return ResumableSourceManager[SkioResumeConfig](inputs, SkioResumeConfig)++ def source_for_pipeline(+ self,+ config: SkioSourceConfig,+ resumable_source_manager: ResumableSourceManager[SkioResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in ENDPOINTS:+ raise ValueError(f"Skio schema {inputs.schema_name} does not exist")++ return skio_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skio/tests/test_skio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/tests/test_skio.pynew file mode 100644index 000000000000..06d7ac89f60f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/tests/test_skio.py@@ -0,0 +1,319 @@+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.skio.settings import SKIO_PAGE_SIZE+from products.warehouse_sources.backend.temporal.data_imports.sources.skio.skio import (+ SkioAPIError,+ SkioResumeConfig,+ _build_order_by,+ _build_where,+ _format_timestamp,+ get_rows,+ validate_credentials,+)++TOKEN = "test-token"++# Verbatim message from the live API for an invalid or revoked token (Hasura returns it with+# HTTP 200 in the GraphQL errors body).+INVALID_TOKEN_BODY = {"errors": [{"message": "Invalid response from authorization hook"}]}+++def _response(payload: dict[str, Any], status_code: int = 200) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = payload+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=response)+ else:+ response.raise_for_status.return_value = None+ return response+++def _rows(start: int, count: int, field: str = "updatedAt") -> list[dict[str, Any]]:+ return [+ {"id": f"id-{index:04d}", field: f"2026-01-01T00:00:{index % 60:02d}+00:00", "status": "ACTIVE"}+ for index in range(start, start + count)+ ]+++def _page(rows: list[dict[str, Any]], query_name: str = "Subscriptions") -> dict[str, Any]:+ return {"data": {query_name: rows}}+++def _manager(resume: SkioResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++def _run(+ session: MagicMock,+ endpoint: str = "subscriptions",+ manager: MagicMock | None = None,+ **kwargs: Any,+) -> tuple[list[list[dict[str, Any]]], MagicMock]:+ manager = manager if manager is not None else _manager()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.skio.skio.make_tracked_session",+ return_value=session,+ ):+ batches = list(+ get_rows(+ api_token=TOKEN,+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager,+ **kwargs,+ )+ )+ return batches, manager+++def _request_variables(session: MagicMock, call_index: int) -> dict[str, Any]:+ return session.post.call_args_list[call_index].kwargs["json"]["variables"]+++class TestSkioTransport:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ (date(2026, 3, 4), "2026-03-04"),+ ("2026-03-04T02:58:14+00:00", "2026-03-04T02:58:14+00:00"),+ ],+ )+ def test_format_timestamp(self, value: Any, expected: str) -> None:+ assert _format_timestamp(value) == expected++ def test_order_by_puts_cursor_field_before_id_tiebreak(self) -> None:+ assert _build_order_by("updatedAt") == [{"updatedAt": "asc"}, {"id": "asc"}]+ assert _build_order_by(None) == [{"id": "asc"}]++ @pytest.mark.parametrize(+ ("_name", "incremental_field", "last_value", "cursor", "expected"),+ [+ ("full_refresh_first_page", None, None, None, None),+ ("full_refresh_next_page", None, None, SkioResumeConfig(last_id="id-0099"), {"id": {"_gt": "id-0099"}}),+ (+ "incremental_first_page",+ "updatedAt",+ datetime(2026, 1, 1, tzinfo=UTC),+ None,+ {"updatedAt": {"_gte": "2026-01-01T00:00:00+00:00"}},+ ),+ (+ "incremental_next_page",+ "updatedAt",+ datetime(2026, 1, 1, tzinfo=UTC),+ SkioResumeConfig(last_id="id-0099", last_value="2026-01-02T00:00:00+00:00"),+ {+ "_and": [+ {"updatedAt": {"_gte": "2026-01-01T00:00:00+00:00"}},+ {+ "_or": [+ {"updatedAt": {"_gt": "2026-01-02T00:00:00+00:00"}},+ {+ "_and": [+ {"updatedAt": {"_eq": "2026-01-02T00:00:00+00:00"}},+ {"id": {"_gt": "id-0099"}},+ ]+ },+ ]+ },+ ]+ },+ ),+ ],+ )+ def test_build_where(+ self,+ _name: str,+ incremental_field: str | None,+ last_value: Any,+ cursor: SkioResumeConfig | None,+ expected: dict[str, Any] | None,+ ) -> None:+ assert _build_where(incremental_field, last_value, cursor) == expected++ def test_paginates_with_keyset_cursor_until_short_page(self) -> None:+ session = MagicMock()+ session.post.side_effect = [+ _response(_page(_rows(0, SKIO_PAGE_SIZE))),+ _response(_page(_rows(SKIO_PAGE_SIZE, 40))),+ ]++ batches, _ = _run(session)++ assert [len(batch) for batch in batches] == [SKIO_PAGE_SIZE, 40]+ assert session.post.call_count == 2+ # The second request continues strictly past the last row of the first page.+ assert _request_variables(session, 1)["where"] == {"id": {"_gt": f"id-{SKIO_PAGE_SIZE - 1:04d}"}}++ def test_full_refresh_first_request_has_no_watermark(self) -> None:+ session = MagicMock()+ session.post.side_effect = [_response(_page(_rows(0, 3)))]++ _run(+ session,+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )++ variables = _request_variables(session, 0)+ assert "where" not in variables+ assert variables["orderBy"] == [{"id": "asc"}]+ assert variables["limit"] == SKIO_PAGE_SIZE++ def test_incremental_request_filters_and_orders_on_cursor_field(self) -> None:+ session = MagicMock()+ session.post.side_effect = [_response(_page(_rows(0, 3)))]++ _run(+ session,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="updatedAt",+ )++ variables = _request_variables(session, 0)+ assert variables["where"] == {"updatedAt": {"_gte": "2026-01-01T00:00:00+00:00"}}+ assert variables["orderBy"] == [{"updatedAt": "asc"}, {"id": "asc"}]++ def test_sends_documented_authorization_header(self) -> None:+ # Skio's auth header is `authorization: API <token>`. The `API ` prefix and lowercase+ # header name are the documented, case-sensitive contract.+ session = MagicMock()+ session.post.side_effect = [_response(_page(_rows(0, 1)))]++ _run(session)++ assert session.post.call_args_list[0].kwargs["headers"] == {"authorization": f"API {TOKEN}"}++ def test_resumes_from_saved_cursor(self) -> None:+ session = MagicMock()+ session.post.side_effect = [_response(_page(_rows(0, 2)))]+ manager = _manager(resume=SkioResumeConfig(last_id="id-0042", last_value=None))++ _run(session, manager=manager)++ assert _request_variables(session, 0)["where"] == {"id": {"_gt": "id-0042"}}++ def test_saves_cursor_before_yielding_the_batch_it_covers(self) -> None:+ session = MagicMock()+ session.post.side_effect = [+ _response(_page(_rows(0, SKIO_PAGE_SIZE))),+ _response(_page(_rows(SKIO_PAGE_SIZE, 1))),+ ]+ manager = _manager()+ saved: list[str | None] = []+ manager.save_state.side_effect = lambda cursor: saved.append(cursor.last_id)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.skio.skio.make_tracked_session",+ return_value=session,+ ):+ generator = get_rows(+ api_token=TOKEN,+ endpoint="subscriptions",+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ next(generator)++ # The cursor covering page one is staged before the yield hands the page to the pipeline,+ # so the pipeline's post-write commit persists exactly the rows already written.+ assert saved == [f"id-{SKIO_PAGE_SIZE - 1:04d}"]++ def test_empty_first_page_yields_nothing(self) -> None:+ session = MagicMock()+ session.post.side_effect = [_response(_page([]))]++ batches, manager = _run(session)++ assert batches == []+ manager.save_state.assert_not_called()++ def test_graphql_errors_raise_with_verbatim_api_message(self) -> None:+ session = MagicMock()+ session.post.side_effect = [_response(INVALID_TOKEN_BODY)]++ with pytest.raises(SkioAPIError, match="Invalid response from authorization hook"):+ _run(session)++ def test_http_error_propagates_for_transport_retry_classification(self) -> None:+ session = MagicMock()+ session.post.side_effect = [_response({}, status_code=403)]++ with pytest.raises(requests.HTTPError):+ _run(session)+++class TestValidateCredentials:+ def _validate(self, session: MagicMock) -> tuple[bool, str | None]:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.skio.skio.make_tracked_session",+ return_value=session,+ ):+ return validate_credentials(TOKEN)++ def test_valid_token(self) -> None:+ session = MagicMock()+ session.post.return_value = _response(_page(_rows(0, 1)))++ assert self._validate(session) == (True, None)++ def test_invalid_token_maps_to_user_message(self) -> None:+ session = MagicMock()+ session.post.return_value = _response(INVALID_TOKEN_BODY)++ assert self._validate(session) == (False, "Invalid Skio API token")++ def test_token_without_table_access_maps_to_user_message(self) -> None:+ # Verbatim live-API message when the token's role cannot see the collection.+ session = MagicMock()+ session.post.return_value = _response(+ {"errors": [{"message": "field 'Subscriptions' not found in type: 'query_root'"}]}+ )++ assert self._validate(session) == (False, "Invalid Skio API token")++ def test_connection_error_reports_unreachable(self) -> None:+ session = MagicMock()+ session.post.side_effect = requests.ConnectionError("boom")++ valid, message = self._validate(session)+ assert valid is False+ assert message == "Could not connect to the Skio API"++ def test_other_graphql_error_surfaces_message(self) -> None:+ session = MagicMock()+ session.post.return_value = _response({"errors": [{"message": "query is not in any of the allowlists"}]})++ valid, message = self._validate(session)+ assert valid is False+ assert message is not None and "query is not in any of the allowlists" in message+++def test_get_rows_is_a_generator_and_defers_requests() -> None:+ # SourceResponse.items is called lazily; building the iterator must not hit the API.+ session = MagicMock()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.skio.skio.make_tracked_session",+ return_value=session,+ ):+ generator = get_rows(+ api_token=TOKEN,+ endpoint="subscriptions",+ logger=MagicMock(),+ resumable_source_manager=_manager(),+ )+ assert isinstance(generator, Iterator)+ session.post.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/skio/tests/test_skio_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/tests/test_skio_source.pynew file mode 100644index 000000000000..46f9e15a4e3a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/skio/tests/test_skio_source.py@@ -0,0 +1,54 @@+import pytest+from unittest.mock import MagicMock++from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.skio import SkioSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.skio.source import SkioSource+++def _inputs(schema_name: str) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-id",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestSkioSource:+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ source = SkioSource()+ with pytest.raises(ValueError, match="does not exist"):+ source.source_for_pipeline(+ SkioSourceConfig(api_token="token"),+ MagicMock(),+ _inputs("not_a_skio_table"),+ )++ def test_get_schemas_filters_by_names(self) -> None:+ source = SkioSource()+ schemas = source.get_schemas(SkioSourceConfig(api_token="token"), team_id=1, names=["orders", "customers"])+ assert sorted(schema.name for schema in schemas) == ["customers", "orders"]++ @pytest.mark.parametrize(+ "api_error_message",+ [+ # Verbatim strings the live API returns, kept as field knowledge: an invalid token and a+ # token whose role can't see the queried collection. Both ride an HTTP 200 body, so+ # they must match on the exception message for the sync to stop retrying.+ "Skio API error: Invalid response from authorization hook",+ "Skio API error: field 'Subscriptions' not found in type: 'query_root'",+ ],+ )+ def test_non_retryable_patterns_match_real_api_errors(self, api_error_message: str) -> None:+ source = SkioSource()+ assert error_message_matches(api_error_message, source.get_non_retryable_errors().keys())