44
55namespace Kreait ;
66
7- use function GuzzleHttp \choose_handler ;
87use GuzzleHttp \Client ;
98use GuzzleHttp \ClientInterface ;
109use GuzzleHttp \Exception \RequestException ;
11- use GuzzleHttp \HandlerStack ;
12- use GuzzleHttp \Middleware ;
1310use Kreait \GcpMetadata \Error ;
1411use 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