Make asynchronous server requests

This commit is contained in:
Mike Cifelli 2024-03-27 13:46:24 -04:00
parent 0a6858fa4a
commit 9cbb59fca3
Signed by: mike
GPG Key ID: 6B08C6BE47D08E4C
3 changed files with 17 additions and 14 deletions

View File

@ -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

View File

@ -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

View File

@ -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,