From 434d3475b04f5d53209a4899da570f1f896c72b1 Mon Sep 17 00:00:00 2001 From: Proxynth Date: Sat, 22 Aug 2026 18:54:54 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20harden=20archi?= =?UTF-8?q?tecture=20and=20extensibility?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - separate application use cases from Laravel infrastructure\n- introduce ports, adapters and transaction boundaries\n- support configurable webhook services and custom providers\n- stabilize audit, retry, CI and static analysis coverage --- .github/workflows/tests.yml | 10 +- composer.json | 2 +- config/larawebhook.php | 19 ++- docs/facade-api.md | 4 + src/Audit/Application/Data/WebhookLogData.php | 22 +++ src/Audit/Application/Data/WebhookLogPage.php | 21 +++ .../Ports/WebhookAuditLogWriter.php | 4 +- .../Ports/WebhookLogReadRepository.php | 4 +- .../Application/Queries/ListWebhookLogs.php | 4 +- .../ReadModels/WebhookFailureDetails.php | 16 -- .../ReadModels/WebhookLogDetails.php | 18 --- .../ReadModels/WebhookLogSummary.php | 15 -- .../Application/UseCases/RecordWebhookLog.php | 4 +- .../Http/Controllers/WebhookLogController.php | 21 +-- .../Http/Resources/WebhookLogResource.php | 3 +- .../EloquentWebhookLogReadRepository.php | 26 +++- .../WebhookLogReadModelFactory.php | 59 +++++++ .../Logging/WebhookLogDataFactory.php | 32 ++++ .../Logging/WebhookLoggerAuditLogWriter.php | 30 ++-- .../Commands/ReceiveWebhookCommand.php | 4 +- .../Commands/ValidateWebhookCommand.php | 4 +- .../Application/Ports/AuditLogRecorder.php | 9 ++ .../Application/Ports/SignatureValidator.php | 4 +- .../Ports/WebhookPayloadParserResolver.php | 4 +- .../Ports/WebhookSecretResolver.php | 4 +- .../Ports/WebhookServiceMetadataResolver.php | 8 +- .../Results/ReceiveWebhookResult.php | 23 ++- .../Services/ReceiveWebhookEventFactory.php | 34 ++++ .../Application/UseCases/ReceiveWebhook.php | 101 ++++++------ .../Application/UseCases/ValidateWebhook.php | 2 +- .../Domain/ValueObjects/RawPayload.php | 7 + .../Config/ConfigWebhookSecretResolver.php | 6 +- .../Laravel/Middleware/ValidateWebhook.php | 14 +- .../Parsing/PayloadParserRegistry.php | 42 +++++ .../Parsing/ProviderPayloadParserResolver.php | 21 ++- .../LaravelWebhookServiceMetadataResolver.php | 49 +++--- .../Validation/ProviderSignatureValidator.php | 4 +- .../Validation/SignatureValidatorRegistry.php | 37 +++++ .../Validation/WebhookValidator.php | 50 ++---- .../Validation/WebhookValidatorFactory.php | 30 ++-- src/Larawebhook.php | 2 +- .../Commands/RetryWebhookCommand.php | 1 - .../Application/Data/ReplayableWebhook.php | 7 +- .../Application/Ports/AuditLogRecorder.php | 9 ++ .../Results/ReplayWebhookResult.php | 22 +++ .../Results/RetryWebhookResult.php | 8 +- .../Application/UseCases/ReplayWebhook.php | 20 ++- .../Application/UseCases/RetryWebhook.php | 39 +++-- .../Laravel/Jobs/RetryWebhookJob.php | 12 +- src/Shared/Application/Ports/Delay.php | 10 ++ .../Application/Ports/TransactionRunner.php | 14 ++ src/Shared/Domain/Enums/WebhookService.php | 8 +- .../ValueObjects/ConfiguredWebhookService.php | 34 ++++ .../ValueObjects/WebhookServiceIdentifier.php | 12 ++ .../Laravel/Facades/Larawebhook.php | 18 +-- .../Laravel}/Larawebhook.php | 145 +++++++++++------- .../WebhookNotificationGateway.php | 47 ++++++ .../Providers/LarawebhookServiceProvider.php | 56 ++++++- .../Laravel/Queries/WebhookLogQueries.php | 35 +++++ .../Laravel/Timing/SleepDelay.php | 17 ++ .../Transactions/LaravelTransactionRunner.php | 16 ++ tests/ArchTest.php | 17 +- .../Ingestion/FakeWebhookSecretResolver.php | 4 +- .../RecordWebhookLogIntegrationTest.php | 11 +- .../PayloadStorage/PayloadStorageModeTest.php | 6 +- .../Queries/GetWebhookFailureDetailsTest.php | 4 +- .../Queries/GetWebhookLogDetailsTest.php | 4 +- .../Queries/ListWebhookLogsTest.php | 19 ++- .../ReadModels/WebhookFailureDetailsTest.php | 3 +- .../ReadModels/WebhookLogDetailsTest.php | 3 +- .../ReadModels/WebhookLogSummaryTest.php | 3 +- .../UseCases/RecordWebhookLogTest.php | 18 ++- tests/Unit/Facades/LarawebhookFacadeTest.php | 12 +- .../UseCases/ReceiveWebhookTest.php | 22 +-- .../UseCases/ValidateWebhookTest.php | 7 +- .../Domain/ValueObjects/RawPayloadTest.php | 9 +- tests/Unit/Jobs/RetryWebhookJobTest.php | 11 +- tests/Unit/LarawebhookServiceProviderTest.php | 7 + tests/Unit/LarawebhookTest.php | 2 +- .../UseCases/ReplayWebhookTest.php | 40 ++--- .../Application/UseCases/RetryWebhookTest.php | 13 +- .../SignatureValidatorRegistryTest.php | 37 +++++ 82 files changed, 1068 insertions(+), 487 deletions(-) create mode 100644 src/Audit/Application/Data/WebhookLogData.php create mode 100644 src/Audit/Application/Data/WebhookLogPage.php create mode 100644 src/Audit/Infrastructure/Laravel/Persistence/WebhookLogReadModelFactory.php create mode 100644 src/Audit/Infrastructure/Logging/WebhookLogDataFactory.php create mode 100644 src/Ingestion/Application/Ports/AuditLogRecorder.php create mode 100644 src/Ingestion/Application/Services/ReceiveWebhookEventFactory.php create mode 100644 src/Ingestion/Infrastructure/Parsing/PayloadParserRegistry.php create mode 100644 src/Ingestion/Infrastructure/Validation/SignatureValidatorRegistry.php create mode 100644 src/Processing/Application/Ports/AuditLogRecorder.php create mode 100644 src/Shared/Application/Ports/Delay.php create mode 100644 src/Shared/Application/Ports/TransactionRunner.php create mode 100644 src/Shared/Domain/ValueObjects/ConfiguredWebhookService.php create mode 100644 src/Shared/Domain/ValueObjects/WebhookServiceIdentifier.php rename src/Shared/{Application => Infrastructure/Laravel}/Larawebhook.php (74%) create mode 100644 src/Shared/Infrastructure/Laravel/Notifications/WebhookNotificationGateway.php create mode 100644 src/Shared/Infrastructure/Laravel/Queries/WebhookLogQueries.php create mode 100644 src/Shared/Infrastructure/Laravel/Timing/SleepDelay.php create mode 100644 src/Shared/Infrastructure/Laravel/Transactions/LaravelTransactionRunner.php create mode 100644 tests/Unit/Validators/SignatureValidatorRegistryTest.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cf1b42d..c1baf6b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -10,20 +10,22 @@ on: jobs: tests: runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php-version: ['8.3', '8.4'] steps: - uses: actions/checkout@v7 - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: '8.3' + php-version: ${{ matrix.php-version }} extensions: mbstring, ctype, json, dom coverage: pcov - name: Install dependencies run: composer install --prefer-dist --no-progress - - name: Run PHPUnit - run: vendor/bin/pest --coverage-text --ci - name: Run tests with coverage - run: vendor/bin/pest --coverage-text --coverage-clover=coverage.xml --ci + run: composer test -- --coverage-text --coverage-clover=coverage.xml --ci - name: Upload coverage to Codecov uses: codecov/codecov-action@v7 with: diff --git a/composer.json b/composer.json index 1c229d7..3ef136a 100644 --- a/composer.json +++ b/composer.json @@ -57,7 +57,7 @@ "require": { "php": "^8.3", "spatie/laravel-package-tools": "^1.12", - "illuminate/contracts": "*", + "illuminate/contracts": "^11.0 || ^12.0 || ^13.0", "symfony/mailer": "^7.0" }, "config": { diff --git a/config/larawebhook.php b/config/larawebhook.php index 8501978..53e0d9f 100644 --- a/config/larawebhook.php +++ b/config/larawebhook.php @@ -6,37 +6,42 @@ | Custom Validators |-------------------------------------------------------------------------- | - | Register custom webhook validators for additional services. + | Register custom signature validators for supported services. + | A custom validator replaces the built-in validator for its service. | Each validator must implement WebhookValidatorInterface. | | Example: - | 'twilio' => \App\Webhooks\TwilioValidator::class, + | 'stripe' => \App\Webhooks\CustomStripeValidator::class, | */ 'custom_validators' => [ // Add your custom validators here ], + 'custom_parsers' => [ + // 'twilio' => \App\Webhooks\TwilioPayloadParser::class, + ], + 'services' => [ 'stripe' => [ 'public' => env('STRIPE_PUBLIC_KEY', 'stripe_public_key_test'), - 'secret' => env('STRIPE_SECRET_KEY', 'stripe_secret_key_test'), - 'webhook_secret' => env('STRIPE_WEBHOOK_SECRET', 'stripe_webhook_secret_key_test'), + 'secret' => env('STRIPE_SECRET_KEY'), + 'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'), 'tolerance' => 300, ], 'github' => [ - 'webhook_secret' => env('GITHUB_WEBHOOK_SECRET', 'github_webhook_secret_key_test'), + 'webhook_secret' => env('GITHUB_WEBHOOK_SECRET'), 'tolerance' => 300, ], 'slack' => [ - 'webhook_secret' => env('SLACK_WEBHOOK_SECRET', 'slack_webhook_secret_test'), + 'webhook_secret' => env('SLACK_WEBHOOK_SECRET'), 'tolerance' => env('SLACK_WEBHOOK_TOLERANCE', 300), ], 'shopify' => [ - 'webhook_secret' => env('SHOPIFY_WEBHOOK_SECRET', 'shopify_webhook_secret_test'), + 'webhook_secret' => env('SHOPIFY_WEBHOOK_SECRET'), 'tolerance' => env('SHOPIFY_WEBHOOK_TOLERANCE', 300), ], ], diff --git a/docs/facade-api.md b/docs/facade-api.md index d20207d..c499985 100644 --- a/docs/facade-api.md +++ b/docs/facade-api.md @@ -31,6 +31,10 @@ For new code, prefer the high-level helpers: They are deprecated for new code. +Plan their removal when upgrading to the next major version. Existing calls remain +supported in the current major version; migrate them to `validateAndLog()` or the +`RecordWebhookLog` use case before upgrading. + Prefer: - `validateAndLog()` when validating and recording a webhook; diff --git a/src/Audit/Application/Data/WebhookLogData.php b/src/Audit/Application/Data/WebhookLogData.php new file mode 100644 index 0000000..2931d79 --- /dev/null +++ b/src/Audit/Application/Data/WebhookLogData.php @@ -0,0 +1,22 @@ + $items */ + public function __construct( + public array $items, + public int $total, + public int $perPage, + public int $currentPage, + public int $lastPage, + /** @var array{first:?string,last:?string,prev:?string,next:?string} */ + public array $links, + ) {} +} diff --git a/src/Audit/Application/Ports/WebhookAuditLogWriter.php b/src/Audit/Application/Ports/WebhookAuditLogWriter.php index 0639b52..5765a71 100644 --- a/src/Audit/Application/Ports/WebhookAuditLogWriter.php +++ b/src/Audit/Application/Ports/WebhookAuditLogWriter.php @@ -5,9 +5,9 @@ namespace Proxynth\Larawebhook\Audit\Application\Ports; use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; interface WebhookAuditLogWriter { - public function record(RecordWebhookLogCommand $command): WebhookLog; + public function record(RecordWebhookLogCommand $command): WebhookLogData; } diff --git a/src/Audit/Application/Ports/WebhookLogReadRepository.php b/src/Audit/Application/Ports/WebhookLogReadRepository.php index ebe4f1b..ec0b09b 100644 --- a/src/Audit/Application/Ports/WebhookLogReadRepository.php +++ b/src/Audit/Application/Ports/WebhookLogReadRepository.php @@ -4,14 +4,14 @@ namespace Proxynth\Larawebhook\Audit\Application\Ports; -use Illuminate\Pagination\LengthAwarePaginator; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogPage; use Proxynth\Larawebhook\Audit\Application\Queries\ListWebhookLogsQuery; use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookFailureDetails; use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookLogDetails; interface WebhookLogReadRepository { - public function paginateSummaries(ListWebhookLogsQuery $query): LengthAwarePaginator; + public function paginateSummaries(ListWebhookLogsQuery $query): WebhookLogPage; public function findDetails(int|string $id): WebhookLogDetails; diff --git a/src/Audit/Application/Queries/ListWebhookLogs.php b/src/Audit/Application/Queries/ListWebhookLogs.php index e0726e9..cd53b19 100644 --- a/src/Audit/Application/Queries/ListWebhookLogs.php +++ b/src/Audit/Application/Queries/ListWebhookLogs.php @@ -4,7 +4,7 @@ namespace Proxynth\Larawebhook\Audit\Application\Queries; -use Illuminate\Pagination\LengthAwarePaginator; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogPage; use Proxynth\Larawebhook\Audit\Application\Ports\WebhookLogReadRepository; final readonly class ListWebhookLogs @@ -13,7 +13,7 @@ public function __construct( private WebhookLogReadRepository $readRepository, ) {} - public function handle(ListWebhookLogsQuery $query): LengthAwarePaginator + public function handle(ListWebhookLogsQuery $query): WebhookLogPage { return $this->readRepository->paginateSummaries($query); } diff --git a/src/Audit/Application/ReadModels/WebhookFailureDetails.php b/src/Audit/Application/ReadModels/WebhookFailureDetails.php index d5ace42..dc51b64 100644 --- a/src/Audit/Application/ReadModels/WebhookFailureDetails.php +++ b/src/Audit/Application/ReadModels/WebhookFailureDetails.php @@ -4,8 +4,6 @@ namespace Proxynth\Larawebhook\Audit\Application\ReadModels; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; - final readonly class WebhookFailureDetails { public function __construct( @@ -20,18 +18,4 @@ public function __construct( public string $createdAt, ) {} - public static function fromModel(WebhookLog $log): self - { - return new self( - id: $log->getKey(), - service: $log->service, - event: $log->event, - status: $log->status, - errorMessage: $log->error_message ?? 'Unknown webhook failure.', - attempt: $log->attempt, - externalId: $log->external_id, - idempotencyKey: $log->idempotency_key, - createdAt: $log->created_at->toISOString() ?? '', - ); - } } diff --git a/src/Audit/Application/ReadModels/WebhookLogDetails.php b/src/Audit/Application/ReadModels/WebhookLogDetails.php index 1a1adbd..379f239 100644 --- a/src/Audit/Application/ReadModels/WebhookLogDetails.php +++ b/src/Audit/Application/ReadModels/WebhookLogDetails.php @@ -4,8 +4,6 @@ namespace Proxynth\Larawebhook\Audit\Application\ReadModels; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; - final readonly class WebhookLogDetails { public function __construct( @@ -22,20 +20,4 @@ public function __construct( public string $updatedAt, ) {} - public static function fromModel(WebhookLog $log): self - { - return new self( - id: $log->id, - service: $log->service, - event: $log->event, - status: $log->status, - payload: $log->payload, - errorMessage: $log->error_message, - attempt: $log->attempt, - externalId: $log->external_id, - idempotencyKey: $log->idempotency_key, - createdAt: $log->created_at->toISOString() ?? '', - updatedAt: $log->updated_at->toISOString() ?? '', - ); - } } diff --git a/src/Audit/Application/ReadModels/WebhookLogSummary.php b/src/Audit/Application/ReadModels/WebhookLogSummary.php index 7b7c11e..f3e688c 100644 --- a/src/Audit/Application/ReadModels/WebhookLogSummary.php +++ b/src/Audit/Application/ReadModels/WebhookLogSummary.php @@ -4,8 +4,6 @@ namespace Proxynth\Larawebhook\Audit\Application\ReadModels; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; - final readonly class WebhookLogSummary { public function __construct( @@ -19,17 +17,4 @@ public function __construct( public string $createdAt, ) {} - public static function fromModel(WebhookLog $log): self - { - return new self( - id: $log->getKey(), - service: $log->service, - event: $log->event, - status: $log->status, - attempt: $log->attempt, - externalId: $log->external_id, - idempotencyKey: $log->idempotency_key, - createdAt: $log->created_at->toISOString() ?? '', - ); - } } diff --git a/src/Audit/Application/UseCases/RecordWebhookLog.php b/src/Audit/Application/UseCases/RecordWebhookLog.php index 8ca98e3..54e2d68 100644 --- a/src/Audit/Application/UseCases/RecordWebhookLog.php +++ b/src/Audit/Application/UseCases/RecordWebhookLog.php @@ -5,8 +5,8 @@ namespace Proxynth\Larawebhook\Audit\Application\UseCases; use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Audit\Application\Ports\WebhookAuditLogWriter; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; final readonly class RecordWebhookLog { @@ -14,7 +14,7 @@ public function __construct( private WebhookAuditLogWriter $writer, ) {} - public function handle(RecordWebhookLogCommand $command): WebhookLog + public function handle(RecordWebhookLogCommand $command): WebhookLogData { return $this->writer->record($command); } diff --git a/src/Audit/Infrastructure/Laravel/Http/Controllers/WebhookLogController.php b/src/Audit/Infrastructure/Laravel/Http/Controllers/WebhookLogController.php index 693649d..62c7f69 100644 --- a/src/Audit/Infrastructure/Laravel/Http/Controllers/WebhookLogController.php +++ b/src/Audit/Infrastructure/Laravel/Http/Controllers/WebhookLogController.php @@ -21,7 +21,7 @@ use Proxynth\Larawebhook\Processing\Application\Commands\ReplayWebhookCommand; use Proxynth\Larawebhook\Processing\Application\UseCases\ReplayWebhook; use Proxynth\Larawebhook\Shared\Application\Ports\EventBus; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\ConfiguredWebhookService; use RuntimeException; use Throwable; @@ -46,19 +46,14 @@ public function index(Request $request): JsonResponse )); return response()->json([ - 'data' => WebhookLogResource::collection($logs), + 'data' => WebhookLogResource::collection($logs->items), 'meta' => [ - 'total' => $logs->total(), - 'per_page' => $logs->perPage(), - 'current_page' => $logs->currentPage(), - 'last_page' => $logs->lastPage(), - ], - 'links' => [ - 'first' => $logs->url(1), - 'last' => $logs->url($logs->lastPage()), - 'prev' => $logs->previousPageUrl(), - 'next' => $logs->nextPageUrl(), + 'total' => $logs->total, + 'per_page' => $logs->perPage, + 'current_page' => $logs->currentPage, + 'last_page' => $logs->lastPage, ], + 'links' => $logs->links, ]); } @@ -121,7 +116,7 @@ private function extractSignatureFromPayload(WebhookLog $log): Signature // For now, we'll regenerate the signature for replay purposes // In a real implementation, you'd store the original signature $payload = json_encode($log->payload); - $secret = $this->secretResolver->resolve(WebhookService::fromString($log->service)); + $secret = $this->secretResolver->resolve(ConfiguredWebhookService::resolve($log->service)); if ($secret === null) { throw new RuntimeException('No secret configured for service: '.$log->service); diff --git a/src/Audit/Infrastructure/Laravel/Http/Resources/WebhookLogResource.php b/src/Audit/Infrastructure/Laravel/Http/Resources/WebhookLogResource.php index 33e6728..7523282 100644 --- a/src/Audit/Infrastructure/Laravel/Http/Resources/WebhookLogResource.php +++ b/src/Audit/Infrastructure/Laravel/Http/Resources/WebhookLogResource.php @@ -12,6 +12,7 @@ use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookLogDetails; use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookLogSummary; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\WebhookLogReadModelFactory; /** * @mixin WebhookLog @@ -34,7 +35,7 @@ public function toArray(Request $request): array $this->resource instanceof WebhookLogSummary => $this->summary($this->resource), $this->resource instanceof WebhookLogDetails => $this->details($this->resource), $this->resource instanceof WebhookFailureDetails => $this->failureDetails($this->resource), - $this->resource instanceof WebhookLog => $this->details(WebhookLogDetails::fromModel($this->resource)), + $this->resource instanceof WebhookLog => $this->details((new WebhookLogReadModelFactory)->details($this->resource)), default => throw new InvalidArgumentException(sprintf( 'WebhookLogResource expects [%s], [%s], [%s] or [%s], [%s] given.', WebhookLogSummary::class, diff --git a/src/Audit/Infrastructure/Laravel/Persistence/EloquentWebhookLogReadRepository.php b/src/Audit/Infrastructure/Laravel/Persistence/EloquentWebhookLogReadRepository.php index 5dd763b..ebbb4fe 100644 --- a/src/Audit/Infrastructure/Laravel/Persistence/EloquentWebhookLogReadRepository.php +++ b/src/Audit/Infrastructure/Laravel/Persistence/EloquentWebhookLogReadRepository.php @@ -4,7 +4,7 @@ namespace Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence; -use Illuminate\Pagination\LengthAwarePaginator; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogPage; use Proxynth\Larawebhook\Audit\Application\Ports\WebhookLogReadRepository; use Proxynth\Larawebhook\Audit\Application\Queries\ListWebhookLogsQuery; use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookFailureDetails; @@ -14,7 +14,7 @@ final class EloquentWebhookLogReadRepository implements WebhookLogReadRepository { - public function paginateSummaries(ListWebhookLogsQuery $query): LengthAwarePaginator + public function paginateSummaries(ListWebhookLogsQuery $query): WebhookLogPage { $logs = WebhookLog::query() ->when($query->service !== null, fn ($builder) => $builder->where('service', $query->service)) @@ -24,8 +24,22 @@ public function paginateSummaries(ListWebhookLogsQuery $query): LengthAwarePagin ->latest() ->paginate($query->perPage); - return $logs->through( - fn (WebhookLog $log): WebhookLogSummary => WebhookLogSummary::fromModel($log) + $factory = new WebhookLogReadModelFactory; + + $mapped = $logs->through(fn (WebhookLog $log): WebhookLogSummary => $factory->summary($log)); + + return new WebhookLogPage( + items: array_values($mapped->items()), + total: $mapped->total(), + perPage: $mapped->perPage(), + currentPage: $mapped->currentPage(), + lastPage: $mapped->lastPage(), + links: [ + 'first' => $mapped->url(1), + 'last' => $mapped->url($mapped->lastPage()), + 'prev' => $mapped->previousPageUrl(), + 'next' => $mapped->nextPageUrl(), + ], ); } @@ -33,7 +47,7 @@ public function findDetails(int|string $id): WebhookLogDetails { $log = WebhookLog::query()->findOrFail($id); - return WebhookLogDetails::fromModel($log); + return (new WebhookLogReadModelFactory)->details($log); } public function findFailureDetails(int|string $id): WebhookFailureDetails @@ -43,6 +57,6 @@ public function findFailureDetails(int|string $id): WebhookFailureDetails ->where('status', 'failed') ->firstOrFail(); - return WebhookFailureDetails::fromModel($log); + return (new WebhookLogReadModelFactory)->failureDetails($log); } } diff --git a/src/Audit/Infrastructure/Laravel/Persistence/WebhookLogReadModelFactory.php b/src/Audit/Infrastructure/Laravel/Persistence/WebhookLogReadModelFactory.php new file mode 100644 index 0000000..0d38b77 --- /dev/null +++ b/src/Audit/Infrastructure/Laravel/Persistence/WebhookLogReadModelFactory.php @@ -0,0 +1,59 @@ +getKey(), + service: $log->service, + event: $log->event, + status: $log->status, + attempt: $log->attempt, + externalId: $log->external_id, + idempotencyKey: $log->idempotency_key, + createdAt: $log->created_at->toISOString() ?? '', + ); + } + + public function details(WebhookLog $log): WebhookLogDetails + { + return new WebhookLogDetails( + id: $log->getKey(), + service: $log->service, + event: $log->event, + status: $log->status, + payload: $log->payload, + errorMessage: $log->error_message, + attempt: $log->attempt, + externalId: $log->external_id, + idempotencyKey: $log->idempotency_key, + createdAt: $log->created_at->toISOString() ?? '', + updatedAt: $log->updated_at->toISOString() ?? '', + ); + } + + public function failureDetails(WebhookLog $log): WebhookFailureDetails + { + return new WebhookFailureDetails( + id: $log->getKey(), + service: $log->service, + event: $log->event, + status: $log->status, + errorMessage: $log->error_message ?? 'Unknown webhook failure.', + attempt: $log->attempt, + externalId: $log->external_id, + idempotencyKey: $log->idempotency_key, + createdAt: $log->created_at->toISOString() ?? '', + ); + } +} diff --git a/src/Audit/Infrastructure/Logging/WebhookLogDataFactory.php b/src/Audit/Infrastructure/Logging/WebhookLogDataFactory.php new file mode 100644 index 0000000..47e69a0 --- /dev/null +++ b/src/Audit/Infrastructure/Logging/WebhookLogDataFactory.php @@ -0,0 +1,32 @@ +getAttribute('created_at'); + $updatedAt = $log->getAttribute('updated_at'); + + return new WebhookLogData( + id: $log->getKey() ?? 0, + service: $log->service, + event: $log->event, + status: $log->status, + payload: $log->payload, + errorMessage: $log->error_message, + attempt: $log->attempt, + externalId: $log->external_id, + idempotencyKey: $log->idempotency_key, + createdAt: $createdAt instanceof CarbonInterface ? $createdAt->toISOString() : '', + updatedAt: $updatedAt instanceof CarbonInterface ? $updatedAt->toISOString() : '', + ); + } +} diff --git a/src/Audit/Infrastructure/Logging/WebhookLoggerAuditLogWriter.php b/src/Audit/Infrastructure/Logging/WebhookLoggerAuditLogWriter.php index 51a9e0e..86119f3 100644 --- a/src/Audit/Infrastructure/Logging/WebhookLoggerAuditLogWriter.php +++ b/src/Audit/Infrastructure/Logging/WebhookLoggerAuditLogWriter.php @@ -5,19 +5,21 @@ namespace Proxynth\Larawebhook\Audit\Infrastructure\Logging; use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Audit\Application\Ports\WebhookAuditLogWriter; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Ingestion\Application\Ports\AuditLogRecorder as IngestionAuditLogRecorder; +use Proxynth\Larawebhook\Processing\Application\Ports\AuditLogRecorder as ProcessingAuditLogRecorder; -final readonly class WebhookLoggerAuditLogWriter implements WebhookAuditLogWriter +final readonly class WebhookLoggerAuditLogWriter implements IngestionAuditLogRecorder, ProcessingAuditLogRecorder, WebhookAuditLogWriter { public function __construct( private WebhookLogger $logger, ) {} - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { if ($command->valid) { - return $this->logger->logSuccess( + $log = $this->logger->logSuccess( service: $command->service, event: $command->event, payload: $command->payload, @@ -25,16 +27,18 @@ public function record(RecordWebhookLogCommand $command): WebhookLog externalId: $command->externalId, idempotencyKey: $command->idempotencyKey, ); + } else { + $log = $this->logger->logFailure( + service: $command->service, + event: $command->event, + payload: $command->payload, + errorMessage: $command->errorMessage ?? 'Webhook validation failed.', + attempt: $command->attempt, + externalId: $command->externalId, + idempotencyKey: $command->idempotencyKey, + ); } - return $this->logger->logFailure( - service: $command->service, - event: $command->event, - payload: $command->payload, - errorMessage: $command->errorMessage ?? 'Webhook validation failed.', - attempt: $command->attempt, - externalId: $command->externalId, - idempotencyKey: $command->idempotencyKey, - ); + return WebhookLogDataFactory::fromModel($log); } } diff --git a/src/Ingestion/Application/Commands/ReceiveWebhookCommand.php b/src/Ingestion/Application/Commands/ReceiveWebhookCommand.php index 536b9f2..c20977b 100644 --- a/src/Ingestion/Application/Commands/ReceiveWebhookCommand.php +++ b/src/Ingestion/Application/Commands/ReceiveWebhookCommand.php @@ -6,12 +6,12 @@ use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; use Proxynth\Larawebhook\Shared\Application\Commands\Command; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; final readonly class ReceiveWebhookCommand implements Command { public function __construct( - public WebhookService $service, + public WebhookServiceIdentifier $service, public string $payload, public Signature $signature, public ?string $externalIdHeaderValue = null, diff --git a/src/Ingestion/Application/Commands/ValidateWebhookCommand.php b/src/Ingestion/Application/Commands/ValidateWebhookCommand.php index dddbb49..f4768e5 100644 --- a/src/Ingestion/Application/Commands/ValidateWebhookCommand.php +++ b/src/Ingestion/Application/Commands/ValidateWebhookCommand.php @@ -7,12 +7,12 @@ use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; use Proxynth\Larawebhook\Shared\Application\Commands\Command; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; final readonly class ValidateWebhookCommand implements Command { public function __construct( - public WebhookService $service, + public WebhookServiceIdentifier $service, public RawPayload $payload, public Signature $signature, public string $event, diff --git a/src/Ingestion/Application/Ports/AuditLogRecorder.php b/src/Ingestion/Application/Ports/AuditLogRecorder.php new file mode 100644 index 0000000..8c774ef --- /dev/null +++ b/src/Ingestion/Application/Ports/AuditLogRecorder.php @@ -0,0 +1,9 @@ + */ public array $events = [], ) {} - public static function success(WebhookLog $log, array $events = []): self + public static function success(WebhookLogData $log, array $events = []): self { return new self( status: self::STATUS_SUCCESS, log: $log, event: $log->event, - externalId: $log->external_id, - idempotencyKey: $log->idempotency_key, + externalId: $log->externalId, + idempotencyKey: $log->idempotencyKey, events: $events, ); } @@ -65,9 +64,8 @@ public static function secretNotConfigured(string $service, array $events = []): } public static function acceptedForRetry( - WebhookLog $log, + WebhookLogData $log, string $event, - string $secret, ?string $externalId, ?string $idempotencyKey, array $events = [], @@ -79,20 +77,19 @@ public static function acceptedForRetry( externalId: $externalId, idempotencyKey: $idempotencyKey, errorMessage: 'Webhook validation failed, queued for retry', - secret: $secret, events: $events, ); } - public static function failed(WebhookLog $log, int $statusCode, array $events = []): self + public static function failed(WebhookLogData $log, int $statusCode, array $events = []): self { return new self( status: self::STATUS_FAILED, log: $log, event: $log->event, - externalId: $log->external_id, - idempotencyKey: $log->idempotency_key, - errorMessage: $log->error_message, + externalId: $log->externalId, + idempotencyKey: $log->idempotencyKey, + errorMessage: $log->errorMessage, failureStatusCode: $statusCode, events: $events, ); diff --git a/src/Ingestion/Application/Services/ReceiveWebhookEventFactory.php b/src/Ingestion/Application/Services/ReceiveWebhookEventFactory.php new file mode 100644 index 0000000..21b13a3 --- /dev/null +++ b/src/Ingestion/Application/Services/ReceiveWebhookEventFactory.php @@ -0,0 +1,34 @@ +id, $log->service, $log->event, $log->status); + } +} diff --git a/src/Ingestion/Application/UseCases/ReceiveWebhook.php b/src/Ingestion/Application/UseCases/ReceiveWebhook.php index e851c6d..6311496 100644 --- a/src/Ingestion/Application/UseCases/ReceiveWebhook.php +++ b/src/Ingestion/Application/UseCases/ReceiveWebhook.php @@ -6,16 +6,13 @@ use Exception; use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; -use Proxynth\Larawebhook\Audit\Application\UseCases\RecordWebhookLog; -use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged; use Proxynth\Larawebhook\Ingestion\Application\Commands\ReceiveWebhookCommand; use Proxynth\Larawebhook\Ingestion\Application\Commands\ValidateWebhookCommand; +use Proxynth\Larawebhook\Ingestion\Application\Ports\AuditLogRecorder; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookPayloadParserResolver; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookSecretResolver; use Proxynth\Larawebhook\Ingestion\Application\Results\ReceiveWebhookResult; -use Proxynth\Larawebhook\Ingestion\Domain\Events\WebhookReceived; -use Proxynth\Larawebhook\Ingestion\Domain\Events\WebhookRejected; -use Proxynth\Larawebhook\Ingestion\Domain\Events\WebhookValidated; +use Proxynth\Larawebhook\Ingestion\Application\Services\ReceiveWebhookEventFactory; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Provider; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload; use Proxynth\Larawebhook\Processing\Application\Ports\IdempotencyResolver; @@ -26,7 +23,8 @@ use Proxynth\Larawebhook\Processing\Domain\ValueObjects\DeliveryAttempt; use Proxynth\Larawebhook\Processing\Domain\ValueObjects\EventType; use Proxynth\Larawebhook\Processing\Domain\ValueObjects\IdempotencyKey; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Application\Ports\TransactionRunner; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; use Symfony\Component\HttpFoundation\Response; final readonly class ReceiveWebhook @@ -39,7 +37,9 @@ public function __construct( private RetryConfigurationResolver $retryConfigurationResolver, private ProcessedWebhookRecorder $processedWebhookRecorder, private ValidateWebhook $validateWebhook, - private RecordWebhookLog $recordWebhookLog, + private AuditLogRecorder $recordWebhookLog, + private TransactionRunner $transactionRunner, + private ReceiveWebhookEventFactory $eventFactory, ) {} /** @@ -47,7 +47,12 @@ public function __construct( */ public function handle(ReceiveWebhookCommand $command): ReceiveWebhookResult { - $provider = Provider::fromString($command->service->value); + return $this->transactionRunner->run(fn (): ReceiveWebhookResult => $this->handleInTransaction($command)); + } + + private function handleInTransaction(ReceiveWebhookCommand $command): ReceiveWebhookResult + { + $provider = Provider::fromString($command->service->value()); $rawPayload = RawPayload::fromString($command->payload); $decodedPayload = $rawPayload->decoded(); @@ -83,11 +88,7 @@ public function handle(ReceiveWebhookCommand $command): ReceiveWebhookResult eventType: EventType::fromString($event), idempotencyKey: $idempotencyKey, ); - $receivedEvent = new WebhookReceived( - provider: $provider->value(), - event: $event, - externalId: $externalId, - ); + $receivedEvent = $this->eventFactory->received($provider->value(), $event, $externalId); $secret = $this->secretResolver->resolve($command->service); @@ -107,25 +108,12 @@ public function handle(ReceiveWebhookCommand $command): ReceiveWebhookResult if ($validation->isValid()) { $webhookEvent->markValidated(); $webhookEvent->markProcessing(); - $validatedEvent = new WebhookValidated( - provider: $validation->service, - event: $validation->event, - externalId: $validation->externalId, + $validatedEvent = $this->eventFactory->validated( + $validation->service, + $validation->event, + $validation->externalId, ); - $log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand( - service: $validation->service, - event: $validation->event, - valid: $validation->isValid(), - payload: $validation->payload, - attempt: DeliveryAttempt::initial()->value(), - externalId: $externalId, - idempotencyKey: $idempotencyKey?->value(), - errorMessage: $validation->errorMessage, - )); - - $webhookEvent->markProcessed(); - if ($idempotencyKey !== null) { $recordResult = $this->processedWebhookRecorder->recordProcessed( service: $provider->value(), @@ -142,29 +130,37 @@ public function handle(ReceiveWebhookCommand $command): ReceiveWebhookResult } } + $log = $this->recordWebhookLog->record(new RecordWebhookLogCommand( + service: $validation->service, + event: $validation->event, + valid: $validation->isValid(), + payload: $validation->payload, + attempt: DeliveryAttempt::initial()->value(), + externalId: $externalId, + idempotencyKey: $idempotencyKey?->value(), + errorMessage: $validation->errorMessage, + )); + + $webhookEvent->markProcessed(); + return ReceiveWebhookResult::success($log, [ $receivedEvent, $validatedEvent, - new WebhookLogged( - webhookLogId: $log->id, - provider: $log->service, - event: $log->event, - status: $log->status, - ), + $this->eventFactory->logged($log), ]); } $webhookEvent->markFailed( $validation->errorMessage ?? 'Webhook validation failed.' ); - $rejectedEvent = new WebhookRejected( - provider: $validation->service, - event: $validation->event, - externalId: $validation->externalId, - reason: $validation->errorMessage ?? 'Webhook validation failed.', + $rejectedEvent = $this->eventFactory->rejected( + $validation->service, + $validation->event, + $validation->externalId, + $validation->errorMessage ?? 'Webhook validation failed.', ); - $log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand( + $log = $this->recordWebhookLog->record(new RecordWebhookLogCommand( service: $validation->service, event: $validation->event, valid: false, @@ -179,39 +175,28 @@ public function handle(ReceiveWebhookCommand $command): ReceiveWebhookResult return ReceiveWebhookResult::acceptedForRetry( log: $log, event: $event, - secret: $secret, externalId: $externalId, idempotencyKey: $idempotencyKey?->value(), events: [ $receivedEvent, $rejectedEvent, - new WebhookLogged( - webhookLogId: $log->id, - provider: $log->service, - event: $log->event, - status: $log->status, - ), + $this->eventFactory->logged($log), ], ); } return ReceiveWebhookResult::failed( log: $log, - statusCode: $this->failureStatusCode($log->error_message), + statusCode: $this->failureStatusCode($log->errorMessage), events: [ $receivedEvent, $rejectedEvent, - new WebhookLogged( - webhookLogId: $log->id, - provider: $log->service, - event: $log->event, - status: $log->status, - ), + $this->eventFactory->logged($log), ], ); } - private function extractEventType(mixed $decodedPayload, WebhookService $service): string + private function extractEventType(mixed $decodedPayload, WebhookServiceIdentifier $service): string { if (! is_array($decodedPayload)) { return 'unknown'; @@ -224,7 +209,7 @@ private function extractEventType(mixed $decodedPayload, WebhookService $service private function extractExternalId( mixed $decodedPayload, - WebhookService $service, + WebhookServiceIdentifier $service, ?string $externalIdHeaderValue ): ?string { if (! is_array($decodedPayload)) { diff --git a/src/Ingestion/Application/UseCases/ValidateWebhook.php b/src/Ingestion/Application/UseCases/ValidateWebhook.php index 5f88cf9..e51e2bf 100644 --- a/src/Ingestion/Application/UseCases/ValidateWebhook.php +++ b/src/Ingestion/Application/UseCases/ValidateWebhook.php @@ -18,7 +18,7 @@ public function __construct( public function handle(ValidateWebhookCommand $command): ValidateWebhookResult { - $serviceName = $command->service->value; + $serviceName = $command->service->value(); $decodedPayload = $command->payload->decoded(); try { diff --git a/src/Ingestion/Domain/ValueObjects/RawPayload.php b/src/Ingestion/Domain/ValueObjects/RawPayload.php index abb5eb5..d6007d4 100644 --- a/src/Ingestion/Domain/ValueObjects/RawPayload.php +++ b/src/Ingestion/Domain/ValueObjects/RawPayload.php @@ -40,6 +40,13 @@ public function decoded(): array : ['raw' => $this->value]; } + public function isValidJson(): bool + { + json_decode($this->value); + + return json_last_error() === JSON_ERROR_NONE; + } + /** * {@inheritDoc} */ diff --git a/src/Ingestion/Infrastructure/Config/ConfigWebhookSecretResolver.php b/src/Ingestion/Infrastructure/Config/ConfigWebhookSecretResolver.php index d6b4ef6..35c92c0 100644 --- a/src/Ingestion/Infrastructure/Config/ConfigWebhookSecretResolver.php +++ b/src/Ingestion/Infrastructure/Config/ConfigWebhookSecretResolver.php @@ -5,13 +5,13 @@ namespace Proxynth\Larawebhook\Ingestion\Infrastructure\Config; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookSecretResolver; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; final class ConfigWebhookSecretResolver implements WebhookSecretResolver { - public function resolve(WebhookService $service): ?string + public function resolve(WebhookServiceIdentifier $service): ?string { - $secret = config("larawebhook.services.{$service->value}.webhook_secret"); + $secret = config("larawebhook.services.{$service->value()}.webhook_secret"); return is_string($secret) && $secret !== '' ? $secret : null; } diff --git a/src/Ingestion/Infrastructure/Laravel/Middleware/ValidateWebhook.php b/src/Ingestion/Infrastructure/Laravel/Middleware/ValidateWebhook.php index 17836cc..b76a733 100644 --- a/src/Ingestion/Infrastructure/Laravel/Middleware/ValidateWebhook.php +++ b/src/Ingestion/Infrastructure/Laravel/Middleware/ValidateWebhook.php @@ -14,7 +14,8 @@ use Proxynth\Larawebhook\Processing\Application\Ports\RetryPolicyResolver; use Proxynth\Larawebhook\Processing\Infrastructure\Laravel\Jobs\RetryWebhookJob; use Proxynth\Larawebhook\Shared\Application\Ports\EventBus; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\ConfiguredWebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; use Symfony\Component\HttpFoundation\Response; class ValidateWebhook @@ -35,9 +36,9 @@ public function __construct( */ public function handle(Request $request, Closure $next, string $service): Response { - $webhookService = WebhookService::tryFromString($service); + $webhookService = ConfiguredWebhookService::resolve($service); - if ($webhookService === null) { + if (! array_key_exists($service, (array) config('larawebhook.services', []))) { return response() ->json("Service '{$service}' is not supported.", Response::HTTP_BAD_REQUEST); } @@ -110,9 +111,8 @@ public function handle(Request $request, Closure $next, string $service): Respon $this->dispatchRetryJob( payload: $payload, signature: $signature, - service: $webhookService->value, + service: $webhookService->value(), event: $result->event ?? 'unknown', - secret: $result->secret ?? '', externalId: $result->externalId, idempotencyKey: $result->idempotencyKey ); @@ -136,7 +136,7 @@ public function handle(Request $request, Closure $next, string $service): Respon return $next($request); } - private function externalIdHeaderValue(Request $request, WebhookService $webhookService): ?string + private function externalIdHeaderValue(Request $request, WebhookServiceIdentifier $webhookService): ?string { $externalIdHeader = $this->metadataResolver->externalIdHeader($webhookService); @@ -154,7 +154,6 @@ private function dispatchRetryJob( Signature $signature, string $service, string $event, - string $secret, ?string $externalId, ?string $idempotencyKey ): void { @@ -167,7 +166,6 @@ private function dispatchRetryJob( $signature, $service, $event, - $secret, 1, $externalId, $idempotencyKey diff --git a/src/Ingestion/Infrastructure/Parsing/PayloadParserRegistry.php b/src/Ingestion/Infrastructure/Parsing/PayloadParserRegistry.php new file mode 100644 index 0000000..9596b37 --- /dev/null +++ b/src/Ingestion/Infrastructure/Parsing/PayloadParserRegistry.php @@ -0,0 +1,42 @@ + $parsers */ + public function __construct(private array $parsers = []) {} + + public function forService(WebhookServiceIdentifier $service): PayloadParserInterface + { + $parser = $this->parsers[$service->value()] ?? null; + + if ($parser === null) { + throw new WebhookException("No payload parser registered for service: {$service->value()}."); + } + + return $parser; + } + + public function forServiceOrNull(WebhookServiceIdentifier $service): ?PayloadParserInterface + { + return $this->parsers[$service->value()] ?? null; + } + + /** @return array */ + public static function defaults(): array + { + return [ + 'stripe' => new StripePayloadParser, + 'github' => new GithubPayloadParser, + 'slack' => new SlackPayloadParser, + 'shopify' => new ShopifyPayloadParser, + ]; + } +} diff --git a/src/Ingestion/Infrastructure/Parsing/ProviderPayloadParserResolver.php b/src/Ingestion/Infrastructure/Parsing/ProviderPayloadParserResolver.php index 8bdc119..a86382e 100644 --- a/src/Ingestion/Infrastructure/Parsing/ProviderPayloadParserResolver.php +++ b/src/Ingestion/Infrastructure/Parsing/ProviderPayloadParserResolver.php @@ -6,17 +6,22 @@ use Proxynth\Larawebhook\Contracts\PayloadParserInterface; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookPayloadParserResolver; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; final readonly class ProviderPayloadParserResolver implements WebhookPayloadParserResolver { - public function forService(WebhookService $service): PayloadParserInterface + public function __construct( + private PayloadParserRegistry $registry = new PayloadParserRegistry([]), + ) {} + + public function forService(WebhookServiceIdentifier $service): PayloadParserInterface { - return match ($service) { - WebhookService::Stripe => new StripePayloadParser, - WebhookService::Github => new GithubPayloadParser, - WebhookService::Slack => new SlackPayloadParser, - WebhookService::Shopify => new ShopifyPayloadParser, - }; + $registry = $this->registry; + + if ($registry->forServiceOrNull($service) === null) { + $registry = new PayloadParserRegistry(PayloadParserRegistry::defaults()); + } + + return $registry->forService($service); } } diff --git a/src/Ingestion/Infrastructure/Support/LaravelWebhookServiceMetadataResolver.php b/src/Ingestion/Infrastructure/Support/LaravelWebhookServiceMetadataResolver.php index bf81186..da168d4 100644 --- a/src/Ingestion/Infrastructure/Support/LaravelWebhookServiceMetadataResolver.php +++ b/src/Ingestion/Infrastructure/Support/LaravelWebhookServiceMetadataResolver.php @@ -6,33 +6,46 @@ use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookServiceMetadataResolver; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; final class LaravelWebhookServiceMetadataResolver implements WebhookServiceMetadataResolver { - public function signatureHeader(WebhookService $service): string + public function signatureHeader(WebhookServiceIdentifier $service): string { - return match ($service) { - WebhookService::Stripe => 'Stripe-Signature', - WebhookService::Github => 'X-Hub-Signature-256', - WebhookService::Slack => 'X-Slack-Signature', - WebhookService::Shopify => 'X-Shopify-Hmac-Sha256', - }; + if ($service instanceof WebhookService) { + return match ($service) { + WebhookService::Stripe => 'Stripe-Signature', + WebhookService::Github => 'X-Hub-Signature-256', + WebhookService::Slack => 'X-Slack-Signature', + WebhookService::Shopify => 'X-Shopify-Hmac-Sha256', + }; + } + + return (string) config("larawebhook.services.{$service->value()}.signature_header", 'X-Webhook-Signature'); } - public function timestampHeader(WebhookService $service): ?string + public function timestampHeader(WebhookServiceIdentifier $service): ?string { - return match ($service) { - WebhookService::Slack => 'X-Slack-Request-Timestamp', - default => null, - }; + if ($service instanceof WebhookService) { + return match ($service) { + WebhookService::Slack => 'X-Slack-Request-Timestamp', + default => null, + }; + } + + return config("larawebhook.services.{$service->value()}.timestamp_header"); } - public function externalIdHeader(WebhookService $service): ?string + public function externalIdHeader(WebhookServiceIdentifier $service): ?string { - return match ($service) { - WebhookService::Github => 'X-GitHub-Delivery', - WebhookService::Shopify => 'X-Shopify-Webhook-Id', - default => null, - }; + if ($service instanceof WebhookService) { + return match ($service) { + WebhookService::Github => 'X-GitHub-Delivery', + WebhookService::Shopify => 'X-Shopify-Webhook-Id', + default => null, + }; + } + + return config("larawebhook.services.{$service->value()}.external_id_header"); } } diff --git a/src/Ingestion/Infrastructure/Validation/ProviderSignatureValidator.php b/src/Ingestion/Infrastructure/Validation/ProviderSignatureValidator.php index 383a90a..9434a23 100644 --- a/src/Ingestion/Infrastructure/Validation/ProviderSignatureValidator.php +++ b/src/Ingestion/Infrastructure/Validation/ProviderSignatureValidator.php @@ -7,7 +7,7 @@ use Proxynth\Larawebhook\Ingestion\Application\Ports\SignatureValidator; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; final readonly class ProviderSignatureValidator implements SignatureValidator { @@ -16,7 +16,7 @@ public function __construct( ) {} public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, diff --git a/src/Ingestion/Infrastructure/Validation/SignatureValidatorRegistry.php b/src/Ingestion/Infrastructure/Validation/SignatureValidatorRegistry.php new file mode 100644 index 0000000..88f6a6a --- /dev/null +++ b/src/Ingestion/Infrastructure/Validation/SignatureValidatorRegistry.php @@ -0,0 +1,37 @@ + $validators */ + public function __construct(private array $validators = []) {} + + public function forService(WebhookServiceIdentifier $service): SignatureValidatorInterface + { + $validator = $this->validators[$service->value()] ?? null; + + if ($validator === null) { + throw new WebhookException("No signature validator registered for service: {$service->value()}."); + } + + return $validator; + } + + /** @return array */ + public static function defaults(): array + { + return [ + 'stripe' => new StripeSignatureValidator, + 'github' => new GithubSignatureValidator, + 'slack' => new SlackSignatureValidator, + 'shopify' => new ShopifySignatureValidator, + ]; + } +} diff --git a/src/Ingestion/Infrastructure/Validation/WebhookValidator.php b/src/Ingestion/Infrastructure/Validation/WebhookValidator.php index f620c1a..03a56ee 100644 --- a/src/Ingestion/Infrastructure/Validation/WebhookValidator.php +++ b/src/Ingestion/Infrastructure/Validation/WebhookValidator.php @@ -7,13 +7,15 @@ use Proxynth\Larawebhook\Exceptions\InvalidSignatureException; use Proxynth\Larawebhook\Exceptions\WebhookException; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\ConfiguredWebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; class WebhookValidator { public function __construct( private readonly string $secret, private readonly int $tolerance = 300, + private readonly ?SignatureValidatorRegistry $registry = null, ) {} /** @@ -21,46 +23,26 @@ public function __construct( * * @param string $payload Raw webhook content * @param Signature $signature Signature provided by the service - * @param string|WebhookService $service Service name or enum + * @param string|WebhookServiceIdentifier $service Service name or identifier * * @throws InvalidSignatureException * @throws WebhookException */ - public function validate(string $payload, Signature $signature, string|WebhookService $service): bool + public function validate(string $payload, Signature $signature, string|WebhookServiceIdentifier $service): bool { - $webhookService = $service instanceof WebhookService - ? $service - : WebhookService::tryFromString($service); - - if ($webhookService === null) { + if (is_string($service) && ! array_key_exists($service, (array) config('larawebhook.services', []))) { throw new WebhookException("Unsupported service: {$service}"); } - return match ($webhookService) { - WebhookService::Stripe => (new StripeSignatureValidator)->validate( - $payload, - $signature, - $this->secret, - $this->tolerance - ), - WebhookService::Github => (new GithubSignatureValidator)->validate( - $payload, - $signature, - $this->secret, - $this->tolerance - ), - WebhookService::Slack => (new SlackSignatureValidator)->validate( - $payload, - $signature, - $this->secret, - $this->tolerance - ), - WebhookService::Shopify => (new ShopifySignatureValidator)->validate( - $payload, - $signature, - $this->secret, - $this->tolerance - ), - }; + $webhookService = is_string($service) ? ConfiguredWebhookService::resolve($service) : $service; + + $registry = $this->registry ?? new SignatureValidatorRegistry(SignatureValidatorRegistry::defaults()); + + return $registry->forService($webhookService)->validate( + $payload, + $signature, + $this->secret, + $this->tolerance, + ); } } diff --git a/src/Ingestion/Infrastructure/Validation/WebhookValidatorFactory.php b/src/Ingestion/Infrastructure/Validation/WebhookValidatorFactory.php index edda74b..2e85dc6 100644 --- a/src/Ingestion/Infrastructure/Validation/WebhookValidatorFactory.php +++ b/src/Ingestion/Infrastructure/Validation/WebhookValidatorFactory.php @@ -6,6 +6,8 @@ use Proxynth\Larawebhook\Exceptions\WebhookException; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookSecretResolver; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\ConfiguredWebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; class WebhookValidatorFactory { @@ -16,46 +18,52 @@ class WebhookValidatorFactory public function __construct( private readonly WebhookSecretResolver $secretResolver, + private readonly ?SignatureValidatorRegistry $signatureValidatorRegistry = null, ) {} /** * @throws WebhookException */ - public function forService(string|WebhookService $service, ?string $secret = null): WebhookValidator + public function forService(string|WebhookServiceIdentifier $service, ?string $secret = null): WebhookValidator { $service = $this->resolveService($service); $resolvedSecret = $secret ?? $this->secretResolver->resolve($service); if ($resolvedSecret === null || $resolvedSecret === '') { - throw new WebhookException("No secret configured for service: {$service->value}"); + throw new WebhookException("No secret configured for service: {$service->value()}."); } if ($secret !== null) { return new WebhookValidator( secret: $resolvedSecret, - tolerance: $this->toleranceForService($service->value), + tolerance: $this->toleranceForService($service->value()), + registry: $this->signatureValidatorRegistry, ); } - if (! isset($this->validators[$service->value])) { - $this->validators[$service->value] = new WebhookValidator( + if (! isset($this->validators[$service->value()])) { + $this->validators[$service->value()] = new WebhookValidator( secret: $resolvedSecret, - tolerance: $this->toleranceForService($service->value), + tolerance: $this->toleranceForService($service->value()), + registry: $this->signatureValidatorRegistry, ); } - return $this->validators[$service->value]; + return $this->validators[$service->value()]; } - private function resolveService(string|WebhookService $service): WebhookService + private function resolveService(string|WebhookServiceIdentifier $service): WebhookServiceIdentifier { if (is_string($service)) { - if (! WebhookService::isSupported($service)) { - throw new WebhookException("Webhook service '$service' is not supported"); + $configured = config("larawebhook.services.{$service}"); + + if (! WebhookService::isSupported($service) + && (! is_array($configured) || empty($configured['webhook_secret']))) { + throw new WebhookException("Webhook service '{$service}' is not supported"); } - return WebhookService::fromString($service); + return ConfiguredWebhookService::resolve($service); } return $service; diff --git a/src/Larawebhook.php b/src/Larawebhook.php index a091dbd..9ddc1c1 100644 --- a/src/Larawebhook.php +++ b/src/Larawebhook.php @@ -4,6 +4,6 @@ namespace Proxynth\Larawebhook; -use Proxynth\Larawebhook\Shared\Application\Larawebhook as BaseLarawebhook; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Larawebhook as BaseLarawebhook; class Larawebhook extends BaseLarawebhook {} diff --git a/src/Processing/Application/Commands/RetryWebhookCommand.php b/src/Processing/Application/Commands/RetryWebhookCommand.php index e4335fc..0f8aabc 100644 --- a/src/Processing/Application/Commands/RetryWebhookCommand.php +++ b/src/Processing/Application/Commands/RetryWebhookCommand.php @@ -14,7 +14,6 @@ public function __construct( public Signature $signature, public string $service, public string $event, - public string $secret, public int $attempt = 0, public ?string $externalId = null, public ?string $idempotencyKey = null, diff --git a/src/Processing/Application/Data/ReplayableWebhook.php b/src/Processing/Application/Data/ReplayableWebhook.php index 57b0159..74aec76 100644 --- a/src/Processing/Application/Data/ReplayableWebhook.php +++ b/src/Processing/Application/Data/ReplayableWebhook.php @@ -9,7 +9,8 @@ use Proxynth\Larawebhook\Processing\Domain\ValueObjects\EventType; use Proxynth\Larawebhook\Processing\Domain\ValueObjects\IdempotencyKey; use Proxynth\Larawebhook\Processing\Domain\ValueObjects\WebhookStatus; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\ConfiguredWebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; final readonly class ReplayableWebhook { @@ -34,8 +35,8 @@ public function toWebhookEvent(): WebhookEvent ); } - public function service(): WebhookService + public function service(): WebhookServiceIdentifier { - return WebhookService::fromString($this->service); + return ConfiguredWebhookService::resolve($this->service); } } diff --git a/src/Processing/Application/Ports/AuditLogRecorder.php b/src/Processing/Application/Ports/AuditLogRecorder.php new file mode 100644 index 0000000..111595f --- /dev/null +++ b/src/Processing/Application/Ports/AuditLogRecorder.php @@ -0,0 +1,9 @@ +id, + service: $log->service, + event: $log->event, + status: $log->status, + attempt: $log->attempt, + externalId: $log->externalId, + idempotencyKey: $log->idempotencyKey, + createdAt: $log->createdAt, + ), + $errorMessage, + $events, + ); + } } diff --git a/src/Processing/Application/Results/RetryWebhookResult.php b/src/Processing/Application/Results/RetryWebhookResult.php index 1e965c0..c931cbc 100644 --- a/src/Processing/Application/Results/RetryWebhookResult.php +++ b/src/Processing/Application/Results/RetryWebhookResult.php @@ -4,7 +4,7 @@ namespace Proxynth\Larawebhook\Processing\Application\Results; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Shared\Application\Results\Result; use Proxynth\Larawebhook\Shared\Domain\Events\DomainEvent; @@ -13,7 +13,7 @@ private function __construct( public bool $success, public bool $shouldRetry, - public WebhookLog $log, + public WebhookLogData $log, public int $attempt, public ?int $nextAttempt = null, public ?int $delaySeconds = null, @@ -21,7 +21,7 @@ private function __construct( public array $events = [], ) {} - public static function success(WebhookLog $log, array $events = []): self + public static function success(WebhookLogData $log, array $events = []): self { return new self( success: true, @@ -33,7 +33,7 @@ public static function success(WebhookLog $log, array $events = []): self } public static function failed( - WebhookLog $log, + WebhookLogData $log, bool $shouldRetry, ?int $nextAttempt = null, ?int $delaySeconds = null, diff --git a/src/Processing/Application/UseCases/ReplayWebhook.php b/src/Processing/Application/UseCases/ReplayWebhook.php index 48c874f..d24fe13 100644 --- a/src/Processing/Application/UseCases/ReplayWebhook.php +++ b/src/Processing/Application/UseCases/ReplayWebhook.php @@ -5,8 +5,6 @@ namespace Proxynth\Larawebhook\Processing\Application\UseCases; use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; -use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookLogSummary; -use Proxynth\Larawebhook\Audit\Application\UseCases\RecordWebhookLog; use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged; use Proxynth\Larawebhook\Audit\Domain\Exceptions\PayloadNotAvailable; use Proxynth\Larawebhook\Exceptions\WebhookException; @@ -16,18 +14,20 @@ use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload; use Proxynth\Larawebhook\Processing\Application\Commands\ReplayWebhookCommand; use Proxynth\Larawebhook\Processing\Application\Exceptions\ReplayWebhookNotAllowed; +use Proxynth\Larawebhook\Processing\Application\Ports\AuditLogRecorder; use Proxynth\Larawebhook\Processing\Application\Ports\ReplayableWebhookRepository; use Proxynth\Larawebhook\Processing\Application\Results\ReplayWebhookResult; use Proxynth\Larawebhook\Processing\Domain\Events\WebhookReplayed; use Proxynth\Larawebhook\Processing\Domain\Exceptions\InvalidWebhookState; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\ConfiguredWebhookService; final readonly class ReplayWebhook { public function __construct( private ReplayableWebhookRepository $replayableWebhookRepository, private ValidateWebhook $validateWebhook, - private RecordWebhookLog $recordWebhookLog, + private AuditLogRecorder $recordWebhookLog, private WebhookSecretResolver $secretResolver, ) {} @@ -53,11 +53,15 @@ public function handle(ReplayWebhookCommand $command): ReplayWebhookResult ); } - $webhookService = WebhookService::fromString($replayableWebhook->service); + $webhookService = ConfiguredWebhookService::resolve($replayableWebhook->service); $secret = $this->secretResolver->resolve($webhookService); if ($secret === null) { - throw new WebhookException("No secret configured for service: {$webhookService->value}"); + if (! $webhookService instanceof WebhookService) { + throw new WebhookException("Webhook service '{$replayableWebhook->service}' is not supported."); + } + + throw new WebhookException("No secret configured for service: {$webhookService->value()}."); } $validation = $this->validateWebhook->handle(new ValidateWebhookCommand( @@ -69,7 +73,7 @@ public function handle(ReplayWebhookCommand $command): ReplayWebhookResult secret: $secret, )); - $log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand( + $log = $this->recordWebhookLog->record(new RecordWebhookLogCommand( service: $validation->service, event: $validation->event, valid: $validation->isValid(), @@ -80,8 +84,8 @@ public function handle(ReplayWebhookCommand $command): ReplayWebhookResult errorMessage: $validation->errorMessage, )); - return ReplayWebhookResult::fromSummary( - WebhookLogSummary::fromModel($log), + return ReplayWebhookResult::fromData( + $log, $validation->errorMessage, [ new WebhookReplayed( diff --git a/src/Processing/Application/UseCases/RetryWebhook.php b/src/Processing/Application/UseCases/RetryWebhook.php index 9dc30d6..e9235f2 100644 --- a/src/Processing/Application/UseCases/RetryWebhook.php +++ b/src/Processing/Application/UseCases/RetryWebhook.php @@ -5,16 +5,17 @@ namespace Proxynth\Larawebhook\Processing\Application\UseCases; use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; -use Proxynth\Larawebhook\Audit\Application\UseCases\RecordWebhookLog; use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged; use Proxynth\Larawebhook\Exceptions\WebhookException; use Proxynth\Larawebhook\Ingestion\Application\Commands\ValidateWebhookCommand; +use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookSecretResolver; 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\AuditLogRecorder; use Proxynth\Larawebhook\Processing\Application\Ports\RetryPolicyResolver; use Proxynth\Larawebhook\Processing\Application\Results\RetryWebhookResult; use Proxynth\Larawebhook\Processing\Domain\Entities\WebhookEvent; @@ -22,13 +23,15 @@ use Proxynth\Larawebhook\Processing\Domain\ValueObjects\EventType; use Proxynth\Larawebhook\Processing\Domain\ValueObjects\IdempotencyKey; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\ConfiguredWebhookService; final readonly class RetryWebhook { public function __construct( private ValidateWebhook $validateWebhook, - private RecordWebhookLog $recordWebhookLog, + private AuditLogRecorder $recordWebhookLog, private RetryPolicyResolver $retryPolicyResolver, + private WebhookSecretResolver $secretResolver, ) {} /** @@ -36,14 +39,19 @@ public function __construct( */ public function handle(RetryWebhookCommand $command): RetryWebhookResult { - $webhookService = WebhookService::tryFromString($command->service); - - if ($webhookService === null) { - throw new WebhookException("Webhook service '{$command->service}' is not supported."); - } + $webhookService = ConfiguredWebhookService::resolve($command->service); $rawPayload = RawPayload::fromString($command->payload); $retryPolicy = $this->retryPolicyResolver->resolve(); + $secret = $this->secretResolver->resolve($webhookService); + + if ($secret === null) { + if (! $webhookService instanceof WebhookService) { + throw new WebhookException("Webhook service '{$command->service}' is not supported."); + } + + throw new WebhookException("No secret configured for service: {$webhookService->value()}."); + } $validation = $this->validateWebhook->handle(new ValidateWebhookCommand( service: $webhookService, @@ -51,7 +59,7 @@ public function handle(RetryWebhookCommand $command): RetryWebhookResult signature: $command->signature, event: $command->event, externalId: $command->externalId, - secret: $command->secret, + secret: $secret, )); $webhookEvent = $this->createWebhookEvent( @@ -60,17 +68,6 @@ public function handle(RetryWebhookCommand $command): RetryWebhookResult idempotencyKey: $command->idempotencyKey, ); - $this->recordWebhookLog->handle(new RecordWebhookLogCommand( - service: $validation->service, - event: $validation->event, - valid: $validation->isValid(), - payload: $validation->payload, - attempt: $command->attempt, - externalId: null, - idempotencyKey: null, - errorMessage: $validation->errorMessage, - )); - if ($validation->isValid()) { return $this->handleValidRetry( command: $command, @@ -107,7 +104,7 @@ private function handleValidRetry( $webhookEvent->markValidated(); $webhookEvent->markProcessing(); - $log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand( + $log = $this->recordWebhookLog->record(new RecordWebhookLogCommand( service: $validation->service, event: $validation->event, valid: true, @@ -143,7 +140,7 @@ private function handleFailedRetry( $webhookEvent->markFailed($reason); - $log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand( + $log = $this->recordWebhookLog->record(new RecordWebhookLogCommand( service: $validation->service, event: $validation->event, valid: false, diff --git a/src/Processing/Infrastructure/Laravel/Jobs/RetryWebhookJob.php b/src/Processing/Infrastructure/Laravel/Jobs/RetryWebhookJob.php index d969b47..bff6474 100644 --- a/src/Processing/Infrastructure/Laravel/Jobs/RetryWebhookJob.php +++ b/src/Processing/Infrastructure/Laravel/Jobs/RetryWebhookJob.php @@ -5,6 +5,7 @@ namespace Proxynth\Larawebhook\Processing\Infrastructure\Laravel\Jobs; use Illuminate\Bus\Queueable; +use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; @@ -15,7 +16,7 @@ use Proxynth\Larawebhook\Processing\Application\UseCases\RetryWebhook; use Proxynth\Larawebhook\Shared\Application\Ports\EventBus; -class RetryWebhookJob implements ShouldQueue +class RetryWebhookJob implements ShouldBeUnique, ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; @@ -32,7 +33,6 @@ public function __construct( private readonly Signature $signature, private readonly string $service, private readonly string $event, - private readonly string $secret, private readonly int $attempt = 0, private readonly ?string $externalId = null, private readonly ?string $idempotencyKey = null, @@ -43,14 +43,15 @@ public function __construct( * * @throws WebhookException */ - public function handle(RetryWebhook $retryWebhook, EventBus $eventBus): void - { + public function handle( + RetryWebhook $retryWebhook, + EventBus $eventBus, + ): void { $result = $retryWebhook->handle(new RetryWebhookCommand( payload: $this->payload, signature: $this->signature, service: $this->service, event: $this->event, - secret: $this->secret, attempt: $this->attempt, externalId: $this->externalId, idempotencyKey: $this->idempotencyKey, @@ -67,7 +68,6 @@ public function handle(RetryWebhook $retryWebhook, EventBus $eventBus): void signature: $this->signature, service: $this->service, event: $this->event, - secret: $this->secret, attempt: $result->nextAttempt ?? $this->attempt + 1, externalId: $this->externalId, idempotencyKey: $this->idempotencyKey, diff --git a/src/Shared/Application/Ports/Delay.php b/src/Shared/Application/Ports/Delay.php new file mode 100644 index 0000000..53cf56b --- /dev/null +++ b/src/Shared/Application/Ports/Delay.php @@ -0,0 +1,10 @@ +value; + } + /** * Check if a service is supported. */ diff --git a/src/Shared/Domain/ValueObjects/ConfiguredWebhookService.php b/src/Shared/Domain/ValueObjects/ConfiguredWebhookService.php new file mode 100644 index 0000000..d7c9c28 --- /dev/null +++ b/src/Shared/Domain/ValueObjects/ConfiguredWebhookService.php @@ -0,0 +1,34 @@ +value; + } +} diff --git a/src/Shared/Domain/ValueObjects/WebhookServiceIdentifier.php b/src/Shared/Domain/ValueObjects/WebhookServiceIdentifier.php new file mode 100644 index 0000000..32c8a9a --- /dev/null +++ b/src/Shared/Domain/ValueObjects/WebhookServiceIdentifier.php @@ -0,0 +1,12 @@ + getNotificationChannels() * @method static void clearCooldown(string $service, string $event) - * @method static ?string getSecret(string|WebhookService $service) + * @method static ?string getSecret(string|WebhookServiceIdentifier $service) * @method static bool isServiceSupported(string $service) * @method static array supportedServices() * @method static array services() - * @method static ?WebhookService service(string $service) + * @method static ?WebhookServiceIdentifier service(string $service) * - * @see \Proxynth\Larawebhook\Shared\Application\Larawebhook + * @see \Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Larawebhook */ class Larawebhook extends Facade { protected static function getFacadeAccessor(): string { - return \Proxynth\Larawebhook\Shared\Application\Larawebhook::class; + return \Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Larawebhook::class; } } diff --git a/src/Shared/Application/Larawebhook.php b/src/Shared/Infrastructure/Laravel/Larawebhook.php similarity index 74% rename from src/Shared/Application/Larawebhook.php rename to src/Shared/Infrastructure/Laravel/Larawebhook.php index 345ee4f..20ba04c 100644 --- a/src/Shared/Application/Larawebhook.php +++ b/src/Shared/Infrastructure/Laravel/Larawebhook.php @@ -2,13 +2,12 @@ declare(strict_types=1); -namespace Proxynth\Larawebhook\Shared\Application; +namespace Proxynth\Larawebhook\Shared\Infrastructure\Laravel; use Illuminate\Database\Eloquent\Collection; use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Audit\Application\UseCases\RecordWebhookLog; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Notifications\FailureDetector; -use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Notifications\NotificationSender; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; use Proxynth\Larawebhook\Exceptions\InvalidSignatureException; use Proxynth\Larawebhook\Exceptions\WebhookException; @@ -20,7 +19,12 @@ use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; use Proxynth\Larawebhook\Processing\Application\Ports\RetryPolicyResolver; use Proxynth\Larawebhook\Processing\Domain\ValueObjects\DeliveryAttempt; +use Proxynth\Larawebhook\Shared\Application\Ports\Delay; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\ConfiguredWebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Notifications\WebhookNotificationGateway; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Queries\WebhookLogQueries; /** * Laravel-friendly public API for LaraWebhook. @@ -34,6 +38,8 @@ */ class Larawebhook { + public function __construct(private readonly ?Delay $delay = null) {} + private ?ValidateWebhook $validateWebhook = null; private ?RecordWebhookLog $recordWebhookLog = null; @@ -42,9 +48,9 @@ class Larawebhook private ?WebhookPayloadParserResolver $payloadParserResolver = null; - private ?NotificationSender $notificationSender = null; + private ?WebhookNotificationGateway $notificationGateway = null; - private ?FailureDetector $failureDetector = null; + private ?WebhookLogQueries $logQueries = null; private ?RetryPolicyResolver $retryPolicyResolver = null; @@ -54,7 +60,7 @@ class Larawebhook * @throws InvalidSignatureException * @throws WebhookException */ - public function validate(string $payload, Signature $signature, string|WebhookService $service): bool + public function validate(string $payload, Signature $signature, string|WebhookServiceIdentifier $service): bool { $webhookService = $this->resolveService($service); $rawPayload = RawPayload::fromString($payload); @@ -62,7 +68,7 @@ public function validate(string $payload, Signature $signature, string|WebhookSe $secret = $this->getSecret($webhookService); if ($secret === null || $secret === '') { - throw new WebhookException("No secret configured for service: {$webhookService->value}"); + throw new WebhookException("No secret configured for service: {$webhookService->value()}."); } $result = $this->getValidateWebhook()->handle(new ValidateWebhookCommand( @@ -89,7 +95,7 @@ public function validate(string $payload, Signature $signature, string|WebhookSe public function validateAndLog( string $payload, Signature $signature, - string|WebhookService $service, + string|WebhookServiceIdentifier $service, string $event ): WebhookLog { return $this->validateAndRecord( @@ -113,7 +119,7 @@ public function validateAndLog( public function validateWithRetries( string $payload, Signature $signature, - string|WebhookService $service, + string|WebhookServiceIdentifier $service, string $event ): WebhookLog { $webhookService = $this->resolveService($service); @@ -145,9 +151,7 @@ public function validateWithRetries( if ($retryPolicy->shouldRetryAfter($attempt)) { $delay = $retryPolicy->delayForAttempt($attempt) ?? 0; - if ($delay > 0) { - sleep($delay); - } + $this->delay()->seconds($delay); } } @@ -168,7 +172,7 @@ public function logSuccess( int $attempt = 0, ?string $idempotencyKey = null ): WebhookLog { - return $this->getRecordWebhookLog()->handle(new RecordWebhookLogCommand( + $recorded = $this->getRecordWebhookLog()->handle(new RecordWebhookLogCommand( service: $service, event: $event, valid: true, @@ -178,6 +182,8 @@ public function logSuccess( idempotencyKey: $idempotencyKey, errorMessage: null, )); + + return $this->toWebhookLog($recorded); } /** @@ -193,7 +199,7 @@ public function logFailure( int $attempt = 0, ?string $idempotencyKey = null ): WebhookLog { - return $this->getRecordWebhookLog()->handle(new RecordWebhookLogCommand( + $recorded = $this->getRecordWebhookLog()->handle(new RecordWebhookLogCommand( service: $service, event: $event, valid: false, @@ -203,6 +209,8 @@ public function logFailure( idempotencyKey: $idempotencyKey, errorMessage: $errorMessage, )); + + return $this->toWebhookLog($recorded); } /** @@ -212,7 +220,7 @@ public function logFailure( */ public function logs(): Collection { - return WebhookLog::latest()->get(); + return $this->getLogQueries()->all(); } /** @@ -222,11 +230,11 @@ public function logs(): Collection * * @throws WebhookException */ - public function logsForService(string|WebhookService $service): Collection + public function logsForService(string|WebhookServiceIdentifier $service): Collection { $service = $this->resolveService($service); - return WebhookLog::service($service->value)->latest()->get(); + return $this->getLogQueries()->forService($service->value()); } /** @@ -236,7 +244,7 @@ public function logsForService(string|WebhookService $service): Collection */ public function failedLogs(): Collection { - return WebhookLog::failed()->latest()->get(); + return $this->getLogQueries()->failed(); } /** @@ -246,7 +254,7 @@ public function failedLogs(): Collection */ public function successfulLogs(): Collection { - return WebhookLog::successful()->latest()->get(); + return $this->getLogQueries()->successful(); } /** @@ -254,7 +262,7 @@ public function successfulLogs(): Collection */ public function getFailureCount(string $service, string $event): int { - return $this->getFailureDetector()->countRecentFailures($service, $event); + return $this->getNotificationGateway()->failureCount($service, $event); } /** @@ -262,7 +270,7 @@ public function getFailureCount(string $service, string $event): int */ public function canSendNotification(string $service, string $event): bool { - return $this->getFailureDetector()->canSendNotification($service, $event); + return $this->getNotificationGateway()->canSend($service, $event); } /** @@ -270,7 +278,7 @@ public function canSendNotification(string $service, string $event): bool */ public function sendNotificationIfNeeded(string $service, string $event): bool { - return $this->getNotificationSender()->sendIfNeeded($service, $event); + return $this->getNotificationGateway()->sendIfNeeded($service, $event); } /** @@ -278,7 +286,7 @@ public function sendNotificationIfNeeded(string $service, string $event): bool */ public function notificationsEnabled(): bool { - return $this->getNotificationSender()->isEnabled(); + return $this->getNotificationGateway()->enabled(); } /** @@ -288,7 +296,7 @@ public function notificationsEnabled(): bool */ public function getNotificationChannels(): array { - return $this->getNotificationSender()->getChannels(); + return $this->getNotificationGateway()->channels(); } /** @@ -296,21 +304,15 @@ public function getNotificationChannels(): array */ public function clearCooldown(string $service, string $event): void { - $this->getFailureDetector()->clearCooldown($service, $event); + $this->getNotificationGateway()->clearCooldown($service, $event); } /** * Get the secret for a service from config. */ - public function getSecret(string|WebhookService $service): ?string + public function getSecret(string|WebhookServiceIdentifier $service): ?string { - $webhookService = $service instanceof WebhookService - ? $service - : WebhookService::tryFromString($service); - - if ($webhookService === null) { - return null; - } + $webhookService = is_string($service) ? ConfiguredWebhookService::resolve($service) : $service; return $this->getSecretResolver()->resolve($webhookService); } @@ -320,7 +322,7 @@ public function getSecret(string|WebhookService $service): ?string */ public function isServiceSupported(string $service): bool { - return WebhookService::isSupported($service); + return array_key_exists($service, (array) config('larawebhook.services', [])); } /** @@ -330,7 +332,7 @@ public function isServiceSupported(string $service): bool */ public function supportedServices(): array { - return WebhookService::values(); + return array_keys((array) config('larawebhook.services', [])); } /** @@ -346,9 +348,13 @@ public function services(): array /** * Get a service enum from string. */ - public function service(string $service): ?WebhookService + public function service(string $service): ?WebhookServiceIdentifier { - return WebhookService::tryFromString($service); + if (! $this->isServiceSupported($service)) { + return null; + } + + return ConfiguredWebhookService::resolve($service); } /** @@ -356,41 +362,40 @@ public function service(string $service): ?WebhookService * * @throws WebhookException */ - private function resolveService(string|WebhookService $service): WebhookService + private function resolveService(string|WebhookServiceIdentifier $service): WebhookServiceIdentifier { if ($service instanceof WebhookService) { return $service; } - if (! WebhookService::isSupported($service)) { + if (! $this->isServiceSupported($service)) { throw new WebhookException("Webhook service '{$service}' is not supported"); } - return WebhookService::fromString($service); + return ConfiguredWebhookService::resolve($service); } - /** - * Get the notification sender instance. - */ - private function getNotificationSender(): NotificationSender + private function getNotificationGateway(): WebhookNotificationGateway { - if ($this->notificationSender === null) { - $this->notificationSender = app(NotificationSender::class); + if ($this->notificationGateway === null) { + $this->notificationGateway = app(WebhookNotificationGateway::class); } - return $this->notificationSender; + return $this->notificationGateway; } - /** - * Get the failure detector instance. - */ - private function getFailureDetector(): FailureDetector + private function delay(): Delay + { + return $this->delay ?? app(Delay::class); + } + + private function getLogQueries(): WebhookLogQueries { - if ($this->failureDetector === null) { - $this->failureDetector = app(FailureDetector::class); + if ($this->logQueries === null) { + $this->logQueries = app(WebhookLogQueries::class); } - return $this->failureDetector; + return $this->logQueries; } private function getValidateWebhook(): ValidateWebhook @@ -438,14 +443,14 @@ private function getPayloadParserResolver(): WebhookPayloadParserResolver return $this->payloadParserResolver; } - private function extractEvent(WebhookService $service, RawPayload $payload): string + private function extractEvent(WebhookServiceIdentifier $service, RawPayload $payload): string { return $this->getPayloadParserResolver() ->forService($service) ->extractEventType($payload->decoded()); } - private function extractExternalId(WebhookService $service, RawPayload $payload): ?string + private function extractExternalId(WebhookServiceIdentifier $service, RawPayload $payload): ?string { return $this->getPayloadParserResolver() ->forService($service) @@ -458,7 +463,7 @@ private function extractExternalId(WebhookService $service, RawPayload $payload) private function validateAndRecord( string $payload, Signature $signature, - string|WebhookService $service, + string|WebhookServiceIdentifier $service, string $event, int $attempt, ?string $externalId = null, @@ -468,7 +473,7 @@ private function validateAndRecord( $secret = $this->getSecret($webhookService); if ($secret === null || $secret === '') { - throw new WebhookException("No secret configured for service: {$webhookService->value}"); + throw new WebhookException("No secret configured for service: {$webhookService->value()}."); } $resolvedExternalId = $externalId ?? $this->extractExternalId($webhookService, $rawPayload); @@ -482,7 +487,7 @@ private function validateAndRecord( secret: $secret, )); - return $this->getRecordWebhookLog()->handle(new RecordWebhookLogCommand( + $recorded = $this->getRecordWebhookLog()->handle(new RecordWebhookLogCommand( service: $validation->service, event: $validation->event, valid: $validation->isValid(), @@ -491,5 +496,27 @@ private function validateAndRecord( externalId: $validation->externalId, errorMessage: $validation->errorMessage, )); + + return $this->toWebhookLog($recorded); + } + + private function toWebhookLog(WebhookLogData $data): WebhookLog + { + $log = WebhookLog::find($data->id); + + if ($log !== null) { + return $log; + } + + return new WebhookLog([ + 'service' => $data->service, + 'event' => $data->event, + 'status' => $data->status, + 'payload' => $data->payload, + 'error_message' => $data->errorMessage, + 'attempt' => $data->attempt, + 'external_id' => $data->externalId, + 'idempotency_key' => $data->idempotencyKey, + ]); } } diff --git a/src/Shared/Infrastructure/Laravel/Notifications/WebhookNotificationGateway.php b/src/Shared/Infrastructure/Laravel/Notifications/WebhookNotificationGateway.php new file mode 100644 index 0000000..b05b077 --- /dev/null +++ b/src/Shared/Infrastructure/Laravel/Notifications/WebhookNotificationGateway.php @@ -0,0 +1,47 @@ +failureDetector->countRecentFailures($service, $event); + } + + public function canSend(string $service, string $event): bool + { + return $this->failureDetector->canSendNotification($service, $event); + } + + public function sendIfNeeded(string $service, string $event): bool + { + return $this->notificationSender->sendIfNeeded($service, $event); + } + + public function enabled(): bool + { + return $this->notificationSender->isEnabled(); + } + + /** @return array */ + public function channels(): array + { + return $this->notificationSender->getChannels(); + } + + public function clearCooldown(string $service, string $event): void + { + $this->failureDetector->clearCooldown($service, $event); + } +} diff --git a/src/Shared/Infrastructure/Laravel/Providers/LarawebhookServiceProvider.php b/src/Shared/Infrastructure/Laravel/Providers/LarawebhookServiceProvider.php index 5fff0d7..8b2b290 100644 --- a/src/Shared/Infrastructure/Laravel/Providers/LarawebhookServiceProvider.php +++ b/src/Shared/Infrastructure/Laravel/Providers/LarawebhookServiceProvider.php @@ -21,18 +21,25 @@ use Proxynth\Larawebhook\Audit\Infrastructure\Logging\WebhookLogger; use Proxynth\Larawebhook\Audit\Infrastructure\Logging\WebhookLoggerAuditLogWriter; use Proxynth\Larawebhook\Audit\Infrastructure\Payload\PayloadStorageResolver; +use Proxynth\Larawebhook\Contracts\PayloadParserInterface; +use Proxynth\Larawebhook\Contracts\SignatureValidatorInterface; +use Proxynth\Larawebhook\Ingestion\Application\Ports\AuditLogRecorder as IngestionAuditLogRecorder; use Proxynth\Larawebhook\Ingestion\Application\Ports\SignatureValidator; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookPayloadParserResolver; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookSecretResolver; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookServiceMetadataResolver; +use Proxynth\Larawebhook\Ingestion\Application\Services\ReceiveWebhookEventFactory; use Proxynth\Larawebhook\Ingestion\Application\UseCases\ReceiveWebhook; use Proxynth\Larawebhook\Ingestion\Application\UseCases\ValidateWebhook as ValidateWebhookUseCase; use Proxynth\Larawebhook\Ingestion\Infrastructure\Config\ConfigWebhookSecretResolver; use Proxynth\Larawebhook\Ingestion\Infrastructure\Laravel\Middleware\ValidateWebhook as ValidateWebhookMiddleware; +use Proxynth\Larawebhook\Ingestion\Infrastructure\Parsing\PayloadParserRegistry; use Proxynth\Larawebhook\Ingestion\Infrastructure\Parsing\ProviderPayloadParserResolver; use Proxynth\Larawebhook\Ingestion\Infrastructure\Support\LaravelWebhookServiceMetadataResolver; use Proxynth\Larawebhook\Ingestion\Infrastructure\Validation\ProviderSignatureValidator; +use Proxynth\Larawebhook\Ingestion\Infrastructure\Validation\SignatureValidatorRegistry; use Proxynth\Larawebhook\Ingestion\Infrastructure\Validation\WebhookValidatorFactory; +use Proxynth\Larawebhook\Processing\Application\Ports\AuditLogRecorder as ProcessingAuditLogRecorder; use Proxynth\Larawebhook\Processing\Application\Ports\IdempotencyResolver; use Proxynth\Larawebhook\Processing\Application\Ports\ProcessedWebhookRecorder; use Proxynth\Larawebhook\Processing\Application\Ports\ReplayableWebhookRepository; @@ -47,9 +54,15 @@ use Proxynth\Larawebhook\Processing\Infrastructure\Idempotency\DefaultIdempotencyResolver; use Proxynth\Larawebhook\Processing\Infrastructure\Persistence\EloquentProcessedWebhookRecorder; use Proxynth\Larawebhook\Processing\Infrastructure\Persistence\EloquentReplayableWebhookRepository; -use Proxynth\Larawebhook\Shared\Application\Larawebhook; +use Proxynth\Larawebhook\Shared\Application\Ports\Delay; use Proxynth\Larawebhook\Shared\Application\Ports\EventBus; +use Proxynth\Larawebhook\Shared\Application\Ports\TransactionRunner; use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\EventBus\LaravelEventBus; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Larawebhook; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Notifications\WebhookNotificationGateway; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Queries\WebhookLogQueries; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Timing\SleepDelay; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Transactions\LaravelTransactionRunner; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; @@ -112,6 +125,8 @@ private function registerServices(): void // Register main Larawebhook class as singleton $this->app->singleton(Larawebhook::class); + $this->app->singleton(WebhookNotificationGateway::class); + $this->app->singleton(WebhookLogQueries::class); $this->app->alias(Larawebhook::class, 'larawebhook'); $this->app->alias(Larawebhook::class, \Proxynth\Larawebhook\Larawebhook::class); @@ -138,6 +153,8 @@ private function registerServices(): void }); $this->app->singleton(WebhookAuditLogWriter::class, WebhookLoggerAuditLogWriter::class); + $this->app->alias(WebhookAuditLogWriter::class, IngestionAuditLogRecorder::class); + $this->app->alias(WebhookAuditLogWriter::class, ProcessingAuditLogRecorder::class); // Register IdempotencyResolver as singleton with default implementation $this->app->singleton(IdempotencyResolver::class, DefaultIdempotencyResolver::class); @@ -149,12 +166,48 @@ private function registerServices(): void $this->app->singleton(WebhookValidatorFactory::class); $this->app->singleton(SignatureValidator::class, ProviderSignatureValidator::class); $this->app->singleton(WebhookServiceMetadataResolver::class, LaravelWebhookServiceMetadataResolver::class); + $this->app->singleton(PayloadParserRegistry::class, function ($app) { + $parsers = PayloadParserRegistry::defaults(); + + foreach (config('larawebhook.custom_parsers', []) as $service => $parser) { + $instance = is_string($parser) ? $app->make($parser) : $parser; + + if (! $instance instanceof PayloadParserInterface) { + throw new \InvalidArgumentException( + "Custom parser for {$service} must implement ".PayloadParserInterface::class + ); + } + + $parsers[$service] = $instance; + } + + return new PayloadParserRegistry($parsers); + }); $this->app->singleton(WebhookPayloadParserResolver::class, ProviderPayloadParserResolver::class); + $this->app->singleton(SignatureValidatorRegistry::class, function ($app) { + $validators = SignatureValidatorRegistry::defaults(); + + foreach (config('larawebhook.custom_validators', []) as $service => $validator) { + $instance = is_string($validator) ? $app->make($validator) : $validator; + + if (! $instance instanceof SignatureValidatorInterface) { + throw new \InvalidArgumentException( + "Custom validator for {$service} must implement ".SignatureValidatorInterface::class + ); + } + + $validators[$service] = $instance; + } + + return new SignatureValidatorRegistry($validators); + }); // Register ReplayWebhook use case $this->app->singleton(ReplayWebhook::class); $this->app->singleton(RetryWebhook::class); $this->app->singleton(EventBus::class, LaravelEventBus::class); + $this->app->singleton(TransactionRunner::class, LaravelTransactionRunner::class); + $this->app->singleton(Delay::class, SleepDelay::class); $this->app->singleton( ReplayableWebhookRepository::class, @@ -175,6 +228,7 @@ private function registerServices(): void $this->app->singleton(ValidateWebhookUseCase::class); $this->app->singleton(RecordWebhookLog::class); $this->app->singleton(ReceiveWebhook::class); + $this->app->singleton(ReceiveWebhookEventFactory::class); $this->app->singleton(WebhookSecretResolver::class, ConfigWebhookSecretResolver::class); diff --git a/src/Shared/Infrastructure/Laravel/Queries/WebhookLogQueries.php b/src/Shared/Infrastructure/Laravel/Queries/WebhookLogQueries.php new file mode 100644 index 0000000..0e68c84 --- /dev/null +++ b/src/Shared/Infrastructure/Laravel/Queries/WebhookLogQueries.php @@ -0,0 +1,35 @@ + */ + public function all(): Collection + { + return WebhookLog::latest()->get(); + } + + /** @return Collection */ + public function forService(string $service): Collection + { + return WebhookLog::service($service)->latest()->get(); + } + + /** @return Collection */ + public function failed(): Collection + { + return WebhookLog::failed()->latest()->get(); + } + + /** @return Collection */ + public function successful(): Collection + { + return WebhookLog::successful()->latest()->get(); + } +} diff --git a/src/Shared/Infrastructure/Laravel/Timing/SleepDelay.php b/src/Shared/Infrastructure/Laravel/Timing/SleepDelay.php new file mode 100644 index 0000000..aecb571 --- /dev/null +++ b/src/Shared/Infrastructure/Laravel/Timing/SleepDelay.php @@ -0,0 +1,17 @@ + 0) { + sleep($seconds); + } + } +} diff --git a/src/Shared/Infrastructure/Laravel/Transactions/LaravelTransactionRunner.php b/src/Shared/Infrastructure/Laravel/Transactions/LaravelTransactionRunner.php new file mode 100644 index 0000000..c7f98d2 --- /dev/null +++ b/src/Shared/Infrastructure/Laravel/Transactions/LaravelTransactionRunner.php @@ -0,0 +1,16 @@ +expect($domains) diff --git a/tests/Fakes/Ingestion/FakeWebhookSecretResolver.php b/tests/Fakes/Ingestion/FakeWebhookSecretResolver.php index ae13c80..fc1b979 100644 --- a/tests/Fakes/Ingestion/FakeWebhookSecretResolver.php +++ b/tests/Fakes/Ingestion/FakeWebhookSecretResolver.php @@ -3,7 +3,7 @@ namespace Proxynth\Larawebhook\Tests\Fakes\Ingestion; use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookSecretResolver; -use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; final readonly class FakeWebhookSecretResolver implements WebhookSecretResolver { @@ -11,7 +11,7 @@ public function __construct( private array $secrets = [], ) {} - public function resolve(WebhookService $service): ?string + public function resolve(WebhookServiceIdentifier $service): ?string { return $this->secrets[$service->value] ?? null; } diff --git a/tests/Feature/Audit/Application/UseCases/RecordWebhookLogIntegrationTest.php b/tests/Feature/Audit/Application/UseCases/RecordWebhookLogIntegrationTest.php index 7b73b23..1ecb054 100644 --- a/tests/Feature/Audit/Application/UseCases/RecordWebhookLogIntegrationTest.php +++ b/tests/Feature/Audit/Application/UseCases/RecordWebhookLogIntegrationTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Audit\Application\UseCases\RecordWebhookLog; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; @@ -17,12 +18,12 @@ idempotencyKey: 'delivery_123', )); - expect($log)->toBeInstanceOf(WebhookLog::class) + expect($log)->toBeInstanceOf(WebhookLogData::class) ->and(WebhookLog::count())->toBe(1) ->and($log->service)->toBe('github') ->and($log->status)->toBe('success') - ->and($log->external_id)->toBe('delivery_123') - ->and($log->idempotency_key)->toBe('delivery_123'); + ->and($log->externalId)->toBe('delivery_123') + ->and($log->idempotencyKey)->toBe('delivery_123'); }); it('records a failed webhook log in persistence', function () { @@ -37,9 +38,9 @@ errorMessage: 'Invalid GitHub webhook signature.', )); - expect($log)->toBeInstanceOf(WebhookLog::class) + expect($log)->toBeInstanceOf(WebhookLogData::class) ->and(WebhookLog::count())->toBe(1) ->and($log->status)->toBe('failed') ->and($log->attempt)->toBe(1) - ->and($log->error_message)->toBe('Invalid GitHub webhook signature.'); + ->and($log->errorMessage)->toBe('Invalid GitHub webhook signature.'); }); diff --git a/tests/Feature/PayloadStorage/PayloadStorageModeTest.php b/tests/Feature/PayloadStorage/PayloadStorageModeTest.php index b24be3e..04d4c55 100644 --- a/tests/Feature/PayloadStorage/PayloadStorageModeTest.php +++ b/tests/Feature/PayloadStorage/PayloadStorageModeTest.php @@ -1,8 +1,8 @@ toBeInstanceOf(WebhookLog::class) + expect($log)->toBeInstanceOf(WebhookLogData::class) ->and($log->status)->toBe('success') ->and($log->payload)->toBeNull(); }); @@ -92,6 +92,6 @@ )); expect($log->status)->toBe('failed') - ->and($log->error_message)->toBe('Invalid signature.') + ->and($log->errorMessage)->toBe('Invalid signature.') ->and($log->payload)->toBeNull(); }); diff --git a/tests/Unit/Audit/Application/Queries/GetWebhookFailureDetailsTest.php b/tests/Unit/Audit/Application/Queries/GetWebhookFailureDetailsTest.php index 1c76f6e..2817922 100644 --- a/tests/Unit/Audit/Application/Queries/GetWebhookFailureDetailsTest.php +++ b/tests/Unit/Audit/Application/Queries/GetWebhookFailureDetailsTest.php @@ -1,6 +1,6 @@ query = $query; - return new LengthAwarePaginator([ + return new WebhookLogPage([ new WebhookLogSummary( id: 2, service: 'github', @@ -38,7 +38,12 @@ public function paginateSummaries(ListWebhookLogsQuery $query): LengthAwarePagin idempotencyKey: 'delivery_1', createdAt: '2026-06-16T12:00:00+00:00', ), - ], 2, $query->perPage); + ], 2, $query->perPage, 1, 1, [ + 'first' => '/logs?page=1', + 'last' => '/logs?page=1', + 'prev' => null, + 'next' => null, + ]); } public function findDetails(int|string $id): WebhookLogDetails @@ -67,7 +72,7 @@ public function findFailureDetails(int|string $id): WebhookFailureDetails ->and($repository->query?->status)->toBe('failed') ->and($repository->query?->event)->toBe('invoice.paid') ->and($repository->query?->date)->toBe('2026-06-16') - ->and($result->total())->toBe(2) - ->and($result->items()[0])->toBeInstanceOf(WebhookLogSummary::class) - ->and($result->items()[0]->id)->toBe(2); + ->and($result->total)->toBe(2) + ->and($result->items[0])->toBeInstanceOf(WebhookLogSummary::class) + ->and($result->items[0]->id)->toBe(2); }); diff --git a/tests/Unit/Audit/Application/ReadModels/WebhookFailureDetailsTest.php b/tests/Unit/Audit/Application/ReadModels/WebhookFailureDetailsTest.php index 685f4dc..e832c2e 100644 --- a/tests/Unit/Audit/Application/ReadModels/WebhookFailureDetailsTest.php +++ b/tests/Unit/Audit/Application/ReadModels/WebhookFailureDetailsTest.php @@ -4,6 +4,7 @@ use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookFailureDetails; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\WebhookLogReadModelFactory; it('can be created from failed webhook log model', function () { $log = WebhookLog::factory()->create([ @@ -16,7 +17,7 @@ 'idempotency_key' => 'delivery_123', ]); - $readModel = WebhookFailureDetails::fromModel($log); + $readModel = (new WebhookLogReadModelFactory)->failureDetails($log); expect($readModel)->toBeInstanceOf(WebhookFailureDetails::class) ->and($readModel->id)->toBe($log->id) diff --git a/tests/Unit/Audit/Application/ReadModels/WebhookLogDetailsTest.php b/tests/Unit/Audit/Application/ReadModels/WebhookLogDetailsTest.php index 4847ee9..3b3f680 100644 --- a/tests/Unit/Audit/Application/ReadModels/WebhookLogDetailsTest.php +++ b/tests/Unit/Audit/Application/ReadModels/WebhookLogDetailsTest.php @@ -4,6 +4,7 @@ use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookLogDetails; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\WebhookLogReadModelFactory; it('can be created from webhook log model', function () { $log = WebhookLog::factory()->create([ @@ -17,7 +18,7 @@ 'idempotency_key' => 'evt_123', ]); - $readModel = WebhookLogDetails::fromModel($log); + $readModel = (new WebhookLogReadModelFactory)->details($log); expect($readModel)->toBeInstanceOf(WebhookLogDetails::class) ->and($readModel->id)->toBe($log->id) diff --git a/tests/Unit/Audit/Application/ReadModels/WebhookLogSummaryTest.php b/tests/Unit/Audit/Application/ReadModels/WebhookLogSummaryTest.php index 3c6e4e2..9741e26 100644 --- a/tests/Unit/Audit/Application/ReadModels/WebhookLogSummaryTest.php +++ b/tests/Unit/Audit/Application/ReadModels/WebhookLogSummaryTest.php @@ -4,6 +4,7 @@ use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookLogSummary; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\WebhookLogReadModelFactory; it('can be created from webhook log model', function () { $log = WebhookLog::factory()->create([ @@ -15,7 +16,7 @@ 'idempotency_key' => 'delivery_123', ]); - $readModel = WebhookLogSummary::fromModel($log); + $readModel = (new WebhookLogReadModelFactory)->summary($log); expect($readModel)->toBeInstanceOf(WebhookLogSummary::class) ->and($readModel->id)->toBe($log->id) diff --git a/tests/Unit/Audit/Application/UseCases/RecordWebhookLogTest.php b/tests/Unit/Audit/Application/UseCases/RecordWebhookLogTest.php index 8b4e44a..a06b921 100644 --- a/tests/Unit/Audit/Application/UseCases/RecordWebhookLogTest.php +++ b/tests/Unit/Audit/Application/UseCases/RecordWebhookLogTest.php @@ -3,9 +3,11 @@ declare(strict_types=1); use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Audit\Application\Ports\WebhookAuditLogWriter; use Proxynth\Larawebhook\Audit\Application\UseCases\RecordWebhookLog; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Audit\Infrastructure\Logging\WebhookLogDataFactory; beforeEach(function () { app()->forgetInstance(WebhookAuditLogWriter::class); @@ -17,11 +19,11 @@ /** @var list */ public array $commands = []; - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { $this->commands[] = $command; - return WebhookLog::make([ + return WebhookLogDataFactory::fromModel(WebhookLog::make([ 'service' => $command->service, 'event' => $command->event, 'status' => $command->valid ? 'success' : 'failed', @@ -30,7 +32,7 @@ public function record(RecordWebhookLogCommand $command): WebhookLog 'external_id' => $command->externalId, 'idempotency_key' => $command->idempotencyKey, 'error_message' => $command->errorMessage, - ]); + ])); } }; @@ -46,7 +48,7 @@ public function record(RecordWebhookLogCommand $command): WebhookLog idempotencyKey: 'delivery_123', )); - expect($log)->toBeInstanceOf(WebhookLog::class) + expect($log)->toBeInstanceOf(WebhookLogData::class) ->and($log->status)->toBe('success') ->and($fakeWriter->commands)->toHaveCount(1) ->and($fakeWriter->commands[0]->service)->toBe('github') @@ -59,11 +61,11 @@ public function record(RecordWebhookLogCommand $command): WebhookLog /** @var list */ public array $commands = []; - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { $this->commands[] = $command; - return WebhookLog::make([ + return WebhookLogDataFactory::fromModel(WebhookLog::make([ 'service' => $command->service, 'event' => $command->event, 'status' => $command->valid ? 'success' : 'failed', @@ -72,7 +74,7 @@ public function record(RecordWebhookLogCommand $command): WebhookLog 'external_id' => $command->externalId, 'idempotency_key' => $command->idempotencyKey, 'error_message' => $command->errorMessage, - ]); + ])); } }; @@ -89,7 +91,7 @@ public function record(RecordWebhookLogCommand $command): WebhookLog errorMessage: 'Invalid GitHub webhook signature.', )); - expect($log)->toBeInstanceOf(WebhookLog::class) + expect($log)->toBeInstanceOf(WebhookLogData::class) ->and($log->status)->toBe('failed') ->and($fakeWriter->commands)->toHaveCount(1) ->and($fakeWriter->commands[0]->valid)->toBeFalse() diff --git a/tests/Unit/Facades/LarawebhookFacadeTest.php b/tests/Unit/Facades/LarawebhookFacadeTest.php index a25c1bb..b367fff 100644 --- a/tests/Unit/Facades/LarawebhookFacadeTest.php +++ b/tests/Unit/Facades/LarawebhookFacadeTest.php @@ -6,13 +6,15 @@ use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Notification; use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Audit\Application\Ports\WebhookAuditLogWriter; use Proxynth\Larawebhook\Audit\Application\UseCases\RecordWebhookLog; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Notifications\FailureDetector; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; -use Proxynth\Larawebhook\Shared\Application\Larawebhook as LarawebhookClass; +use Proxynth\Larawebhook\Audit\Infrastructure\Logging\WebhookLogDataFactory; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Facades\Larawebhook; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Larawebhook as LarawebhookClass; describe('Larawebhook Facade', function () { it('extends the base Facade class', function () { @@ -178,7 +180,7 @@ { public ?RecordWebhookLogCommand $command = null; - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { $this->command = $command; @@ -194,7 +196,7 @@ public function record(RecordWebhookLogCommand $command): WebhookLog $log->id = 1001; - return $log; + return WebhookLogDataFactory::fromModel($log); } }; @@ -218,7 +220,7 @@ public function record(RecordWebhookLogCommand $command): WebhookLog { public ?RecordWebhookLogCommand $command = null; - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { $this->command = $command; @@ -234,7 +236,7 @@ public function record(RecordWebhookLogCommand $command): WebhookLog $log->id = 1002; - return $log; + return WebhookLogDataFactory::fromModel($log); } }; diff --git a/tests/Unit/Ingestion/Application/UseCases/ReceiveWebhookTest.php b/tests/Unit/Ingestion/Application/UseCases/ReceiveWebhookTest.php index 2a41ed5..fa05c67 100644 --- a/tests/Unit/Ingestion/Application/UseCases/ReceiveWebhookTest.php +++ b/tests/Unit/Ingestion/Application/UseCases/ReceiveWebhookTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Illuminate\Support\Facades\Queue; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; use Proxynth\Larawebhook\Ingestion\Application\Commands\ReceiveWebhookCommand; @@ -69,10 +70,10 @@ function githubPayload(string $deliveryId = 'delivery_123'): string expect($result)->toBeInstanceOf(ReceiveWebhookResult::class) ->and($result->isSuccess())->toBeTrue() - ->and($result->log)->toBeInstanceOf(WebhookLog::class) + ->and($result->log)->toBeInstanceOf(WebhookLogData::class) ->and($result->log->service)->toBe('github') ->and($result->log->status)->toBe('success') - ->and($result->log->external_id)->toBe('delivery_123') + ->and($result->log->externalId)->toBe('delivery_123') ->and($result->idempotencyKey)->toBe('delivery_123') ->and($result->events)->toHaveCount(3) ->and($result->events[0])->toBeInstanceOf(WebhookReceived::class) @@ -127,7 +128,7 @@ function githubPayload(string $deliveryId = 'delivery_123'): string expect($result->isSuccess())->toBeTrue() ->and($result->externalId)->toBeNull() - ->and($result->log?->external_id)->toBeNull() + ->and($result->log?->externalId)->toBeNull() ->and($result->idempotencyKey)->toStartWith('payload_hash:'); }); @@ -168,7 +169,7 @@ function githubPayload(string $deliveryId = 'delivery_123'): string )); expect($result->isFailed())->toBeTrue() - ->and($result->log)->toBeInstanceOf(WebhookLog::class) + ->and($result->log)->toBeInstanceOf(WebhookLogData::class) ->and($result->log?->status)->toBe('failed') ->and($result->failureStatusCode)->toBeInt() ->and($result->errorMessage)->not->toBeNull() @@ -202,10 +203,9 @@ function githubPayload(string $deliveryId = 'delivery_123'): string )); expect($result->isAcceptedForRetry())->toBeTrue() - ->and($result->log)->toBeInstanceOf(WebhookLog::class) + ->and($result->log)->toBeInstanceOf(WebhookLogData::class) ->and($result->log?->status)->toBe('failed') ->and($result->event)->not->toBeNull() - ->and($result->secret)->toBe('github_secret') ->and($result->idempotencyKey)->toBe('delivery_retry'); }); @@ -250,8 +250,8 @@ function githubPayload(string $deliveryId = 'delivery_123'): string expect($result->isSuccess())->toBeTrue() ->and($result->externalId)->toBeNull() ->and($result->idempotencyKey)->toStartWith('payload_hash:') - ->and($result->log?->external_id)->toBeNull() - ->and($result->log?->idempotency_key)->toBe($result->idempotencyKey); + ->and($result->log?->externalId)->toBeNull() + ->and($result->log?->idempotencyKey)->toBe($result->idempotencyKey); }); it('processes valid webhook through domain event lifecycle', function () { @@ -270,9 +270,9 @@ function githubPayload(string $deliveryId = 'delivery_123'): string )); expect($result->isSuccess())->toBeTrue() - ->and($result->log)->toBeInstanceOf(WebhookLog::class) + ->and($result->log)->toBeInstanceOf(WebhookLogData::class) ->and($result->log?->status)->toBe('success') - ->and($result->log?->external_id)->toBe('delivery_123') + ->and($result->log?->externalId)->toBe('delivery_123') ->and($result->idempotencyKey)->toBe('delivery_123'); }); @@ -291,7 +291,7 @@ function githubPayload(string $deliveryId = 'delivery_123'): string )); expect($result->isFailed())->toBeTrue() - ->and($result->log)->toBeInstanceOf(WebhookLog::class) + ->and($result->log)->toBeInstanceOf(WebhookLogData::class) ->and($result->log?->status)->toBe('failed') ->and($result->errorMessage)->not->toBeNull(); }); diff --git a/tests/Unit/Ingestion/Application/UseCases/ValidateWebhookTest.php b/tests/Unit/Ingestion/Application/UseCases/ValidateWebhookTest.php index 538595a..7f35894 100644 --- a/tests/Unit/Ingestion/Application/UseCases/ValidateWebhookTest.php +++ b/tests/Unit/Ingestion/Application/UseCases/ValidateWebhookTest.php @@ -8,6 +8,7 @@ use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload; use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; beforeEach(function () { app()->forgetInstance(SignatureValidator::class); @@ -19,7 +20,7 @@ public array $calls = []; public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, @@ -62,7 +63,7 @@ public function validate( $fakeValidator = new class implements SignatureValidator { public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, @@ -97,7 +98,7 @@ public function validate( public ?string $capturedSecret = null; public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, diff --git a/tests/Unit/Ingestion/Domain/ValueObjects/RawPayloadTest.php b/tests/Unit/Ingestion/Domain/ValueObjects/RawPayloadTest.php index 8975bab..e30c914 100644 --- a/tests/Unit/Ingestion/Domain/ValueObjects/RawPayloadTest.php +++ b/tests/Unit/Ingestion/Domain/ValueObjects/RawPayloadTest.php @@ -21,5 +21,12 @@ }); it('returns an empty array when payload is not valid json object', function () { - expect(RawPayload::fromString('invalid')->decoded())->toBe(['raw' => 'invalid']); + $payload = RawPayload::fromString('invalid'); + + expect($payload->isValidJson())->toBeFalse() + ->and($payload->decoded())->toBe(['raw' => 'invalid']); +}); + +it('identifies valid json payloads', function () { + expect(RawPayload::fromString('{"event":"test"}')->isValidJson())->toBeTrue(); }); diff --git a/tests/Unit/Jobs/RetryWebhookJobTest.php b/tests/Unit/Jobs/RetryWebhookJobTest.php index 01efd95..38b01f2 100644 --- a/tests/Unit/Jobs/RetryWebhookJobTest.php +++ b/tests/Unit/Jobs/RetryWebhookJobTest.php @@ -18,6 +18,8 @@ beforeEach(function () { config()->set('larawebhook.retries.enabled', true); + config()->set('larawebhook.services.github.webhook_secret', 'github_secret_key'); + config()->set('larawebhook.services.stripe.webhook_secret', 'secret'); app()->instance( RetryPolicyResolver::class, new FakeRetryPolicyResolver(new RetryPolicy( @@ -34,7 +36,6 @@ signature: incomingSignature('test_signature'), service: 'stripe', event: 'payment.succeeded', - secret: 'secret', attempt: 2, externalId: 'delivery_123', idempotencyKey: 'dedupe_123', @@ -47,6 +48,8 @@ ->and($job->attempt())->toBe(2) ->and($job->externalId())->toBe('delivery_123') ->and($job->idempotencyKey())->toBe('dedupe_123'); + + expect(serialize($job))->not->toContain('secret'); }); it('keeps the unique id stable for the same payload', function () { @@ -55,7 +58,6 @@ signature: incomingSignature('test_signature'), service: 'stripe', event: 'payment.succeeded', - secret: 'secret', ); $job2 = new RetryWebhookJob( @@ -63,7 +65,6 @@ signature: incomingSignature('test_signature'), service: 'stripe', event: 'payment.succeeded', - secret: 'secret', ); expect($job1->uniqueId())->toBe($job2->uniqueId()); @@ -83,7 +84,6 @@ signature: $signature, service: 'github', event: 'push', - secret: $secret, attempt: 0, externalId: 'delivery_123', idempotencyKey: 'delivery_123', @@ -102,7 +102,6 @@ signature: incomingSignature('sha256=invalid'), service: 'github', event: 'push', - secret: 'github_secret_key', attempt: 0, externalId: 'delivery_123', idempotencyKey: 'delivery_123', @@ -134,7 +133,6 @@ signature: incomingSignature('sha256=invalid'), service: 'github', event: 'push', - secret: 'github_secret_key', attempt: 0, externalId: 'delivery_123', idempotencyKey: 'delivery_123', @@ -159,7 +157,6 @@ signature: Signature::fromString('sha256=invalid'), service: 'github', event: 'opened', - secret: 'github_secret', attempt: 1, externalId: 'delivery_123', idempotencyKey: 'delivery_123', diff --git a/tests/Unit/LarawebhookServiceProviderTest.php b/tests/Unit/LarawebhookServiceProviderTest.php index 38e86d1..8d12a16 100644 --- a/tests/Unit/LarawebhookServiceProviderTest.php +++ b/tests/Unit/LarawebhookServiceProviderTest.php @@ -17,7 +17,9 @@ use Proxynth\Larawebhook\Ingestion\Application\Ports\WebhookServiceMetadataResolver; use Proxynth\Larawebhook\Processing\Application\Ports\ReplayableWebhookRepository; use Proxynth\Larawebhook\Processing\Application\UseCases\RetryWebhook; +use Proxynth\Larawebhook\Shared\Application\Ports\Delay; use Proxynth\Larawebhook\Shared\Application\Ports\EventBus; +use Proxynth\Larawebhook\Shared\Application\Ports\TransactionRunner; use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\EventBus\LaravelEventBus; use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Providers\LarawebhookServiceProvider; @@ -30,6 +32,11 @@ ->and($instance1)->toBe($instance2); }); + it('registers infrastructure boundaries for delay and transactions', function () { + expect(app(Delay::class))->toBeInstanceOf(Delay::class) + ->and(app(TransactionRunner::class))->toBeInstanceOf(TransactionRunner::class); + }); + it('registers NotificationSender as singleton', function () { $instance1 = app(NotificationSender::class); $instance2 = app(NotificationSender::class); diff --git a/tests/Unit/LarawebhookTest.php b/tests/Unit/LarawebhookTest.php index 744bb3a..e0fea21 100644 --- a/tests/Unit/LarawebhookTest.php +++ b/tests/Unit/LarawebhookTest.php @@ -7,8 +7,8 @@ use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; use Proxynth\Larawebhook\Exceptions\InvalidSignatureException; use Proxynth\Larawebhook\Exceptions\WebhookException; -use Proxynth\Larawebhook\Shared\Application\Larawebhook; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Larawebhook; beforeEach(function () { $this->larawebhook = new Larawebhook; diff --git a/tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php b/tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php index c2c5e9d..fb7d429 100644 --- a/tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php +++ b/tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php @@ -3,11 +3,12 @@ declare(strict_types=1); use Proxynth\Larawebhook\Audit\Application\Commands\RecordWebhookLogCommand; -use Proxynth\Larawebhook\Audit\Application\Ports\WebhookAuditLogWriter; +use Proxynth\Larawebhook\Audit\Application\Data\WebhookLogData; use Proxynth\Larawebhook\Audit\Application\ReadModels\WebhookLogSummary; use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged; use Proxynth\Larawebhook\Audit\Domain\Exceptions\PayloadNotAvailable; use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog; +use Proxynth\Larawebhook\Audit\Infrastructure\Logging\WebhookLogDataFactory; use Proxynth\Larawebhook\Exceptions\WebhookException; use Proxynth\Larawebhook\Ingestion\Application\Commands\ValidateWebhookCommand; use Proxynth\Larawebhook\Ingestion\Application\Ports\SignatureValidator; @@ -17,16 +18,19 @@ use Proxynth\Larawebhook\Processing\Application\Commands\ReplayWebhookCommand; use Proxynth\Larawebhook\Processing\Application\Data\ReplayableWebhook; use Proxynth\Larawebhook\Processing\Application\Exceptions\ReplayWebhookNotAllowed; +use Proxynth\Larawebhook\Processing\Application\Ports\AuditLogRecorder; use Proxynth\Larawebhook\Processing\Application\Ports\ReplayableWebhookRepository; use Proxynth\Larawebhook\Processing\Application\Results\ReplayWebhookResult; use Proxynth\Larawebhook\Processing\Application\UseCases\ReplayWebhook; use Proxynth\Larawebhook\Processing\Domain\Events\WebhookReplayed; use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService; +use Proxynth\Larawebhook\Shared\Domain\ValueObjects\WebhookServiceIdentifier; use Proxynth\Larawebhook\Shared\Infrastructure\Laravel\Providers\LarawebhookServiceProvider; use Proxynth\Larawebhook\Tests\Fakes\Ingestion\FakeWebhookSecretResolver; beforeEach(function () { app()->register(LarawebhookServiceProvider::class, true); + config()->set('larawebhook.services.github.webhook_secret', 'github_secret'); }); function replayableWebhook( @@ -64,7 +68,7 @@ public function findReplayableById(int|string $id): ReplayableWebhook public ?ValidateWebhookCommand $command = null; public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, @@ -82,11 +86,11 @@ public function validate( } }; - $auditWriter = new class implements WebhookAuditLogWriter + $auditWriter = new class implements AuditLogRecorder { public ?RecordWebhookLogCommand $command = null; - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { $this->command = $command; @@ -105,13 +109,13 @@ public function record(RecordWebhookLogCommand $command): WebhookLog $log->created_at = now(); $log->updated_at = now(); - return $log; + return WebhookLogDataFactory::fromModel($log); } }; app()->instance(ReplayableWebhookRepository::class, $repository); app()->instance(SignatureValidator::class, $signatureValidator); - app()->instance(WebhookAuditLogWriter::class, $auditWriter); + app()->instance(AuditLogRecorder::class, $auditWriter); $result = app(ReplayWebhook::class)->handle(new ReplayWebhookCommand( webhookLogId: 123, @@ -147,7 +151,7 @@ public function findReplayableById(int|string $id): ReplayableWebhook app()->instance(SignatureValidator::class, new class implements SignatureValidator { public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, @@ -156,9 +160,9 @@ public function validate( } }); - app()->instance(WebhookAuditLogWriter::class, new class implements WebhookAuditLogWriter + app()->instance(AuditLogRecorder::class, new class implements AuditLogRecorder { - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { throw new LogicException('Not expected.'); } @@ -182,7 +186,7 @@ public function findReplayableById(int|string $id): ReplayableWebhook app()->instance(SignatureValidator::class, new class implements SignatureValidator { public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, @@ -191,9 +195,9 @@ public function validate( } }); - app()->instance(WebhookAuditLogWriter::class, new class implements WebhookAuditLogWriter + app()->instance(AuditLogRecorder::class, new class implements AuditLogRecorder { - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { throw new LogicException('Not expected.'); } @@ -226,7 +230,7 @@ public function findReplayableById(int|string $id): ReplayableWebhook app()->instance(SignatureValidator::class, new class implements SignatureValidator { public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, @@ -235,9 +239,9 @@ public function validate( } }); - app()->instance(WebhookAuditLogWriter::class, new class implements WebhookAuditLogWriter + app()->instance(AuditLogRecorder::class, new class implements AuditLogRecorder { - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { throw new LogicException('Not expected.'); } @@ -261,7 +265,7 @@ public function findReplayableById(int|string $id): ReplayableWebhook app()->instance(SignatureValidator::class, new class implements SignatureValidator { public function validate( - WebhookService $service, + WebhookServiceIdentifier $service, RawPayload $payload, Signature $signature, string $secret, @@ -270,9 +274,9 @@ public function validate( } }); - app()->instance(WebhookAuditLogWriter::class, new class implements WebhookAuditLogWriter + app()->instance(AuditLogRecorder::class, new class implements AuditLogRecorder { - public function record(RecordWebhookLogCommand $command): WebhookLog + public function record(RecordWebhookLogCommand $command): WebhookLogData { throw new LogicException('Not expected.'); } diff --git a/tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php b/tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php index 5e94e34..3bec19f 100644 --- a/tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php +++ b/tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php @@ -16,6 +16,7 @@ use Proxynth\Larawebhook\Tests\Fakes\Processing\FakeRetryPolicyResolver; beforeEach(function () { + config()->set('larawebhook.services.github.webhook_secret', 'github_secret'); app()->instance( RetryPolicyResolver::class, new FakeRetryPolicyResolver(new RetryPolicy( @@ -35,7 +36,6 @@ signature: $signature, service: WebhookService::Github->value, event: 'pull_request.opened', - secret: $secret, attempt: 0, externalId: 'delivery_123', idempotencyKey: 'dedupe_123', @@ -58,6 +58,8 @@ ->and($log->external_id)->toBeNull() ->and($log->idempotency_key)->toBeNull() ->and($log->error_message)->toBeNull(); + + expect(WebhookLog::count())->toBe(1); }); it('records a failed retry and schedules the next attempt when attempts remain', function () { @@ -69,7 +71,6 @@ signature: incomingSignature('sha256=invalid'), service: WebhookService::Github->value, event: 'pull_request.opened', - secret: $secret, attempt: 0, externalId: 'delivery_123', idempotencyKey: 'dedupe_123', @@ -90,6 +91,8 @@ ->and($log->attempt)->toBe(0) ->and($log->external_id)->toBeNull() ->and($log->idempotency_key)->toBeNull(); + + expect(WebhookLog::count())->toBe(1); }); it('records a failed retry and stops retrying at the max attempt', function () { @@ -106,7 +109,6 @@ signature: incomingSignature('sha256=invalid'), service: WebhookService::Github->value, event: 'pull_request.opened', - secret: 'github_secret', attempt: 0, externalId: 'delivery_123', idempotencyKey: 'dedupe_123', @@ -124,7 +126,6 @@ signature: incomingSignature('sha256=invalid'), service: 'unsupported', event: 'pull_request.opened', - secret: 'github_secret', )); })->throws(WebhookException::class, "Webhook service 'unsupported' is not supported."); @@ -142,7 +143,6 @@ signature: incomingSignature('sha256=invalid'), service: WebhookService::Github->value, event: 'pull_request.opened', - secret: 'github_secret', attempt: 1, externalId: 'delivery_123', idempotencyKey: 'dedupe_123', @@ -160,7 +160,6 @@ signature: incomingSignature(githubSignature('{"action":"opened"}')->value()), service: WebhookService::Github->value, event: 'opened', - secret: 'github_secret', attempt: 1, externalId: 'delivery_123', idempotencyKey: 'delivery_123', @@ -184,7 +183,6 @@ signature: Signature::fromString('sha256=invalid'), service: WebhookService::Github->value, event: 'opened', - secret: 'github_secret', attempt: 1, externalId: 'delivery_123', idempotencyKey: 'delivery_123', @@ -208,7 +206,6 @@ signature: githubSignature('{"action":"opened"}'), service: WebhookService::Github->value, event: 'opened', - secret: 'github_secret', attempt: 1, externalId: 'delivery_123', idempotencyKey: null, diff --git a/tests/Unit/Validators/SignatureValidatorRegistryTest.php b/tests/Unit/Validators/SignatureValidatorRegistryTest.php new file mode 100644 index 0000000..d3dc951 --- /dev/null +++ b/tests/Unit/Validators/SignatureValidatorRegistryTest.php @@ -0,0 +1,37 @@ + $custom, + ]); + + expect($registry->forService(WebhookService::Stripe))->toBe($custom); +}); + +it('resolves a configured service outside the built-in enum', function () { + $service = ConfiguredWebhookService::resolve('twilio'); + + expect($service->value())->toBe('twilio') + ->and($service)->not->toBeInstanceOf(WebhookService::class); +});