#Process/Supervisor structure

16 messages · Page 1 of 1 (latest)

toxic oasis
#

Complete newbie here trying to write a small library/module for interacting with a certain API and I'm having trouble structuring things
the interface I'm aiming for looks something like this:

defmodule Connection do
  def start_link(_arg) ... end
  def send(pid, ws, message) ... end
  def subscribe(pid, ws, message_type) ... end
  def unsubscribe(pid, ws, message_type) ... end
end

You'd call start_link, get a PID back and call the other functions with it etc
the API itself is rather strange and requires a client to be connected to two separate websockets at the same time so to try to make things simple I'm using a one_for_all supervisor to restart both whenever one fails

- connection_serv (keeps track of and serves messages to subscribers) 
- connection_ws_sup (one_for_all, started by connection_serv)
  - connection_ws0 (relays msgs to connection_serv)
  - connection_ws1 (relays msgs to connection_serv)

What I'm confused about is how connection_serv and connection_ws_sup should be "linked" together. I feel like the right thing to do here is to add another supervisor but then the server wouldn't be the "root" process anymore, and I'd have to be able to somehow reach the server with the supervisor's PID to implement the above interface. Should I just link the two processes together instead?

ancient merlin
#

I don't know the ideal solution, but I would do something like this as a working draft:

Supervisor -> Start Process A
Process A init/2 -> Start Process B
Process A init/2 -> Monitor process B
#

So, if process B dies here, you would be able to handle it in process A, and let process A die. The supervisor would pick this up, restarting A and so on and so on

#

does that make sense?

toxic oasis
#

That sounds like it'd work but now I'm thinking what if code external to this module needs to supervise process A?

#

there's no way to transfer a process from one supervisor to another right?

ancient merlin
#

You don't. You let the user determine how they do it if this was a library

#

All that I can think of at the moment is ideally giving the user the option to name the process instead.

#

Users might want to use a Registry for example

#

The only thing that matters is how your thing handles the nature of the API; how people use it is up to them and a process identifier already gives a lot of options.

toxic oasis
#

it feels a little silly having to implement my own supervision when supervisors are a thing though

ancient merlin
#

It does, but the problem in this instance is that something you've surmised: you can't get the PID of the child processes when the supervisor starts it up.

#

If you didn't need to link them or have one process directly know how to communicate to the other, then using your original idea would work