Skip to content

Commit

Permalink
Merge pull request #1004 from spiral/feature/retry-without-attribute
Browse files Browse the repository at this point in the history
Add the ability to use RetryableException without the RetryPolicy attribute
  • Loading branch information
butschster authored Oct 18, 2023
2 parents 0936229 + 517f358 commit 13cd72c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/Queue/src/Interceptor/Consume/RetryPolicyInterceptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,12 @@ public function process(string $controller, string $action, array $parameters, C
try {
return $core->callAction($controller, $action, $parameters);
} catch (\Throwable $e) {
$attribute = $this->reader->firstClassMetadata(new \ReflectionClass($controller), Attribute::class);
if ($attribute === null) {
$policy = $this->getRetryPolicy($e, new \ReflectionClass($controller));

if ($policy === null) {
throw $e;
}

$policy = $this->getRetryPolicy($e, $attribute);

$headers = $parameters['headers'] ?? [];
$attempts = (int)($headers['attempts'][0] ?? 0);

Expand All @@ -49,14 +48,16 @@ public function process(string $controller, string $action, array $parameters, C
}
}

private function getRetryPolicy(\Throwable $exception, Attribute $attribute): RetryPolicy
private function getRetryPolicy(\Throwable $exception, \ReflectionClass $handler): ?RetryPolicy
{
$attribute = $this->reader->firstClassMetadata($handler, Attribute::class);

if ($exception instanceof JobException && $exception->getPrevious() !== null) {
$exception = $exception->getPrevious();
}

$policy = $exception instanceof RetryableExceptionInterface ? $exception->getRetryPolicy() : null;

return $policy ?? $attribute->getRetryPolicy();
return $policy ?? $attribute?->getRetryPolicy() ?? null;
}
}
20 changes: 20 additions & 0 deletions src/Queue/tests/Interceptor/Consume/RetryPolicyInterceptorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,26 @@ public function testWithDefaultRetryPolicy(): void
}
}

public function testWithoutRetryPolicyAttribute(): void
{
$this->reader->expects($this->once())->method('firstClassMetadata')->willReturn(null);

$this->core
->expects($this->once())
->method('callAction')
->with(self::class, 'bar', [])
->willThrowException(new TestRetryException(
retryPolicy: new \Spiral\Queue\RetryPolicy(maxAttempts: 2, delay: 4)
));

try {
$this->interceptor->process(self::class, 'bar', [], $this->core);
} catch (RetryException $e) {
$this->assertSame(4, $e->getOptions()->getDelay());
$this->assertSame(['attempts' => ['1']], $e->getOptions()->getHeaders());
}
}

public function testWithRetryPolicyInAttribute(): void
{
$this->reader->expects($this->once())->method('firstClassMetadata')->willReturn(
Expand Down

0 comments on commit 13cd72c

Please sign in to comment.