Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk-php): map a silent gateway on the stream handler to a timeout
Yudhi Armyndharis39f6c1c8f40e
diff --git a/sdk/php/README.md b/sdk/php/README.mdindex de50f0223..ca539c4d7 100644--- a/sdk/php/README.md+++ b/sdk/php/README.md@@ -79,13 +79,15 @@ may still have been applied, so re-read the state before repeating it. In a routforward that fails before reaching the owner node answers 503, one that fails after the requestreached it answers 502 or 504, and a 503 from the owner itself is relayed unchanged.-Timeouts differ on Guzzle's stream handler, which Guzzle uses on a host without `ext-curl` (the cURL-handler is unaffected). A gateway that stays silent past the timeout surfaces as a Guzzle exception-instead of `OpenWATimeoutException`: before the response headers on either Guzzle major-(`ConnectException` on Guzzle 7, `RequestException` on Guzzle 8) and, on Guzzle 7, in the middle of the-body. On Guzzle 7 a `timeout` of `0` does not turn the wait for the response headers off either: PHP's-`default_socket_timeout` (60 seconds by default) still ends it. Catch `GuzzleHttp\Exception\TransferException`-as well as `OpenWATimeoutException` if the application must handle a silent gateway on such a host.+Guzzle's stream handler, which Guzzle uses on a host without `ext-curl`, throws a plain Guzzle exception+when a gateway stays silent past the timeout, before the response headers on either Guzzle major and, on+Guzzle 7, in the middle of the body. The SDK turns such a failure into `OpenWATimeoutException` when it has no+response and lasted at least the whole `timeout`, so a failure of that length from another cause, such as a+slow name-resolution error, is reported as a timeout too. A `timeout` of `0` has no bound to compare with, and+on Guzzle 7 the wait for the response headers is still ended by PHP's `default_socket_timeout` (60 seconds by+default), which surfaces as a `GuzzleHttp\Exception\ConnectException`: catch+`GuzzleHttp\Exception\TransferException` as well as `OpenWATimeoutException` if the application sets+`timeout` to `0` on such a host.```phpuse OpenWA\Exceptions\OpenWANotFoundException;diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.phpindex aea208508..a2af599d2 100644--- a/sdk/php/src/Http/HttpExecutor.php+++ b/sdk/php/src/Http/HttpExecutor.php@@ -8,6 +8,8 @@ use GuzzleHttp\ClientInterface;use GuzzleHttp\Exception\ConnectException;use GuzzleHttp\Exception\ConnectTimeoutException;use GuzzleHttp\Exception\NetworkTimeoutException;+use GuzzleHttp\Exception\RequestException;+use GuzzleHttp\Exception\ResponseException;use GuzzleHttp\Exception\ResponseTimeoutException;use OpenWA\Exceptions\OpenWAApiException;use OpenWA\Exceptions\OpenWAException;@@ -262,6 +264,7 @@ class HttpExecutor$options['json'] = $body;}+ $started = hrtime(true);try {$response = $this->http->request($method, $url, $options);} catch (ConnectTimeoutException | NetworkTimeoutException | ResponseTimeoutException $e) {@@ -270,7 +273,12 @@ class HttpExecutor// Guzzle 7 exposes cURL errno 28 in the context; custom transports may only supply a message.$errno = method_exists($e, 'getHandlerContext') ? ($e->getHandlerContext()['errno'] ?? null) : null;$isTimeout = $errno === 28 || str_contains($e->getMessage(), 'timed out');- if ($isTimeout) {+ if ($isTimeout || $this->failedAfterTimeout($e, $started)) {+ throw new OpenWATimeoutException($this->timeout);+ }+ throw $e;+ } catch (RequestException $e) {+ if ($this->failedAfterTimeout($e, $started)) {throw new OpenWATimeoutException($this->timeout);}throw $e;@@ -286,6 +294,22 @@ class HttpExecutorreturn $response;}+ /**+ * Guzzle's stream handler (a host without ext-curl) reports a gateway that stays silent past the timeout+ * as a plain ConnectException (before the headers, Guzzle 7) or a RequestException without a response+ * (before the headers on Guzzle 8, in the middle of the body on Guzzle 7): no errno, no timeout text.+ * Such a failure is a timeout when it took at least the whole timeout. cURL failures carry their own+ * "cURL error" text and are left alone, and a timeout of 0 (no bound) never matches.+ */+ private function failedAfterTimeout(\Throwable $e, int $startedNs): bool+ {+ return $this->timeout > 0+ && (hrtime(true) - $startedNs) / 1e9 >= $this->timeout+ && !str_starts_with($e->getMessage(), 'cURL error')+ && !$e instanceof ResponseException+ && !(method_exists($e, 'hasResponse') && $e->hasResponse());+ }+private function buildApiException(ResponseInterface $response, string $method, string $path): OpenWAApiException{$status = $response->getStatusCode();diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.phpindex b630ea56a..795e8809a 100644--- a/sdk/php/tests/ClientTest.php+++ b/sdk/php/tests/ClientTest.php@@ -640,6 +640,99 @@ class ClientTest extends TestCase}}+ /**+ * Guzzle's stream handler (a host without ext-curl) reports a gateway that stays silent past the timeout+ * as a ConnectException (before the headers, Guzzle 7) or a RequestException without a response (before+ * the headers on Guzzle 8, in the middle of the body on Guzzle 7), with no errno and no timeout text.+ *+ * @dataProvider silentGatewayFailures+ */+ public function testAResponseLessFailureAfterTheWholeTimeoutMapsToTimeoutException(\Throwable $failure, bool $binary): void+ {+ $client = self::clientWhoseHandlerFails($failure, 0.05, 0.08);++ try {+ $binary ? $client->status->media('s', 'status') : $client->sessions->list();+ $this->fail('Expected a timeout exception');+ } catch (OpenWATimeoutException $e) {+ $this->assertSame(0.05, $e->getTimeout());+ }+ }++ /** @dataProvider silentGatewayFailures */+ public function testTheSameFailureBeforeTheTimeoutIsNotATimeout(\Throwable $failure, bool $binary): void+ {+ $client = self::clientWhoseHandlerFails($failure, 30.0, 0.0);++ try {+ $binary ? $client->status->media('s', 'status') : $client->sessions->list();+ $this->fail('Expected the transport exception');+ } catch (\GuzzleHttp\Exception\TransferException $e) {+ $this->assertSame($failure, $e);+ }+ }++ public static function silentGatewayFailures(): array+ {+ $request = new \GuzzleHttp\Psr7\Request('GET', '/api/sessions');+ $failures = [+ 'connect failure' => new \GuzzleHttp\Exception\ConnectException('Connection refused for URI http://localhost:2785/api/sessions', $request),+ 'request failure' => new \GuzzleHttp\Exception\RequestException('Unable to read from stream', $request),+ ];+ $cases = [];+ foreach ($failures as $name => $failure) {+ $cases[$name . ' JSON'] = [$failure, false];+ $cases[$name . ' binary'] = [$failure, true];+ }+ return $cases;+ }++ public function testAFailureThatIsNotASilentGatewayStaysUnmappedEvenAfterTheTimeout(): void+ {+ $request = new \GuzzleHttp\Psr7\Request('GET', '/api/sessions');+ $failures = [+ // a response was received, so the gateway was not silent+ 'with a response' => new \GuzzleHttp\Exception\ServerException('Server error', $request, new \GuzzleHttp\Psr7\Response(502)),+ // cURL reports its own errno, which decides the mapping (28 above, anything else here)+ 'cURL error' => new \GuzzleHttp\Exception\ConnectException('cURL error 6: Could not resolve host: gateway.invalid', $request),+ ];+ foreach ($failures as $name => $failure) {+ try {+ self::clientWhoseHandlerFails($failure, 0.05, 0.08)->sessions->list();+ $this->fail("Expected the transport exception ({$name})");+ } catch (\GuzzleHttp\Exception\TransferException $e) {+ $this->assertSame($failure, $e, $name);+ }+ }+ }++ public function testNoTimeoutMeansNoFailureIsMappedToOne(): void+ {+ $failure = new \GuzzleHttp\Exception\ConnectException('Connection refused', new \GuzzleHttp\Psr7\Request('GET', '/api/sessions'));++ try {+ self::clientWhoseHandlerFails($failure, 0.0, 0.01)->sessions->list();+ $this->fail('Expected the transport exception');+ } catch (\GuzzleHttp\Exception\ConnectException $e) {+ $this->assertSame($failure, $e);+ }+ }++ private static function clientWhoseHandlerFails(\Throwable $failure, float $timeout, float $afterSeconds): \OpenWA\Client+ {+ $handler = static function () use ($failure, $afterSeconds) {+ usleep((int) ($afterSeconds * 1e6));+ return \GuzzleHttp\Promise\Create::rejectionFor($failure);+ };++ return new \OpenWA\Client([+ 'baseUrl' => 'http://localhost:2785',+ 'apiKey' => 'k',+ 'timeout' => $timeout,+ 'httpClient' => new \GuzzleHttp\Client(['handler' => \GuzzleHttp\HandlerStack::create($handler)]),+ ]);+ }+public function testTimedOutMessageWithoutErrnoMapsToTimeoutException(): void{// Transports that leave the handler context empty (e.g. the stream handler)