Sunday, August 3, 2014

empty supervisor

Problem

Sometimes Erlang application consists only of utility functions without any processes spawning. In such cases usually supervisor child specification in supervisor:init/1 is an empty list. Supervisor's process, which does nothing, is likely something developers should not worry about, but this situation can be resolved in more elegant way.

Solution

If application's boilerplate code is generated from standard template (for example,
rebar create-app), it usually contains:

  1. <application>.app (<application>.app.src) with application specification;
  2. <application>_sup.erl, which implements supervisor behaviour;
  3. <application>_app.erl, which implements application behaviour.
If supervisor's module is removed, application crashes on start since application:start/2 callback must return a pid of supervisor. So <application>_app.erl should be removed as well. After that application can not be started again, because module with application behaviour implementation is specified in <application>.app (<application>.app.src) in mod section.

{mod, { <application>_app, []}}
So that should be deleted too. As a result two unnecessary files were deleted from the project. Example of described application could be found here.

Exceptions

In very rare applications "state" could be stored not in process' state but in public ETS or other "not pure functional" techniques might be used. For that cases application:start/2 callback should be implemented even with empty supervisor. For instance, public ETS could be created on start of application.
Sometimes processes are started not under top-level supervisor, illustration of this is Cowboy web server. In all examples empty supervisor is used and Cowboy is started in application:start/2 callback.