A finishing project

The last project puts the pieces of the course into one small system: a supervisor, a worker that keeps a state, a test suite and a release. It is deliberately small, because the point is the shape and not the code: every part of it is a lesson the reader has already met, and the new thing is how they fit together.

The application resource

An OTP application is a folder with an ebin and one .app file, and a rebar3 project writes it from a .app.src resource. The resource names the application, its version, its callback module, the modules it holds and the applications it needs at start; this project needs kernel and stdlib and nothing else:

{application, course_kv, [{description, "A supervised key-value store"}, {vsn, "0.1.0"}, {modules, [kv]}, {registered, [kv, kv_store]}, {applications, [kernel, stdlib]}, {mod, {kv, []}}, {env, []}]}.

The block is a fragment on purpose: it is the resource file, not a program. {mod, {kv, []}} names the module whose start/2 starts the tree. The OTP applications lesson starts one by hand; the project layout lesson shows where the file lives.

A supervised store

The store below is a supervisor and its worker in one module, which is not how a large application is written but keeps this example in one file. The worker keeps a map in its loop and answers set and fetch; the program fills two keys, kills the worker and asks again:

kv.erl

-module(kv). -behaviour(supervisor). -export([main/0, start_link/0, stop/0, set/2, fetch/1, start_worker/0]). -export([init/1]). main() -> logger:set_primary_config(level, none), {ok, _Sup} = start_link(), ok = set(a, 1), ok = set(b, 2), io:format("before the crash: ~p ~p~n", [fetch(a), fetch(b)]), Old = whereis(kv_store), exit(Old, boom), _New = wait_for_new(Old, 200), io:format("after the restart: ~p ~p~n", [fetch(a), fetch(b)]), ok = stop(). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). stop() -> case whereis(?MODULE) of undefined -> ok; Pid -> unlink(Pid), exit(Pid, shutdown), wait_gone(100) end. set(Key, Value) -> kv_store ! {put, Key, Value, self()}, receive {stored, Key} -> ok end. fetch(Key) -> kv_store ! {get, Key, self()}, receive {value, Key, Value} -> Value end. start_worker() -> Pid = spawn_link(fun() -> true = register(kv_store, self()), loop(#{}) end), {ok, Pid}. init([]) -> SupFlags = #{strategy => one_for_one, intensity => 5, period => 10}, Child = #{id => kv_store, start => {?MODULE, start_worker, []}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}, {ok, {SupFlags, [Child]}}. loop(Store) -> receive {put, Key, Value, From} -> From ! {stored, Key}, loop(Store#{Key => Value}); {get, Key, From} -> From ! {value, Key, maps:get(Key, Store, undefined)}, loop(Store) end. wait_for_new(_Old, 0) -> exit(no_store); wait_for_new(Old, Tries) -> case whereis(kv_store) of Pid when is_pid(Pid), Pid =/= Old -> Pid; _Other -> timer:sleep(10), wait_for_new(Old, Tries - 1) end. wait_gone(0) -> ok; wait_gone(Tries) -> case whereis(?MODULE) of undefined -> ok; _Pid -> timer:sleep(5), wait_gone(Tries - 1) end.

erlc kv.erl

erl -noshell -eval 'kv:main(), halt()'

before the crash: 1 2 after the restart: undefined undefined

The supervisor restarted the worker, and the two keys are gone: the state lived in the loop, so a new loop starts from the empty map. That is the whole lesson of the ETS and DETS lessons: a store that must survive the restart keeps its data outside the process, and the process is only the door to it. A real store would name the table in init/1 and let the worker read it after every restart.

A test suite

EUnit runs every exported function whose name ends in _test and no header is needed. The suite starts the store, exercises it and stops it, so each test begins from a clean tree:

kv_tests.erl

-module(kv_tests). -export([store_test/0, missing_test/0]). store_test() -> {ok, _Sup} = kv:start_link(), ok = kv:set(a, 1), 1 = kv:fetch(a), ok = kv:stop(). missing_test() -> {ok, _Sup} = kv:start_link(), undefined = kv:fetch(nothing), ok = kv:stop().

erlc kv.erl kv_tests.erl

erl -noshell -pa . -eval 'eunit:test(kv_tests, []), halt().'

2 tests passed.

Each test is a sequence of matches: a value that does not match raises badmatch, EUnit counts the exception as a failure and prints the expected and the actual value. The EUnit lesson explains the naming rule, the asserts of a test that needs one, and why the Alpine package has no eunit.hrl. A project runs the same suite with rebar3 eunit, and the xref and static checks lesson puts it in a CI loop next to Dialyzer.

A release

The last step is a release: rebar3 release compiles the application, copies it and its dependencies into a folder with a boot script, and that folder starts on a machine that has no Erlang installed of its own. The releases lesson builds one and reads its folders; the file that turns the project into a release is one block in rebar.config:

{relx, [{release, {course_kv, "0.1.0"}, [course_kv, sasl]}, {dev_mode, false}, {include_erts, true}]}.

The block is a fragment, not a file of this page. With it, rebar3 release writes _build/default/rel/course_kv, and bin/course_kv start runs the supervised store as a service. The hot upgrades lesson takes the next step: a second version of the same release, installed while the first one runs.

That is the shape of a finished Erlang system: an application resource, a supervised tree with the state outside the process that serves it, a test suite that starts and stops the tree, and a release that carries its own runtime. Every lesson of the course is one of those pieces, and the course page opens the chapter that has the one a reader needs next.

Questions

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

  1. What does the mod key of an application resource name?

    Answer

    The module with the start callback

    {mod, {Module, Args}} names the application callback module and its start argument.

  2. What happens to the keys of the store when the worker is killed?

    Answer

    They are gone, because the state lived in the loop

    The map is an argument of the loop, so a restarted loop begins with the empty map.

  3. How does the store survive a restart in a real system?

    Answer

    With the data outside the process, in ETS or DETS

    The process is only the door to the data; a table owned elsewhere keeps it.

  4. Which functions does EUnit run in a test module?

    Answer

    The exported functions whose name ends in _test

    EUnit runs the exported _test functions, and _test_ generators with them.

  5. What does rebar3 release produce?

    Answer

    A folder with the runtime, the applications and a boot script

    The release carries its own ERTS and starts the application from its boot script.

  6. Why does each test start and stop the store?

    Answer

    So every test begins from a clean tree

    A test that leaves a registered name behind makes the next one fail for the wrong reason.

  7. What does this module print? -module(q1). -behaviour(supervisor). -export([main/0, init/1]). main() -> logger:set_primary_config(level, none), {ok, _} = supervisor:start_link({local, q1_sup}, q1, []), io:format("~p~n", [whereis(q1_sup) =/= undefined]). init([]) -> {ok, {#{strategy => one_for_one}, []}}.

    Answer

    true

    The supervisor is registered under the name the caller asked for, so the lookup finds it.

  8. What does this module print? -module(q2). -export([main/0, loop/1]). main() -> Loop = spawn(?MODULE, loop, [#{}]), Loop ! {put, a, 1}, timer:sleep(20), io:format("~p~n", [is_process_alive(Loop)]). loop(Store) -> receive {put, K, V} -> loop(Store#{K => V}) end.

    Answer

    true

    The loop handles the message and calls itself with the new map, so the process stays alive.

  9. What does this module print? -module(q3). -behaviour(supervisor). -export([main/0, init/1]). main() -> {ok, Sup} = supervisor:start_link({local, q3_sup}, q3, []), unlink(Sup), exit(Sup, shutdown), timer:sleep(50), io:format("~p~n", [whereis(q3_sup)]). init([]) -> {ok, {#{strategy => one_for_one}, []}}.

    Answer

    undefined

    A supervisor stopped with shutdown unregisters its name, so the lookup answers undefined.

  10. What does this module print? -module(q4). -export([main/0]). main() -> Store = #{a => 1}, io:format("~p ~p~n", [maps:get(a, Store, undefined), maps:get(b, Store, undefined)]).

    Answer

    1 undefined

    The key a is present and b is not, so the default of the three argument form answers undefined.

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. The release command was not run here: it builds and starts a release.

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