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.

9.0 KB
Raw Blame
from products.warehouse_sources.sources.sdk import IncrementalField, IncrementalFieldType, frozen

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
}