Skip to content

Commit

Permalink
Add inactivity timeout to TO interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
Nek- committed May 14, 2024
1 parent 483df9a commit d9dbf89
Show file tree
Hide file tree
Showing 3 changed files with 38 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
5 changes: 4 additions & 1 deletion src/Interceptor/SetRequestTimeout.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ public function __construct(
float $tcpConnectTimeout = 10,
float $tlsHandshakeTimeout = 10,
float $transferTimeout = 10,
float $inactivityTimeout = 10,
) {
parent::__construct(static function (Request $request) use (
$tcpConnectTimeout,
$tlsHandshakeTimeout,
$transferTimeout
$transferTimeout,
$inactivityTimeout
) {
$request->setTcpConnectTimeout($tcpConnectTimeout);
$request->setTlsHandshakeTimeout($tlsHandshakeTimeout);
$request->setTransferTimeout($transferTimeout);
$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 d9dbf89

Please sign in to comment.