diff --git a/app/Client/Connector.php b/app/Client/Connector.php index 748e41f6..22512671 100644 --- a/app/Client/Connector.php +++ b/app/Client/Connector.php @@ -33,8 +33,10 @@ use App\Support\ContextDetector; use Illuminate\Support\Facades\Cache; use Illuminate\Support\LazyCollection; +use Illuminate\Support\Str; use Saloon\CachePlugin\Contracts\Driver; use Saloon\CachePlugin\Drivers\LaravelCacheDriver; +use Saloon\Enums\Method; use Saloon\Enums\PipeOrder; use Saloon\Http\Auth\TokenAuthenticator; use Saloon\Http\Connector as SaloonConnector; @@ -100,6 +102,8 @@ public function boot(PendingRequest $pendingRequest): void order: PipeOrder::LAST, ); + $this->addIdempotencyKey($pendingRequest); + if (! method_exists($pendingRequest->getRequest(), 'getInclude')) { return; } @@ -109,6 +113,26 @@ public function boot(PendingRequest $pendingRequest): void } } + /** + * Cloud replays the first successful response for a repeated key instead of creating + * or starting the same thing twice. The key lives on the request, so sending the same + * request again reuses it. + */ + protected function addIdempotencyKey(PendingRequest $pendingRequest): void + { + if (! in_array($pendingRequest->getMethod(), [Method::POST, Method::PATCH], true)) { + return; + } + + $headers = $pendingRequest->getRequest()->headers(); + + if ($headers->get('Idempotency-Key') === null) { + $headers->add('Idempotency-Key', (string) Str::uuid()); + } + + $pendingRequest->headers()->add('Idempotency-Key', $headers->get('Idempotency-Key')); + } + public function resolveBaseUrl(): string { return Cloud::baseUrl().'/api'; diff --git a/tests/Feature/IdempotencyKeyTest.php b/tests/Feature/IdempotencyKeyTest.php new file mode 100644 index 00000000..dbd39048 --- /dev/null +++ b/tests/Feature/IdempotencyKeyTest.php @@ -0,0 +1,39 @@ +withMockClient(new MockClient([MockResponse::make(['data' => []])])); + + return $connector->send($request)->getPendingRequest()->headers()->get('Idempotency-Key'); +} + +it('sends a new idempotency key with each POST and PATCH request', function () { + $start = sentIdempotencyKey(new StartEnvironmentRequest(new StartEnvironmentRequestData('env-1'))); + $otherStart = sentIdempotencyKey(new StartEnvironmentRequest(new StartEnvironmentRequestData('env-1'))); + $update = sentIdempotencyKey(new UpdateEnvironmentRequest(new UpdateEnvironmentRequestData('env-1', name: 'prod'))); + + expect($start)->toBeUuid() + ->and($update)->toBeUuid() + ->and($otherStart)->not->toBe($start); +}); + +it('reuses the idempotency key when the same request is sent again', function () { + $request = new StartEnvironmentRequest(new StartEnvironmentRequestData('env-1')); + + expect(sentIdempotencyKey($request))->toBe(sentIdempotencyKey($request)); +}); + +it('sends no idempotency key with GET requests', function () { + expect(sentIdempotencyKey(new GetEnvironmentRequest('env-1')))->toBeNull(); +});