-
Notifications
You must be signed in to change notification settings - Fork 255
Feature [client]: add supervised connection pool with legacy mode opt… #523
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
VladoPlavsic
wants to merge
3
commits into
elixir-grpc:master
Choose a base branch
from
VladoPlavsic:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| # Connection Pool | ||
|
|
||
| The Elixir gRPC client maintains a **connection pool** for every target address. Rather than opening a fresh HTTP/2 connection for each RPC, callers share a fixed set of long-lived connections. This reduces connection overhead, improves throughput under concurrency, and enables fine-grained control over how many connections and concurrent streams your client opens. | ||
|
|
||
| The pool is managed transparently: when you call a stub, the client checks out a connection, tracks the open stream count, and returns the connection when the call finishes. All of this happens without any additional code on your side. | ||
|
|
||
| --- | ||
|
|
||
| ## How It Works | ||
|
|
||
| When `GRPC.Stub.connect/2` is called, a supervised pool of connections is started for the target address. Each connection is an independent HTTP/2 session capable of multiplexing many concurrent streams. | ||
|
|
||
| On each RPC call the client: | ||
|
|
||
| 1. Picks first connection from the pool with number open streams that is still below the configured limit. | ||
| 2. Increments that connection's open-stream counter and records a lease. | ||
| 3. Runs the RPC. | ||
| 4. Decrements the counter and releases the lease when the call completes. | ||
|
|
||
| If every connection in the pool has reached `max_streams`, the client opens an **overflow** connection up to `max_overflow` extra connections. Overflow connections aren't discarded once the load subsides, but if pool dies or connections are otherwise dropped we reset to initial count. | ||
|
|
||
| --- | ||
|
|
||
| ## Configuration | ||
|
|
||
| Pool behaviour is controlled via the `:pool` option passed to `GRPC.Stub.connect/2` or `GRPC.Client.Connection.connect/2`. | ||
|
|
||
| | Option | Type | Default | Description | | ||
| |:-------------------------|:----------------------------|:--------|:-------------------------------------------------------------------------------------------------------------------| | ||
| | `:size` | `non_neg_integer` | `1` | Number of persistent connections kept open. | | ||
| | `:max_overflow` | `non_neg_integer or nil` | `0` | Maximum number of extra connections created when the pool is fully saturated. `nil` means no client-side limit. | | ||
| | `:max_streams` | `pos_integer or nil` | `nil` | Maximum concurrent streams per connection. `nil` means no client-side limit (server limit applies). | | ||
| | `:health_check_enabled` | `boolean` | `false` | When `true`, a periodic gRPC health-check ping is sent on each connection every 10 minutes. | | ||
|
|
||
| --- | ||
|
|
||
| ## Examples | ||
|
|
||
| ### Default pool (single connection) | ||
|
|
||
| ```elixir | ||
| iex> {:ok, channel} = GRPC.Stub.connect("localhost:50051") | ||
| iex> {:ok, reply} = channel |> MyService.Stub.my_rpc(request) | ||
| ``` | ||
|
|
||
| ### Multiple persistent connections | ||
|
|
||
| Open three connections upfront to distribute concurrent load: | ||
|
|
||
| ```elixir | ||
| iex> {:ok, channel} = GRPC.Stub.connect("localhost:50051", pool: %{size: 3}) | ||
| iex> {:ok, reply} = channel |> MyService.Stub.my_rpc(request) | ||
| ``` | ||
|
|
||
| ### Overflow connections | ||
|
|
||
| Keep two persistent connections and allow up to five overflow connections during traffic spikes: | ||
|
|
||
| ```elixir | ||
| iex> {:ok, channel} = | ||
| ...> GRPC.Stub.connect("localhost:50051", | ||
| ...> pool: %{size: 2, max_overflow: 5} | ||
| ...> ) | ||
| ``` | ||
|
|
||
| ### Limiting streams per connection | ||
|
|
||
| Cap each connection at 100 concurrent streams. Requests beyond this limit will use a new overflow connection (if allowed): | ||
|
|
||
| ```elixir | ||
| iex> {:ok, channel} = | ||
| ...> GRPC.Stub.connect("localhost:50051", | ||
| ...> pool: %{size: 2, max_overflow: 1, max_streams: 100} | ||
| ...> ) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## Disconnect | ||
|
|
||
| Calling `GRPC.Stub.disconnect/1` stops the pool supervisor and closes all underlying connections: | ||
|
|
||
| ```elixir | ||
| iex> {:ok, channel} = GRPC.Stub.connect("localhost:50051") | ||
| iex> {:ok, _} = GRPC.Stub.disconnect(channel) | ||
| ``` | ||
|
|
||
| The returned channel has `pool: nil`, indicating the pool is no longer active. | ||
|
|
||
| --- |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| defmodule GRPC.Client.Pool do | ||
| @moduledoc false | ||
|
|
||
| alias GRPC.Channel | ||
| alias GRPC.Client.Pool.Config | ||
|
|
||
| @call_timeout 7_000 | ||
|
|
||
| @spec start_for_address(Channel.t(), term(), non_neg_integer(), keyword()) :: | ||
| {:ok, Channel.t()} | {:error, any()} | ||
| def start_for_address(%Channel{} = vc, host, port, norm_opts) do | ||
| pool_opts = norm_opts[:pool] | ||
| address_pool_ref = make_ref() | ||
|
|
||
| config = %Config{ | ||
| pool_ref: address_pool_ref, | ||
| channel: %Channel{vc | host: host, port: port}, | ||
| pool_size: Map.get(pool_opts, :size, 1), | ||
| max_pool_overflow: Map.get(pool_opts, :max_overflow, 0), | ||
| max_client_streams_per_connection: Map.get(pool_opts, :max_streams), | ||
| adapter_opts: norm_opts[:adapter_opts] || [], | ||
| health_check_enabled: Map.get(pool_opts, :health_check_enabled, false) | ||
| } | ||
|
|
||
| case DynamicSupervisor.start_child( | ||
| GRPC.Client.Supervisor, | ||
| {GRPC.Client.Pool.Supervisor, config} | ||
| ) do | ||
| {:ok, _} -> | ||
| {:ok, %Channel{vc | host: host, port: port, pool: address_pool_ref}} | ||
|
|
||
| {:error, reason} -> | ||
| {:error, reason} | ||
| end | ||
| end | ||
|
|
||
| @spec stop_for_address(reference()) :: :ok | ||
| def stop_for_address(pool_ref) do | ||
| case Registry.lookup(GRPC.Client.Pool.Registry, {GRPC.Client.Pool.Supervisor, pool_ref}) do | ||
| [{sup_pid, _}] -> Supervisor.stop(sup_pid, :normal) | ||
| [] -> :ok | ||
| end | ||
| rescue | ||
| _ -> :ok | ||
| end | ||
|
|
||
| @spec checkout(reference()) :: {GRPC.Client.Pool.Server.State.Channel.t(), Channel.t()} | nil | ||
| def checkout(pool_ref) do | ||
| case Registry.lookup(GRPC.Client.Pool.Registry, {GRPC.Client.Pool.Server, pool_ref}) do | ||
| [{pool_pid, _}] -> | ||
| case GenServer.call(pool_pid, :take_channel, @call_timeout) do | ||
| nil -> nil | ||
| %GRPC.Client.Pool.Server.State.Channel{channel: channel} = wrapped -> {wrapped, channel} | ||
| end | ||
|
|
||
| [] -> | ||
| nil | ||
| end | ||
| end | ||
|
|
||
| @spec checkin(reference(), GRPC.Client.Pool.Server.State.Channel.t()) :: :ok | ||
| def checkin(pool_ref, wrapped_channel) do | ||
| case Registry.lookup(GRPC.Client.Pool.Registry, {GRPC.Client.Pool.Server, pool_ref}) do | ||
| [{pool_pid, _}] -> | ||
| GenServer.cast(pool_pid, {:return_channel, wrapped_channel, self()}) | ||
|
|
||
| [] -> | ||
| :ok | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| defmodule GRPC.Client.Pool.Config do | ||
| @moduledoc false | ||
|
|
||
| defstruct [ | ||
| :pool_ref, | ||
| :channel, | ||
| :pool_size, | ||
| :max_pool_overflow, | ||
| :max_client_streams_per_connection, | ||
| :adapter_opts, | ||
| :health_check_enabled | ||
| ] | ||
|
|
||
| @type t :: %__MODULE__{ | ||
| pool_ref: reference(), | ||
| channel: GRPC.Channel.t(), | ||
| pool_size: non_neg_integer(), | ||
| max_pool_overflow: non_neg_integer() | nil, | ||
| max_client_streams_per_connection: non_neg_integer() | nil, | ||
| adapter_opts: keyword(), | ||
| health_check_enabled: boolean() | ||
| } | ||
| end |
35 changes: 35 additions & 0 deletions
35
grpc/lib/grpc/client/pool/health_check/dynamic_supervisor.ex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| defmodule GRPC.Client.Pool.HealthCheck.DynamicSupervisor do | ||
| @moduledoc """ | ||
| Supervises health-check GenServers, restarts them in case of crush, | ||
| allows starting new ones dynamically | ||
| """ | ||
|
|
||
| use DynamicSupervisor | ||
|
|
||
| alias GRPC.Client.Pool.Config | ||
| alias GRPC.Client.Pool.HealthCheck.Server | ||
| alias GRPC.Client.Pool.Server.State.Channel | ||
|
|
||
| @spec start_link(Config.t()) :: Supervisor.on_start() | ||
| def start_link(%Config{} = config) do | ||
| DynamicSupervisor.start_link(__MODULE__, config, name: via_tuple(config.pool_ref)) | ||
| end | ||
|
|
||
| @impl DynamicSupervisor | ||
| def init(_args), do: DynamicSupervisor.init(strategy: :one_for_one) | ||
|
|
||
| @spec start(Channel.id(), Process.dest(), reference()) :: DynamicSupervisor.on_start_child() | ||
| def start(channel_id, conn_pid, pool_ref) do | ||
| [{dynamic_supervisor_pid, _value}] = | ||
| Registry.lookup(GRPC.Client.Pool.Registry, {__MODULE__, pool_ref}) | ||
|
|
||
| DynamicSupervisor.start_child( | ||
| dynamic_supervisor_pid, | ||
| {Server, %{channel_id: channel_id, conn_pid: conn_pid, pool_ref: pool_ref}} | ||
| ) | ||
| end | ||
|
|
||
| defp via_tuple(pool_ref) do | ||
| {:via, Registry, {GRPC.Client.Pool.Registry, {__MODULE__, pool_ref}}} | ||
| end | ||
| end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Previously
RPC.Client.Connectionwas doing this:Should
GRPC.Client.Pool.start_for_address/4also take care of the path vs host thing?I worry doing this would break for anyone who tries to do something like:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
as far as I can tell these two functions are identical - except for second parameter name. That's why I decided to remove it (the resolution happens before this function call)