Skip to content

Commit 73681de

Browse files
authored
Merge pull request #130 from tharropoulos/fix/retry-5xx-responses
fix(api-call): retry 5xx responses from the default http client
2 parents bcdb36c + ed41d0f commit 73681de

2 files changed

Lines changed: 100 additions & 4 deletions

File tree

‎src/ApiCall.php‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -309,11 +309,16 @@ private function makeRequest(string $method, string $endPoint, bool $asJson, arr
309309
// For network errors, set exception and continue to retry logic
310310
$this->setNodeHealthCheck($node, false);
311311
$lastException = $exception;
312-
} catch (Exception $exception) {
313-
if ($exception instanceof TypesenseClientError) {
312+
} catch (TypesenseClientError $exception) {
313+
// For 4xx errors, and errors without an HTTP status, don't retry - throw immediately
314+
if ($exception->getCode() < 500) {
314315
throw $exception;
315316
}
316-
317+
318+
// For 5xx errors, set exception and continue to retry logic
319+
$this->setNodeHealthCheck($node, false);
320+
$lastException = $exception;
321+
} catch (Exception $exception) {
317322
$this->setNodeHealthCheck($node, false);
318323
$lastException = $exception;
319324
}

‎tests/Feature/ApiCallRetryTest.php‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Typesense\Exceptions\ServerError;
99
use Typesense\Exceptions\RequestMalformed;
1010
use Typesense\Exceptions\ObjectNotFound;
11+
use Typesense\Exceptions\ServiceUnavailable;
1112
use Http\Client\Exception\HttpException;
1213
use Http\Client\Exception\TransferException;
1314
use JsonException;
@@ -54,7 +55,8 @@ public function testExceptionsCarryTheHttpStatusCode(): void
5455
public function testThrownExceptionsCarryTheStatusCodeAndTheServerMessage(): void
5556
{
5657
$httpClient = $this->createMock(ClientInterface::class);
57-
$httpClient->method('sendRequest')
58+
$httpClient->expects($this->once())
59+
->method('sendRequest')
5860
->willReturn($this->createJsonResponseMock('{"message": "Not found."}', 404));
5961

6062
$config = new Configuration([
@@ -632,4 +634,93 @@ public function testSearchSurfacesATimeoutWhenEveryAttemptReturns408(): void
632634

633635
$client->collections['books']->documents->search(['q' => '*', 'query_by' => 'title']);
634636
}
637+
638+
public function testThrowsTheLastErrorWhenEveryAttemptReturns5xx(): void
639+
{
640+
$expectedExceptions = [
641+
500 => ServerError::class,
642+
502 => TypesenseClientError::class,
643+
503 => ServiceUnavailable::class,
644+
];
645+
646+
foreach ($expectedExceptions as $statusCode => $expectedException) {
647+
$callCount = 0;
648+
649+
$httpClient = $this->createMock(ClientInterface::class);
650+
$httpClient->method('sendRequest')
651+
->willReturnCallback(function () use (&$callCount, $statusCode) {
652+
$callCount++;
653+
654+
return $this->createJsonResponseMock(
655+
'{"message": "Attempt ' . $callCount . ' failed."}',
656+
$statusCode
657+
);
658+
});
659+
660+
$config = new Configuration([
661+
'api_key' => 'test-key',
662+
'nodes' => [
663+
['host' => 'node1', 'port' => 8108, 'protocol' => 'http'],
664+
['host' => 'node2', 'port' => 8108, 'protocol' => 'http']
665+
],
666+
'num_retries' => 2,
667+
'retry_interval_seconds' => 0.001,
668+
'client' => $httpClient
669+
]);
670+
671+
$apiCall = new ApiCall($config);
672+
673+
try {
674+
$apiCall->get('/test', []);
675+
$this->fail("Expected a {$expectedException} for HTTP {$statusCode}.");
676+
} catch (TypesenseClientError $exception) {
677+
$this->assertSame($expectedException, get_class($exception));
678+
$this->assertSame($statusCode, $exception->getCode());
679+
$this->assertSame('Attempt 3 failed.', $exception->getMessage());
680+
}
681+
682+
$this->assertSame(3, $callCount);
683+
}
684+
}
685+
686+
public function test5xxResponseMarksTheNodeUnhealthy(): void
687+
{
688+
$requestedHosts = [];
689+
690+
$httpClient = $this->createMock(ClientInterface::class);
691+
$httpClient->method('sendRequest')
692+
->willReturnCallback(function (RequestInterface $request) use (&$requestedHosts) {
693+
$requestedHosts[] = $request->getUri()->getHost();
694+
695+
if ($request->getUri()->getHost() === 'node2') {
696+
return $this->createJsonResponseMock('{"message": "Not Ready or Lagging"}', 503);
697+
}
698+
699+
return $this->createJsonResponseMock('{"success": true}');
700+
});
701+
702+
$config = new Configuration([
703+
'api_key' => 'test-key',
704+
'nodes' => [
705+
['host' => 'node1', 'port' => 8108, 'protocol' => 'http'],
706+
['host' => 'node2', 'port' => 8108, 'protocol' => 'http']
707+
],
708+
'num_retries' => 2,
709+
'retry_interval_seconds' => 0.001,
710+
'randomize_nodes' => false,
711+
'client' => $httpClient
712+
]);
713+
714+
$apiCall = new ApiCall($config);
715+
716+
// Nodes are picked round-robin, so the first request starts on node2
717+
$this->assertEquals(['success' => true], $apiCall->get('/test', []));
718+
$this->assertTrue($config->getNodes()[0]->isHealthy());
719+
$this->assertFalse($config->getNodes()[1]->isHealthy());
720+
721+
// node2 is next in line, but is skipped until its health check is due
722+
$this->assertEquals(['success' => true], $apiCall->get('/test', []));
723+
724+
$this->assertSame(['node2', 'node1', 'node1'], $requestedHosts);
725+
}
635726
}

0 commit comments

Comments
 (0)