public function getChannelRef()

in src/GcpExtensionChannel.php [142:177]


    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];
    }