googleapis / google-cloud-php

Google Cloud Client Library for PHP
https://cloud.google.com/php/docs/reference
Apache License 2.0
1.09k stars 436 forks source link

fix: [PubSub] Prevent fatal error when using emulator without grpc #7588

Closed kynx closed 2 months ago

kynx commented 2 months ago

This fixes https://github.com/googleapis/google-cloud-php/issues/7187

Unfortunately using the PubSub emulator is still not entirely straightforward with REST: the https schema is hardcoded in Google\ApiCore\RequestBuilder::buildUri(), probably for very good reason!

I have managed to get it to work by supplying a modified httpHandler:

// double the # of characters before truncation by default
        $bodySummarizer = new BodySummarizer(240);
        $stack = HandlerStack::create();
        $stack->remove('http_errors');
        $stack->unshift(Middleware::httpErrors($bodySummarizer), 'http_errors');
        $stack->push(Middleware::mapRequest(static function (RequestInterface $request) {
            $uri = $request->getUri();
            return $request->withUri($uri->withScheme('http')); // convert https -> http for emulator
        }));
        $client = new Client(['handler' => $stack]);

        $pubSubClient = new PubSubClient([
            'projectId'         => 'emulator-project',
            'credentialsConfig' => [
                'keyFile' => [
                    "client_id"     => "fake-fake-fake.apps.googleusercontent.com",
                    "client_secret" => "fake-fake-fake",
                    "refresh_token" => "fake-fake-fake",
                    "type"          => "authorized_user",
                ],
            ],
            'transportConfig' => [
                'rest' => [
                    'httpHandler' => [HttpHandlerFactory::build($client), 'async'],
                ],
            ],
        ]);
google-cla[bot] commented 2 months ago

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

kynx commented 2 months ago

@bshaffer Thanks for adding this to the next release! Sorry about the CS: CONTRIBUTING.md seems a bit out of data - the composer style script mentioned there no longer exists.

I'll probably forget everything about this within a month. If I wanted to add the example above to the online docs, where would I make a PR?