Skip to content

Commit 0e5f242

Browse files
committed
Make requests less resilient, but faster
1 parent 856103d commit 0e5f242

2 files changed

Lines changed: 11 additions & 24 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
* Use IP address instead of hostname for the Google Metadata service to avoid slow requests when not on Compute Engine
66
* The availability status of the Metadata Service is now cached to save requests
7+
* Configured the underlying HTTP client to be less resilient, but faster
78

89
## 1.0.1 - 2018-07-28
910

src/GcpMetadata.php

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,9 @@
44

55
namespace Kreait;
66

7-
use function GuzzleHttp\choose_handler;
87
use GuzzleHttp\Client;
98
use GuzzleHttp\ClientInterface;
109
use GuzzleHttp\Exception\RequestException;
11-
use GuzzleHttp\HandlerStack;
12-
use GuzzleHttp\Middleware;
1310
use Kreait\GcpMetadata\Error;
1411
use Psr\Http\Message\ResponseInterface;
1512

@@ -31,7 +28,15 @@ class GcpMetadata
3128

3229
public function __construct(ClientInterface $client = null)
3330
{
34-
$this->client = $client;
31+
$this->client = $client ?? $this->createClient();
32+
}
33+
34+
private function createClient(): Client
35+
{
36+
return new Client([
37+
'connect_timeout' => 1.0, // Default is 0 = indefinitely
38+
'timeout' => 1.0 // Default is 0 = indefinitely
39+
]);
3540
}
3641

3742
public function isAvailable(): bool
@@ -70,7 +75,7 @@ private function request(string $type, string $property = '', array $params = []
7075
];
7176

7277
try {
73-
$response = $this->client()->request('GET', $url, $options);
78+
$response = $this->client->request('GET', $url, $options);
7479

7580
$this->verifyHttpStatus($response);
7681
$this->verifyHeaders($response);
@@ -112,23 +117,4 @@ private function parseResponse(ResponseInterface $response)
112117

113118
return $lines;
114119
}
115-
116-
private function client(): ClientInterface
117-
{
118-
if (!$this->client) {
119-
$decider = function ($retries) {
120-
return $retries < 3;
121-
};
122-
123-
$stack = new HandlerStack(choose_handler());
124-
$stack->push(Middleware::redirect(), 'allow_redirects');
125-
$stack->push(Middleware::retry($decider));
126-
127-
$this->client = new Client([
128-
'handler' => $stack,
129-
]);
130-
}
131-
132-
return $this->client;
133-
}
134120
}

0 commit comments

Comments
 (0)