Current section

Files

Jump to
grains lib grains supervisor.ex
Raw

lib/grains/supervisor.ex

defmodule Grains.Supervisor do
use Supervisor
alias Grains.Bread
@type t :: Supervisor.name()
def start_link(recipe, grains, args \\ []) do
bread = Bread.bake(recipe, grains, args)
with :ok <- Bread.check(bread) do
name = Grains.concat_name(bread, GrainMainSup)
Supervisor.start_link(__MODULE__, [bread, name], name: name)
end
end
def init([bread, name]) do
bread_sup = Grains.concat_name(bread, BreadSup)
table = :ets.new(name, [:named_table])
true = :ets.insert(table, {:bread, bread})
children = [
%{
id: :bread_supervisor,
type: :supervisor,
start:
{Supervisor, :start_link,
[
bread.child_specs,
[strategy: :one_for_one, name: bread_sup]
]}
}
]
Supervisor.init(children, strategy: :one_for_one)
end
@doc """
Retrieve the root bread name.
This function assumes that the supervisor has a registered name.
"""
def get_root_name(supervisor) do
{:registered_name, name} = Process.info(supervisor, :registered_name)
[{:bread, bread}] = :ets.lookup(name, :bread)
bread.name
end
@doc """
Retrieve the bread supervisor.
Crashes if `:bread_supervisor` is not started.
"""
def get_bread_supervisor(supervisor) do
{:bread_supervisor, pid, :supervisor, _} =
supervisor
|> Supervisor.which_children()
|> Enum.find(fn {id, _, _, _} -> id == :bread_supervisor end)
pid
end
@doc """
Retrieve the id and registered name of currently running grains.
"""
def which_grains(supervisor) do
supervisor
|> get_bread_supervisor()
|> Supervisor.which_children()
|> Enum.map(fn {id, pid, _, _} ->
{:registered_name, registered_name} = Process.info(pid, :registered_name)
%{id: id, registered_name: registered_name}
end)
end
@doc """
Get the original recipe underlying the `supervisor`.
"""
def get_original_recipe!(supervisor) when is_pid(supervisor) do
{:registered_name, name} = Process.info(supervisor, :registered_name)
get_original_recipe!(name)
end
def get_original_recipe!(name) when is_atom(name) do
[{:bread, bread}] = :ets.lookup(name, :bread)
bread.original_recipe
end
end