ebart

ebart

How to use Registry with Genservers to get or set data in children processes?

I’ve read interesting topic where I found practical example of how to use new Registry. Based on mentioned topic I’ve created Supervisors and Genservers, but I’m not sure if this implementation is correct for my needs or if I’m missing something. I want to create Room by room id than under it spawn Groups and many Users, Room should store all users and groups ids to fast check if user or group exists. Also I want to let user join and leave at once many groups or get all groups that user belongs to. In code below I got stuck in all functions with require IEx;IEx.pry, e.g. :get_user_groups how can I get user groups from children processes? Can I use Registry to subscribe users to their groups or in current implementation can I just extract this data by e.g. Registry.lookup?

Supervisors:

defmodule MyApp.Room.SystemsSupervisor do
  use Supervisor

  def start_link() do
    IO.puts "Starting MyApp.Room.SystemsSupervisor"

    Supervisor.start_link(
      __MODULE__,
      nil
    )
  end

  def init(_) do
    children = [
      supervisor(Registry, [:unique, Registry.ProcessRegistry], id: :proc),
      supervisor(MyApp.Room.RoomSupervisor, [])
    ]

    supervise(children, strategy: :rest_for_one)
  end
end

defmodule MyApp.Room.RoomSupervisor do
  use Supervisor

  def start_link() do
    IO.puts "Starting MyApp.Room.RoomSupervisor"

    Supervisor.start_link(
      __MODULE__,
      nil,
      name: :rooms_supervisor
    )
  end

  def start_child(room_id, user) do
    Supervisor.start_child(
      :rooms_supervisor,
      [room_id, user]
    )
  end

  def init(_) do
    children = [
      supervisor(MyApp.Room.SingleRoomSupervisor, []),
    ]

    supervise(children, strategy: :simple_one_for_one)
  end
end

defmodule MyApp.Room.SingleRoomSupervisor do
  use Supervisor

  def start_link(room_id, user) do
    IO.puts "Starting SingleRoomSupervisor"

    Supervisor.start_link(
      __MODULE__,
      {room_id, user},
      name: via_tuple(room_id)
    )
  end

  defp via_tuple(room_id) do
    {:via, Registry, {Registry.ProcessRegistry, {:room_sup, room_id}}}
  end

  def init({room_id, user}) do
    children = [
      supervisor(MyApp.Room.UserSupervisor, [room_id]),
      supervisor(MyApp.Room.GroupSupervisor, [room_id]),
      worker(MyApp.Room.Room, [room_id, user]),
    ]

    supervise(children, strategy: :one_for_all)
  end
end

defmodule MyApp.Room.GroupSupervisor do
  use Supervisor

  def start_link(room_id) do
    IO.puts "Starting MyApp.Room.GroupSupervisor"

    Supervisor.start_link(
      __MODULE__,
      nil,
      name: via_tuple(room_id)
    )
  end

  defp via_tuple(room_id) do
    {:via, Registry, {Registry.ProcessRegistry, {:group_sup, room_id}}}
  end

  def start_child(room_id, group_id, user_id) do
    Supervisor.start_child(
      via_tuple(room_id), #user_id
      [group_id, user_id]
    )
  end

  def init(_) do
    children = [
      worker(MyApp.Room.Group, [])
    ]

    supervise(children, strategy: :simple_one_for_one)
  end
end

defmodule MyApp.Room.UserSupervisor do
  use Supervisor

  def start_link(room_id) do
    IO.puts "Starting MyApp.Room.UserSupervisor"

    Supervisor.start_link(
      __MODULE__,
      nil,
      name: via_tuple(room_id)
    )
  end

  defp via_tuple(room_id) do
    {:via, Registry, {Registry.ProcessRegistry, {:user_sup, room_id}}}
  end

  def start_child(room_id, user) do
    Supervisor.start_child(
      via_tuple(room_id),
      [user.id, user.username]
    )
  end

  def init(_) do
    children = [
      worker(MyApp.Room.User, [])
    ]

    supervise(children, strategy: :simple_one_for_one)
  end
end

Genservers:

defmodule MyApp.Room.Room do
  use GenServer

  defstruct groups: [], users: [], room_id: :none

  # Client API

  def start_link(room_id, user) do
    IO.puts "Starting Room for #{room_id}"

    GenServer.start_link(
      __MODULE__,
      {room_id, user},
      name: via_tuple(room_id)
    )
  end

  defp via_tuple(room_id) do
    {:via, Registry, {Registry.ProcessRegistry, {:room, room_id}}}
  end

  def new(room_id, user) do
    # r = Registry.lookup(Registry.ProcessRegistry, {:room, room_id})
    # g = GenServer.whereis(via_tuple(room_id))
    # IO.inspect {g, "vs", r}
    case GenServer.whereis(via_tuple(room_id)) do
      nil ->
        MyApp.Room.RoomSupervisor.start_child(room_id, user)
      room_pid ->
        send(room_pid, {:real_init, room_id, user})
    end
  end

  def get_user_groups(room_id, user_id) do
    GenServer.call(via_tuple(room_id), {:get_user_groups, user_id}, 50 * 10000)
  end

  def user_joined_groups(room_id, user_id, groups) do
    GenServer.call(via_tuple(room_id), {:user_joined_groups, user_id, groups}, 50 * 10000)
  end

  def user_left_groups(room_id, user_id, groups) do
    GenServer.call(via_tuple(room_id), {:user_left_groups, user_id, groups}, 50 * 10000)
  end
  
  # Server Callbacks

  def init({room_id, user}) do
    send(self(), {:real_init, room_id, user})

    {:ok, %__MODULE__{room_id: room_id}}
  end

  def handle_call({:get_user_groups, user_id}, _from, state) do
    require IEx;IEx.pry
    {:noreply, state}
  end
  
  def handle_call({:user_joined_groups, user_id, groups}, _from, state) do
    require IEx;IEx.pry
    {:noreply, state}
  end

  def handle_call({:user_left_groups, user_id, groups}, _from, state) do
    require IEx;IEx.pry
    {:noreply, state}
  end

  def handle_info({:real_init, room_id, user}, state) do
    areas = prepare_areas(room_id, user)
    {:ok, _user} = MyApp.Room.UserSupervisor.start_child(room_id, user)

    {:noreply, %__MODULE__{state | areas: state.areas ++ areas, users: state.users ++ [user.id]}}
  end

  # Helper Functions

  defp prepare_areas(room_id, user) do
    for group <- user.groups do
      MyApp.Room.Group.new(room_id, group, user.id)
      group.id
    end
  end
end

defmodule MyApp.Room.Group do
  use GenServer

  defstruct users: [], group_id: :none

  # Client API

  def start_link(group_id, user_id) do
    IO.puts "Starting group: #{group_id}"

    GenServer.start_link(
      __MODULE__,
      [group_id, user_id],
      name: via_tuple(group_id)
    )
  end

  defp via_tuple(group_id) do
    {:via, Registry, {Registry.ProcessRegistry, {:group, group_id}}}
  end

  def new(room_id, group_id, user_id) do
    case GenServer.whereis(via_tuple(group_id)) do
      nil ->
        IO.inspect {"creating group #{group_id} with user: #{user_id}"}
        MyApp.Room.GroupSupervisor.start_child(room_id, group_id, user_id)
      group_pid ->
        IO.inspect {"updating group #{group_id} with user: #{user_id}"}
        send(group_pid, {:add_user, user_id})
    end
  end

  # Server Callbacks

  def init([group_id, user_id]) do
    {:ok, %__MODULE__{group_id: group_id, users: [user_id]}}
  end

  def handle_info({:add_user, user_id}, state) do
    {:noreply, %__MODULE__{state | users: state.users ++ [user_id]}}
  end
end


defmodule MyApp.Room.User do
  use GenServer

  defstruct username: nil, id: :none, metas: []

  # Client API

  def start_link(user_id, username) do
    IO.puts "Starting user: #{user_id}"

    GenServer.start_link(
      __MODULE__,
      [user_id, username],
      name: via_tuple(user_id)
    )
  end

  defp via_tuple(user_id) do
    {:via, Registry, {Registry.ProcessRegistry, {:user, user_id}}}
  end

  # Server Callbacks

  def init([user_id, username]) do
    {:ok, %__MODULE__{id: user_id, username: username}}
  end

end

First Post!

kokolegorille

kokolegorille

Hello @ebart

It’s not quite clear (to me) what You really want to achieve… Can You elaborate?

Why do You want to spawn a group process?
What is the link between User and Roles? I guess User can be member of group.

I guess if I wanted to know get_user_groups, I would not query the room, but the user.

Also if I wanted to send/receive info from a group of genserver, I would not ask Registry, but I would query the supervisor. (Supervisor.which_children)

Greetings

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement