Search code examples
httpgoogle-app-enginephp-7gcloudgoogle-cloud-tasks

Do I need to close http CloudTasksClient in Google Cloud?


I'm setting up Google Cloud Tasks with PHP via http and can't understand do I need to close the connection or not?

There are two places I'm looking:

1) Docs

$client = new CloudTasksClient();
$queueName = $client->queueName($projectId, $locationId, $queueId);

$httpRequest = new HttpRequest();
$httpRequest->setUrl($url);
$httpRequest->setHttpMethod(HttpMethod::POST);
$task = new Task();
$task->setHttpRequest($httpRequest);
$response = $client->createTask($queueName, $task);

2) Gcloud Client Library

$cloudTasksClient = new CloudTasksClient();
try {
    $formattedParent = $cloudTasksClient->queueName('[PROJECT]', '[LOCATION]', '[QUEUE]');
    $task = new Task();
    $response = $cloudTasksClient->createTask($formattedParent, $task);
} finally {
    $cloudTasksClient->close();
}

My version:

$client = new CloudTasksClient();
try{
    $queueName = $client->queueName($projectId, $locationId, $queueId);
    $httpRequest = new HttpRequest();
    $httpRequest->setUrl($url);
    $httpRequest->setHttpMethod(HttpMethod::POST);
    $task = new Task();
    $task->setHttpRequest($httpRequest);
    $response = $client->createTask($queueName, $task);
}
catch(Exception $e){
    $this->logError("Error");
}
finally {
    $client->close();  <-- ???????? ( Do I need this )
}

I'm using App Engine, if it makes any difference.


Solution

  • Typically a close() statement is to gracefully wrap up the connection resource, such as flushing pending data and freeing memory.

    In review of the code, close() seems to do the following:

    • Gracefully clean up in-progress RPC calls
    • Release some memory resources
    • Does not currently appear to have an effect on REST calls
    • Create a space for future, Cloud Tasks-specific teardown activities

    As a best practice, it should be done. However, if your PHP script is pretty focused on the Cloud Tasks interaction it appears to have limited impact.

    Traversing the code

    Looking at the Cloud Tasks client code, it appears the close method is defined in the GapicClientTrait.

    It turns out this statement is a passthru to the transport:

        /**
         * Initiates an orderly shutdown in which preexisting calls continue but new
         * calls are immediately cancelled.
         *
         * @experimental
         */
        public function close()
        {
            $this->transport->close();
        }
    

    The code for available transports has options for REST and gRPC.

    Following REST to the HttpUnaryTransportTrait, this appears to be a no-op:

        public function close()
        {
            // Nothing to do.
        }
    

    Following gRPC to Grpc\BaseStub we reach the gRPC client implementation.