bezzoon
bezzoon

Reputation: 2019

How to model a supervisor tree in Elixir

Let's say that I have a Zone dynamic supervisor (zone is a genserver), and each Zone has its own Player dynamic supervisor (player is a genserver).

So each Zone has many players, and I have many zones.

Is the way to do that just to store the PID of the Player supervisor in the Zone GenServer?

Is this the correct approach? And then when I start a Zone start a Player supervisor as well?

This is purely conceptual and I am new to doing this sort of thing. I would appreciate any learning resources on this as well!

Upvotes: 2

Views: 67

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

just to store the PID of the PlayerSupervisor in the ZoneGenServer?

This would be not robust enough if the PlayerSupervisor crashes for some reason. One way would be to make ZoneGenServer trap exists of the respective PlayerSupervisor and also crash upon PlayerSupervisor crash, but that would mean you are implementing part of OTP already provided. I would go with the following (ZoneSupervisor is started with :rest_for_one strategy, all others with :one_for_one):


           ————————————————————
           |  ZoneSupervisor  |
           ————————————————————
               ⇓          ⇓
————————————————————  ——————————————————
| PlayerSupervisor |  |  ZoneGenServer |
————————————————————  ——————————————————
         ⇓
————————————————————
|  PlayerGenServer |
————————————————————

Now when we are safe against crashes, the only thing would be to make ZoneGenServer aware of PlayerSupervisor. It might be done by asking ZoneSupervisor about its children and/or by name registration with {:via, module, term}. Using PID as a process handler is vulnerable to process restarts (due to crashes etc.) PID changes, the registered name does not.

Upvotes: 4

Related Questions