feat: add supervisor

main
Moritz Böhme 2024-08-07 08:21:57 +02:00
parent 1550e896a0
commit 846d0fb16d
Signed by: moritz
GPG Key ID: 970C6E89EB0547A9
5 changed files with 29 additions and 8 deletions

View File

@ -3,7 +3,10 @@ defmodule Todo.Cache do
@impl GenServer @impl GenServer
def init(_init_args) do def init(_init_args) do
IO.puts("Starting #{__MODULE__}")
Todo.Database.start() Todo.Database.start()
{:ok, %{}} {:ok, %{}}
end end
@ -22,11 +25,11 @@ defmodule Todo.Cache do
end end
end end
def start() do def start_link(_) do
GenServer.start(__MODULE__, nil) GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end end
def server_process(pid, name) do def server_process(name) do
GenServer.call(pid, {:server_process, name}) GenServer.call(__MODULE__, {:server_process, name})
end end
end end

View File

@ -19,6 +19,8 @@ defmodule Todo.Database do
@impl GenServer @impl GenServer
def init(_) do def init(_) do
IO.puts("Starting #{__MODULE__}")
File.mkdir_p!(@db_folder) File.mkdir_p!(@db_folder)
{:ok, nil, {:continue, :init}} {:ok, nil, {:continue, :init}}
@ -36,14 +38,13 @@ defmodule Todo.Database do
end) end)
|> Map.new() |> Map.new()
IO.inspect(workers)
{:noreply, workers} {:noreply, workers}
end end
@impl GenServer @impl GenServer
def handle_cast({:store, key, data}, workers) do def handle_cast({:store, key, data}, workers) do
workers workers
|> get_worker(key) |> choose_worker(key)
|> DatabaseWorker.store(key, data) |> DatabaseWorker.store(key, data)
{:noreply, workers} {:noreply, workers}
@ -53,7 +54,7 @@ defmodule Todo.Database do
def handle_call({:get, key}, _, workers) do def handle_call({:get, key}, _, workers) do
data = data =
workers workers
|> get_worker(key) |> choose_worker(key)
|> DatabaseWorker.get(key) |> DatabaseWorker.get(key)
{:reply, data, workers} {:reply, data, workers}

View File

@ -15,6 +15,8 @@ defmodule Todo.DatabaseWorker do
@impl GenServer @impl GenServer
def init(db_folder) do def init(db_folder) do
IO.puts("Starting #{__MODULE__} with db folder #{db_folder}.")
{:ok, db_folder} {:ok, db_folder}
end end
@ -44,5 +46,4 @@ defmodule Todo.DatabaseWorker do
def file_name({db_folder, key}) do def file_name({db_folder, key}) do
Path.join(db_folder, to_string(key)) Path.join(db_folder, to_string(key))
end end
end end

View File

@ -23,6 +23,8 @@ defmodule Todo.Server do
@impl GenServer @impl GenServer
def init(name) do def init(name) do
IO.puts("Starting #{__MODULE__} for #{name}.")
{:ok, {name, nil}, {:continue, :init}} {:ok, {name, nil}, {:continue, :init}}
end end

14
lib/todo/system.ex Normal file
View File

@ -0,0 +1,14 @@
defmodule Todo.System do
use Supervisor
def start_link do
Supervisor.start_link(__MODULE__, nil)
end
def init(_) do
Supervisor.init(
[Todo.Cache],
strategy: :one_for_one
)
end
end