diff --git a/lib/chronoscope/application.ex b/lib/chronoscope/application.ex index 735d1ac..79488ab 100644 --- a/lib/chronoscope/application.ex +++ b/lib/chronoscope/application.ex @@ -15,6 +15,7 @@ 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}, Chronoscope.NTS.Client, # Start to serve requests, typically the last entry diff --git a/lib/chronoscope/nts.ex b/lib/chronoscope/nts.ex index 02796bb..5f12213 100644 --- a/lib/chronoscope/nts.ex +++ b/lib/chronoscope/nts.ex @@ -7,17 +7,25 @@ defmodule Chronoscope.NTS do require Logger - alias Chronoscope.NTS.Client + alias Chronoscope.NTS def healthy?() do - GenServer.call(Client, :healthy?) + true end def list() do - GenServer.call(Client, :list) + DynamicSupervisor.count_children(Chronoscope.DynamicSupervisor) + |> IO.inspect() end def key_establishment(host, port) do - GenServer.call(Client, {:key_establishment, %{host: host, port: port}}, 10_000) + # todo don't use atoms for this + name = String.to_atom("#{host}#{port}") + + if GenServer.whereis(name) == nil do + DynamicSupervisor.start_child(Chronoscope.DynamicSupervisor, {NTS.Client, name: name}) + end + + GenServer.call(name, {:key_establishment, %{host: host, port: port}}) end end diff --git a/lib/chronoscope/nts/client.ex b/lib/chronoscope/nts/client.ex index 04ab01c..ca2b66b 100644 --- a/lib/chronoscope/nts/client.ex +++ b/lib/chronoscope/nts/client.ex @@ -5,8 +5,8 @@ defmodule Chronoscope.NTS.Client do @interval_in_seconds 30 - def start_link(_) do - GenServer.start_link(__MODULE__, :ok, name: __MODULE__) + def start_link(name: name) do + GenServer.start_link(__MODULE__, :ok, name: name) end @impl true @@ -14,11 +14,6 @@ defmodule Chronoscope.NTS.Client do {:ok, %{}} end - @impl true - def handle_call(:healthy?, _from, state) do - {:reply, true, state} - end - @impl true def handle_call(:list, _from, state) do {:reply, state, state} @@ -56,17 +51,16 @@ defmodule Chronoscope.NTS.Client do defp initial_data(now) do %{ - response: {:error, "uninitialized"}, + key_establishment_response: {:error, "initializing"}, last_key_establishment: DateTime.add(now, -@interval_in_seconds, :second) } end defp current_data(server, now) do - # fixme - handle each request asynchronously response = Chronoscope.TaskSupervisor |> Task.Supervisor.async(fn -> KeyEstablishmentClient.key_establishment(server) end) - |> Task.await(10_000) + |> Task.await() %{ key_establishment_response: response,