Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 1 addition & 1 deletion plugin.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
76 changes: 60 additions & 16 deletions src/Shopify/HttpShopifyClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -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 [
Expand All @@ -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(
Expand All @@ -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),
);
Expand All @@ -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) {
Expand Down Expand Up @@ -127,25 +130,25 @@ 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),
);
}

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
Expand Down Expand Up @@ -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';
Expand Down
52 changes: 48 additions & 4 deletions src/Shopify/Queries.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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 }
}
}
}
Expand All @@ -73,14 +75,15 @@ 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 }
product { id }
originalUnitPriceSet { shopMoney { amount } }
totalDiscountSet { shopMoney { amount } }
}
pageInfo { hasNextPage endCursor }
}
}
pageInfo { hasNextPage endCursor }
Expand All @@ -98,19 +101,60 @@ 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 }
product { id }
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) {
Expand Down
Loading
Loading