Skip to content

Commit 97b3040

Browse files
committed
Dynamically start Finch pool with the given proxy configs
1 parent 07f39a5 commit 97b3040

File tree

3 files changed

+39
-53
lines changed

3 files changed

+39
-53
lines changed

lib/http_client/adapters/finch.ex

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,18 +43,45 @@ defmodule HTTPClient.Adapters.Finch do
4343
defp normalize_option({:recv_timeout, value}), do: {:receive_timeout, value}
4444
defp normalize_option({key, value}), do: {key, value}
4545

46-
defp get_client do
47-
case Application.get_env(:http_client, :proxy, nil) do
48-
nil -> FinchHTTPClient
49-
proxies -> get_client_with_proxy(proxies)
46+
defp get_client() do
47+
:http_client
48+
|> Application.get_env(:proxy)
49+
|> get_client_name()
50+
end
51+
52+
defp get_client_name(nil), do: HTTPClient.Finch
53+
54+
defp get_client_name(proxies) when is_list(proxies) do
55+
proxies
56+
|> Enum.random()
57+
|> get_client_name()
58+
end
59+
60+
defp get_client_name(proxy) when is_map(proxy) do
61+
name = custom_pool_name(proxy)
62+
pools = %{default: [conn_opts: [proxy: compose_proxy(proxy)]]}
63+
child_spec = {Finch, name: name, pools: pools}
64+
65+
case DynamicSupervisor.start_child(HTTPClient.FinchSupervisor, child_spec) do
66+
{:ok, _} -> name
67+
{:error, {:already_started, _}} -> name
5068
end
5169
end
5270

53-
defp get_client_with_proxy(proxy) when is_map(proxy) do
54-
FinchHTTPClientWithProxy_0
71+
defp compose_proxy(proxy) do
72+
{proxy.scheme, proxy.address, to_integer(proxy.port), proxy.opts}
5573
end
5674

57-
defp get_client_with_proxy(proxies) when is_list(proxies) do
58-
:"FinchHTTPClientWithProxy_#{Enum.random(0..length(proxies))}"
75+
defp to_integer(term) when is_integer(term), do: term
76+
defp to_integer(term) when is_binary(term), do: String.to_integer(term)
77+
78+
defp custom_pool_name(opts) do
79+
name =
80+
opts
81+
|> :erlang.term_to_binary()
82+
|> :erlang.md5()
83+
|> Base.url_encode64(padding: false)
84+
85+
Module.concat(HTTPClient.FinchSupervisor, "Pool_#{name}")
5986
end
6087
end

lib/http_client/adapters/finch/config.ex

Lines changed: 0 additions & 44 deletions
This file was deleted.

lib/http_client/application.ex

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ defmodule HTTPClient.Application do
44
use Application
55

66
def start(_type, _args) do
7-
children = [] ++ HTTPClient.Adapters.Finch.Config.children()
7+
children = [
8+
{Finch, name: HTTPClient.Finch},
9+
{DynamicSupervisor, strategy: :one_for_one, name: HTTPClient.FinchSupervisor}
10+
]
811

912
opts = [strategy: :one_for_one, name: HTTPClient.Supervisor]
1013
Supervisor.start_link(children, opts)

0 commit comments

Comments
 (0)