Skip to content

Commit

Permalink
Add inactivity timeout to SetRequestTimeout interceptor (#362)
Browse files Browse the repository at this point in the history
Co-authored-by: Aaron Piotrowski <[email protected]>
  • Loading branch information
Nek- and trowski authored Jun 2, 2024
1 parent dd0b75e commit d0383fa
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ The big disadvantage of network interceptors is that they have to be rather quic
- `SetRequestHeaderIfUnset`
- `SetResponseHeader`
- `SetResponseHeaderIfUnset`
- `SetRequestTimeout`
- [`CookieHandler`](https://github.com/amphp/http-client-cookies)
- [`PrivateCache`](https://github.com/amphp/http-client-cache)

Expand Down
8 changes: 7 additions & 1 deletion src/Interceptor/SetRequestTimeout.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,22 @@ public function __construct(
float $tcpConnectTimeout = 10,
float $tlsHandshakeTimeout = 10,
float $transferTimeout = 10,
?float $inactivityTimeout = null,
) {
parent::__construct(static function (Request $request) use (
$tcpConnectTimeout,
$tlsHandshakeTimeout,
$transferTimeout
$transferTimeout,
$inactivityTimeout
) {
$request->setTcpConnectTimeout($tcpConnectTimeout);
$request->setTlsHandshakeTimeout($tlsHandshakeTimeout);
$request->setTransferTimeout($transferTimeout);

if (null !== $inactivityTimeout) {
$request->setInactivityTimeout($inactivityTimeout);
}

return $request;
});
}
Expand Down
33 changes: 33 additions & 0 deletions test/TimeoutTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,4 +242,37 @@ public function testTimeoutDuringTlsEnableInterceptor(): void
$server->close();
}
}

public function testTimeoutDuringInactivity(): void
{
$server = listen("tcp://127.0.0.1:0");

EventLoop::queue(static function () use ($server): void {
while ($client = $server->accept()) {
$client->write("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n.");

EventLoop::unreference(EventLoop::delay(3, static function () use ($client): void {
$client->close();
}));
}
});

$this->setTimeout(2);

try {
$uri = "http://" . $server->getAddress() . "/";

$request = new Request($uri);

$client = new InterceptedHttpClient(new PooledHttpClient, new SetRequestTimeout(10, 10, 10, 1), []);
$response = $client->request($request, new NullCancellation);

$this->expectException(StreamException::class);
$this->expectExceptionMessage("HTTP response did not complete: Inactivity timeout exceeded, more than 1 seconds elapsed from last data received");

$response->getBody()->buffer();
} finally {
$server->close();
}
}
}

0 comments on commit d0383fa

Please sign in to comment.