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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

namespace Proxynth\Larawebhook\Processing\Application\DTOs;
namespace Proxynth\Larawebhook\Processing\Application\Data;

use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Provider;
use Proxynth\Larawebhook\Processing\Domain\Entities\WebhookEvent;
Expand All @@ -26,7 +26,7 @@ public function __construct(

public function toWebhookEvent(): WebhookEvent
{
return WebhookEvent::replayable(
return WebhookEvent::fromHistory(
provider: Provider::fromString($this->service),
eventType: EventType::fromString($this->event),
idempotencyKey: IdempotencyKey::optional($this->idempotencyKey),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace Proxynth\Larawebhook\Processing\Application\Ports;

use Proxynth\Larawebhook\Processing\Application\DTOs\ReplayableWebhook;
use Proxynth\Larawebhook\Processing\Application\Data\ReplayableWebhook;

interface ReplayableWebhookRepository
{
Expand Down
96 changes: 89 additions & 7 deletions src/Processing/Application/UseCases/RetryWebhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,18 @@
use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged;
use Proxynth\Larawebhook\Exceptions\WebhookException;
use Proxynth\Larawebhook\Ingestion\Application\Commands\ValidateWebhookCommand;
use Proxynth\Larawebhook\Ingestion\Application\Results\ValidateWebhookResult;
use Proxynth\Larawebhook\Ingestion\Application\UseCases\ValidateWebhook;
use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Provider;
use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload;
use Proxynth\Larawebhook\Processing\Application\Commands\RetryWebhookCommand;
use Proxynth\Larawebhook\Processing\Application\Data\RetryPolicy;
use Proxynth\Larawebhook\Processing\Application\Ports\RetryPolicyResolver;
use Proxynth\Larawebhook\Processing\Application\Results\RetryWebhookResult;
use Proxynth\Larawebhook\Processing\Domain\Entities\WebhookEvent;
use Proxynth\Larawebhook\Processing\Domain\Events\WebhookProcessingFailed;
use Proxynth\Larawebhook\Processing\Domain\ValueObjects\EventType;
use Proxynth\Larawebhook\Processing\Domain\ValueObjects\IdempotencyKey;
use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService;

final readonly class RetryWebhook
Expand Down Expand Up @@ -48,7 +54,13 @@ public function handle(RetryWebhookCommand $command): RetryWebhookResult
secret: $command->secret,
));

$log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand(
$webhookEvent = $this->createWebhookEvent(
service: $validation->service,
event: $validation->event,
idempotencyKey: $command->idempotencyKey,
);

$this->recordWebhookLog->handle(new RecordWebhookLogCommand(
service: $validation->service,
event: $validation->event,
valid: $validation->isValid(),
Expand All @@ -60,21 +72,91 @@ public function handle(RetryWebhookCommand $command): RetryWebhookResult
));

if ($validation->isValid()) {
return RetryWebhookResult::success($log, [
return $this->handleValidRetry(
command: $command,
validation: $validation,
webhookEvent: $webhookEvent,
);
}

return $this->handleFailedRetry(
command: $command,
validation: $validation,
webhookEvent: $webhookEvent,
retryPolicy: $retryPolicy,
);
}

private function createWebhookEvent(
string $service,
string $event,
?string $idempotencyKey,
): WebhookEvent {
return WebhookEvent::received(
provider: Provider::fromString($service),
eventType: EventType::fromString($event),
idempotencyKey: IdempotencyKey::optional($idempotencyKey),
);
}

private function handleValidRetry(
RetryWebhookCommand $command,
ValidateWebhookResult $validation,
WebhookEvent $webhookEvent,
): RetryWebhookResult {
$webhookEvent->markValidated();
$webhookEvent->markProcessing();

$log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand(
service: $validation->service,
event: $validation->event,
valid: true,
payload: $validation->payload,
attempt: $command->attempt,
externalId: null,
idempotencyKey: null,
errorMessage: null,
));

$webhookEvent->markProcessed();

return RetryWebhookResult::success(
log: $log,
events: [
new WebhookLogged(
webhookLogId: $log->id,
provider: $log->service,
event: $log->event,
status: $log->status,
),
]);
}
],
);
}

$shouldRetry = $retryPolicy->shouldRetryAfter($command->attempt);
private function handleFailedRetry(
RetryWebhookCommand $command,
ValidateWebhookResult $validation,
WebhookEvent $webhookEvent,
RetryPolicy $retryPolicy,
): RetryWebhookResult {
$reason = $validation->errorMessage ?? 'Webhook validation failed.';

$webhookEvent->markFailed($reason);

$log = $this->recordWebhookLog->handle(new RecordWebhookLogCommand(
service: $validation->service,
event: $validation->event,
valid: false,
payload: $validation->payload,
attempt: $command->attempt,
externalId: null,
idempotencyKey: null,
errorMessage: $reason,
));

return RetryWebhookResult::failed(
log: $log,
shouldRetry: $shouldRetry,
shouldRetry: $retryPolicy->shouldRetryAfter($command->attempt),
nextAttempt: $retryPolicy->nextAttemptAfter($command->attempt),
delaySeconds: $retryPolicy->delayForAttempt($command->attempt),
events: [
Expand All @@ -83,7 +165,7 @@ public function handle(RetryWebhookCommand $command): RetryWebhookResult
event: $validation->event,
externalId: $validation->externalId,
attempt: $command->attempt,
reason: $validation->errorMessage ?? 'Webhook validation failed.',
reason: $reason,
),
new WebhookLogged(
webhookLogId: $log->id,
Expand Down
16 changes: 16 additions & 0 deletions src/Processing/Domain/Entities/WebhookEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ public static function received(
);
}

public static function fromHistory(
Provider $provider,
EventType $eventType,
?IdempotencyKey $idempotencyKey,
WebhookStatus $status,
bool $valid = true,
): self {
return new self(
provider: $provider,
eventType: $eventType,
idempotencyKey: $idempotencyKey,
status: $status,
valid: $valid,
);
}

public function markValidated(): void
{
$this->ensureNotTerminal();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Proxynth\Larawebhook\Exceptions\WebhookException;
use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature;
use Proxynth\Larawebhook\Processing\Application\Commands\RetryWebhookCommand;
use Proxynth\Larawebhook\Processing\Application\UseCases\RetryWebhook;
Expand Down Expand Up @@ -38,6 +39,8 @@ public function __construct(

/**
* Execute the job.
*
* @throws WebhookException
*/
public function handle(RetryWebhook $retryWebhook): void
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace Proxynth\Larawebhook\Processing\Infrastructure\Persistence;

use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog;
use Proxynth\Larawebhook\Processing\Application\DTOs\ReplayableWebhook;
use Proxynth\Larawebhook\Processing\Application\Data\ReplayableWebhook;
use Proxynth\Larawebhook\Processing\Application\Ports\ReplayableWebhookRepository;

final class EloquentReplayableWebhookRepository implements ReplayableWebhookRepository
Expand Down
25 changes: 25 additions & 0 deletions tests/Unit/Processing/Application/Data/ReplayableWebhookTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

use Proxynth\Larawebhook\Processing\Application\Data\ReplayableWebhook;

it('restores webhook event from replayable webhook state', function () {
$replayable = new ReplayableWebhook(
id: 1,
service: 'github',
event: 'opened',
payload: ['action' => 'opened'],
attempt: 0,
externalId: 'delivery_123',
idempotencyKey: 'delivery_123',
status: 'failed',
);

$event = $replayable->toWebhookEvent();

expect($event->provider()->value())->toBe('github')
->and($event->eventType()->value())->toBe('opened')
->and($event->status()->value())->toBe('failed')
->and($event->idempotencyKey()?->value())->toBe('delivery_123');
});
20 changes: 19 additions & 1 deletion tests/Unit/Processing/Application/UseCases/ReplayWebhookTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\RawPayload;
use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature;
use Proxynth\Larawebhook\Processing\Application\Commands\ReplayWebhookCommand;
use Proxynth\Larawebhook\Processing\Application\DTOs\ReplayableWebhook;
use Proxynth\Larawebhook\Processing\Application\Data\ReplayableWebhook;
use Proxynth\Larawebhook\Processing\Application\Exceptions\ReplayWebhookNotAllowed;
use Proxynth\Larawebhook\Processing\Application\Ports\ReplayableWebhookRepository;
use Proxynth\Larawebhook\Processing\Application\Results\ReplayWebhookResult;
Expand Down Expand Up @@ -287,3 +287,21 @@ public function record(RecordWebhookLogCommand $command): WebhookLog
signature: Signature::fromString('sha256=invalid'),
)))->toThrow(WebhookException::class, 'No secret configured for service: github');
});

it('throws when webhook event state does not allow replay', function () {
app()->instance(ReplayableWebhookRepository::class, new class implements ReplayableWebhookRepository
{
public function findReplayableById(int|string $id): ReplayableWebhook
{
return replayableWebhook(
id: $id,
status: 'processing',
);
}
});

expect(fn () => app(ReplayWebhook::class)->handle(new ReplayWebhookCommand(
webhookLogId: 1,
signature: Signature::fromString('sha256=valid'),
)))->toThrow(ReplayWebhookNotAllowed::class);
});
63 changes: 63 additions & 0 deletions tests/Unit/Processing/Application/UseCases/RetryWebhookTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
use Proxynth\Larawebhook\Audit\Domain\Events\WebhookLogged;
use Proxynth\Larawebhook\Audit\Infrastructure\Laravel\Persistence\Models\WebhookLog;
use Proxynth\Larawebhook\Exceptions\WebhookException;
use Proxynth\Larawebhook\Ingestion\Domain\ValueObjects\Signature;
use Proxynth\Larawebhook\Processing\Application\Commands\RetryWebhookCommand;
use Proxynth\Larawebhook\Processing\Application\Data\RetryPolicy;
use Proxynth\Larawebhook\Processing\Application\Ports\RetryPolicyResolver;
use Proxynth\Larawebhook\Processing\Application\UseCases\RetryWebhook;
use Proxynth\Larawebhook\Processing\Domain\Events\WebhookProcessingFailed;
use Proxynth\Larawebhook\Processing\Domain\Exceptions\InvalidWebhookState;
use Proxynth\Larawebhook\Shared\Domain\Enums\WebhookService;
use Proxynth\Larawebhook\Tests\Fakes\Processing\FakeRetryPolicyResolver;

Expand Down Expand Up @@ -151,3 +153,64 @@
->and($result->nextAttempt)->toBe(2)
->and($result->delaySeconds)->toBe(42);
});

it('records a successful retry through webhook event transitions', function () {
$result = app(RetryWebhook::class)->handle(new RetryWebhookCommand(
payload: '{"action":"opened"}',
signature: incomingSignature(githubSignature('{"action":"opened"}')->value()),
service: WebhookService::Github->value,
event: 'opened',
secret: 'github_secret',
attempt: 1,
externalId: 'delivery_123',
idempotencyKey: 'delivery_123',
));

expect($result->isSuccess())->toBeTrue();

$log = WebhookLog::query()->latest('id')->first();

expect($log->status)->toBe('success')
->and($log->service)->toBe('github')
->and($log->event)->toBe('opened')
->and($log->attempt)->toBe(1)
->and($log->external_id)->toBeNull()
->and($log->idempotency_key)->toBeNull();
});

it('records a failed retry through webhook event transitions', function () {
$result = app(RetryWebhook::class)->handle(new RetryWebhookCommand(
payload: '{"action":"opened"}',
signature: Signature::fromString('sha256=invalid'),
service: WebhookService::Github->value,
event: 'opened',
secret: 'github_secret',
attempt: 1,
externalId: 'delivery_123',
idempotencyKey: 'delivery_123',
));

expect($result->isFailed())->toBeTrue()
->and($result->shouldRetry)->toBeTrue()
->and($result->nextAttempt)->toBe(2);

$log = WebhookLog::query()->latest('id')->first();

expect($log->status)->toBe('failed')
->and($log->attempt)->toBe(1)
->and($log->external_id)->toBeNull()
->and($log->idempotency_key)->toBeNull();
});

it('requires idempotency key to mark a retry as processed', function () {
expect(fn () => app(RetryWebhook::class)->handle(new RetryWebhookCommand(
payload: '{"action":"opened"}',
signature: githubSignature('{"action":"opened"}'),
service: WebhookService::Github->value,
event: 'opened',
secret: 'github_secret',
attempt: 1,
externalId: 'delivery_123',
idempotencyKey: null,
)))->toThrow(InvalidWebhookState::class);
});
Loading