OTP design principles

The behaviours of this chapter are one idea repeated: a module declares that it follows a contract, the runtime calls the functions of the contract, and the module fills them in. OTP design principles are that idea carried through a whole system: every process is a callback module of a behaviour, every tree has a supervisor, every application names its dependencies, and every release can be started, stopped and upgraded. The GenServer, supervisors, applications and releases lessons build the parts; this one states the rules that hold them together.

A behaviour is a contract

A behaviour module declares the callbacks with the -callback attribute, and the compiler turns those declarations into a behaviour_info/1 function. A module that adds -behaviour(job) promises to export every function of that list, and the compiler checks the promise. The program below declares its own behaviour with one callback, reads the list back, and runs the check a plugin loader runs before it calls a plugin:

job.erl

-module(job). -export([main/0, callbacks/0, check/1]). -callback run(term()) -> ok | {error, term()}. main() -> io:format("job callbacks: ~p~n", [callbacks()]), io:format("job check: ~p~n", [check(?MODULE)]), io:format("application: ~w~n", [lists:sort(application:behaviour_info(callbacks))]). callbacks() -> ?MODULE:behaviour_info(callbacks). check(Module) -> {module, Module} = code:ensure_loaded(Module), Required = Module:behaviour_info(callbacks), Missing = [Callback || {Name, Arity} = Callback <- Required, not erlang:function_exported(Module, Name, Arity)], case Missing of [] -> ok; _ -> {missing, Missing} end.

erlc job.erl

erl -noshell -eval 'job:main(), halt().'

job callbacks: [{run,1}] job check: {missing,[{run,1}]} application: [{config_change,3},{prep_stop,1},{start,2},{start_phase,3},{stop,1}]

The module declares run/1 and does not export it, so its own check finds the callback missing: that is what a plugin loader reports as {missing, [{run,1}]} instead of crashing into an undef halfway through a call. erlang:function_exported/3 answers only for a module that is loaded, which is why the check loads it first, and the last line reads the callback list of a behaviour OTP itself ships.

When the contract is broken

The compiler reports a missing callback as a warning, and a project that compiles with -Werror treats that warning as a failed build. The file below declares gen_server and exports only init/1. The block is a fragment: the -module line is left out so that the two attributes it reports on are the whole subject, and the line numbers are those of the saved file, where the module line is line one. The command is the plain compiler of a reader, so the warning does not stop it:

half_server.erl

-behaviour(gen_server). -export([init/1]). init(_Args) -> {ok, 0}.

erlc half_server.erl

half_server.erl:2:2: Warning: undefined callback function handle_call/3 (behaviour 'gen_server') half_server.erl:2:2: Warning: undefined callback function handle_cast/2 (behaviour 'gen_server')

The warning names the line of -behaviour, not the missing function, and a real build with -Werror stops there. The mistake a beginner makes is to read that warning as harmless because the module compiles: it does compile, and it fails the first time the runtime calls a callback that is not there. The callbacks of gen_server are init/1, handle_call/3, handle_cast/2, handle_info/2 and terminate/2, plus the optional handle_continue/2 and code_change/3. The contract is also the shape of what a callback returns: a handle_call/3 that answers a bare ok instead of {reply, Value, State} stops the server with bad_return_value at the first call.

The checklist

These are the rules the lessons of this chapter followed one at a time. A module that breaks one of them still compiles, which is why the list is worth keeping:

A codebase that follows the list is one where a crash report names the process, the supervisor restarts the part that failed, and the release that is running is the one that was tested. That is what OTP design principles buy, and none of it needs a package from outside the Erlang distribution.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a behaviour module declare?

    Answer

    The callbacks another module must export

    -callback attributes become behaviour_info/1, and the declarations are the contract.

  2. What does the compiler do when a module declares -behaviour(gen_server) and misses a callback?

    Answer

    It warns, and with -Werror the build fails

    A missing callback is a warning that a project with warnings as errors turns into a failed build.

  3. What does Module:behaviour_info(callbacks) answer?

    Answer

    The list of {Name, Arity} pairs the behaviour requires

    The attribute list is compiled into that function, and a loader can read it before it calls anything.

  4. Why does a start function have to link the child it starts?

    Answer

    The supervisor only learns of a death through the link

    An unlinked child dies alone, and the supervisor keeps a dead pid in its bookkeeping.

  5. Why must state that survives a restart live outside the process?

    Answer

    A restart starts a new process with its initial state

    The supervisor restores the shape of the tree, and init/1 starts from the initial state again.

  6. What does a blocking call in a callback do to a server?

    Answer

    It blocks every request behind it

    One process handles one message at a time, so a slow callback delays the whole mailbox.

  7. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [lists:sort(application:behaviour_info(callbacks))]).

    Answer

    [{config_change,3},{prep_stop,1},{start,2},{start_phase,3},{stop,1}]

    The application behaviour declares five callbacks, and behaviour_info/1 answers them sorted.

  8. What does this module print? -module(q2). -export([main/0]). main() -> Loaded = code:ensure_loaded(lists), Exported = erlang:function_exported(lists, reverse, 1), io:format("~p~n", [{Loaded, Exported}]).

    Answer

    {{module,lists},true}

    The module is loaded first, and a loaded module that defines the callback exports it.

  9. What does this module print? -module(q3). -export([main/0]). -callback ping() -> pong. main() -> io:format("~p~n", [?MODULE:behaviour_info(callbacks)]).

    Answer

    [{ping,0}]

    A callback is a name and an arity, and a behaviour with one callback answers one pair.

  10. What does this module print? -module(q4). -behaviour(gen_server). -export([main/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]). main() -> {ok, Pid} = gen_server:start(?MODULE, 5, []), io:format("~p~n", [gen_server:call(Pid, state)]). init(State) -> {ok, State}. handle_call(state, _From, State) -> {reply, State, State}. handle_cast(_Message, State) -> {noreply, State}. handle_info(_Message, State) -> {noreply, State}. terminate(_Reason, _State) -> ok.

    Answer

    5

    The start function passes five to init/1, and the call replies with the state the loop keeps.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev