diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d83ccc..a13c6d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,11 +63,6 @@ jobs: config: phpunit.pgsql.xml port: 5432 username: inventoros - - database: warehouse-core - config: phpunit.xml - port: '' - username: '' - core_ref: feat/warehouse-stock-overview - database: mysql config: phpunit.mysql.xml port: 3306 diff --git a/CHANGELOG.md b/CHANGELOG.md index 7974cc0..30e3275 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this plugin are documented here. The format follows [Keep ## [Unreleased] +## [1.0.3] - Unreleased + +### Fixed + +- Bound GraphQL query sizes and finish nested product variants, order lines and inventory locations before returning records. Retry short throttles on the same read page; refuse broken cursors and partial records. + ## [1.0.2] - 2026-10-07 ### Fixed diff --git a/README.md b/README.md index 6684668..ff1aea7 100644 --- a/README.md +++ b/README.md @@ -131,3 +131,15 @@ README screenshots: `SCREENSHOTS=1 npx playwright test -c plugins/shopify/e2e/pl ## License AGPL-3.0-or-later. See [LICENSE](LICENSE). + +### GraphQL page sizes and rate limits + +Catalog and order reads use small parent pages and finish nested variant, order +line and inventory-location connections before returning a record. Large +products or orders are not silently truncated. A missing/repeated cursor refuses +partial data. Read-only requests can wait on the same page up to three times, +with a total wait of at most 30 seconds; longer throttles return to the existing +queue retry policy. Mutations keep their existing idempotency and queue retries. + +Query shapes are bounded below Shopify's default 1,000-point single-query limit. +Shopify can assign field costs, so response throttle metadata remains authoritative. diff --git a/plugin.json b/plugin.json index 7592d8c..eb80763 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "Shopify", "description": "Connect Inventoros with Shopify for asynchronous two-way product, inventory and order sync, with webhooks, retries, mappings and sync health checks.", - "version": "1.0.2", + "version": "1.0.3", "author": "Inventoros", "author_url": "https://inventoros.com", "license": "AGPL-3.0-or-later", diff --git a/src/Shopify/HttpShopifyClient.php b/src/Shopify/HttpShopifyClient.php index 6a0a8d7..03cef4a 100644 --- a/src/Shopify/HttpShopifyClient.php +++ b/src/Shopify/HttpShopifyClient.php @@ -7,6 +7,7 @@ use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\Http; +use Illuminate\Support\Sleep; use Inventoros\Plugins\Shopify\Kit\Exceptions\PermanentError; use Inventoros\Plugins\Shopify\Kit\Exceptions\RateLimited; use Inventoros\Plugins\Shopify\Kit\Exceptions\TransientError; @@ -21,7 +22,8 @@ * local mirror of that bucket (CostBudget); after it, the bucket is * corrected from extensions.cost.throttleStatus. An empty bucket, a * THROTTLED error or an HTTP 429 raises RateLimited with the wait, and the - * job re-queues itself instead of sleeping. + * read operations wait briefly on the same page, then jobs re-queue. + * Mutations always use the existing job retry policy without sleeping. * * Errors: 401/403 PermanentError(authentication), 404 and GraphQL or user * errors PermanentError, 5xx and network failures TransientError. The @@ -41,7 +43,7 @@ public function __construct( public function shop(): array { - $data = $this->query(Queries::SHOP, [], 2); + $data = $this->read(Queries::SHOP, [], 2); $shop = $data['shop'] ?? []; return [ @@ -55,7 +57,7 @@ public function shop(): array public function locations(?string $after = null): Page { - $data = $this->query(Queries::LOCATIONS, ['first' => self::PAGE_SIZE, 'after' => $after], 10); + $data = $this->read(Queries::LOCATIONS, ['first' => self::PAGE_SIZE, 'after' => $after], 10); $connection = $data['locations'] ?? []; return new Page( @@ -71,15 +73,15 @@ public function locations(?string $after = null): Page public function products(?string $after = null, ?string $updatedSince = null): Page { - $data = $this->query(Queries::PRODUCTS, [ - 'first' => self::PAGE_SIZE, + $data = $this->read(Queries::PRODUCTS, [ + 'first' => 3, 'after' => $after, 'query' => $updatedSince === null ? null : "updated_at:>='{$updatedSince}'", - ], 260); + ], 600); $connection = $data['products'] ?? []; return new Page( - array_map([Normalizer::class, 'product'], $connection['nodes'] ?? []), + array_map(fn ($node) => Normalizer::product($this->complete($node, 'variants', Queries::PRODUCT_VARIANTS, 'product', 400)), $connection['nodes'] ?? []), $connection['pageInfo']['endCursor'] ?? null, (bool) ($connection['pageInfo']['hasNextPage'] ?? false), ); @@ -89,16 +91,17 @@ public function inventoryLevels(array $inventoryItemIds): array { $levels = []; - foreach (array_chunk(array_values(array_unique($inventoryItemIds)), 50) as $chunk) { - $data = $this->query(Queries::INVENTORY_LEVELS, [ + foreach (array_chunk(array_values(array_unique($inventoryItemIds)), 5) as $chunk) { + $data = $this->read(Queries::INVENTORY_LEVELS, [ 'ids' => array_map(fn ($id) => Gid::make('InventoryItem', $id), $chunk), - ], 120); + ], 450); foreach ($data['nodes'] ?? [] as $item) { if (! is_array($item) || ! isset($item['id'])) { continue; } + $item = $this->complete($item, 'inventoryLevels', Queries::INVENTORY_ITEM_LEVELS, 'inventoryItem', 400); foreach ($item['inventoryLevels']['nodes'] ?? [] as $level) { $available = 0; foreach ($level['quantities'] ?? [] as $quantity) { @@ -127,15 +130,15 @@ public function orders(?string $after = null, ?string $updatedSince = null, ?str $createdSince === null ? null : "created_at:>='{$createdSince}'", ]); - $data = $this->query(Queries::ORDERS, [ - 'first' => 25, + $data = $this->read(Queries::ORDERS, [ + 'first' => 2, 'after' => $after, 'query' => $filters === [] ? null : implode(' AND ', $filters), - ], 300); + ], 800); $connection = $data['orders'] ?? []; return new Page( - array_map([Normalizer::class, 'order'], $connection['nodes'] ?? []), + array_map(fn ($node) => Normalizer::order($this->complete($node, 'lineItems', Queries::ORDER_LINES, 'order', 800)), $connection['nodes'] ?? []), $connection['pageInfo']['endCursor'] ?? null, (bool) ($connection['pageInfo']['hasNextPage'] ?? false), ); @@ -143,9 +146,9 @@ public function orders(?string $after = null, ?string $updatedSince = null, ?str public function order(string $id): ?array { - $data = $this->query(Queries::ORDER, ['id' => Gid::make('Order', $id)], 30); + $data = $this->read(Queries::ORDER, ['id' => Gid::make('Order', $id)], 400); - return is_array($data['order'] ?? null) ? Normalizer::order($data['order']) : null; + return is_array($data['order'] ?? null) ? Normalizer::order($this->complete($data['order'], 'lineItems', Queries::ORDER_LINES, 'order', 800)) : null; } public function setInventoryQuantities(array $quantities, string $idempotencyKey): void @@ -250,6 +253,47 @@ private function query(string $query, array $variables, int $expectedCost): arra return is_array($body['data'] ?? null) ? $body['data'] : []; } + /** Finish a nested connection before returning a record to an importer. */ + private function complete(array $node, string $field, string $query, string $root, int $cost): array + { + $connection = $node[$field] ?? []; + $seen = []; + while ($connection['pageInfo']['hasNextPage'] ?? false) { + $cursor = $connection['pageInfo']['endCursor'] ?? null; + if (! is_string($cursor) || $cursor === '' || isset($seen[$cursor])) { + throw new PermanentError('Shopify returned a missing or repeated pagination cursor; refusing a partial record.'); + } + $seen[$cursor] = true; + $data = $this->read($query, ['id' => $node['id'], 'after' => $cursor], $cost); + if (! is_array($data[$root][$field] ?? null)) { + throw new TransientError('Shopify omitted a nested page; refusing a partial record. Retry the sync.'); + } + $connection = $data[$root][$field]; + $node[$field]['nodes'] = array_merge($node[$field]['nodes'] ?? [], $connection['nodes'] ?? []); + } + $node[$field]['pageInfo'] = $connection['pageInfo'] ?? ['hasNextPage' => false, 'endCursor' => null]; + + return $node; + } + + /** Short read-only waits preserve progress within a multi-page record. */ + private function read(string $query, array $variables, int $cost): array + { + $waited = 0; + for ($attempt = 0; ; $attempt++) { + try { + return $this->query($query, $variables, $cost); + } catch (RateLimited $error) { + $delay = max(1, $error->retryAfter); + if ($attempt >= 3 || $waited + $delay > 30) { + throw $error; // The job's existing throttle retry takes over. + } + Sleep::for($delay)->seconds(); + $waited += $delay; + } + } + } + private function endpoint(): string { return 'https://'.$this->shopDomain.'/admin/api/'.$this->apiVersion.'/graphql.json'; diff --git a/src/Shopify/Queries.php b/src/Shopify/Queries.php index 712a324..05037dc 100644 --- a/src/Shopify/Queries.php +++ b/src/Shopify/Queries.php @@ -32,12 +32,13 @@ final class Queries products(first: $first, after: $after, query: $query, sortKey: UPDATED_AT) { nodes { id title status updatedAt - variants(first: 100) { + variants(first: 50) { nodes { id sku title price barcode selectedOptions { name value } inventoryItem { id } } + pageInfo { hasNextPage endCursor } } } pageInfo { hasNextPage endCursor } @@ -50,12 +51,13 @@ final class Queries nodes(ids: $ids) { ... on InventoryItem { id - inventoryLevels(first: 50) { + inventoryLevels(first: 25) { nodes { updatedAt location { id } quantities(names: ["available"]) { name quantity } } + pageInfo { hasNextPage endCursor } } } } @@ -73,7 +75,7 @@ final class Queries totalTaxSet { shopMoney { amount } } totalShippingPriceSet { shopMoney { amount } } totalDiscountsSet { shopMoney { amount } } - lineItems(first: 100) { + lineItems(first: 50) { nodes { id sku name quantity variant { id } @@ -81,6 +83,7 @@ final class Queries originalUnitPriceSet { shopMoney { amount } } totalDiscountSet { shopMoney { amount } } } + pageInfo { hasNextPage endCursor } } } pageInfo { hasNextPage endCursor } @@ -98,7 +101,7 @@ final class Queries totalTaxSet { shopMoney { amount } } totalShippingPriceSet { shopMoney { amount } } totalDiscountsSet { shopMoney { amount } } - lineItems(first: 100) { + lineItems(first: 50) { nodes { id sku name quantity variant { id } @@ -106,11 +109,52 @@ final class Queries originalUnitPriceSet { shopMoney { amount } } totalDiscountSet { shopMoney { amount } } } + pageInfo { hasNextPage endCursor } } } } GQL; + public const PRODUCT_VARIANTS = <<<'GQL' + query ProductVariants($id: ID!, $after: String) { + product(id: $id) { + id + variants(first: 100, after: $after) { + nodes { id sku title price barcode selectedOptions { name value } inventoryItem { id } } + pageInfo { hasNextPage endCursor } + } + } + } + GQL; + + public const ORDER_LINES = <<<'GQL' + query OrderLines($id: ID!, $after: String) { + order(id: $id) { + id + lineItems(first: 100, after: $after) { + nodes { + id sku name quantity variant { id } product { id } + originalUnitPriceSet { shopMoney { amount } } + totalDiscountSet { shopMoney { amount } } + } + pageInfo { hasNextPage endCursor } + } + } + } + GQL; + + public const INVENTORY_ITEM_LEVELS = <<<'GQL' + query InventoryItemLevels($id: ID!, $after: String) { + inventoryItem(id: $id) { + id + inventoryLevels(first: 100, after: $after) { + nodes { updatedAt location { id } quantities(names: ["available"]) { name quantity } } + pageInfo { hasNextPage endCursor } + } + } + } + GQL; + public const SET_QUANTITIES = <<<'GQL' mutation SetQuantities($input: InventorySetQuantitiesInput!, $idempotencyKey: String!) { inventorySetQuantities(input: $input) @idempotent(key: $idempotencyKey) { diff --git a/tests/Feature/NestedPaginationTest.php b/tests/Feature/NestedPaginationTest.php new file mode 100644 index 0000000..38d1b0f --- /dev/null +++ b/tests/Feature/NestedPaginationTest.php @@ -0,0 +1,105 @@ + $data, 'extensions' => ['cost' => ['throttleStatus' => [ + 'currentlyAvailable' => 10000, 'maximumAvailable' => 10000, 'restoreRate' => 100, + ]]]]; + } + + public function test_all_variants_are_loaded_and_a_throttle_retries_the_same_nested_page(): void + { + Sleep::fake(); + $fixture = FakeShopifyClient::fixture('products_page1'); + $node = $fixture['data']['products']['nodes'][0]; + $node['variants']['pageInfo'] = ['hasNextPage' => true, 'endCursor' => 'variants-50']; + $extra = $node['variants']['nodes'][0]; + $extra['id'] = 'gid://shopify/ProductVariant/9999'; + Http::fake(['*' => Http::sequence() + ->push($this->response(['products' => ['nodes' => [$node], 'pageInfo' => ['hasNextPage' => true, 'endCursor' => 'parent-3']]])) + ->push([], 429, ['Retry-After' => '2']) + ->push($this->response(['product' => ['variants' => ['nodes' => [$extra], 'pageInfo' => ['hasNextPage' => false, 'endCursor' => 'end']]]]))]); + + $page = $this->client()->products(); + $this->assertSame('9999', $page->items[0]['variants'][count($node['variants']['nodes'])]['id']); + $this->assertSame('parent-3', $page->endCursor); + $this->assertTrue($page->hasNextPage); + $requests = Http::recorded()->map(fn ($pair) => json_decode($pair[0]->body(), true))->all(); + $this->assertSame(3, $requests[0]['variables']['first']); + $this->assertSame('variants-50', $requests[1]['variables']['after']); + $this->assertSame($requests[1]['variables'], $requests[2]['variables']); + Sleep::assertSleptTimes(1); + Http::assertSentCount(3); + } + + public function test_order_lines_and_inventory_locations_are_not_truncated(): void + { + $order = FakeShopifyClient::fixture('orders')['data']['orders']['nodes'][0]; + $line = $order['lineItems']['nodes'][0]; + $line['id'] = 'gid://shopify/LineItem/9999'; + $order['lineItems']['pageInfo'] = ['hasNextPage' => true, 'endCursor' => 'lines-50']; + $inventory = FakeShopifyClient::fixture('inventory_levels')['data']['nodes'][0]; + $level = $inventory['inventoryLevels']['nodes'][0]; + $level['location']['id'] = 'gid://shopify/Location/9999'; + $inventory['inventoryLevels']['pageInfo'] = ['hasNextPage' => true, 'endCursor' => 'locations-25']; + Http::fake(['*' => Http::sequence() + ->push($this->response(['orders' => ['nodes' => [$order]]])) + ->push($this->response(['order' => ['lineItems' => ['nodes' => [$line], 'pageInfo' => ['hasNextPage' => false]]]])) + ->push($this->response(['nodes' => [$inventory]])) + ->push($this->response(['inventoryItem' => ['inventoryLevels' => ['nodes' => [$level], 'pageInfo' => ['hasNextPage' => false]]]]))]); + + $client = $this->client(); + $orders = $client->orders(); + $this->assertSame('9999', $orders->items[0]['line_items'][count($order['lineItems']['nodes'])]['id']); + $levels = $client->inventoryLevels(['4001']); + $this->assertSame('9999', $levels[count($inventory['inventoryLevels']['nodes'])]['location_id']); + Http::assertSent(fn ($request) => (json_decode($request->body(), true)['variables']['first'] ?? null) === 2); + Http::assertSent(fn ($request) => (json_decode($request->body(), true)['variables']['after'] ?? null) === 'locations-25'); + } + + public function test_a_broken_nested_cursor_refuses_a_partial_record(): void + { + $order = FakeShopifyClient::fixture('orders')['data']['orders']['nodes'][0]; + $order['lineItems']['pageInfo'] = ['hasNextPage' => true, 'endCursor' => 'repeated']; + Http::fake(['*' => Http::sequence() + ->push($this->response(['order' => $order])) + ->push($this->response(['order' => ['lineItems' => ['nodes' => [], 'pageInfo' => ['hasNextPage' => true, 'endCursor' => 'repeated']]]]))]); + $this->expectException(PermanentError::class); + $this->expectExceptionMessage('refusing a partial record'); + $this->client()->order('5001'); + } + + public function test_long_throttles_return_to_the_existing_job_retry_without_sleeping(): void + { + Sleep::fake(); + Http::fake(['*' => Http::response([], 429, ['Retry-After' => '120'])]); + try { + $this->client()->products(); + $this->fail('Expected rate limit.'); + } catch (RateLimited $error) { + $this->assertSame(120, $error->retryAfter); + } + Sleep::assertNeverSlept(); + Http::assertSentCount(1); + } +}