feat: extend supervision tree

main
Moritz Böhme 2024-08-07 10:33:19 +02:00
parent 1c197381b7
commit 7ba3b1cd4f
Signed by: moritz
GPG Key ID: 970C6E89EB0547A9
4 changed files with 21 additions and 25 deletions

View File

@ -1,33 +1,25 @@
defmodule Todo.Cache do defmodule Todo.Cache do
use GenServer use DynamicSupervisor
@impl GenServer def start_link(init_arg) do
def init(_init_args) do
IO.puts("Starting #{__MODULE__}") IO.puts("Starting #{__MODULE__}")
{:ok, %{}} DynamicSupervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
end end
@impl GenServer @impl DynamicSupervisor
def handle_call({:server_process, name}, _from, state) do def init(_) do
case Map.fetch(state, name) do DynamicSupervisor.init(strategy: :one_for_one)
{:ok, process} -> end
{:reply, process, state}
:error -> def server_process(todo_list_name) do
{:ok, new_process} = Todo.Server.start_link(name) case start_child(todo_list_name) do
{:ok, pid} -> pid
new_state = Map.put(state, name, new_process) {:error, {:already_started, pid}} -> pid
{:reply, new_process, new_state}
end end
end end
def start_link(_) do defp start_child(todo_list_name) do
GenServer.start_link(__MODULE__, nil, name: __MODULE__) DynamicSupervisor.start_child(__MODULE__, {Todo.Server, todo_list_name})
end
def server_process(name) do
GenServer.call(__MODULE__, {:server_process, name})
end end
end end

View File

@ -45,6 +45,6 @@ defmodule Todo.Database do
end end
defp choose_worker(key) do defp choose_worker(key) do
:erlang.phash2(key, @pool_size) :erlang.phash2(key, @pool_size) + 1
end end
end end

View File

@ -44,7 +44,7 @@ defmodule Todo.DatabaseWorker do
{:ok, contents} -> {:ok, contents} ->
:erlang.binary_to_term(contents) :erlang.binary_to_term(contents)
_ -> {:error, :enoent} ->
nil nil
end end

View File

@ -1,8 +1,12 @@
defmodule Todo.Server do defmodule Todo.Server do
use GenServer use GenServer, restart: :temporary
def start_link(name) do def start_link(name) do
GenServer.start_link(__MODULE__, name) GenServer.start_link(__MODULE__, name, name: via_tuple(name))
end
def via_tuple(name) do
Todo.ProcessRegistry.via_tuple({__MODULE__, name})
end end
def add(pid, entry) do def add(pid, entry) do