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

View File

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

View File

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

View File

@ -1,8 +1,12 @@
defmodule Todo.Server do
use GenServer
use GenServer, restart: :temporary
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
def add(pid, entry) do