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 Loop Returns source (#117509)

Tom Owers6f23e412230b
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 943e6711fec6..3a06263916ba 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
@@ -7429,10 +7429,10 @@ Today (3): `advanced_shipping_notices`, `destinations`, `returns`
Diffed against: <https://docs.loopreturns.com/llms.txt>
-- [ ] `Orders (GET /api/v1/orders)` — resolve return order IDs and supply sales denominators for return-rate analysis (high)
-- [ ] `Products (GET /api/v1/products)` — resolve product references on returned and exchanged items for catalog analysis (high)
-- [ ] `Product variants (GET /api/v1/products/{productId}/product-variants)` — resolve variant references for return rates by SKU and product option (high)
-- [ ] `Customers (GET /api/v1/customers)` — analyze repeat return behavior and customer cohorts beyond the email on a return (medium)
+- [x] `Orders (GET /api/v1/orders)` — resolve return order IDs and supply sales denominators for return-rate analysis (high)
+- [x] `Products (GET /api/v1/products)` — resolve product references on returned and exchanged items for catalog analysis (high)
+- [x] `Product variants (GET /api/v1/products/{productId}/product-variants)` — resolve variant references for return rates by SKU and product option (high)
+- [x] `Customers (GET /api/v1/customers)` — analyze repeat return behavior and customer cohorts beyond the email on a return (medium)
- [ ] `Return notes (GET /api/v1/warehouse/return/{id}/notes)` — analyze support explanations and operational handling of returns (medium)
- [ ] `Inventories (GET /api/v1/inventories)` — compare exchange demand with stock availability by variant and location (medium)
- [ ] `Locations (GET /api/v1/locations)` — provide location names and metadata for inventory analysis (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/canonical_descriptions.py
index b9c33499a6fc..414b5079a47c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/canonical_descriptions.py
@@ -122,4 +122,76 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"address": "Postal address of the destination.",
},
},
+ "orders": {
+ "description": "Orders in your shop that Loop knows about, with their line items, totals, fulfillments and refunds.",
+ "docs_url": "https://docs.loopreturns.com/api-reference/latest/orders/list-orders",
+ "columns": {
+ "id": "Unique identifier for the order, created by Loop.",
+ "external_id": "Identifier of the order in the external commerce platform.",
+ "name": "Name of the order.",
+ "sales_channel": "Name of the sales channel the order came from.",
+ "customer": "Customer who placed the order.",
+ "status": "Status of the order: active, archived, cancelled or unknown.",
+ "financial_status": "Financial status of the order.",
+ "total_price": "Price of the order in minor units, such as cents, with its currency.",
+ "total_discounts": "Discounts applied to the order, in minor units.",
+ "total_taxes": "Tax amount for the order, in minor units.",
+ "line_items": "Items bought on the order.",
+ "fulfillments": "Fulfillments of the order.",
+ "refunds": "Refunds issued against the order.",
+ "cancel_reason": "Reason the order was cancelled, if it was.",
+ "processed_at": "When the order was processed in the source system.",
+ "created_at": "When the order was created.",
+ "updated_at": "When the order was last updated.",
+ },
+ },
+ "products": {
+ "description": "Products in your shop catalog.",
+ "docs_url": "https://docs.loopreturns.com/api-reference/latest/products/list-products",
+ "columns": {
+ "id": "Unique identifier for the product, created by Loop.",
+ "external_id": "Identifier of the product in the external commerce platform.",
+ "sales_channel": "Name of the sales channel.",
+ "sku": "SKU of the product.",
+ "name": "Name of the product.",
+ "type": "Type used to classify and group similar products.",
+ "vendor": "Manufacturer or seller of the product.",
+ "price": "Price of the product in minor units, such as cents, with its currency.",
+ "collections": "Collections the product belongs to.",
+ "tags": "Tags used to classify and group products.",
+ "default_variant_id": "Identifier of the product's default variant, set only when the product has no explicit variants.",
+ "created_at": "When the product was created.",
+ "updated_at": "When the product was last updated.",
+ },
+ },
+ "product_variants": {
+ "description": "Variants of each product in your shop catalog, such as a size or color.",
+ "docs_url": "https://docs.loopreturns.com/api-reference/latest/products/list-product-variants",
+ "columns": {
+ "id": "Unique identifier for the product variant, created by Loop.",
+ "product_id": "Identifier of the parent product, created by Loop.",
+ "external_id": "Identifier of the product variant in the external commerce platform.",
+ "sku": "SKU of the product variant.",
+ "name": "Name of the product variant.",
+ "barcode": "Barcode of the product variant.",
+ "product": "Details of the parent product.",
+ "price": "Price of the product variant in minor units, such as cents, with its currency.",
+ "inventories": "Available count of the product variant per location.",
+ "options": "Options of the product variant that the customer can select.",
+ },
+ },
+ "customers": {
+ "description": "Customers of your shop.",
+ "docs_url": "https://docs.loopreturns.com/api-reference/latest/customers/list-customers",
+ "columns": {
+ "id": "Unique identifier for the customer, created by Loop.",
+ "external_id": "Identifier of the customer in the external commerce platform.",
+ "sales_channel": "Name of the sales channel the customer belongs to.",
+ "first_name": "Given name of the customer.",
+ "last_name": "Surname of the customer.",
+ "email": "Email address of the customer.",
+ "phone": "Phone number of the customer.",
+ "tags": "Tags associated with the customer.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py
index b1737051110b..2a0595f2f467 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py
@@ -11,11 +11,16 @@ 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,
SinglePagePaginator,
)
+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 (
Endpoint,
EndpointResource,
@@ -23,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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.loop_returns.settings import (
+ CURSOR_PAGE_SIZE,
DEFAULT_BACKFILL_DAYS,
DEFAULT_PAGE_SIZE,
FILTER_FIELDS,
@@ -119,8 +125,17 @@ def resolve_filter_field(should_use_incremental_field: bool, incremental_field:
return FILTER_FIELDS[0]
-def next_cursor(response: Response) -> Optional[str]:
- """The `cursor` value of the response's `nextPageUrl`, or `None` on the last page.
+def _has_next_link(response: Response, link_key: str) -> bool:
+ try:
+ body = response.json()
+ except ValueError:
+ return False
+
+ return isinstance(body, dict) and bool(body.get(link_key))
+
+
+def next_cursor(response: Response, link_key: str = "nextPageUrl") -> Optional[str]:
+ """The `cursor` value of the response's next page link, or `None` on the last page.
The cursor is re-applied to our own params rather than following `nextPageUrl` verbatim, so the
window and state filters stay attached to every page even if Loop's link were to drop them.
@@ -133,7 +148,7 @@ def next_cursor(response: Response) -> Optional[str]:
if not isinstance(body, dict):
return None
- next_page_url = body.get("nextPageUrl")
+ next_page_url = body.get(link_key)
if not next_page_url or not isinstance(next_page_url, str):
return None
@@ -147,16 +162,17 @@ def next_cursor(response: Response) -> Optional[str]:
return cursors[0]
[email protected](frozen=True)
class LoopReturnsResumeConfig:
- """Checkpoint for a windowed endpoint: which state pass, which window, which page.
+ """Checkpoint for a windowed endpoint (which state pass, which window, which page), or the
+ next page cursor of a cursor-paginated endpoint, which has no `window_start`.
Windows are re-derived from `window_start` with a fixed width, so boundaries stay identical
across attempts. State is saved after a batch is yielded, so a crash re-yields the last batch
(merge dedupes on the primary key) instead of skipping it.
"""
- window_start: str
+ window_start: Optional[str] = None
state_index: int = 0
cursor: Optional[str] = None
@@ -279,12 +295,86 @@ class LoopReturnsPaginator(BasePaginator):
return f"LoopReturnsPaginator(endpoint={self._config.name})"
+class LoopCursorPaginator(BasePaginator):
+ """Follows the `cursor` in the `next_page_url` of Loop's catalog endpoints.
+
+ Like `LoopReturnsPaginator`, the cursor is re-applied to our own params, so `limit` and
+ `sort_order` stay on every page even if Loop's link were to drop them.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._cursor: Optional[str] = None
+ self._previous_cursor: Optional[str] = None
+
+ def _apply(self, request: Request) -> None:
+ params = request.params if request.params is not None else {}
+ request.params = params
+ if self._cursor is not None:
+ params["cursor"] = self._cursor
+ else:
+ params.pop("cursor", None)
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ cursor = next_cursor(response, link_key="next_page_url")
+ if cursor is not None and cursor == self._previous_cursor:
+ # These tables are full refresh, so ending early would publish a truncated snapshot.
+ raise ValueError(f"Loop Returns pagination is not advancing (repeated cursor {cursor!r})")
+
+ if cursor is not None:
+ self._previous_cursor = cursor
+ self._cursor = cursor
+ self._has_next_page = True
+ return
+
+ if _has_next_link(response, "next_page_url"):
+ raise ValueError("Loop Returns next_page_url carried no usable cursor")
+
+ self._has_next_page = False
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ if not self._has_next_page or self._cursor is None:
+ return None
+ return {"cursor": self._cursor}
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ cursor = state.get("cursor")
+ if not cursor:
+ return
+
+ self._cursor = str(cursor)
+ # Seed the repeat guard so a checkpoint whose cursor the API echoes back stops instead of
+ # looping on the same page.
+ self._previous_cursor = self._cursor
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return "LoopCursorPaginator()"
+
+
def get_resource(config: LoopReturnsEndpointConfig, should_use_incremental_field: bool) -> EndpointResource:
endpoint: Endpoint = {"path": config.path}
if config.data_selector is not None:
endpoint["data_selector"] = config.data_selector
- return {
+ params: dict[str, Any] = {}
+ if config.cursor_paginate:
+ params["limit"] = CURSOR_PAGE_SIZE
+ params["sort_order"] = "asc"
+ if config.parent is not None:
+ params["parent_id"] = {"type": "resolve", "resource": config.parent, "field": "id"}
+ # A parent deleted between the parent listing and its child request has no children left.
+ endpoint["response_actions"] = [{"status_code": 404, "action": "ignore"}]
+ if params:
+ endpoint["params"] = params
+
+ resource: EndpointResource = {
"name": config.name,
"table_name": config.name,
"write_disposition": {"disposition": "merge", "strategy": "upsert"}
@@ -293,25 +383,33 @@ def get_resource(config: LoopReturnsEndpointConfig, should_use_incremental_field
"endpoint": endpoint,
"table_format": "delta",
}
+ if config.parent is not None:
+ resource["include_from_parent"] = ["id"]
+ resource["data_map"] = rename_parent_fields(config.parent, {"id": config.parent_id_column})
+ return resource
def probe_endpoint(api_key: str, api_version: str, endpoint: str) -> tuple[bool, str | None]:
"""One cheap request against `endpoint`, reporting whether the key can read it."""
config = LOOP_RETURNS_ENDPOINTS[endpoint]
+ # A child endpoint needs a parent id in its path, and its parent's list needs the same scope.
+ probe_config = LOOP_RETURNS_ENDPOINTS[config.parent] if config.parent is not None else config
params: dict[str, Any] = {}
- if config.windowed:
+ if probe_config.windowed:
end = datetime.now(UTC)
params["from"] = _format_datetime(end - timedelta(hours=1))
params["to"] = _format_datetime(end)
- if config.paginate:
+ if probe_config.paginate:
params["paginate"] = "true"
params["pageSize"] = 1
+ if probe_config.cursor_paginate:
+ params["limit"] = 1
session = make_tracked_session(redact_values=(api_key,))
try:
response = session.get(
- f"{base_url(api_version)}{config.path}",
+ f"{base_url(api_version)}{probe_config.path}",
headers={AUTH_HEADER: api_key},
params=params,
timeout=PROBE_TIMEOUT_SECONDS,
@@ -340,11 +438,17 @@ def validate_credentials(api_key: str, api_version: str, schema_name: Optional[s
if is_valid:
return True, None
- # A key scoped for another table only is still a working key, so don't block setup on the
- # returns probe alone. Per-table scope gaps surface in the table picker instead.
- fallback_valid, _ = probe_endpoint(api_key, api_version, "destinations")
- if fallback_valid:
- return True, None
+ # A key scoped for other tables only is still a working key, so don't block setup on the
+ # returns probe alone. One table per scope is enough. Per-table scope gaps surface in the
+ # table picker instead.
+ probed_scopes = {LOOP_RETURNS_ENDPOINTS["returns"].required_scope}
+ for name, config in LOOP_RETURNS_ENDPOINTS.items():
+ if config.required_scope in probed_scopes:
+ continue
+ probed_scopes.add(config.required_scope)
+ fallback_valid, _ = probe_endpoint(api_key, api_version, name)
+ if fallback_valid:
+ return True, None
return False, error
@@ -378,7 +482,9 @@ def loop_returns_source(
window_end = now or datetime.now(UTC)
paginator: BasePaginator
- if config.windowed:
+ if config.cursor_paginate:
+ paginator = LoopCursorPaginator()
+ elif config.windowed:
paginator = LoopReturnsPaginator(
config=config,
window_start=resolve_window_start(
@@ -406,16 +512,28 @@ def loop_returns_source(
},
"resources": [get_resource(config, should_use_incremental_field)],
}
+ if config.parent is not None:
+ rest_config["resources"].insert(0, get_resource(LOOP_RETURNS_ENDPOINTS[config.parent], False))
+
+ # A fan-out's resume state lists every finished parent, which grows with the catalog, so a
+ # child endpoint restarts from its first parent instead.
+ resumable = (config.windowed or config.cursor_paginate) and config.parent is None
initial_paginator_state: Optional[dict[str, Any]] = None
- if config.windowed and resumable_source_manager.can_resume():
+ if resumable and resumable_source_manager.can_resume():
resume_config = resumable_source_manager.load_state()
if resume_config is not None:
initial_paginator_state = dataclasses.asdict(resume_config)
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# Called after each batch is yielded; `None` once the paginator is exhausted.
- if not state or not state.get("window_start"):
+ if not state:
+ return
+ if config.cursor_paginate:
+ if state.get("cursor"):
+ resumable_source_manager.save_state(LoopReturnsResumeConfig(cursor=str(state["cursor"])))
+ return
+ if not state.get("window_start"):
return
resumable_source_manager.save_state(
LoopReturnsResumeConfig(
@@ -425,20 +543,27 @@ def loop_returns_source(
)
)
- resource = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- # Window bounds are computed here, not by the framework's incremental params.
- None,
- resume_hook=save_checkpoint if config.windowed else None,
- initial_paginator_state=initial_paginator_state,
- )
+ resource: Resource
+ if config.parent is not None:
+ resource = next(
+ item for item in rest_api_resources(rest_config, team_id, job_id, None) if item.name == endpoint
+ )
+ else:
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ # Window bounds are computed here, not by the framework's incremental params.
+ None,
+ resume_hook=save_checkpoint if resumable else None,
+ initial_paginator_state=initial_paginator_state,
+ )
return SourceResponse(
name=endpoint,
items=lambda: resource,
primary_keys=list(config.primary_keys),
+ supports_resume=resumable,
# Loop documents no ordering within a window, so a mid-sync watermark write could skip rows
# the run never reached. "desc" defers that write to a successful job end
# (finalize_desc_sort_incremental_value); the next run re-reads from the old watermark and
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.py
index f9d6fd215a61..d0f39f051700 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.py
@@ -16,6 +16,10 @@ MAX_WINDOW_DAYS = 90
# stay well under the cap to keep a single page's payload modest.
DEFAULT_PAGE_SIZE = 250
+# `limit` cap on the cursor-paginated catalog endpoints (orders, products, product variants and
+# customers). Loop documents 250 as the maximum on orders, customers and product variants.
+CURSOR_PAGE_SIZE = 250
+
# How far back a first sync reaches when the user doesn't give a start date. Without `from`/`to`
# Loop only returns the previous 24 hours, so a default is required for a usable backfill.
DEFAULT_BACKFILL_DAYS = 730
@@ -42,6 +46,8 @@ class LoopReturnsEndpointConfig:
data_selector: str | None = None
# Cursor pagination through `paginate`/`pageSize` with a `nextPageUrl` in the body.
paginate: bool = False
+ # Cursor pagination through `limit`/`cursor` with a `next_page_url` in the body.
+ cursor_paginate: bool = False
# Endpoint accepts `from`/`to`, so history is walked in windows.
windowed: bool = False
# States fetched one pass each; empty means the endpoint has no `state` param.
@@ -52,6 +58,10 @@ class LoopReturnsEndpointConfig:
partition_key: str | None = None
# API key scope the endpoint needs, as named in Loop's dashboard.
required_scope: str = "Returns"
+ # Endpoint whose row `id` fills the `{parent_id}` path placeholder, one request per parent row.
+ parent: str | None = None
+ # Column that carries the parent row's `id` on each child row.
+ parent_id_column: str = "parent_id"
LOOP_RETURNS_ENDPOINTS: dict[str, LoopReturnsEndpointConfig] = {
@@ -83,6 +93,44 @@ LOOP_RETURNS_ENDPOINTS: dict[str, LoopReturnsEndpointConfig] = {
data_selector="destinations",
required_scope="Destinations (Read)",
),
+ "orders": LoopReturnsEndpointConfig(
+ name="orders",
+ path="/orders",
+ primary_keys=("id",),
+ data_selector="orders",
+ cursor_paginate=True,
+ partition_key="created_at",
+ required_scope="Order (Read)",
+ ),
+ "products": LoopReturnsEndpointConfig(
+ name="products",
+ path="/products",
+ primary_keys=("id",),
+ data_selector="products",
+ cursor_paginate=True,
+ partition_key="created_at",
+ required_scope="Product (Read)",
+ ),
+ "product_variants": LoopReturnsEndpointConfig(
+ name="product_variants",
+ path="/products/{parent_id}/product-variants",
+ # Rows from every product land in one table, and the docs don't say that a variant id is
+ # unique across products, so the parent product id is part of the key.
+ primary_keys=("product_id", "id"),
+ data_selector="product_variants",
+ cursor_paginate=True,
+ required_scope="Product (Read)",
+ parent="products",
+ parent_id_column="product_id",
+ ),
+ "customers": LoopReturnsEndpointConfig(
+ name="customers",
+ path="/customers",
+ primary_keys=("id",),
+ data_selector="customers",
+ cursor_paginate=True,
+ required_scope="Customers (Read)",
+ ),
}
ENDPOINTS = tuple(LOOP_RETURNS_ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/source.py
index 59e556fd0182..0a28936a3f91 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/source.py
@@ -70,7 +70,7 @@ class LoopReturnsSource(ResumableSource[LoopReturnsSourceConfig, LoopReturnsResu
docsUrl="https://posthog.com/docs/cdp/sources/loop-returns",
caption="""Enter your Loop API key to pull your returns data into the PostHog Data warehouse.
-Create a key in Loop under **Settings** > **Developers**. The key needs the `Returns` scope for the returns and advanced shipping notice tables, and `Destinations (Read)` for the destinations table.
+Create a key in Loop under **Settings** > **Developers**. The key needs the `Returns` scope for the returns and advanced shipping notice tables, `Destinations (Read)` for the destinations table, `Order (Read)` for the orders table, `Product (Read)` for the products and product variants tables, and `Customers (Read)` for the customers table.
Start date is optional and sets how far back the first sync reaches. Without it, syncing starts two years ago.""",
iconPath="/static/services/loop_returns.png",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.py
index 42f917b92ede..87a01ac702f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.py
@@ -11,6 +11,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.loopreturns import (
@@ -220,6 +221,109 @@ class TestLoopReturnsSource:
assert result.queries == [{}]
assert result.saved_states == []
+ @pytest.mark.parametrize(
+ ("label", "last_next_page_url"),
+ [
+ ("null_next_link", None),
+ ],
+ )
+ def test_a_cursor_endpoint_walks_pages_until_the_next_link_ends(
+ self, label: str, last_next_page_url: str | None
+ ) -> None:
+ result = self._driver().run(
+ "orders",
+ [
+ ScriptedResponse(
+ json={
+ "orders": [{"id": 1}, {"id": 2}],
+ "next_page_url": "https://api.loopreturns.com/api/v1/orders?cursor=c1",
+ }
+ ),
+ ScriptedResponse(json={"orders": [{"id": 3}], "next_page_url": last_next_page_url}),
+ ],
+ api_version=API_VERSION,
+ )
+
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == [1, 2, 3]
+ assert result.params("cursor") == [None, "c1"]
+ # Our own page size and sort stay on every page, whatever Loop's next link carries.
+ assert result.params("limit") == ["250", "250"]
+ assert result.params("sort_order") == ["asc", "asc"]
+ assert result.saved_states == [LoopReturnsResumeConfig(cursor="c1")]
+
+ @pytest.mark.parametrize(
+ ("label", "second_link", "message"),
+ [
+ ("repeated_cursor", "https://api.loopreturns.com/api/v1/orders?cursor=c1", "not advancing"),
+ ("link_without_cursor", "https://api.loopreturns.com/api/v1/orders?limit=250", "no usable cursor"),
+ ],
+ )
+ def test_a_cursor_endpoint_fails_when_the_next_link_cannot_be_followed(
+ self, label: str, second_link: str, message: str
+ ) -> None:
+ result = self._driver().run(
+ "orders",
+ [
+ ScriptedResponse(
+ json={"orders": [{"id": 1}], "next_page_url": "https://api.loopreturns.com/api/v1/orders?cursor=c1"}
+ ),
+ ScriptedResponse(json={"orders": [{"id": 2}], "next_page_url": second_link}),
+ ],
+ api_version=API_VERSION,
+ )
+
+ assert isinstance(result.raised, ValueError)
+ assert message in str(result.raised)
+
+ def test_a_resumed_cursor_endpoint_starts_at_the_saved_cursor(self) -> None:
+ result = self._driver().run(
+ "customers",
+ [ScriptedResponse(json={"customers": [{"id": 7}], "next_page_url": None})],
+ resume_state=LoopReturnsResumeConfig(cursor="c5"),
+ api_version=API_VERSION,
+ )
+
+ assert result.raised is None
+ assert result.params("cursor") == ["c5"]
+ assert [row["id"] for row in result.rows] == [7]
+
+ def test_product_variants_fan_out_over_every_product(self) -> None:
+ result = self._driver().run(
+ "product_variants",
+ route(
+ {
+ "/products": [
+ ScriptedResponse(json={"products": [{"id": 10}, {"id": 20}], "next_page_url": None}),
+ ],
+ "/products/10/product-variants": [
+ ScriptedResponse(
+ json={
+ "product_variants": [{"id": 1}],
+ "next_page_url": "https://api.loopreturns.com/api/v1/products/10/product-variants?cursor=v1",
+ }
+ ),
+ ScriptedResponse(json={"product_variants": [{"id": 2}], "next_page_url": None}),
+ ],
+ # A product deleted after the product listing ran.
+ "/products/20/product-variants": [ScriptedResponse(status=404, json={"message": "Not found"})],
+ }
+ ),
+ api_version=API_VERSION,
+ )
+
+ assert result.raised is None
+ assert [(row["product_id"], row["id"]) for row in result.rows] == [(10, 1), (10, 2)]
+ assert all("_products_id" not in row for row in result.rows)
+ assert result.paths == [
+ "/api/v1/products",
+ "/api/v1/products/10/product-variants",
+ "/api/v1/products/10/product-variants",
+ "/api/v1/products/20/product-variants",
+ ]
+ assert result.params("cursor") == [None, None, "v1", None]
+ assert result.saved_states == []
+
class TestCredentialValidation:
@pytest.mark.parametrize(
@@ -228,14 +332,16 @@ class TestCredentialValidation:
("returns_readable", [200], True),
# A key scoped only for destinations still works, just for fewer tables.
("returns_denied_destinations_readable", [401, 200], True),
- ("everything_denied", [401, 401], False),
- ("forbidden", [403, 403], False),
- ("server_error", [500, 500], False),
+ # One probe per scope: returns, destinations, orders, products, then customers.
+ ("only_customers_readable", [401, 401, 401, 401, 200], True),
+ ("everything_denied", [401] * 5, False),
+ ("forbidden", [403] * 5, False),
+ ("server_error", [500], False),
],
)
def test_validate_credentials(self, label: str, status_codes: list[int], expected_valid: bool) -> None:
responses = [ScriptedResponse(status=code, json={}) for code in status_codes]
- script = always(responses[0]) if status_codes == [500, 500] else responses
+ script = always(responses[0]) if status_codes == [500] else responses
with scripted_network(script):
is_valid, error = validate_credentials(API_KEY, API_VERSION)
@@ -243,18 +349,26 @@ class TestCredentialValidation:
assert (error is None) is expected_valid
def test_a_denied_key_names_the_scope_to_add(self) -> None:
- with scripted_network([ScriptedResponse(status=401), ScriptedResponse(status=401)]):
+ with scripted_network(always(ScriptedResponse(status=401))):
_, error = validate_credentials(API_KEY, API_VERSION)
assert error is not None
assert "Returns" in error
- def test_validating_one_schema_probes_only_that_endpoint(self) -> None:
- with scripted_network([ScriptedResponse(json={"destinations": []})]) as network:
- is_valid, error = validate_credentials(API_KEY, API_VERSION, schema_name="destinations")
+ @pytest.mark.parametrize(
+ ("schema_name", "expected_url"),
+ [
+ ("destinations", "https://api.loopreturns.com/api/v1/destinations"),
+ # A variant request needs a product id, so the product list stands in for it.
+ ("product_variants", "https://api.loopreturns.com/api/v1/products?limit=1"),
+ ],
+ )
+ def test_validating_one_schema_probes_only_that_endpoint(self, schema_name: str, expected_url: str) -> None:
+ with scripted_network([ScriptedResponse(json={})]) as network:
+ is_valid, error = validate_credentials(API_KEY, API_VERSION, schema_name=schema_name)
assert (is_valid, error) == (True, None)
- assert network.requests_log[0].url == "https://api.loopreturns.com/api/v1/destinations"
+ assert [request.url for request in network.requests_log] == [expected_url]
def test_a_network_failure_is_reported_not_raised(self) -> None:
with scripted_network(always(RequestsConnectionError("no route to host"))):