.php_cs.dist000064400000000515151742731660007000 0ustar00setRules([ '@PSR2' => true, 'concat_space' => ['spacing' => 'one'], 'no_unused_imports' => true, 'method_argument_space' => false, ]) ->setFinder( PhpCsFixer\Finder::create() ->notPath('firestore') ->in(__DIR__) ) ; LICENSE000064400000026136151742731660005575 0ustar00 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. README.md000064400000000734151742731660006043 0ustar00# gRPC for GCP extensions Copyright 2018 [The gRPC Authors](https://github.com/grpc/grpc/blob/master/AUTHORS) ## About This Repository This repo is created to support GCP specific extensions for gRPC. To use the extension features, please refer to [src](src). This repo also contains supporting infrastructures such as end2end tests and benchmarks for accessing cloud APIs with gRPC client libraries. ## License Apache 2.0 - See [LICENSE](LICENSE) for more information. composer.json000064400000001055151742731660007303 0ustar00{ "name": "google/grpc-gcp", "description": "gRPC GCP library for channel management", "license": "Apache-2.0", "version": "0.1.2", "require": { "php": ">=5.5.0", "google/protobuf": "^v3.3.0", "grpc/grpc": "^v1.13.0", "google/auth": "^1.3", "psr/cache": "^1.0.1" }, "require-dev": { "phpunit/phpunit": "4.8.36", "google/cloud-spanner": "^1.7" }, "autoload": { "psr-4": { "Grpc\\Gcp\\": "src/", "": "src/generated/" } } } doc/gRPC-client-user-guide.md000064400000015546151742731660012000 0ustar00# Instructions for create a gRPC client for google cloud services ## Overview This instruction includes a step by step guide for creating a gRPC client to test the google cloud service from an empty linux VM, using GCE ubuntu 16.04 TLS instance. The main steps are followed as steps below: - Environment prerequisite - Install protobuf plugin and gRPC-PHP/protobuf extension - Generate client API from .proto files - Create the client and send/receive RPC. ## Environment Prerequisite **Linux** ```sh $ [sudo] apt-get install build-essential autoconf libtool pkg-config zip unzip zlib1g-dev ``` **PHP** * `php` 5.5 or above, 7.0 or above * `pecl` * `composer` ```sh $ [sudo] apt-get install php php-dev $ curl -sS https://getcomposer.org/installer | php $ [sudo] mv composer.phar /usr/local/bin/composer ``` ## Install protobuf plugin and gRPC-PHP/protobuf extension `grpc_php_plugin` is used to generate client API from `*.proto `files. Currently, The only way to install `grpc_php_plugin` is to build from the gRPC source. **Install protobuf, gRPC, which will install the plugin** ```sh $ git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc $ cd grpc $ git submodule update --init # install protobuf $ cd third_party/protobuf $ ./autogen.sh && ./configure && make -j8 $ [sudo] make install $ [sudo] ldconfig # install gRPC $ cd ../.. $ make -j8 $ [sudo] make install ``` It will generate `grpc_php_plugin` under `/usr/local/bin`. **Install gRPC-PHP extension** ```sh $ [sudo] pecl install protobuf $ [sudo] pecl install grpc ``` It will generate `protobuf.so` and `grpc.so` under PHP's extension directory. Note gRPC-PHP extension installed by pecl doesn't work on RHEL6 system. ## Generate client API from .proto files The common way to generate the client API is to use `grpc_php_plugin` directly. Since the plugin won't find the dependency by itself. It works if all your service proto files and dependent proto files are inside one directory. The command looks like: ```sh $ mkdir $HOME/project $ protoc --proto_path=./ --php_out=$HOME/project \ --grpc_out=$HOME/project \ --plugin=protoc-gen-grpc=./bins/opt/grpc_php_plugin \ path/to/your/proto_dependency_directory1/*.proto \ path/to/your/proto_dependency_directory2/*.proto \ path/to/your/proto_directory/*.proto ``` Take `Firestore` service under [googleapis github repo](https://github.com/googleapis/googleapis) for example. The proto files required for generating client API are ``` google/api/annotations.proto google/api/http.proto google/api/httpbody.proto google/longrunning/operations.proto google/rpc/code.proto google/rpc/error_details.proto google/rpc/status.proto google/type/latlng.proto google/firestore/v1beta1/firestore.proto google/firestore/v1beta1/common.proto google/firestore/v1beta1/query.proto google/firestore/v1beta1/write.proto google/firestore/v1beta1/document.proto ``` Thus the command looks like: ```sh $ protoc --proto_path=googleapis --plugin=protoc-gen-grpc=`which grpc_php_plugin` \ --php_out=./ --grpc_out=./ google/api/annotations.proto google/api/http.proto \ google/api/httpbody.proto google/longrunning/operations.proto google/rpc/code.proto \ google/rpc/error_details.proto google/rpc/status.proto google/type/latlng.proto \ google/firestore/v1beta1/firestore.proto google/firestore/v1beta1/common.proto \ google/firestore/v1beta1/query.proto google/firestore/v1beta1/write.proto \ google/firestore/v1beta1/document.proto ``` Since most of cloud services already publish proto files under [googleapis github repo](https://github.com/googleapis/googleapis), you can use it's Makefile to generate the client API. The `Makefile` will help you generate the client API as well as find the dependencies. The command will simply be: ```sh $ cd $HOME $ mkdir project $ git clone https://github.com/googleapis/googleapis.git $ cd googleapis $ make LANGUAGE=php OUTPUT=$HOME/project # (It's okay if you see error like Please add 'syntax = "proto3";' # to the top of your .proto file.) ``` The client API library is generated under `$HOME/project`. Take [`Firestore`](https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto) as example, the Client API is under `project/Google/Cloud/Firestore/V1beta1/FirestoreClient.php` depends on your package name inside .proto file. An easy way to find your client is ```sh $ find ./ -name [service_name]Client.php ``` ## Create the client and send/receive RPC. Now it's time to use the client API to send and receive RPCs. ```sh $ cd $HOME/project ``` **Install gRPC-PHP composer library** ```sh $ vim composer.json ######## you need to change the path and service namespace. { "require": { "google/cloud": "^0.52.1" }, "autoload": { "psr-4": { "FireStore\\": "src/", "Google\\Cloud\\Firestore\\V1beta1\\": "Google/Cloud/Firestore/V1beta1/" } } } ######## $ composer install ``` **Set credentials file** ``` sh $ vim $HOME/key.json ## Paste you credential file downloaded from your cloud project ## which you can find in APIs&Services => credentials => create credentials ## => Service account key => your credentials $ export GOOGLE_APPLICATION_CREDENTIALS=$HOME/key.json ``` **Implement Service Client** Take a unary-unary RPC `listDocument` from `FirestoreClient` as example. Create a file name `ListDocumentClient.php`. - import library ``` require_once __DIR__ . '/vendor/autoload.php'; use Google\Cloud\Firestore\V1beta1\FirestoreClient; use Google\Cloud\Firestore\V1beta1\ListDocumentsRequest; use Google\Auth\ApplicationDefaultCredentials; ``` - Google Auth ``` $host = "firestore.googleapis.com"; $credentials = \Grpc\ChannelCredentials::createSsl(); // WARNING: the environment variable "GOOGLE_APPLICATION_CREDENTIALS" needs to be set $auth = ApplicationDefaultCredentials::getCredentials(); $opts = [ 'credentials' => $credentials, 'update_metadata' => $auth->getUpdateMetadataFunc(), ] ``` - Create Client ``` $firestoreClient = new FirestoreClient($host, $opts); ``` - Make and receive RPC call ``` $argument = new ListDocumentsRequest(); $project_id = xxxxxxx; $argument->setParent("projects/$project_id/databases/(default)/documents"); list($Response, $error) = $firestoreClient->ListDocuments($argument)->wait(); ``` - print RPC response ``` $documents = $Response->getDocuments(); $index = 0; foreach($documents as $document) { $index++; $name = $document->getName(); echo "=> Document $index: $name\n"; $fields = $document->getFields(); foreach ($fields as $name => $value) { echo "$name => ".$value->getStringValue()."\n"; } } ``` - run the script ```sh $ php -d extension=grpc.so -d extension=protobuf.so ListDocumentClient.php ``` For different kinds of RPC(unary-unary, unary-stream, stream-unary, stream-stream), please check [grpc.io PHP part](https://grpc.io/docs/tutorials/basic/php.html#calling-service-methods) for reference. src/ChannelRef.php000064400000006260151742731660010071 0ustar00target = $target; $this->channel_id = $channel_id; $this->affinity_ref = $affinity_ref; $this->active_stream_ref = $active_stream_ref; $this->opts = $opts; $this->has_deserialized = new CreatedByDeserializeCheck(); } public function getRealChannel($credentials) { // TODO(ddyihai): remove this check once the serialize handler for // \Grpc\Channel is implemented(issue https://github.com/grpc/grpc/issues/15870). if (!$this->has_deserialized->getData()) { // $real_channel exists and is not created by the deserialization. return $this->real_channel; } // If this ChannelRef is created by deserialization, $real_channel is invalid // thus needs to be recreated becasue Grpc\Channel don't have serialize and // deserialize handler. // Since [target + augments + credentials] will be the same during the recreation, // it will reuse the underline grpc channel in C extension without creating a // new connection. // 'credentials' in the array $opts will be unset during creating the channel. if (!array_key_exists('credentials', $this->opts)) { $this->opts['credentials'] = $credentials; } $real_channel = new \Grpc\Channel($this->target, $this->opts); $this->real_channel = $real_channel; // Set deserialization to false so it won't be recreated within the same script. $this->has_deserialized->setData(0); return $real_channel; } public function getAffinityRef() { return $this->affinity_ref; } public function getActiveStreamRef() { return $this->active_stream_ref; } public function affinityRefIncr() { $this->affinity_ref += 1; } public function affinityRefDecr() { $this->affinity_ref -= 1; } public function activeStreamRefIncr() { $this->active_stream_ref += 1; } public function activeStreamRefDecr() { $this->active_stream_ref -= 1; } } src/Config.php000064400000014434151742731660007273 0ustar00gcp_call_invoker = new \Grpc\DefaultCallInvoker(); return; } $gcp_channel = null; $url_host = parse_url($target, PHP_URL_HOST); $this->hostname = $url_host ? $url_host : $target; $channel_pool_key = $this->hostname . '.gcp.channel.' . getmypid(); $this->cross_script_shmem_enabled = $this->crossScriptShmemEnabled(); if (!$cacheItemPool) { // If there is no cacheItemPool, use shared memory for // caching the configuration and channel pool. if (! extension_loaded('sysvshm')) { throw \RuntimeException( 'sysvshm extension is required to use this ItemPool'); } $channel_pool_key = intval(base_convert(sha1($channel_pool_key), 16, 10)); $shm_id = $this->getShmem(); if (shm_has_var($shm_id, $channel_pool_key)) { $shm_var = shm_get_var($shm_id, $channel_pool_key); $gcp_call_invoker = unserialize($shm_var); } else { $affinity_conf = $this->parseConfObject($conf); $gcp_call_invoker = new GCPCallInvoker($affinity_conf); } $this->gcp_call_invoker = $gcp_call_invoker; shm_detach($shm_id); register_shutdown_function(function ($gcp_call_invoker, $channel_pool_key, $shm_id) { $shm_id = $this->getShmem(); if (! $this->cross_script_shmem_enabled) { // Clean up memory if cross-script shared memory is not needed. shm_remove($shm_id); } else { // Push the current gcp_channel back into the pool when the script finishes. if (!shm_put_var($shm_id, $channel_pool_key, serialize($gcp_call_invoker))) { echo "[warning]: failed to update the item pool\n"; } } shm_detach($shm_id); }, $gcp_call_invoker, $channel_pool_key, $shm_id); } else { $item = $cacheItemPool->getItem($channel_pool_key); if ($item->isHit()) { // Channel pool for the $hostname API has already created. $gcp_call_invoker = unserialize($item->get()); } else { $affinity_conf = $this->parseConfObject($conf); // Create GCP channel based on the information. $gcp_call_invoker = new GCPCallInvoker($affinity_conf); } $this->gcp_call_invoker = $gcp_call_invoker; register_shutdown_function(function ($gcp_call_invoker, $cacheItemPool, $item) { // Push the current gcp_channel back into the pool when the script finishes. $item->set(serialize($gcp_call_invoker)); $cacheItemPool->save($item); }, $gcp_call_invoker, $cacheItemPool, $item); } } /** * @return \Grpc\CallInvoker The call invoker to be hooked into the gRPC */ public function callInvoker() { return $this->gcp_call_invoker; } /** * @return string The URI of the endpoint */ public function getTarget() { return $this->channel->getTarget(); } private function parseConfObject($conf_object) { $config = json_decode($conf_object->serializeToJsonString(), true); if (isset($config['channelPool'])) { $affinity_conf['channelPool'] = $config['channelPool']; } $aff_by_method = array(); if (isset($config['method'])) { for ($i = 0; $i < count($config['method']); $i++) { // In proto3, if the value is default, eg 0 for int, it won't be serialized. // Thus serialized string may not have `command` if the value is default 0(BOUND). if (!array_key_exists('command', $config['method'][$i]['affinity'])) { $config['method'][$i]['affinity']['command'] = 'BOUND'; } $aff_by_method[$config['method'][$i]['name'][0]] = $config['method'][$i]['affinity']; } } $affinity_conf['affinity_by_method'] = $aff_by_method; return $affinity_conf; } private function crossScriptShmemEnabled() { $force_enable_gcp = filter_var( getenv('ENABLE_GCP_CHANNEL_MANAGEMENT'), FILTER_VALIDATE_BOOLEAN ); return in_array(php_sapi_name(), $this->supported_sapis) || $force_enable_gcp; } private function getShmem() { $shmid = shm_attach(getmypid(), 200000, 0600); if ($shmid === false) { throw new \RuntimeException( 'Failed to attach to the shared memory' ); } return $shmid; } } src/CreatedByDeserializeCheck.php000064400000003167151742731660013050 0ustar00data = 1; } /** * @return string */ public function serialize() { return '0'; } /** * @param string $data */ public function unserialize($data) { $this->data = 1; } /** * @param $data */ public function setData($data) { $this->data = $data; } /** * @return int */ public function getData() { return $this->data; } } src/GCPBidiStreamingCall.php000064400000006161151742731660011733 0ustar00_rpcPreProcess($data); $this->real_call = new \Grpc\BidiStreamingCall($channel_ref->getRealChannel( $this->gcp_channel->credentials), $this->method, $this->deserialize, $this->options); $this->real_call->start($this->metadata_rpc); return $this->real_call; } /** * Pick a channel and start the call. * * @param array $metadata Metadata to send with the call, if applicable * (optional) */ public function start(array $metadata = []) { $this->metadata_rpc = $metadata; } /** * Reads the next value from the server. * * @return mixed The next value from the server, or null if there is none */ public function read() { if (!$this->has_real_call) { $this->createRealCall(); $this->has_real_call = true; } $response = $this->real_call->read(); if ($response) { $this->response = $response; } return $response; } /** * Write a single message to the server. This cannot be called after * writesDone is called. * * @param ByteBuffer $data The data to write * @param array $options An array of options, possible keys: * 'flags' => a number (optional) */ public function write($data, array $options = []) { if (!$this->has_real_call) { $this->createRealCall($data); $this->has_real_call = true; } $this->real_call->write($data, $options); } /** * Indicate that no more writes will be sent. */ public function writesDone() { if (!$this->has_real_call) { $this->createRealCall(); $this->has_real_call = true; } $this->real_call->writesDone(); } /** * Wait for the server to send the status, and return it. * * @return \stdClass The status object, with integer $code, string * $details, and array $metadata members */ public function getStatus() { $status = $this->real_call->getStatus(); $this->_rpcPostProcess($status, $this->response); return $status; } } src/GCPCallInvoker.php000064400000005617151742731660010634 0ustar00affinity_conf = $affinity_conf; } /** * @param string $hostname * @param array $opts * @return GcpExtensionChannel */ public function createChannelFactory($hostname, $opts) { if ($this->channel) { // $call_invoker object has already created from previews PHP-FPM scripts. // Only need to udpate the $opts including the credentials. $this->channel->updateOpts($opts); } else { $opts['affinity_conf'] = $this->affinity_conf; $channel = new GcpExtensionChannel($hostname, $opts); $this->channel = $channel; } return $this->channel; } // _getChannel is used for testing only. public function GetChannel() { return $this->channel; } public function UnaryCall($channel, $method, $deserialize, $options) { return new GCPUnaryCall($channel, $method, $deserialize, $options); } public function ClientStreamingCall($channel, $method, $deserialize, $options) { return new GCPClientStreamCall($channel, $method, $deserialize, $options); } public function ServerStreamingCall($channel, $method, $deserialize, $options) { return new GCPServerStreamCall($channel, $method, $deserialize, $options); } public function BidiStreamingCall($channel, $method, $deserialize, $options) { return new GCPBidiStreamingCall($channel, $method, $deserialize, $options); } } src/GCPClientStreamCall.php000064400000004611151742731660011602 0ustar00_rpcPreProcess($data); $this->real_call = new \Grpc\ClientStreamingCall($channel_ref->getRealChannel( $this->gcp_channel->credentials), $this->method, $this->deserialize, $this->options); $this->real_call->start($this->metadata_rpc); return $this->real_call; } /** * Pick a channel and start the call. * * @param array $metadata Metadata to send with the call, if applicable * (optional) */ public function start(array $metadata = []) { // Postpone first rpc to write function(), where we can pick a channel // from the channel pool. $this->metadata_rpc = $metadata; } /** * Write a single message to the server. This cannot be called after * wait is called. * * @param ByteBuffer $data The data to write * @param array $options An array of options, possible keys: * 'flags' => a number (optional) */ public function write($data, array $options = []) { if (!$this->has_real_call) { $this->createRealCall($data); $this->has_real_call = true; } $this->real_call->write($data, $options); } /** * Wait for the server to respond with data and a status. * * @return array [response data, status] */ public function wait() { list($response, $status) = $this->real_call->wait(); $this->_rpcPostProcess($status, $response); return [$response, $status]; } } src/GCPServerStreamCall.php000064400000005340151742731660011632 0ustar00real_call = new \Grpc\ServerStreamingCall($channel, $this->method, $this->deserialize, $this->options); $this->has_real_call = true; return $this->real_call; } /** * Pick a channel and start the call. * * @param mixed $data The data to send * @param array $metadata Metadata to send with the call, if applicable * (optional) * @param array $options An array of options, possible keys: * 'flags' => a number (optional) */ public function start($argument, $metadata, $options) { $channel_ref = $this->_rpcPreProcess($argument); $this->createRealCall($channel_ref->getRealChannel( $this->gcp_channel->credentials)); $this->real_call->start($argument, $metadata, $options); } /** * @return mixed An iterator of response values */ public function responses() { $response = $this->real_call->responses(); // Since the last response is empty for the server streaming RPC, // the second last one is the last RPC response with payload. // Use this one for searching the affinity key. // The same as BidiStreaming. if ($response) { $this->response = $response; } return $response; } /** * Wait for the server to send the status, and return it. * * @return \stdClass The status object, with integer $code, string * $details, and array $metadata members */ public function getStatus() { $status = $this->real_call->getStatus(); $this->_rpcPostProcess($status, $this->response); return $status; } /** * @return mixed The metadata sent by the server */ public function getMetadata() { return $this->real_call->getMetadata(); } } src/GCPUnaryCall.php000064400000004203151742731660010303 0ustar00real_call = new \Grpc\UnaryCall($channel, $this->method, $this->deserialize, $this->options); $this->has_real_call = true; return $this->real_call; } /** * Pick a channel and start the call. * * @param mixed $data The data to send * @param array $metadata Metadata to send with the call, if applicable * (optional) * @param array $options An array of options, possible keys: * 'flags' => a number (optional) */ public function start($argument, $metadata, $options) { $channel_ref = $this->_rpcPreProcess($argument); $real_channel = $channel_ref->getRealChannel($this->gcp_channel->credentials); $this->createRealCall($real_channel); $this->real_call->start($argument, $metadata, $options); } /** * Wait for the server to respond with data and a status. * * @return array [response data, status] */ public function wait() { list($response, $status) = $this->real_call->wait(); $this->_rpcPostProcess($status, $response); return [$response, $status]; } /** * @return mixed The metadata sent by the server */ public function getMetadata() { return $this->real_call->getMetadata(); } } src/GcpBaseCall.php000064400000015123151742731660010162 0ustar00gcp_channel = $channel; $this->method = $method; $this->deserialize = $deserialize; $this->options = $options; $this->_affinity = null; if (isset($this->gcp_channel->affinity_conf['affinity_by_method'][$method])) { $this->_affinity = $this->gcp_channel->affinity_conf['affinity_by_method'][$method]; } } /** * Pick a ChannelRef from the channel pool based on the request and * the affinity config. * * @param mixed $argument Requests. * * @return ChannelRef */ protected function _rpcPreProcess($argument) { $this->affinity_key = null; if ($this->_affinity) { $command = $this->_affinity['command']; if ($command == self::BOUND || $command == self::UNBIND) { $this->affinity_key = $this->getAffinityKeyFromProto($argument); } } $this->channel_ref = $this->gcp_channel->getChannelRef($this->affinity_key); $this->channel_ref->activeStreamRefIncr(); return $this->channel_ref; } /** * Update ChannelRef when RPC finishes. * * @param \stdClass $status The status object, with integer $code, string * $details, and array $metadata members * @param mixed $response Response. */ protected function _rpcPostProcess($status, $response) { if ($this->_affinity) { $command = $this->_affinity['command']; if ($command == self::BIND) { if ($status->code != \Grpc\STATUS_OK) { return; } $affinity_key = $this->getAffinityKeyFromProto($response); $this->gcp_channel->bind($this->channel_ref, $affinity_key); } elseif ($command == self::UNBIND) { $this->gcp_channel->unbind($this->affinity_key); } } $this->channel_ref->activeStreamRefDecr(); } /** * Get the affinity key based on the affinity config. * * @param mixed $proto Objects may contain the affinity key. * * @return string Affinity key. */ protected function getAffinityKeyFromProto($proto) { if ($this->_affinity) { $names = $this->_affinity['affinityKey']; $names_arr = explode(".", $names); foreach ($names_arr as $name) { $getAttrMethod = 'get' . ucfirst($name); $proto = call_user_func_array(array($proto, $getAttrMethod), array()); } return $proto; } echo "Cannot find the field in the proto\n"; } /** * @return mixed The metadata sent by the server */ public function getMetadata() { if (!$this->has_real_call) { $this->createRealCall(); $this->has_real_call = true; } return $this->real_call->getMetadata(); } /** * @return mixed The trailing metadata sent by the server */ public function getTrailingMetadata() { if (!$this->has_real_call) { $this->createRealCall(); $this->has_real_call = true; } return $this->real_call->getTrailingMetadata(); } /** * @return string The URI of the endpoint */ public function getPeer() { if (!$this->has_real_call) { $this->createRealCall(); $this->has_real_call = true; } return $this->real_call->getPeer(); } /** * Cancels the call. */ public function cancel() { if (!$this->has_real_call) { $this->has_real_call = true; $this->createRealCall(); } $this->real_call->cancel(); } /** * Serialize a message to the protobuf binary format. * * @param mixed $data The Protobuf message * * @return string The protobuf binary format */ protected function _serializeMessage($data) { return $this->real_call->_serializeMessage($data); } /** * Deserialize a response value to an object. * * @param string $value The binary value to deserialize * * @return mixed The deserialized value */ protected function _deserializeResponse($value) { return $this->real_call->_deserializeResponse($value); } /** * Set the CallCredentials for the underlying Call. * * @param CallCredentials $call_credentials The CallCredentials object */ public function setCallCredentials($call_credentials) { $this->call->setCredentials($call_credentials); } } src/GcpExtensionChannel.php000064400000024125151742731660011763 0ustar00channel_refs; } /** * @param string $hostname * @param array $opts Options to create a \Grpc\Channel and affinity config */ public function __construct($hostname = null, $opts = array()) { if ($hostname == null || !is_array($opts)) { throw new \InvalidArgumentException("Expected hostname is empty"); } $this->max_size = 10; $this->max_concurrent_streams_low_watermark = 100; if (isset($opts['affinity_conf'])) { if (isset($opts['affinity_conf']['channelPool'])) { if (isset($opts['affinity_conf']['channelPool']['maxSize'])) { $this->max_size = $opts['affinity_conf']['channelPool']['maxSize']; } if (isset($opts['affinity_conf']['channelPool']['maxConcurrentStreamsLowWatermark'])) { $this->max_concurrent_streams_low_watermark = $opts['affinity_conf']['channelPool']['maxConcurrentStreamsLowWatermark']; } } $this->affinity_by_method = $opts['affinity_conf']['affinity_by_method']; $this->affinity_conf = $opts['affinity_conf']; } $this->target = $hostname; $this->affinity_key_to_channel_ref = array(); $this->channel_refs = array(); $this->updateOpts($opts); // Initiate a Grpc\Channel at the beginning in order to keep the same // behavior as the Grpc. $channel_ref = $this->getChannelRef(); $channel_ref->getRealChannel($this->credentials); } /** * @param array $opts Options to create a \Grpc\Channel */ public function updateOpts($opts) { if (isset($opts['credentials'])) { $this->credentials = $opts['credentials']; } unset($opts['affinity_conf']); unset($opts['credentials']); $this->options = $opts; $this->is_closed = false; } /** * Bind the ChannelRef with the affinity key. This is a private method. * * @param ChannelRef $channel_ref * @param string $affinity_key * * @return ChannelRef */ public function bind($channel_ref, $affinity_key) { if (!array_key_exists($affinity_key, $this->affinity_key_to_channel_ref)) { $this->affinity_key_to_channel_ref[$affinity_key] = $channel_ref; } $channel_ref->affinityRefIncr(); return $channel_ref; } /** * Unbind the affinity key. This is a private method. * * @param string $affinity_key * * @return ChannelRef */ public function unbind($affinity_key) { $channel_ref = null; if (array_key_exists($affinity_key, $this->affinity_key_to_channel_ref)) { $channel_ref = $this->affinity_key_to_channel_ref[$affinity_key]; $channel_ref->affinityRefDecr(); } unset($this->affinity_key_to_channel_ref[$affinity_key]); return $channel_ref; } public function cmp_by_active_stream_ref($a, $b) { return $a->getActiveStreamRef() - $b->getActiveStreamRef(); } /** * Pick or create a ChannelRef from the pool by affinity key. * * @param string $affinity_key * * @return ChannelRef */ public function getChannelRef($affinity_key = null) { if ($affinity_key) { if (array_key_exists($affinity_key, $this->affinity_key_to_channel_ref)) { return $this->affinity_key_to_channel_ref[$affinity_key]; } return $this->getChannelRef(); } usort($this->channel_refs, array($this, 'cmp_by_active_stream_ref')); if (count($this->channel_refs) > 0 && $this->channel_refs[0]->getActiveStreamRef() < $this->max_concurrent_streams_low_watermark) { return $this->channel_refs[0]; } $num_channel_refs = count($this->channel_refs); if ($num_channel_refs < $this->max_size) { // grpc_target_persist_bound stands for how many channels can be persisted for // the same target in the C extension. It is possible that the user use the pure // gRPC and this GCP extension at the same time, which share the same target. In this case // pure gRPC channel may occupy positions in C extension, which deletes some channels created // by this GCP extension. // If that happens, it won't cause the script failure because we saves all arguments for creating // a channel instead of a channel itself. If we watch to fetch a GCP channel already deleted, // it will create a new channel. The only cons is the latency of the first RPC will high because // it will establish the connection again. if (!isset($this->options['grpc_target_persist_bound']) || $this->options['grpc_target_persist_bound'] < $this->max_size) { $this->options['grpc_target_persist_bound'] = $this->max_size; } $cur_opts = array_merge($this->options, ['grpc_gcp_channel_id' => $num_channel_refs]); $channel_ref = new ChannelRef($this->target, $num_channel_refs, $cur_opts); array_unshift($this->channel_refs, $channel_ref); } return $this->channel_refs[0]; } /** * Get the connectivity state of the channel * * @param bool $try_to_connect try to connect on the channel * * @return int The grpc connectivity state * @throws \InvalidArgumentException */ public function getConnectivityState($try_to_connect = false) { // Since getRealChannel is creating a PHP Channel object. However in gRPC, when a Channel // object is closed, we only mark this Object to be invalid. Thus, we need a global variable // to mark whether this GCPExtensionChannel is close or not. if ($this->is_closed) { throw new \RuntimeException("Channel has already been closed"); } $ready = 0; $idle = 0; $connecting = 0; $transient_failure = 0; $shutdown = 0; foreach ($this->channel_refs as $channel_ref) { $state = $channel_ref->getRealChannel($this->credentials)->getConnectivityState($try_to_connect); print_r($state); switch ($state) { case \Grpc\CHANNEL_READY: $ready += 1; break; case \Grpc\CHANNEL_FATAL_FAILURE: $shutdown += 1; continue; case \Grpc\CHANNEL_CONNECTING: $connecting += 1; continue; case \Grpc\CHANNEL_TRANSIENT_FAILURE: $transient_failure += 1; continue; case \Grpc\CHANNEL_IDLE: $idle += 1; continue; } } if ($ready > 0) { return \Grpc\CHANNEL_READY; } elseif ($idle > 0) { return \Grpc\CHANNEL_IDLE; } elseif ($connecting > 0) { return \Grpc\CHANNEL_CONNECTING; } elseif ($transient_failure > 0) { return \Grpc\CHANNEL_TRANSIENT_FAILURE; } elseif ($shutdown > 0) { return \Grpc\CHANNEL_SHUTDOWN; } } /** * Watch the connectivity state of the channel until it changed * * @param int $last_state The previous connectivity state of the channel * @param Timeval $deadline_obj The deadline this function should wait until * * @return bool If the connectivity state changes from last_state * before deadline * @throws \InvalidArgumentException */ public function watchConnectivityState($last_state, $deadline_obj = null) { if ($deadline_obj == null || !is_a($deadline_obj, '\Grpc\Timeval')) { throw new \InvalidArgumentException(""); } // Since getRealChannel is creating a PHP Channel object. However in gRPC, when a Channel // object is closed, we only mark this Object to be invalid. Thus, we need a global variable // to mark whether this GCPExtensionChannel is close or not. if ($this->is_closed) { throw new \RuntimeException("Channel has already been closed"); } $state = 0; foreach ($this->channel_refs as $channel_ref) { $state = $channel_ref->getRealChannel($this->credentials)->watchConnectivityState($last_state, $deadline_obj); } return $state; } /** * Get the endpoint this call/stream is connected to * * @return string The URI of the endpoint */ public function getTarget() { return $this->target; } /** * Close the channel */ public function close() { foreach ($this->channel_refs as $channel_ref) { $channel_ref->getRealChannel($this->credentials)->close(); } $this->is_closed = true; } } src/generated/GPBMetadata/GrpcGcp.php000064400000003213151742731660013413 0ustar00internalAddGeneratedFile(hex2bin( "0ac9030a0e677270635f6763702e70726f746f1208677270632e67637022" . "670a09417069436f6e66696712310a0c6368616e6e656c5f706f6f6c1802" . "2001280b321b2e677270632e6763702e4368616e6e656c506f6f6c436f6e" . "66696712270a066d6574686f6418e9072003280b32162e677270632e6763" . "702e4d6574686f64436f6e66696722690a114368616e6e656c506f6f6c43" . "6f6e66696712100a086d61785f73697a6518012001280d12140a0c69646c" . "655f74696d656f7574180220012804122c0a246d61785f636f6e63757272" . "656e745f73747265616d735f6c6f775f77617465726d61726b1803200128" . "0d22490a0c4d6574686f64436f6e666967120c0a046e616d651801200328" . "09122b0a08616666696e69747918e9072001280b32182e677270632e6763" . "702e416666696e697479436f6e6669672285010a0e416666696e69747943" . "6f6e66696712310a07636f6d6d616e6418022001280e32202e677270632e" . "6763702e416666696e697479436f6e6669672e436f6d6d616e6412140a0c" . "616666696e6974795f6b6579180320012809222a0a07436f6d6d616e6412" . "090a05424f554e44100012080a0442494e441001120a0a06554e42494e44" . "1002620670726f746f33" )); static::$is_initialized = true; } } src/generated/Grpc/Gcp/AffinityConfig.php000064400000004376151742731660014333 0ustar00grpc.gcp.AffinityConfig */ class AffinityConfig extends \Google\Protobuf\Internal\Message { /** * The affinity command applies on the selected gRPC methods. * * Generated from protobuf field .grpc.gcp.AffinityConfig.Command command = 2; */ private $command = 0; /** * The field path of the affinity key in the request/response message. * For example: "f.a", "f.b.d", etc. * * Generated from protobuf field string affinity_key = 3; */ private $affinity_key = ''; public function __construct() { \GPBMetadata\GrpcGcp::initOnce(); parent::__construct(); } /** * The affinity command applies on the selected gRPC methods. * * Generated from protobuf field .grpc.gcp.AffinityConfig.Command command = 2; * @return int */ public function getCommand() { return $this->command; } /** * The affinity command applies on the selected gRPC methods. * * Generated from protobuf field .grpc.gcp.AffinityConfig.Command command = 2; * @param int $var * @return $this */ public function setCommand($var) { GPBUtil::checkEnum($var, \Grpc\Gcp\AffinityConfig_Command::class); $this->command = $var; return $this; } /** * The field path of the affinity key in the request/response message. * For example: "f.a", "f.b.d", etc. * * Generated from protobuf field string affinity_key = 3; * @return string */ public function getAffinityKey() { return $this->affinity_key; } /** * The field path of the affinity key in the request/response message. * For example: "f.a", "f.b.d", etc. * * Generated from protobuf field string affinity_key = 3; * @param string $var * @return $this */ public function setAffinityKey($var) { GPBUtil::checkString($var, true); $this->affinity_key = $var; return $this; } } src/generated/Grpc/Gcp/AffinityConfig_Command.php000064400000002323151742731660015757 0ustar00Grpc\Gcp\AffinityConfig\Command */ class AffinityConfig_Command { /** * The annotated method will be required to be bound to an existing session * to execute the RPC. The corresponding will be * used to find the affinity key from the request message. * * Generated from protobuf enum BOUND = 0; */ const BOUND = 0; /** * The annotated method will establish the channel affinity with the channel * which is used to execute the RPC. The corresponding * will be used to find the affinity key from the * response message. * * Generated from protobuf enum BIND = 1; */ const BIND = 1; /** * The annotated method will remove the channel affinity with the channel * which is used to execute the RPC. The corresponding * will be used to find the affinity key from the * request message. * * Generated from protobuf enum UNBIND = 2; */ const UNBIND = 2; } src/generated/Grpc/Gcp/ApiConfig.php000064400000004307151742731660013265 0ustar00grpc.gcp.ApiConfig */ class ApiConfig extends \Google\Protobuf\Internal\Message { /** * The channel pool configurations. * * Generated from protobuf field .grpc.gcp.ChannelPoolConfig channel_pool = 2; */ private $channel_pool = null; /** * The method configurations. * * Generated from protobuf field repeated .grpc.gcp.MethodConfig method = 1001; */ private $method; public function __construct() { \GPBMetadata\GrpcGcp::initOnce(); parent::__construct(); } /** * The channel pool configurations. * * Generated from protobuf field .grpc.gcp.ChannelPoolConfig channel_pool = 2; * @return \Grpc\Gcp\ChannelPoolConfig */ public function getChannelPool() { return $this->channel_pool; } /** * The channel pool configurations. * * Generated from protobuf field .grpc.gcp.ChannelPoolConfig channel_pool = 2; * @param \Grpc\Gcp\ChannelPoolConfig $var * @return $this */ public function setChannelPool($var) { GPBUtil::checkMessage($var, \Grpc\Gcp\ChannelPoolConfig::class); $this->channel_pool = $var; return $this; } /** * The method configurations. * * Generated from protobuf field repeated .grpc.gcp.MethodConfig method = 1001; * @return \Google\Protobuf\Internal\RepeatedField */ public function getMethod() { return $this->method; } /** * The method configurations. * * Generated from protobuf field repeated .grpc.gcp.MethodConfig method = 1001; * @param \Grpc\Gcp\MethodConfig[]|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setMethod($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Grpc\Gcp\MethodConfig::class); $this->method = $arr; return $this; } } src/generated/Grpc/Gcp/ChannelPoolConfig.php000064400000006474151742731660014765 0ustar00grpc.gcp.ChannelPoolConfig */ class ChannelPoolConfig extends \Google\Protobuf\Internal\Message { /** * The max number of channels in the pool. * * Generated from protobuf field uint32 max_size = 1; */ private $max_size = 0; /** * The idle timeout (seconds) of channels without bound affinity sessions. * * Generated from protobuf field uint64 idle_timeout = 2; */ private $idle_timeout = 0; /** * The low watermark of max number of concurrent streams in a channel. * New channel will be created once it get hit, until we reach the max size * of the channel pool. * * Generated from protobuf field uint32 max_concurrent_streams_low_watermark = 3; */ private $max_concurrent_streams_low_watermark = 0; public function __construct() { \GPBMetadata\GrpcGcp::initOnce(); parent::__construct(); } /** * The max number of channels in the pool. * * Generated from protobuf field uint32 max_size = 1; * @return int */ public function getMaxSize() { return $this->max_size; } /** * The max number of channels in the pool. * * Generated from protobuf field uint32 max_size = 1; * @param int $var * @return $this */ public function setMaxSize($var) { GPBUtil::checkUint32($var); $this->max_size = $var; return $this; } /** * The idle timeout (seconds) of channels without bound affinity sessions. * * Generated from protobuf field uint64 idle_timeout = 2; * @return int|string */ public function getIdleTimeout() { return $this->idle_timeout; } /** * The idle timeout (seconds) of channels without bound affinity sessions. * * Generated from protobuf field uint64 idle_timeout = 2; * @param int|string $var * @return $this */ public function setIdleTimeout($var) { GPBUtil::checkUint64($var); $this->idle_timeout = $var; return $this; } /** * The low watermark of max number of concurrent streams in a channel. * New channel will be created once it get hit, until we reach the max size * of the channel pool. * * Generated from protobuf field uint32 max_concurrent_streams_low_watermark = 3; * @return int */ public function getMaxConcurrentStreamsLowWatermark() { return $this->max_concurrent_streams_low_watermark; } /** * The low watermark of max number of concurrent streams in a channel. * New channel will be created once it get hit, until we reach the max size * of the channel pool. * * Generated from protobuf field uint32 max_concurrent_streams_low_watermark = 3; * @param int $var * @return $this */ public function setMaxConcurrentStreamsLowWatermark($var) { GPBUtil::checkUint32($var); $this->max_concurrent_streams_low_watermark = $var; return $this; } } src/generated/Grpc/Gcp/MethodConfig.php000064400000005106151742731660013772 0ustar00grpc.gcp.MethodConfig */ class MethodConfig extends \Google\Protobuf\Internal\Message { /** * A fully qualified name of a gRPC method, or a wildcard pattern ending * with .*, such as foo.bar.A, foo.bar.*. Method configs are evaluated * sequentially, and the first one takes precedence. * * Generated from protobuf field repeated string name = 1; */ private $name; /** * The channel affinity configurations. * * Generated from protobuf field .grpc.gcp.AffinityConfig affinity = 1001; */ private $affinity = null; public function __construct() { \GPBMetadata\GrpcGcp::initOnce(); parent::__construct(); } /** * A fully qualified name of a gRPC method, or a wildcard pattern ending * with .*, such as foo.bar.A, foo.bar.*. Method configs are evaluated * sequentially, and the first one takes precedence. * * Generated from protobuf field repeated string name = 1; * @return \Google\Protobuf\Internal\RepeatedField */ public function getName() { return $this->name; } /** * A fully qualified name of a gRPC method, or a wildcard pattern ending * with .*, such as foo.bar.A, foo.bar.*. Method configs are evaluated * sequentially, and the first one takes precedence. * * Generated from protobuf field repeated string name = 1; * @param string[]|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setName($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING); $this->name = $arr; return $this; } /** * The channel affinity configurations. * * Generated from protobuf field .grpc.gcp.AffinityConfig affinity = 1001; * @return \Grpc\Gcp\AffinityConfig */ public function getAffinity() { return $this->affinity; } /** * The channel affinity configurations. * * Generated from protobuf field .grpc.gcp.AffinityConfig affinity = 1001; * @param \Grpc\Gcp\AffinityConfig $var * @return $this */ public function setAffinity($var) { GPBUtil::checkMessage($var, \Grpc\Gcp\AffinityConfig::class); $this->affinity = $var; return $this; } } src/grpc_gcp.proto000064400000005041151742731660010220 0ustar00// Copyright 2018 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. syntax = "proto3"; package grpc.gcp; message ApiConfig { // The channel pool configurations. ChannelPoolConfig channel_pool = 2; // The method configurations. repeated MethodConfig method = 1001; } message ChannelPoolConfig { // The max number of channels in the pool. uint32 max_size = 1; // The idle timeout (seconds) of channels without bound affinity sessions. uint64 idle_timeout = 2; // The low watermark of max number of concurrent streams in a channel. // New channel will be created once it get hit, until we reach the max size // of the channel pool. uint32 max_concurrent_streams_low_watermark = 3; } message MethodConfig { // A fully qualified name of a gRPC method, or a wildcard pattern ending // with .*, such as foo.bar.A, foo.bar.*. Method configs are evaluated // sequentially, and the first one takes precedence. repeated string name = 1; // The channel affinity configurations. AffinityConfig affinity = 1001; } message AffinityConfig { enum Command { // The annotated method will be required to be bound to an existing session // to execute the RPC. The corresponding will be // used to find the affinity key from the request message. BOUND = 0; // The annotated method will establish the channel affinity with the channel // which is used to execute the RPC. The corresponding // will be used to find the affinity key from the // response message. BIND = 1; // The annotated method will remove the channel affinity with the channel // which is used to execute the RPC. The corresponding // will be used to find the affinity key from the // request message. UNBIND = 2; } // The affinity command applies on the selected gRPC methods. Command command = 2; // The field path of the affinity key in the request/response message. // For example: "f.a", "f.b.d", etc. string affinity_key = 3; }