Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk-php): buffer the response inside the transport guard
Yudhi Armyndharis67f625a40fac
diff --git a/sdk/php/README.md b/sdk/php/README.mdindex 9d45ab46e..864de687c 100644--- a/sdk/php/README.md+++ b/sdk/php/README.md@@ -53,6 +53,8 @@ $client = new Client([The SDK `timeout` (30 seconds by default) applies to every request, including those sent through an injected client, and overrides that client's own `timeout`. On Guzzle 8 it is also sent as `read_timeout`, the idle bound of Guzzle's stream handler (the one in use when ext-curl is missing, or when you inject a `StreamHandler`), so it replaces a `read_timeout` set on the injected client, and `0` removes that bound. The SDK has no separate idle-timeout setting: a stricter idle bound means a lower `timeout`, which also limits the whole call except on Guzzle 7's stream handler, where it bounds each wait instead (see [Errors](#errors)). cURL handlers ignore `read_timeout`, and Guzzle 7 leaves the injected client's value alone.+Responses are buffered even when an injected client sets `stream` to `true`, so JSON, binary and error bodies share the same read-failure handling.+The optional `defaultHeaders` map accepts strings, scalar values, null, and non-empty lists of those values. Numbers, booleans, and null are converted to text. An empty list is rejected by header name before any request is sent because Guzzle 8 cannot represent a header with zero values. Use `''` for an empty header value.## Messagingdiff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.phpindex 70a9ad9a4..43b6d7403 100644--- a/sdk/php/src/Http/HttpExecutor.php+++ b/sdk/php/src/Http/HttpExecutor.php@@ -225,6 +225,8 @@ class HttpExecutor$secrets = (self::$secrets ?? new \WeakMap())[$this] ?? ['apiKey' => '', 'headers' => []];$options = ['http_errors' => false,+ // These APIs consume the whole body, so read failures must occur inside the transport catch.+ 'stream' => false,// Per-request options override injected Guzzle client defaults, so the SDK's configured// timeout is enforced consistently on both default and caller-supplied clients.'timeout' => $this->timeout,diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.phpindex 93df47ed2..e4f8007ec 100644--- a/sdk/php/tests/ClientTest.php+++ b/sdk/php/tests/ClientTest.php@@ -739,6 +739,125 @@ class ClientTest extends TestCase}}+ /** @dataProvider responseBodyKinds */+ public function testAnInjectedStreamingClientClassifiesBodyTimeouts(string $kind): void+ {+ $this->withNativeResponse($kind, false, function (\OpenWA\Client $client) use ($kind): void {+ if ($kind === 'error') {+ try {+ $client->request('GET', '/api/anything');+ $this->fail('Expected the complete 503 response');+ } catch (OpenWAServiceUnavailableException $error) {+ $this->assertSame(503, $error->getStatus());+ $this->assertSame('fixture failure', $error->getBody()['message']);+ }+ } elseif ($kind === 'binary') {+ $this->assertSame(+ ['data' => "\0PNG_fixture", 'contentType' => 'application/octet-stream'],+ $client->status->media('s', 'item')+ );+ } else {+ $this->assertSame(['ok' => true], $client->request('GET', '/api/anything'));+ }+ });++ $this->withNativeResponse($kind, true, function (\OpenWA\Client $client) use ($kind): void {+ try {+ $kind === 'binary' ? $client->status->media('s', 'item') : $client->request('GET', '/api/anything');+ $this->fail('Expected a body timeout, not partial response data');+ } catch (OpenWATimeoutException $error) {+ $this->assertSame(0.1, $error->getTimeout());+ }+ });+ }++ public static function responseBodyKinds(): array+ {+ return ['JSON' => ['json'], 'binary' => ['binary'], 'error' => ['error']];+ }++ private function withNativeResponse(string $kind, bool $stall, callable $check): void+ {+ $server = <<<'PHP'+$socket = stream_socket_server('tcp://127.0.0.1:0', $errno, $error);+if ($socket === false) { exit(2); }+fwrite(STDOUT, stream_socket_get_name($socket, false) . "\n");+fflush(STDOUT);+$connection = stream_socket_accept($socket, 2.0);+if ($connection === false) { fclose($socket); exit(3); }+stream_set_timeout($connection, 1);+$request = '';+while (!str_contains($request, "\r\n\r\n") && strlen($request) < 16_384) {+ $part = fread($connection, 1024);+ if ($part === false || $part === '') { break; }+ $request .= $part;+}+if (!str_contains($request, "\r\n\r\n")) { fclose($connection); fclose($socket); exit(4); }+$body = match ($argv[1]) {+ 'binary' => "\0PNG_fixture",+ 'error' => '{"statusCode":503,"message":"fixture failure","error":"Service Unavailable"}',+ default => '{"ok":true}',+};+$status = $argv[1] === 'error' ? '503 Service Unavailable' : '200 OK';+$type = $argv[1] === 'binary' ? 'application/octet-stream' : 'application/json';+@fwrite($connection, "HTTP/1.1 {$status}\r\nContent-Type: {$type}\r\nContent-Length: " . strlen($body) . "\r\nConnection: close\r\n\r\n");+@fwrite($connection, substr($body, 0, 1));+fflush($connection);+if ($argv[2] === '1') { usleep(500_000); }+@fwrite($connection, substr($body, 1));+fclose($connection);+fclose($socket);+PHP;+ $process = proc_open(+ [PHP_BINARY, '-n', '-r', $server, $kind, $stall ? '1' : '0'],+ [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],+ $pipes,+ null,+ ['TZ' => 'UTC']+ );+ $this->assertIsResource($process);+ stream_set_blocking($pipes[1], false);+ stream_set_blocking($pipes[2], false);+ try {+ $address = '';+ $deadline = hrtime(true) + 2_000_000_000;+ while (!str_contains($address, "\n") && hrtime(true) < $deadline) {+ $address .= (string) fread($pipes[1], 256);+ $this->assertLessThan(512, strlen($address));+ usleep(2_000);+ }+ $this->assertMatchesRegularExpression('/\A127\.0\.0\.1:[1-9][0-9]{0,4}\n\z/', $address);+ $http = new \GuzzleHttp\Client([+ 'handler' => \GuzzleHttp\HandlerStack::create(new \GuzzleHttp\Handler\StreamHandler()),+ 'stream' => true,+ ]);+ $check(new \OpenWA\Client([+ 'baseUrl' => 'http://' . trim($address),+ 'apiKey' => 'fixture-key',+ 'timeout' => $stall ? 0.1 : 1.0,+ 'httpClient' => $http,+ ]));+ } finally {+ $deadline = hrtime(true) + 1_000_000_000;+ while (proc_get_status($process)['running'] && hrtime(true) < $deadline) {+ usleep(5_000);+ }+ if (proc_get_status($process)['running']) {+ proc_terminate($process);+ usleep(30_000);+ if (proc_get_status($process)['running']) {+ proc_terminate($process, 9);+ }+ }+ $serverError = (string) stream_get_contents($pipes[2], 8192);+ foreach ($pipes as $pipe) {+ fclose($pipe);+ }+ proc_close($process);+ }+ $this->assertSame('', $serverError);+ }+private static function clientWhoseHandlerFails(\Throwable $failure, float $timeout, float $afterSeconds): \OpenWA\Client{$handler = static function () use ($failure, $afterSeconds) {