Skip to content

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

feat(data-warehouse): add 4 missing tables to the Recurly source (#118306)

Tom Owers7010e5166003
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 39f1e10aa933..92c43e87a63e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -10060,10 +10060,10 @@ Today (16): `accounts`, `acquisitions`, `add_ons`, `coupons`, `credit_payments`,
Diffed against: <https://raw.githubusercontent.com/recurly/recurly-client-python/master/openapi/api.yaml>
-- [ ] `/accounts/{account_id}/coupon_redemptions (also /invoices/{id}/coupon_redemptions, /subscriptions/{id}/coupon_redemptions)` — the join table between coupons and accounts/invoices/subscriptions - without it synced coupons cannot be attributed to revenue (high)
-- [ ] `/business_entities` — lookup resolving the business_entity_id carried on accounts, invoices and subscriptions (high)
-- [ ] `/subscriptions/{subscription_id}/add_ons/{add_on_id}/usage` — usage records behind usage-based billing; the metered quantity that produces invoice line items (high)
-- [ ] `/external_invoices (and /external_subscriptions/{id}/external_invoices)` — app-store revenue for the external_subscriptions already synced (high)
+- [x] `/accounts/{account_id}/coupon_redemptions (also /invoices/{id}/coupon_redemptions, /subscriptions/{id}/coupon_redemptions)` — the join table between coupons and accounts/invoices/subscriptions - without it synced coupons cannot be attributed to revenue (high)
+- [x] `/business_entities` — lookup resolving the business_entity_id carried on accounts, invoices and subscriptions (high)
+- [x] `/subscriptions/{subscription_id}/add_ons/{add_on_id}/usage` — usage records behind usage-based billing; the metered quantity that produces invoice line items (high)
+- [x] `/external_invoices (and /external_subscriptions/{id}/external_invoices)` — app-store revenue for the external_subscriptions already synced (high)
- [ ] `/external_products and /external_products/{id}/external_product_references` — lookup resolving the product/reference IDs on external subscriptions (medium)
- [ ] `/accounts/{account_id}/billing_infos` — payment method type, card brand and expiry per account - drives churn and decline analysis (medium)
- [ ] `/accounts/{account_id}/balance` — outstanding balance per account in each currency, the standard AR metric (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/canonical_descriptions.py
index 82b3e0eb4933..0363fde87fec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/canonical_descriptions.py
@@ -68,6 +68,37 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
deleted_at="Time at which the add-on was deleted, if it has been.",
),
},
+ "business_entities": {
+ "description": "A business entity whose address Recurly uses on invoices and for tax calculation, depending on subscriber location.",
+ "docs_url": "https://recurly.com/developers/api/v2021-02-25/index.html#tag/business_entities",
+ "columns": _columns(
+ code="The entity code of the business entity.",
+ name="Name of the business entity, shown on the invoice.",
+ invoice_display_address="Address of the business entity that appears on the invoice.",
+ tax_address="Address of the business entity that is used to calculate taxes.",
+ default_vat_number="Default VAT number used on the invoice.",
+ default_registration_number="Default registration number used on the invoice.",
+ subscriber_location_countries="Countries for which this business entity is used.",
+ default_liability_gl_account_id="ID of the default liability general ledger account.",
+ default_revenue_gl_account_id="ID of the default revenue general ledger account.",
+ ),
+ },
+ "coupon_redemptions": {
+ "description": "A coupon applied to an account or subscription, used to track promotions.",
+ "docs_url": "https://recurly.com/developers/api/v2021-02-25/index.html#tag/coupon_redemption",
+ "columns": _columns(
+ account_id="ID of the account the coupon was applied to.",
+ uuid="Recurly's UUID for the coupon redemption.",
+ account="The account the coupon was applied to.",
+ subscription_id="ID of the subscription the coupon was applied to, if any.",
+ coupon="The coupon that was redeemed.",
+ state="State of the coupon redemption (active or inactive).",
+ remaining_duration="Number of billing cycles or time units left before the coupon expires.",
+ currency="Three-letter ISO currency code of the redemption.",
+ discounted="Amount discounted when the coupon was applied.",
+ removed_at="Time at which the redemption was removed from the account.",
+ ),
+ },
"coupons": {
"description": "A discount coupon that can be redeemed against subscriptions or invoices.",
"docs_url": "https://recurly.com/developers/api/v2021-02-25/index.html#tag/coupon",
@@ -124,6 +155,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
expires_at="Time at which the external subscription expires.",
),
},
+ "external_invoices": {
+ "description": "An invoice from a third-party platform such as the Apple App Store or Google Play Store.",
+ "docs_url": "https://recurly.com/developers/api/v2021-02-25/index.html#tag/external_invoice",
+ "columns": _columns(
+ account="The account the external invoice belongs to.",
+ external_subscription="The external subscription the invoice is for.",
+ external_id="Identifier of the invoice in the external platform.",
+ state="State of the external invoice.",
+ total="Total amount of the external invoice.",
+ currency="Three-letter ISO currency code of the external invoice.",
+ line_items="Line items on the external invoice.",
+ purchased_at="Time at which the invoice was created in the external platform.",
+ ),
+ },
"gift_cards": {
"description": "A gift card that can be redeemed to credit an account's balance.",
"docs_url": "https://recurly.com/developers/api/v2021-02-25/index.html#tag/gift_card",
@@ -278,4 +323,25 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
voided_at="Time at which the transaction was voided.",
),
},
+ "usage": {
+ "description": "A usage record logged on a usage-based subscription add-on and billed in arrears.",
+ "docs_url": "https://recurly.com/developers/api/v2021-02-25/index.html#tag/usage",
+ "columns": _columns(
+ subscription_id="ID of the subscription the usage was logged on.",
+ add_on_id="ID of the add-on the usage was logged on.",
+ merchant_tag="Your own identifier for the usage record.",
+ amount="Amount of usage. Can be positive, negative, or zero.",
+ usage_type="Type of usage (price or percentage).",
+ tier_type="Pricing model of the add-on (flat, tiered, stairstep, or volume).",
+ tiers="Tiers and prices of the add-on at the usage timestamp.",
+ percentage_tiers="Percentage tiers of the add-on at the usage timestamp.",
+ measured_unit_id="ID of the measured unit of the add-on.",
+ recording_timestamp="Time at which the usage was recorded in your system.",
+ usage_timestamp="Time at which the usage happened. Sets the billing period of the usage.",
+ usage_percentage="Percentage of the monetary amount of usage that is charged.",
+ unit_amount="Unit price of the usage.",
+ unit_amount_decimal="Unit price of the usage, with sub-cent precision.",
+ billed_at="Time at which the usage was billed on an invoice.",
+ ),
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/recurly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/recurly.py
index e0f3ad4127ac..587e83a96558 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/recurly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/recurly.py
@@ -1,4 +1,5 @@
import dataclasses
+from collections.abc import Callable
from datetime import UTC, date, datetime
from typing import Any, Optional
from urllib.parse import parse_qs, urlparse
@@ -9,10 +10,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ rename_parent_fields,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
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 EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.recurly.settings import (
RECURLY_BASE_URLS,
@@ -28,9 +36,49 @@ DEFAULT_SORT_FIELD = "updated_at"
VALID_SORT_FIELDS = ("created_at", "updated_at")
[email protected](frozen=True)
class RecurlyResumeConfig:
- next_cursor: str
+ # Top-level endpoints: the cursor of the next page.
+ next_cursor: str = ""
+ # Fan-out endpoints: the framework's dependent-resource resume state
+ # (`{"completed": [...], "current": ..., "child_state": ...}`).
+ fanout_state: Optional[dict[str, Any]] = None
+
+
[email protected](frozen=True)
+class RecurlyFanout:
+ # Child path param -> field of the (mapped) parent row that fills it. Each field is also
+ # copied onto the child rows under the path param's name.
+ path_bindings: dict[str, str]
+ child_params: dict[str, Any]
+ parent_data_map: Optional[Callable[[dict[str, Any]], list[dict[str, Any]]]] = None
+
+
+def _usage_add_ons(subscription: dict[str, Any]) -> list[dict[str, Any]]:
+ """Explode a subscription into one row per usage add-on, which is what the usage endpoint is keyed on."""
+ rows: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for subscription_add_on in subscription.get("add_ons") or []:
+ add_on = subscription_add_on.get("add_on") or {}
+ add_on_id = add_on.get("id")
+ # Fixed add-ons have no usage records, so requesting them only wastes a call.
+ if add_on.get("add_on_type") != "usage" or not add_on_id or add_on_id in seen:
+ continue
+ seen.add(add_on_id)
+ rows.append({"subscription_id": subscription["id"], "add_on_id": add_on_id})
+ return rows
+
+
+RECURLY_FANOUTS: dict[str, RecurlyFanout] = {
+ # The v2021-02-25 spec declares no `limit` or `order` for this list, and Recurly 400s on
+ # undeclared params (see `gift_cards`), so it is listed with the defaults.
+ "coupon_redemptions": RecurlyFanout(path_bindings={"account_id": "id"}, child_params={}),
+ "usage": RecurlyFanout(
+ path_bindings={"subscription_id": "subscription_id", "add_on_id": "add_on_id"},
+ child_params={"limit": PAGE_LIMIT, "sort": "recorded_timestamp", "order": "asc"},
+ parent_data_map=_usage_add_ons,
+ ),
+}
def _headers() -> dict[str, str]:
@@ -168,6 +216,96 @@ def get_resource(
}
+def _client_config(api_key: str, region: str) -> ClientConfig:
+ return {
+ "base_url": _base_url(region),
+ "headers": _headers(),
+ "auth": {
+ "type": "http_basic",
+ "username": api_key,
+ "password": "",
+ },
+ "paginator": RecurlyPaginator(),
+ }
+
+
+def _fanout_resource(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[RecurlyResumeConfig],
+) -> Resource:
+ config = RECURLY_ENDPOINTS[endpoint]
+ fanout = RECURLY_FANOUTS[endpoint]
+ parent_name = config.parent
+ assert parent_name is not None
+
+ parent: EndpointResource = {
+ "name": parent_name,
+ "table_name": parent_name,
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": "data",
+ "path": RECURLY_ENDPOINTS[parent_name].path,
+ "params": {"limit": PAGE_LIMIT, "sort": "created_at", "order": "asc"},
+ },
+ "table_format": "delta",
+ }
+ if fanout.parent_data_map is not None:
+ parent["data_map"] = fanout.parent_data_map
+
+ child_params: dict[str, Any] = {
+ param: {"type": "resolve", "resource": parent_name, "field": field}
+ for param, field in fanout.path_bindings.items()
+ }
+ child_params.update(fanout.child_params)
+ child: EndpointResource = {
+ "name": endpoint,
+ "table_name": endpoint,
+ "write_disposition": "replace",
+ "include_from_parent": list(fanout.path_bindings.values()),
+ "endpoint": {
+ "data_selector": "data",
+ "path": config.path,
+ "params": child_params,
+ # A parent removed between the listing and its child fetch must not fail the whole sync.
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
+ },
+ "table_format": "delta",
+ }
+
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_key, region),
+ "resource_defaults": {},
+ "resources": [parent, child],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None and resume_config.fanout_state:
+ initial_paginator_state = resume_config.fanout_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(RecurlyResumeConfig(fanout_state=state))
+
+ resources = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ child_resource = next(r for r in resources if r.name == endpoint)
+ return child_resource.add_map(
+ rename_parent_fields(parent_name, {field: param for param, field in fanout.path_bindings.items()})
+ )
+
+
def recurly_source(
api_key: str,
region: str,
@@ -179,19 +317,13 @@ def recurly_source(
should_use_incremental_field: bool = False,
incremental_field: Optional[str] = None,
) -> Resource:
+ if RECURLY_ENDPOINTS[endpoint].parent is not None:
+ return _fanout_resource(api_key, region, endpoint, team_id, job_id, resumable_source_manager)
+
incremental = should_use_incremental_field and RECURLY_ENDPOINTS[endpoint].supports_incremental
config: RESTAPIConfig = {
- "client": {
- "base_url": _base_url(region),
- "headers": _headers(),
- "auth": {
- "type": "http_basic",
- "username": api_key,
- "password": "",
- },
- "paginator": RecurlyPaginator(),
- },
+ "client": _client_config(api_key, region),
"resource_defaults": {
"write_disposition": {"disposition": "merge", "strategy": "upsert"} if incremental else "replace",
},
@@ -203,7 +335,7 @@ def recurly_source(
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume_config = resumable_source_manager.load_state()
- if resume_config is not None:
+ if resume_config is not None and resume_config.next_cursor:
initial_paginator_state = {"next_cursor": resume_config.next_cursor}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/settings.py
index 77681e3361a2..2ac0d00d941c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/settings.py
@@ -25,15 +25,29 @@ class RecurlyEndpoint:
# parameters at all — no `limit`, `sort`, `order`, or `begin_time`. Recurly rejects the
# request with a 400 validation error if any are sent, so it can only ever be listed bare.
supports_list_params: bool = True
+ # Set for endpoints that only exist per parent row (e.g. `/accounts/{account_id}/...`).
+ # They fan out over the parent listing and are always full refresh: rows arrive grouped
+ # by parent, not in time order, so an ascending watermark would skip rows.
+ parent: str | None = None
+ primary_keys: tuple[str, ...] = ("id",)
RECURLY_ENDPOINTS: dict[str, RecurlyEndpoint] = {
"accounts": RecurlyEndpoint("accounts", "/accounts", True),
"acquisitions": RecurlyEndpoint("acquisitions", "/acquisitions", True),
"add_ons": RecurlyEndpoint("add_ons", "/add_ons", True),
+ "business_entities": RecurlyEndpoint("business_entities", "/business_entities", False, supports_list_params=False),
+ "coupon_redemptions": RecurlyEndpoint(
+ "coupon_redemptions",
+ "/accounts/{account_id}/coupon_redemptions",
+ False,
+ parent="accounts",
+ primary_keys=("account_id", "id"),
+ ),
"coupons": RecurlyEndpoint("coupons", "/coupons", True),
"credit_payments": RecurlyEndpoint("credit_payments", "/credit_payments", True),
"dunning_campaigns": RecurlyEndpoint("dunning_campaigns", "/dunning_campaigns", False),
+ "external_invoices": RecurlyEndpoint("external_invoices", "/external_invoices", False),
"external_subscriptions": RecurlyEndpoint("external_subscriptions", "/external_subscriptions", False),
"gift_cards": RecurlyEndpoint("gift_cards", "/gift_cards", False, supports_list_params=False),
"invoices": RecurlyEndpoint("invoices", "/invoices", True),
@@ -44,6 +58,13 @@ RECURLY_ENDPOINTS: dict[str, RecurlyEndpoint] = {
"shipping_methods": RecurlyEndpoint("shipping_methods", "/shipping_methods", True),
"subscriptions": RecurlyEndpoint("subscriptions", "/subscriptions", True),
"transactions": RecurlyEndpoint("transactions", "/transactions", True),
+ # Usage ids are unique site-wide (Recurly serves them at `/usage/{usage_id}`).
+ "usage": RecurlyEndpoint(
+ "usage",
+ "/subscriptions/{subscription_id}/add_ons/{add_on_id}/usage",
+ False,
+ parent="subscriptions",
+ ),
}
ENDPOINTS = tuple(RECURLY_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/source.py
index f7d2a57c2b49..7b4f27d8c9c5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/source.py
@@ -129,7 +129,7 @@ class RecurlySource(ResumableSource[RecurlySourceConfig, RecurlyResumeConfig]):
return SourceResponse(
name=resource.name,
items=lambda: resource,
- primary_keys=["id"],
+ primary_keys=list(RECURLY_ENDPOINTS[inputs.schema_name].primary_keys),
column_hints=resource.column_hints,
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/tests/test_recurly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/tests/test_recurly.py
index ed03eff74c23..9d340d9e3c38 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/tests/test_recurly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recurly/tests/test_recurly.py
@@ -8,6 +8,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
ScriptedResponse,
SourceDriver,
always,
+ route,
scripted_network,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.recurly import (
@@ -18,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.recurly.re
RecurlyResumeConfig,
_extract_cursor,
_format_datetime,
+ _usage_add_ons,
get_resource,
validate_credentials,
)
@@ -62,6 +64,36 @@ class TestRecurlyHelpers:
assert _format_datetime("2024-01-02T00:00:00Z") == "2024-01-02T00:00:00Z"
+class TestUsageAddOns:
+ @pytest.mark.parametrize(
+ "add_ons, expected_add_on_ids",
+ [
+ ([], []),
+ (None, []),
+ ([{"add_on": {"id": "u1", "add_on_type": "usage"}}], ["u1"]),
+ ([{"add_on": {"id": "f1", "add_on_type": "fixed"}}], []),
+ ([{"add_on": {"id": "u1"}}], []),
+ ([{"add_on": {"add_on_type": "usage"}}], []),
+ ([{"add_on": None}, {}], []),
+ (
+ [
+ {"add_on": {"id": "u1", "add_on_type": "usage"}},
+ {"add_on": {"id": "f1", "add_on_type": "fixed"}},
+ {"add_on": {"id": "u1", "add_on_type": "usage"}},
+ {"add_on": {"id": "u2", "add_on_type": "usage"}},
+ ],
+ ["u1", "u2"],
+ ),
+ ],
+ )
+ def test_explodes_subscription_into_usage_add_ons(
+ self, add_ons: list[dict[str, Any]] | None, expected_add_on_ids: list[str]
+ ) -> None:
+ rows = _usage_add_ons({"id": "sub-1", "add_ons": add_ons})
+
+ assert rows == [{"subscription_id": "sub-1", "add_on_id": add_on_id} for add_on_id in expected_add_on_ids]
+
+
class TestRecurlyPaginator:
def test_update_state_has_more_but_missing_cursor_terminates(self):
paginator = RecurlyPaginator()
@@ -174,3 +206,120 @@ class TestRecurlySourceResumeBehavior:
result = self._driver().run("accounts", [ScriptedResponse(json=_list_body([{"id": "a"}], has_more=False))])
assert result.params("cursor") == [None]
+
+
+class TestRecurlyFanOut:
+ @staticmethod
+ def _driver() -> SourceDriver:
+ return SourceDriver(RecurlySource(), RecurlySourceConfig(api_key="test-key", region="us"))
+
+ def test_coupon_redemptions_walk_every_account_and_tag_rows(self) -> None:
+ result = self._driver().run(
+ "coupon_redemptions",
+ route(
+ {
+ "/accounts": [
+ ScriptedResponse(
+ json=_list_body(
+ [{"id": "a1"}, {"id": "a2"}], has_more=True, next_path="/accounts?cursor=p2"
+ )
+ ),
+ ScriptedResponse(json=_list_body([{"id": "a3"}])),
+ ],
+ "/accounts/a1/coupon_redemptions": [
+ ScriptedResponse(
+ json=_list_body(
+ [{"id": "r1"}], has_more=True, next_path="/accounts/a1/coupon_redemptions?cursor=c2"
+ )
+ ),
+ ScriptedResponse(json=_list_body([{"id": "r2"}])),
+ ],
+ # An account closed between the listing and its child fetch.
+ "/accounts/a2/coupon_redemptions": [ScriptedResponse(status=404, json={"error": {}})],
+ "/accounts/a3/coupon_redemptions": [ScriptedResponse(json=_list_body([{"id": "r3"}]))],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert [(row["account_id"], row["id"]) for row in result.rows] == [("a1", "r1"), ("a1", "r2"), ("a3", "r3")]
+ assert all("_accounts_id" not in row for row in result.rows)
+ assert result.response is not None
+ assert result.response.primary_keys == ["account_id", "id"]
+ child_queries = [request.query for request in result.requests if request.path.endswith("/coupon_redemptions")]
+ # The spec declares no `limit` or `order` here, so only the pagination cursor may be sent.
+ assert child_queries == [{}, {"cursor": ("c2",)}, {}, {}]
+
+ def test_usage_requests_only_usage_add_ons_and_tags_rows(self) -> None:
+ subscriptions: list[dict[str, Any]] = [
+ {
+ "id": "s1",
+ "add_ons": [
+ {"add_on": {"id": "u1", "add_on_type": "usage"}},
+ {"add_on": {"id": "f1", "add_on_type": "fixed"}},
+ ],
+ },
+ {"id": "s2", "add_ons": []},
+ {"id": "s3", "add_ons": [{"add_on": {"id": "u2", "add_on_type": "usage"}}]},
+ ]
+ result = self._driver().run(
+ "usage",
+ route(
+ {
+ "/subscriptions": [ScriptedResponse(json=_list_body(subscriptions))],
+ "/subscriptions/s1/add_ons/u1/usage": [
+ ScriptedResponse(
+ json=_list_body(
+ [{"id": "x1"}], has_more=True, next_path="/subscriptions/s1/add_ons/u1/usage?cursor=c2"
+ )
+ ),
+ ScriptedResponse(json=_list_body([{"id": "x2"}])),
+ ],
+ "/subscriptions/s3/add_ons/u2/usage": [ScriptedResponse(json=_list_body([{"id": "x3"}]))],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert [(row["subscription_id"], row["add_on_id"], row["id"]) for row in result.rows] == [
+ ("s1", "u1", "x1"),
+ ("s1", "u1", "x2"),
+ ("s3", "u2", "x3"),
+ ]
+ usage_requests = [request for request in result.requests if request.path.endswith("/usage")]
+ assert [request.path for request in usage_requests] == [
+ "/subscriptions/s1/add_ons/u1/usage",
+ "/subscriptions/s1/add_ons/u1/usage",
+ "/subscriptions/s3/add_ons/u2/usage",
+ ]
+ assert {(r.param("sort"), r.param("order"), r.param("limit")) for r in usage_requests} == {
+ ("recorded_timestamp", "asc", "200")
+ }
+
+ def test_resume_skips_completed_parents_and_continues_the_current_one(self) -> None:
+ result = self._driver().run(
+ "coupon_redemptions",
+ route(
+ {
+ "/accounts": [ScriptedResponse(json=_list_body([{"id": "a1"}, {"id": "a2"}, {"id": "a3"}]))],
+ "/accounts/a2/coupon_redemptions": [ScriptedResponse(json=_list_body([{"id": "r2"}]))],
+ "/accounts/a3/coupon_redemptions": [ScriptedResponse(json=_list_body([{"id": "r3"}]))],
+ }
+ ),
+ resume_state=RecurlyResumeConfig(
+ fanout_state={
+ "completed": ["/accounts/a1/coupon_redemptions"],
+ "current": "/accounts/a2/coupon_redemptions",
+ "child_state": {"next_cursor": "c-resumed"},
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["r2", "r3"]
+ child_requests = [r for r in result.requests if r.path.endswith("/coupon_redemptions")]
+ assert [(r.path, r.param("cursor")) for r in child_requests] == [
+ ("/accounts/a2/coupon_redemptions", "c-resumed"),
+ ("/accounts/a3/coupon_redemptions", None),
+ ]
+ assert all(state.next_cursor == "" and state.fanout_state for state in result.saved_states)