A new supplier is one class, not a new integration, and 42 passing tests show the switch changed nothing.
OK (42 tests, 287 assertions)
0 errors, 0 failures, 0 skipped, 4.3 seconds. PHPUnit on PHP 8.5.13, Laravel 12.73.0. Run captured 2026-11-21 04:54:41 UTC.
Duplicate Claim Race2 passed
- Two workers on one batch create each product exactly once
- Control check then create duplicates products in the same race
Inventory Publisher5 passed
- Paced publisher sends only changes in batches of 250 with zero throttles
- Unpaced baseline on the same catalogue gets throttled
- A second run with no changes makes no calls
- Every quantity carries change from quantity and each batch an idempotency key
- A stale record is refused by compare and set instead of overwriting
Parity6 passed
- Legacy path still matches its recorded golden output with data set "alpha_soap"
- Legacy path still matches its recorded golden output with data set "bravo_rest"
- Adapter path output is identical to the legacy golden output with data set "alpha_soap"
- Adapter path output is identical to the legacy golden output with data set "bravo_rest"
- The diff catches a single changed field
- The diff catches a dropped variant and a reordered list
Price2 passed
- Supplier price formats become integer cents
- Unreadable or sub cent prices are refused
Registry Boot8 passed
- The shipped configuration boots and resolves both suppliers
- A misconfigured adapter stops the app at boot with data set "missing class key"
- A misconfigured adapter stops the app at boot with data set "class does not exist"
- A misconfigured adapter stops the app at boot with data set "class is not an adapter"
- A misconfigured adapter stops the app at boot with data set "unknown transport"
- A misconfigured adapter stops the app at boot with data set "fixture path missing"
- A misconfigured adapter stops the app at boot with data set "key mismatch"
- An unknown key is refused at lookup
Supplier Adapter Contract15 passed
- It reports the key it is registered under with data set "alpha_soap"
- It reports the key it is registered under with data set "bravo_rest"
- It reports the key it is registered under with data set "charlie_rest"
- Products are canonical and complete with data set "alpha_soap"
- Products are canonical and complete with data set "bravo_rest"
- Products are canonical and complete with data set "charlie_rest"
- Stock covers every sku with whole numbers with data set "alpha_soap"
- Stock covers every sku with whole numbers with data set "bravo_rest"
- Stock covers every sku with whole numbers with data set "charlie_rest"
- Output is deterministic with data set "alpha_soap"
- Output is deterministic with data set "bravo_rest"
- Output is deterministic with data set "charlie_rest"
- A broken response throws and never returns partial data with data set "alpha_soap"
- A broken response throws and never returns partial data with data set "bravo_rest"
- A broken response throws and never returns partial data with data set "charlie_rest"
Variant Matching4 passed
- Messy colour and size rows auto match only when certain
- Review items carry their candidates and reason
- A rerun updates open review items instead of duplicating them
- Two equal variants are never auto picked
Three invented suppliers (one SOAP, two REST) sit behind one interface, chosen by configuration. The new path gives the same Shopify output as the old one, two workers on one batch create each product once, unclear colour and size data goes to a person, and stock is published in batches that stay under the rate limit.
The raw run: console output and JUnit XML (local paths shortened). Open a group above to see each test.
The design in ten lines
- One interface,
SupplierAdapter:key(),products(),stock(). Nothing else. - An adapter owns its transport (SOAP or REST) and its transformation, and returns canonical products and stock levels.
- Adapters never call Shopify. The core owns the Shopify writes, the queues and the locking.
- A config file maps each supplier key to its adapter class; the container builds it.
- The registry checks every entry when the app boots. A missing class, a wrong interface, an unknown transport or a key mismatch stops the app before any job runs.
- Every adapter must pass one contract suite, and its cases come from the config, so a new supplier is tested automatically.
- Migration proof: golden output recorded from the old integration before any change, then the adapter path must match it with zero diff.
- Duplicate guard: a claim row under a unique key, committed before the Shopify call. The database picks one winner.
- Variant matching auto-links only exact matches after cleaning; anything close goes to a review table with its candidates.
- Inventory: changed quantities only, 250 per call, each with
changeFromQuantity, paced on the cost Shopify reports back.
What the tests measured
The tests in the run above wrote these numbers out. The control run's duplicate count varies from run to run; its test asserts only that it is above zero.
The Shopify side is a fake with a leaky bucket of 1,000 points refilling at 50 per second, the values in Shopify's own example response. Its cost per call (10 plus 1 per quantity) is simulated. Paced publishing waited 47.6 simulated seconds; the refill minimum for this batch is 44.6.
The matcher cases
| Supplier colour | Size | Result |
|---|---|---|
| NAVY BLUE | s | matched T-NAVY-S |
| nvy | Medium | matched T-NAVY-M |
| Navy | X-Large | matched T-NAVY-XL |
| navy | extra large | matched T-NAVY-XL |
| Heather Gray | m | matched T-HGREY-M |
| HTHR GREY | XXL | matched T-HGREY-2XL |
| heather grey | 2X | matched T-HGREY-2XL |
| roy blue | lg | matched T-ROYAL-L |
| Red | Large | matched T-RED-L |
| Royal | L | review: close to Royal Blue |
| Drk Red | L | review: one edit from Dark Red |
| Navy Blu | M | review: typo |
| Grey Heather | M | review: word order swapped |
| Navy | S/M | review: size Shopify does not carry |
| Heather Grey | S | review: colour and size exist, not together |
| (empty) | M | review: no colour at all |
One of these failed on the first run: "S/M" was flattened to "SM" and read as Small. Size ranges now go to review.
The code
The interface
/**
* One class per supplier. The adapter owns its transport (SOAP or REST) and its
* transformation; it returns canonical shapes only. The core owns Shopify writes,
* queues and locking, so no adapter ever talks to Shopify.
*/
interface SupplierAdapter
{
/** The key this adapter is registered under in config/suppliers.php. */
public function key(): string;
/**
* @return list<CanonicalProduct>
* @throws \App\Suppliers\Exceptions\SupplierResponseException on any response it cannot fully read
*/
public function products(): array;
/**
* @return list<StockLevel>
* @throws \App\Suppliers\Exceptions\SupplierResponseException
*/
public function stock(): array;
}The registry, checked at boot
return [
'adapters' => [
'alpha_soap' => [
'class' => AlphaSoapAdapter::class,
'transport' => 'soap',
'source' => ['driver' => 'fixtures', 'path' => 'tests/Fixtures/suppliers/alpha_soap'],
],
'bravo_rest' => [
'class' => BravoRestAdapter::class,
'transport' => 'rest',
'source' => ['driver' => 'fixtures', 'path' => 'tests/Fixtures/suppliers/bravo_rest'],
],
'charlie_rest' => [
'class' => CharlieRestAdapter::class,
'transport' => 'rest',
'source' => ['driver' => 'fixtures', 'path' => 'tests/Fixtures/suppliers/charlie_rest'],
],
],
];/** Fail at boot, not mid-run: a missing or misconfigured adapter stops every worker and command here. */
public function boot(): void
{
$this->app->make(SupplierRegistry::class)->validate();
}/** Every configured problem at once, so one boot shows the whole list. */
public function validate(): void
{
$errors = [];
if ($this->adapters === []) {
$errors[] = 'config/suppliers.php lists no adapters';
}
foreach ($this->adapters as $key => $entry) {
$class = $entry['class'] ?? null;
if (! is_string($class) || $class === '') {
$errors[] = "[{$key}] has no 'class'";
continue;
}
if (! class_exists($class)) {
$errors[] = "[{$key}] class {$class} does not exist";
continue;
}
if (! is_subclass_of($class, SupplierAdapter::class)) {
$errors[] = "[{$key}] {$class} does not implement SupplierAdapter";
continue;
}
if (! in_array($entry['transport'] ?? null, self::TRANSPORTS, true)) {
$errors[] = "[{$key}] 'transport' must be one of: ".implode(', ', self::TRANSPORTS);
}
try {
$adapter = $this->make($key);
if ($adapter->key() !== $key) {
$errors[] = "[{$key}] {$class}::key() returns '{$adapter->key()}'";
}
} catch (MisconfiguredSupplierException $e) {
$errors[] = $e->getMessage();
}
}
if ($errors !== []) {
throw new MisconfiguredSupplierException("Supplier registry refused to boot:\n- ".implode("\n- ", $errors));
}
}The parity test
#[DataProvider('suppliers')]
public function test_adapter_path_output_is_identical_to_the_legacy_golden_output(string $key): void
{
$diff = ParityDiff::diff($this->golden($key), $this->adapterPayloads($key));
$this->assertSame([], $diff, "parity diff for {$key}:\n".implode("\n", $diff));
$this->assertSame($this->golden($key), $this->adapterPayloads($key), 'byte-for-byte, order included');
}
public function test_the_diff_catches_a_single_changed_field(): void
{
$golden = $this->golden('alpha_soap');
$changed = $golden;
$changed[0]['variants'][1]['price'] = '6.49';
$this->assertSame(['$.0.variants.1.price: "6.50" -> "6.49"'], ParityDiff::diff($golden, $changed));
}The claim, and the race test
/** @return 'created'|'skipped' */
public function link(CanonicalProduct $product): string
{
try {
DB::table('supplier_product_links')->insert([
'supplier_key' => $product->supplierKey,
'supplier_product_id' => $product->supplierProductId,
'claimed_by' => $this->worker,
'claimed_at' => now(),
]); // auto-committed: the claim is visible to every other worker before any Shopify call
} catch (UniqueConstraintViolationException) {
return 'skipped'; // another worker owns this item
}
$gid = $this->writer->create($this->mapper->map($product));
DB::table('supplier_product_links')
->where(['supplier_key' => $product->supplierKey, 'supplier_product_id' => $product->supplierProductId])
->update(['shopify_product_id' => $gid]);
return 'created';
}public function test_two_workers_on_one_batch_create_each_product_exactly_once(): void
{
$r = $this->race(naive: false);
$this->assertSame(self::ITEMS, $r['links'], 'one link row per item');
$this->assertSame(self::ITEMS, $r['distinctLinks']);
$this->assertSame(0, $r['unlinked'], 'every claim got its Shopify ID');
$this->assertCount(self::ITEMS, $r['creates'], 'Shopify saw one create per item');
$this->assertSame($r['creates'], array_values(array_unique($r['creates'])), 'no product created twice');
$this->assertSame(self::ITEMS, $r['tallies'][0]['created'] + $r['tallies'][1]['created']);
$this->assertSame(self::ITEMS, $r['tallies'][0]['skipped'] + $r['tallies'][1]['skipped'], 'every item was attempted by both workers; each lost once');
$this->assertSame(0, $r['tallies'][0]['duplicate'] + $r['tallies'][1]['duplicate']);
Evidence::record('claim-race', ['items' => self::ITEMS, 'workers' => $r['tallies'], 'link_rows' => $r['links'], 'shopify_creates' => count($r['creates'])]);
}The pacing loop
public function publish(array $target, array &$lastPublished, string $locationId): PublishReport
{
$report = new PublishReport;
$changed = array_filter($target, fn (int $qty, string $id) => ($lastPublished[$id] ?? null) !== $qty, ARRAY_FILTER_USE_BOTH);
$report->changed = count($changed);
foreach (array_chunk($changed, self::MAX_BATCH, true) as $chunk) {
$quantities = [];
foreach ($chunk as $id => $qty) {
// changeFromQuantity is required from API 2026-04; null opts out for items we never published
$quantities[] = ['inventoryItemId' => $id, 'locationId' => $locationId, 'quantity' => $qty, 'changeFromQuantity' => $lastPublished[$id] ?? null];
}
$key = 'inv-'.bin2hex(random_bytes(16)); // one key per batch, reused only by its own retries: a retry cannot apply twice
while (true) {
if ($this->pace) {
$this->waitForBudget($report);
}
$response = $this->api->setQuantities($quantities, $key);
$report->calls++;
$this->throttle = $response['extensions']['cost']['throttleStatus'] ?? $this->throttle;
$this->lastCost = (float) ($response['extensions']['cost']['requestedQueryCost'] ?? $this->lastCost);
if (($response['errors'][0]['extensions']['code'] ?? null) === 'THROTTLED') {
$report->throttled++;
$this->waitForBudget($report); // even the unpaced path must back off before retrying
continue;
}
if (! empty($response['errors']) || ! empty($response['data']['inventorySetQuantities']['userErrors'])) {
throw new \RuntimeException('inventorySetQuantities failed: '.json_encode($response['errors'] ?? $response['data']));
}
break;
}
$report->largestBatch = max($report->largestBatch, count($quantities));
foreach ($chunk as $id => $qty) {
$lastPublished[$id] = $qty;
}
}
return $report;
}
/** Sleep until the bucket holds the estimated cost of the next call. */
private function waitForBudget(PublishReport $report): void
{
if ($this->throttle === null || $this->lastCost === null) {
return; // first call: nothing measured yet
}
$short = $this->lastCost + self::HEADROOM - (float) $this->throttle['currentlyAvailable'];
if ($short > 0) {
$seconds = ceil($short / (float) $this->throttle['restoreRate'] * 1000) / 1000; // whole milliseconds, never a hair short
$this->clock->sleep($seconds);
$report->secondsWaited += $seconds;
$this->throttle['currentlyAvailable'] = $this->lastCost + self::HEADROOM; // what the bucket holds after the wait
}
}Onboarding a third supplier
The third supplier went in as its own commit: one adapter class, one config entry and its recorded responses. No core file changed, and the contract suite picked it up.
laravel demo: onboard invented supplier charlie_rest with the new pattern only (1 class, 1 config entry, recorded responses); contract suite picks it up, 42 pass
Suppliers/Adapters/CharlieRestAdapter.php | 91 +++++++++++++++++++
supplier-adapters/config/suppliers.php | 8 +-
suppliers/charlie_rest/inventory.json | 1 +
charlie_rest/products.page1.json | 14 +++
charlie_rest/products.page2.json | 14 +++
5 files changed, 127 insertions(+), 1 deletion(-)
Not built here
- MySQL and real queue workers. The race test runs two OS processes on a SQLite file; the unique-key mechanism is the same on MySQL, but MySQL's own locking was not exercised.
- Live supplier transports. Only recorded responses; no SoapClient or HTTP source.
- A real Shopify store, bulk operations and webhooks. The Shopify client is a fake.
- Recovery of a stuck claim. If the Shopify create fails after a claim, the claim row stays without a Shopify ID; the retry with a lookup first is not built.
- The whole pipeline as one queued job, from supplier pull to stock publish.