From 859fed92c46192ada0ee5ed8574e8cc76c2209b7 Mon Sep 17 00:00:00 2001 From: Proxynth Date: Thu, 9 Jul 2026 19:02:29 +0200 Subject: [PATCH] refactor: use webhook event aggregate in retry and replay --- .../{DTOs => Data}/ReplayableWebhook.php | 4 +- .../Ports/ReplayableWebhookRepository.php | 2 +- .../Application/UseCases/RetryWebhook.php | 96 +++++++++++++++++-- .../Domain/Entities/WebhookEvent.php | 16 ++++ .../Laravel/Jobs/RetryWebhookJob.php | 3 + .../EloquentReplayableWebhookRepository.php | 2 +- .../Data/ReplayableWebhookTest.php | 25 +++++ .../UseCases/ReplayWebhookTest.php | 20 +++- .../Application/UseCases/RetryWebhookTest.php | 63 ++++++++++++ .../Domain/Entities/WebhookEventTest.php | 90 +++++++++++++++++ 10 files changed, 309 insertions(+), 12 deletions(-) rename src/Processing/Application/{DTOs => Data}/ReplayableWebhook.php (92%) create mode 100644 tests/Unit/Processing/Application/Data/ReplayableWebhookTest.php diff --git a/src/Processing/Application/DTOs/ReplayableWebhook.php b/src/Processing/Application/Data/ReplayableWebhook.php similarity index 92% rename from src/Processing/Application/DTOs/ReplayableWebhook.php rename to src/Processing/Application/Data/ReplayableWebhook.php index 2272b04..57b0159 100644 --- a/src/Processing/Application/DTOs/ReplayableWebhook.php +++ b/src/Processing/Application/Data/ReplayableWebhook.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Proxynth\Larawebhook\Processing\Application\DTOs; +namespace Proxynth\Larawebhook\Processing\Application\Data; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Provider; use Proxynth\Larawebhook\Processing\Domain\Entities\WebhookEvent; @@ -26,7 +26,7 @@ public function __construct( public function toWebhookEvent(): WebhookEvent { - return WebhookEvent::replayable( + return WebhookEvent::fromHistory( provider: Provider::fromString($this->service), eventType: EventType::fromString($this->event), idempotencyKey: IdempotencyKey::optional($this->idempotencyKey), diff --git a/src/Processing/Application/Ports/ReplayableWebhookRepository.php b/src/Processing/Application/Ports/ReplayableWebhookRepository.php index 92c23a3..4ecdfda 100644 --- a/src/Processing/Application/Ports/ReplayableWebhookRepository.php +++ b/src/Processing/Application/Ports/ReplayableWebhookRepository.php @@ -4,7 +4,7 @@ namespace Proxynth\Larawebhook\Processing\Application\Ports; -use Proxynth\Larawebhook\Processing\Application\DTOs\ReplayableWebhook; +use Proxynth\Larawebhook\Processing\Application\Data\ReplayableWebhook; interface ReplayableWebhookRepository { diff --git a/src/Processing/Application/UseCases/RetryWebhook.php b/src/Processing/Application/UseCases/RetryWebhook.php index 9850b96..9dc30d6 100644 --- a/src/Processing/Application/UseCases/RetryWebhook.php +++ b/src/Processing/Application/UseCases/RetryWebhook.php @@ -9,12 +9,18 @@ use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged; use Proxynth\Larawebhook\Exceptions\WebhookException; use Proxynth\Larawebhook\Ingestion\Application\Commands\ValidateWebhookCommand; +use Proxynth\Larawebhook\Ingestion\Application\Results\ValidateWebhookResult; use Proxynth\Larawebhook\Ingestion\Application\UseCases\ValidateWebhook; +use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Provider; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload; use Proxynth\Larawebhook\Processing\Application\Commands\RetryWebhookCommand; +use Proxynth\Larawebhook\Processing\Application\Data\RetryPolicy; use Proxynth\Larawebhook\Processing\Application\Ports\RetryPolicyResolver; use Proxynth\Larawebhook\Processing\Application\Results\RetryWebhookResult; +use Proxynth\Larawebhook\Processing\Domain\Entities\WebhookEvent; use Proxynth\Larawebhook\Processing\Domain\Events\WebhookProcessingFailed; +use Proxynth\Larawebhook\Processing\Domain\ValueObjects\EventType; +use Proxynth\Larawebhook\Processing\Domain\ValueObjects\IdempotencyKey; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; final readonly class RetryWebhook @@ -48,7 +54,13 @@ public function handle(RetryWebhookCommand $command): RetryWebhookResult secret: $command->secret, )); - $log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand( + $webhookEvent = $this->createWebhookEvent( + service: $validation->service, + event: $validation->event, + idempotencyKey: $command->idempotencyKey, + ); + + $this->recordWebhookLog->handle(new RecordWebhookLogCommand( service: $validation->service, event: $validation->event, valid: $validation->isValid(), @@ -60,21 +72,91 @@ public function handle(RetryWebhookCommand $command): RetryWebhookResult )); if ($validation->isValid()) { - return RetryWebhookResult::success($log, [ + return $this->handleValidRetry( + command: $command, + validation: $validation, + webhookEvent: $webhookEvent, + ); + } + + return $this->handleFailedRetry( + command: $command, + validation: $validation, + webhookEvent: $webhookEvent, + retryPolicy: $retryPolicy, + ); + } + + private function createWebhookEvent( + string $service, + string $event, + ?string $idempotencyKey, + ): WebhookEvent { + return WebhookEvent::received( + provider: Provider::fromString($service), + eventType: EventType::fromString($event), + idempotencyKey: IdempotencyKey::optional($idempotencyKey), + ); + } + + private function handleValidRetry( + RetryWebhookCommand $command, + ValidateWebhookResult $validation, + WebhookEvent $webhookEvent, + ): RetryWebhookResult { + $webhookEvent->markValidated(); + $webhookEvent->markProcessing(); + + $log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand( + service: $validation->service, + event: $validation->event, + valid: true, + payload: $validation->payload, + attempt: $command->attempt, + externalId: null, + idempotencyKey: null, + errorMessage: null, + )); + + $webhookEvent->markProcessed(); + + return RetryWebhookResult::success( + log: $log, + events: [ new WebhookLogged( webhookLogId: $log->id, provider: $log->service, event: $log->event, status: $log->status, ), - ]); - } + ], + ); + } - $shouldRetry = $retryPolicy->shouldRetryAfter($command->attempt); + private function handleFailedRetry( + RetryWebhookCommand $command, + ValidateWebhookResult $validation, + WebhookEvent $webhookEvent, + RetryPolicy $retryPolicy, + ): RetryWebhookResult { + $reason = $validation->errorMessage ?? 'Webhook validation failed.'; + + $webhookEvent->markFailed($reason); + + $log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand( + service: $validation->service, + event: $validation->event, + valid: false, + payload: $validation->payload, + attempt: $command->attempt, + externalId: null, + idempotencyKey: null, + errorMessage: $reason, + )); return RetryWebhookResult::failed( log: $log, - shouldRetry: $shouldRetry, + shouldRetry: $retryPolicy->shouldRetryAfter($command->attempt), nextAttempt: $retryPolicy->nextAttemptAfter($command->attempt), delaySeconds: $retryPolicy->delayForAttempt($command->attempt), events: [ @@ -83,7 +165,7 @@ public function handle(RetryWebhookCommand $command): RetryWebhookResult event: $validation->event, externalId: $validation->externalId, attempt: $command->attempt, - reason: $validation->errorMessage ?? 'Webhook validation failed.', + reason: $reason, ), new WebhookLogged( webhookLogId: $log->id, diff --git a/src/Processing/Domain/Entities/WebhookEvent.php b/src/Processing/Domain/Entities/WebhookEvent.php index 05bbcdf..299c3ef 100644 --- a/src/Processing/Domain/Entities/WebhookEvent.php +++ b/src/Processing/Domain/Entities/WebhookEvent.php @@ -43,6 +43,22 @@ public static function received( ); } + public static function fromHistory( + Provider $provider, + EventType $eventType, + ?IdempotencyKey $idempotencyKey, + WebhookStatus $status, + bool $valid = true, + ): self { + return new self( + provider: $provider, + eventType: $eventType, + idempotencyKey: $idempotencyKey, + status: $status, + valid: $valid, + ); + } + public function markValidated(): void { $this->ensureNotTerminal(); diff --git a/src/Processing/Infrastructure/Laravel/Jobs/RetryWebhookJob.php b/src/Processing/Infrastructure/Laravel/Jobs/RetryWebhookJob.php index baa0d14..409e4ef 100644 --- a/src/Processing/Infrastructure/Laravel/Jobs/RetryWebhookJob.php +++ b/src/Processing/Infrastructure/Laravel/Jobs/RetryWebhookJob.php @@ -9,6 +9,7 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; +use Proxynth\Larawebhook\Exceptions\WebhookException; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; use Proxynth\Larawebhook\Processing\Application\Commands\RetryWebhookCommand; use Proxynth\Larawebhook\Processing\Application\UseCases\RetryWebhook; @@ -38,6 +39,8 @@ public function __construct( /** * Execute the job. + * + * @throws WebhookException */ public function handle(RetryWebhook $retryWebhook): void { diff --git a/src/Processing/Infrastructure/Persistence/EloquentReplayableWebhookRepository.php b/src/Processing/Infrastructure/Persistence/EloquentReplayableWebhookRepository.php index 6b4372b..c66ed0d 100644 --- a/src/Processing/Infrastructure/Persistence/EloquentReplayableWebhookRepository.php +++ b/src/Processing/Infrastructure/Persistence/EloquentReplayableWebhookRepository.php @@ -5,7 +5,7 @@ namespace Proxynth\Larawebhook\Processing\Infrastructure\Persistence; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; -use Proxynth\Larawebhook\Processing\Application\DTOs\ReplayableWebhook; +use Proxynth\Larawebhook\Processing\Application\Data\ReplayableWebhook; use Proxynth\Larawebhook\Processing\Application\Ports\ReplayableWebhookRepository; final class EloquentReplayableWebhookRepository implements ReplayableWebhookRepository diff --git a/tests/Unit/Processing/Application/Data/ReplayableWebhookTest.php b/tests/Unit/Processing/Application/Data/ReplayableWebhookTest.php new file mode 100644 index 0000000..10f4d03 --- /dev/null +++ b/tests/Unit/Processing/Application/Data/ReplayableWebhookTest.php @@ -0,0 +1,25 @@ + 'opened'], + attempt: 0, + externalId: 'delivery_123', + idempotencyKey: 'delivery_123', + status: 'failed', + ); + + $event = $replayable->toWebhookEvent(); + + expect($event->provider()->value())->toBe('github') + ->and($event->eventType()->value())->toBe('opened') + ->and($event->status()->value())->toBe('failed') + ->and($event->idempotencyKey()?->value())->toBe('delivery_123'); +}); diff --git a/tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php b/tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php index 4878696..c2c5e9d 100644 --- a/tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php +++ b/tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php @@ -15,7 +15,7 @@ use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; use Proxynth\Larawebhook\Processing\Application\Commands\ReplayWebhookCommand; -use Proxynth\Larawebhook\Processing\Application\DTOs\ReplayableWebhook; +use Proxynth\Larawebhook\Processing\Application\Data\ReplayableWebhook; use Proxynth\Larawebhook\Processing\Application\Exceptions\ReplayWebhookNotAllowed; use Proxynth\Larawebhook\Processing\Application\Ports\ReplayableWebhookRepository; use Proxynth\Larawebhook\Processing\Application\Results\ReplayWebhookResult; @@ -287,3 +287,21 @@ public function record(RecordWebhookLogCommand $command): WebhookLog signature: Signature::fromString('sha256=invalid'), )))->toThrow(WebhookException::class, 'No secret configured for service: github'); }); + +it('throws when webhook event state does not allow replay', function () { + app()->instance(ReplayableWebhookRepository::class, new class implements ReplayableWebhookRepository + { + public function findReplayableById(int|string $id): ReplayableWebhook + { + return replayableWebhook( + id: $id, + status: 'processing', + ); + } + }); + + expect(fn () => app(ReplayWebhook::class)->handle(new ReplayWebhookCommand( + webhookLogId: 1, + signature: Signature::fromString('sha256=valid'), + )))->toThrow(ReplayWebhookNotAllowed::class); +}); diff --git a/tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php b/tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php index 472fc08..5e94e34 100644 --- a/tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php +++ b/tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php @@ -5,11 +5,13 @@ use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; use Proxynth\Larawebhook\Exceptions\WebhookException; +use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; use Proxynth\Larawebhook\Processing\Application\Commands\RetryWebhookCommand; use Proxynth\Larawebhook\Processing\Application\Data\RetryPolicy; use Proxynth\Larawebhook\Processing\Application\Ports\RetryPolicyResolver; use Proxynth\Larawebhook\Processing\Application\UseCases\RetryWebhook; use Proxynth\Larawebhook\Processing\Domain\Events\WebhookProcessingFailed; +use Proxynth\Larawebhook\Processing\Domain\Exceptions\InvalidWebhookState; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; use Proxynth\Larawebhook\Tests\Fakes\Processing\FakeRetryPolicyResolver; @@ -151,3 +153,64 @@ ->and($result->nextAttempt)->toBe(2) ->and($result->delaySeconds)->toBe(42); }); + +it('records a successful retry through webhook event transitions', function () { + $result = app(RetryWebhook::class)->handle(new RetryWebhookCommand( + payload: '{"action":"opened"}', + signature: incomingSignature(githubSignature('{"action":"opened"}')->value()), + service: WebhookService::Github->value, + event: 'opened', + secret: 'github_secret', + attempt: 1, + externalId: 'delivery_123', + idempotencyKey: 'delivery_123', + )); + + expect($result->isSuccess())->toBeTrue(); + + $log = WebhookLog::query()->latest('id')->first(); + + expect($log->status)->toBe('success') + ->and($log->service)->toBe('github') + ->and($log->event)->toBe('opened') + ->and($log->attempt)->toBe(1) + ->and($log->external_id)->toBeNull() + ->and($log->idempotency_key)->toBeNull(); +}); + +it('records a failed retry through webhook event transitions', function () { + $result = app(RetryWebhook::class)->handle(new RetryWebhookCommand( + payload: '{"action":"opened"}', + signature: Signature::fromString('sha256=invalid'), + service: WebhookService::Github->value, + event: 'opened', + secret: 'github_secret', + attempt: 1, + externalId: 'delivery_123', + idempotencyKey: 'delivery_123', + )); + + expect($result->isFailed())->toBeTrue() + ->and($result->shouldRetry)->toBeTrue() + ->and($result->nextAttempt)->toBe(2); + + $log = WebhookLog::query()->latest('id')->first(); + + expect($log->status)->toBe('failed') + ->and($log->attempt)->toBe(1) + ->and($log->external_id)->toBeNull() + ->and($log->idempotency_key)->toBeNull(); +}); + +it('requires idempotency key to mark a retry as processed', function () { + expect(fn () => app(RetryWebhook::class)->handle(new RetryWebhookCommand( + payload: '{"action":"opened"}', + signature: githubSignature('{"action":"opened"}'), + service: WebhookService::Github->value, + event: 'opened', + secret: 'github_secret', + attempt: 1, + externalId: 'delivery_123', + idempotencyKey: null, + )))->toThrow(InvalidWebhookState::class); +}); diff --git a/tests/Unit/Processing/Domain/Entities/WebhookEventTest.php b/tests/Unit/Processing/Domain/Entities/WebhookEventTest.php index 3ff9d4a..1098c2b 100644 --- a/tests/Unit/Processing/Domain/Entities/WebhookEventTest.php +++ b/tests/Unit/Processing/Domain/Entities/WebhookEventTest.php @@ -134,3 +134,93 @@ function webhookEvent( $event->replay(); })->throws(InvalidWebhookState::class); + +it('transitions through retry success flow', function () { + $event = WebhookEvent::received( + provider: Provider::fromString('github'), + eventType: EventType::fromString('opened'), + idempotencyKey: IdempotencyKey::optional('delivery_123'), + ); + + $event->markValidated(); + $event->markProcessing(); + $event->markProcessed(); + + expect($event->status()->value())->toBe('processed'); +}); + +it('transitions through retry failure flow', function () { + $event = WebhookEvent::received( + provider: Provider::fromString('github'), + eventType: EventType::fromString('opened'), + idempotencyKey: IdempotencyKey::optional('delivery_123'), + ); + + $event->markFailed('Invalid signature'); + + expect($event->status()->value())->toBe('failed'); +}); + +it('does not allow processing before validation', function () { + $event = WebhookEvent::received( + provider: Provider::fromString('github'), + eventType: EventType::fromString('opened'), + idempotencyKey: IdempotencyKey::optional('delivery_123'), + ); + + expect(fn () => $event->markProcessing()) + ->toThrow(InvalidWebhookState::class); +}); + +it('does not allow processed before processing', function () { + $event = WebhookEvent::received( + provider: Provider::fromString('github'), + eventType: EventType::fromString('opened'), + idempotencyKey: IdempotencyKey::optional('delivery_123'), + ); + + $event->markValidated(); + + expect(fn () => $event->markProcessed()) + ->toThrow(InvalidWebhookState::class); +}); + +it('can be restored from history', function () { + $event = WebhookEvent::fromHistory( + provider: Provider::fromString('github'), + eventType: EventType::fromString('opened'), + idempotencyKey: IdempotencyKey::optional('delivery_123'), + status: WebhookStatus::failed(), + ); + + expect($event->provider()->value())->toBe('github') + ->and($event->eventType()->value())->toBe('opened') + ->and($event->status()->value())->toBe('failed') + ->and($event->idempotencyKey()?->value())->toBe('delivery_123'); +}); + +it('allows replay from failed webhook', function () { + $event = WebhookEvent::fromHistory( + provider: Provider::fromString('github'), + eventType: EventType::fromString('opened'), + idempotencyKey: IdempotencyKey::optional('delivery_123'), + status: WebhookStatus::failed(), + ); + + $replayed = $event->replay(); + + expect($replayed->provider()->value())->toBe('github') + ->and($replayed->eventType()->value())->toBe('opened'); +}); + +it('does not allow replay from received webhook', function () { + $event = WebhookEvent::fromHistory( + provider: Provider::fromString('github'), + eventType: EventType::fromString('opened'), + idempotencyKey: IdempotencyKey::optional('delivery_123'), + status: WebhookStatus::received(), + ); + + expect(fn () => $event->replay()) + ->toThrow(InvalidWebhookState::class); +});