elixir-todo-list/lib/todo/database.ex

51 lines
967 B
Elixir
Raw Normal View History

2024-08-07 00:09:00 +02:00
defmodule Todo.Database do
2024-08-07 10:03:31 +02:00
use Supervisor
2024-08-07 00:09:00 +02:00
@db_folder "./persist"
2024-08-07 10:03:31 +02:00
@pool_size 3
2024-08-07 00:09:00 +02:00
2024-08-07 10:03:31 +02:00
def start_link do
Supervisor.start_link(__MODULE__, nil)
2024-08-07 00:09:00 +02:00
end
2024-08-07 10:03:31 +02:00
@impl Supervisor
2024-08-07 00:09:00 +02:00
def init(_) do
2024-08-07 10:03:31 +02:00
IO.puts("Starting #{__MODULE__}.")
2024-08-07 08:21:57 +02:00
2024-08-07 00:09:00 +02:00
File.mkdir_p!(@db_folder)
2024-08-07 10:03:31 +02:00
children = Enum.map(1..@pool_size, &worker_spec/1)
2024-08-07 00:09:00 +02:00
2024-08-07 10:03:31 +02:00
Supervisor.init(children, strategy: :one_for_one)
2024-08-07 00:09:00 +02:00
end
2024-08-07 10:03:31 +02:00
defp worker_spec(worker_id) do
default_worker_spec = {Todo.DatabaseWorker, {@db_folder, worker_id}}
Supervisor.child_spec(default_worker_spec, id: worker_id)
2024-08-07 00:48:49 +02:00
end
2024-08-07 00:09:00 +02:00
2024-08-07 10:03:31 +02:00
def child_spec(_) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, []},
type: :supervisor
}
end
2024-08-07 00:09:00 +02:00
2024-08-07 10:03:31 +02:00
def store(key, data) do
key
|> choose_worker()
|> Todo.DatabaseWorker.store(key, data)
2024-08-07 00:09:00 +02:00
end
2024-08-07 10:03:31 +02:00
def get(key) do
key
|> choose_worker()
|> Todo.DatabaseWorker.get(key)
end
2024-08-07 00:48:49 +02:00
2024-08-07 10:03:31 +02:00
defp choose_worker(key) do
2024-08-07 10:33:19 +02:00
:erlang.phash2(key, @pool_size) + 1
2024-08-07 00:09:00 +02:00
end
end