Trying to understand best way to structure supervision tree in game / player application

I have a room supervisor that starts rooms, and a player supervisor that starts players.

Room has add_player_into/2 function which starts a player through player supervisor and then adds it’s ref into it’s own state

This is what I want because I want the room to stay up if a player crashes, but also be notified.

I’m stuck at if I want all monitored players to crash if my room crashes. It feels like supervision is the only way?

If it is the only way, I read somewhere that supervisors should contain no logic or state and just handle spawning children (which was the reason for the supervision tree I used). If so, how do I handle logic that belongs at the supervisor level? Spawn a named child that handles that state?

‘logic that belongs at the supervisor level’ such as stopping all contained players is exactly the (only) kind of logic that should be part of a Supervisor.

In this case, you probably want to link your players to the room supervisor, but have the room supervisor trap exits (which will notify it about players crashing without crashing itself, but will have players crashing as soon as the room supervisor crashes).

1 Like

That makes sense,

What about logic that also belongs at the room level? Say room state logic. Should I have room supervisor spawn a room server as well as player servers?

Ideally you should decouple logic from OTP behaviours such as GenServers. A great book that exemplifies this is “Functional Web Development with Elixir, OTP and Phoenix”, where the author makes a multiplayer battleships game (with a different name) and he builds the entire game logic separate from the processes that use it.

If you only want to be notified, then having a look a Monitors VS Supervisors may be more up your alley.

As for what kind of logic should a behaviour contain, it depends, @Qqwy gave you a good advice IMHO.

Usually something like this diagram: nomnoml

(The normal lines are supervision-links, the dashed lines are monitors).

These kinds of setups are also described in great detail in Elixir in Action, which I wholeheartedly recommend :smiley:!

2 Likes