From 06f165fc36b101d17e9a0d4bb988ee244a7966b0 Mon Sep 17 00:00:00 2001 From: Mike Cifelli Date: Thu, 28 Mar 2024 09:33:39 -0400 Subject: [PATCH] Use a registry for nts clients --- lib/chronoscope/application.ex | 5 +++-- lib/chronoscope/nts.ex | 21 ++++++++++++++------- lib/chronoscope/nts/client.ex | 3 ++- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/lib/chronoscope/application.ex b/lib/chronoscope/application.ex index d2e16ca..df51260 100644 --- a/lib/chronoscope/application.ex +++ b/lib/chronoscope/application.ex @@ -15,8 +15,9 @@ defmodule Chronoscope.Application do {Finch, name: Chronoscope.Finch}, # Start a worker by calling: Chronoscope.Worker.start_link(arg) # {Chronoscope.Worker, arg}, - {DynamicSupervisor, name: Chronoscope.DynamicSupervisor, strategy: :one_for_one}, - {Task.Supervisor, name: Chronoscope.TaskSupervisor}, + {DynamicSupervisor, name: Chronoscope.NTS.DynamicSupervisor, strategy: :one_for_one}, + {Task.Supervisor, name: Chronoscope.NTS.TaskSupervisor}, + {Registry, [keys: :unique, name: Chronoscope.NTS.Registry]}, # Start to serve requests, typically the last entry ChronoscopeWeb.Endpoint ] diff --git a/lib/chronoscope/nts.ex b/lib/chronoscope/nts.ex index 0f56ea7..9315101 100644 --- a/lib/chronoscope/nts.ex +++ b/lib/chronoscope/nts.ex @@ -14,19 +14,26 @@ defmodule Chronoscope.NTS do end def list() do - Chronoscope.DynamicSupervisor + NTS.DynamicSupervisor |> DynamicSupervisor.which_children() |> Enum.map(fn {_, pid, _, _} -> GenServer.call(pid, :list) end) end def key_establishment(host, port) do - # todo don't use atoms for this - name = String.to_atom("#{host}:#{port}") + name = "#{host}:#{port}" - if GenServer.whereis(name) == nil do - DynamicSupervisor.start_child(Chronoscope.DynamicSupervisor, {NTS.Client, host: host, port: port, name: name}) + case Registry.lookup(NTS.Registry, name) do + [{pid, _}] -> + GenServer.call(pid, :key_establishment) + + [] -> + NTS.DynamicSupervisor + |> DynamicSupervisor.start_child({ + NTS.Client, + host: host, port: port, name: {:via, Registry, {NTS.Registry, name}} + }) + + key_establishment(host, port) end - - GenServer.call(name, :key_establishment) end end diff --git a/lib/chronoscope/nts/client.ex b/lib/chronoscope/nts/client.ex index 1752435..00ac080 100644 --- a/lib/chronoscope/nts/client.ex +++ b/lib/chronoscope/nts/client.ex @@ -1,6 +1,7 @@ defmodule Chronoscope.NTS.Client do use GenServer + alias Chronoscope.NTS alias Chronoscope.NTS.KeyEstablishmentClient @interval_in_seconds 30 @@ -54,7 +55,7 @@ defmodule Chronoscope.NTS.Client do defp server_response(state) do server = Map.take(state, [:host, :port]) - Chronoscope.TaskSupervisor + NTS.TaskSupervisor |> Task.Supervisor.async(fn -> KeyEstablishmentClient.key_establishment(server) end) |> Task.await() end