How to write mesh-native services with mcl-core

View Source

A "mesh-native" service is one that talks to other services over the mesh — connects, calls, publishes, subscribes, moves bytes — without hand-rolling any of the plumbing macula already gives you.

If you only need the boot lifecycle (mcl_core_service, capability declaration, store/read-model wiring), see service_anatomy.md first — this guide assumes you already have a booting service and want it to actually talk to the mesh.

Each wrapper is referred to below as piece A/B/C/D/E/F/G/H; the CHANGELOG, from 0.1.0 onward, records how each one landed.

mcl_core does not reimplement mesh I/O. Every wrapper below is a thin resolve-your-handles-then-call-the-real-thing layer over macula's own supervised primitives — macula_publisher, macula_subscriber, macula_response, macula_feeder/macula_download — not raw synchronous calls (macula:publish/4, macula:call/5, ...). That distinction is why you get things a hand-rolled catch macula:publish(...) never gave you: cancellable in-flight operations, automatic reconnect-survival, and (for publish) free pubsub.publish_started_v1/_completed_v1 mesh facts.

Two layers, not one. macula (the SDK) wraps its own raw wire protocol into those supervised OTP behaviours — that work is macula's, already done, for every primitive mentioned in this guide, streaming and file-push included. mcl_core wraps a second time, on top of some of those, resolving this service's own pool/realm automatically so you don't repeat that boilerplate. Only some primitives have that second layer yet — chapters 4 and 5 below are explicit about which.

Chapter 1: How to connect to the mesh

There is nothing to call to "connect." A service configured with station seeds (see service_anatomy.md's sys.config.src section) connects automatically at boot: mcl_core_sup starts the mesh pool as an ordinary supervised child (piece A) alongside your service's own supervision tree. If the pool process ever dies unexpectedly, OTP restarts it — no code anywhere reacts to a crash, because nothing needs to. A station being temporarily unreachable doesn't crash anything either: each seed dials and retries forever on its own timer, invisibly, whether or not any station ever answers.

What you actually interact with is mcl_core:mesh_handles/0 — the pool + realm pair every wrapper in this guide resolves internally before doing real work:

-spec mesh_handles() -> {ok, Pool :: term(), Realm :: binary()} | {error, mesh_unavailable}.

You will rarely call this directly — every function in chapters 2–5 resolves it for you and degrades the same way if this service isn't attached to a pool or has no realm configured yet: {error, mesh_unavailable}, never a raise. If you ever find yourself writing case {mcl_core:macula_client(), mcl_core:realm()} of {{ok,_}, {ok,_}} -> ... ; _ -> ok end by hand, stop — that pairing already exists, and reaching for it yourself means duplicating boilerplate ~20 services in this workspace independently wrote before it did.

The individual accessors underneath (macula_client/0, realm/0, identity_key/0, and mcl_core_identity's org/0) never raise either, even if called before this service's identity subsystem has started — they return {error, not_booted} (piece H) rather than the noproc exit three independent services used to hand-roll a try/catch around. In practice you shouldn't need to know this; it matters only if you're reaching past the facade into mcl_core_identity directly.

Chapter 2: How to call functions over the mesh (RPC)

Serving a call (piece B)

Add handler => {HandlerModule, Args} to a capability in your capabilities/0 callback. HandlerModule implements -behaviour(macula_response):

%% my_x_service.erl
capabilities() ->
    [#{name => <<"my_x.echo">>, version => 1,
       handler => {my_x_echo_handler, []},
       %% WHO MAY CALL IT. Required for a handler-bearing capability, and
       %% there is no default (macula 18, macula#147): `open' (any
       %% identified caller), `{callers, members}', `{callers, role}',
       %% `{callers, {nodes, [NodeId]}}', `handler_authorizes', or one of
       %% the token-gated policies. mcl_core refuses to register this
       %% capability without it, naming it.
       auth => {callers, members}}].
%% my_x_echo_handler.erl
-module(my_x_echo_handler).
-behaviour(macula_response).
-export([init/1, handle_request/2]).

init(_Args) -> {ok, []}.

handle_request(Payload, State) ->
    {reply, #{echo => Payload}, State}.

mcl_core:boot/1 registers this into mcl_core_capabilities, which advertises it via macula_response:advertise_direct/7 — the one call that both registers the handler with the pool and publishes the signed procedure_advertisement DHT record naming your serving station, so it's discoverable and callable. Re-advertised every 30s; a station's wire-level registration is tied to the connection that sent it and doesn't survive that connection being replaced, so a single advertise-at-boot isn't enough (an earlier tube service hit this live before advertise_direct existed).

A capability with no handler key still gets the legacy discoverable-but-not-callable path — for a capability another mechanism serves. It is written as a DHT record, never through macula:advertise/5, so nothing can call it and no auth policy is asked of it.

Calling another service's RPC (pre-existing, piece B's consumer side)

mcl_core:call_capability(Org, <<"my_x.echo">>, #{ping => <<"pong">>},
                          5_000).
%% => {ok, #{echo := #{ping := <<"pong">>}}}

This resolves the provider from the DHT and dials its serving station directly (macula:call_station/7 under the hood, not pool-routed macula:call/5), failing over to the next provider on error. Pass Opts (via mcl_core_capabilities:call_capability/5,7) for ucan_token (present a capability token to a gated provider). The 10.x verify => true cert-chain mode is gone with the cert authorization form: in 11.x the trust check is the D25 authorization (the pool verifies the advertisement chain against its pinned realm_trust keys) plus the pinned expected_node_id dial.

Payload keys, and whether to retry (pieces F and G)

Reply/args keys arrive as atoms, not binaries. macula's frame decoder round-trips a payload's keys through binary_to_existing_atom/1. Use mcl_core_wire:field/2,3 instead of pattern-matching binary keys directly — it tries the atom form first, falls back to binary, and takes an optional default:

handle_request(Payload, State) ->
    Text = mcl_core_wire:field(text, Payload),
    Kind = mcl_core_wire:field(<<"kind">>, Payload, <<"raw">>),
    ...

Deciding whether a failed call is worth retrying: mcl_core_wire:retryable/1 asks macula's own published BOLT#4 retry policy (macula_bolt4:is_retryable/1) rather than you keeping a hand-copied code table that rots the moment BOLT#4 grows a code:

case mcl_core:call_capability(Org, CapName, Payload, 5_000) of
    {ok, Reply} -> handle(Reply);
    Failure ->
        case mcl_core_wire:retryable(Failure) of
            true  -> schedule_retry();
            false -> give_up()
        end
end.

Chapter 3: How to do Pub/Sub over the mesh

Publishing (piece C)

mcl_core_pubsub:publish(<<"my_x.thing_happened">>, #{id => Id}).
%% => ok  (fire-and-forget, default mode)

Three outcome-handling modes via Opts:

ModeBehavior
async_silent (default)Starts the publish, returns ok immediately, discards the outcome.
async_logSame, but logs a warning if the publish failed.
syncBlocks until the publish resolves (or Opts's timeout, default 5000ms) and returns the real outcome.
mcl_core_pubsub:publish(Topic, Payload, #{mode => sync, timeout => 2_000}).
mcl_core_pubsub:publish(Topic, Payload, #{realm => OtherRealm}).  %% dual-realm publish
mcl_core_pubsub:publish_many([TopicA, TopicB], Payload).          %% one fact, N topics

realm lets you publish on a realm other than this service's own — a real, deployed pattern (a fleet realm for internal plumbing, a separate business/public realm for the facts themselves, off the same pool).

Subscribing (piece D)

Declare the desired set in your service module's optional subscriptions/0 callback — mcl_core:boot/1 wires each one into a supervised macula_subscriber once your own start/1 has returned:

%% my_x_service.erl
subscriptions() ->
    [#{topic => <<"other.thing_happened">>,
       module => my_x_event_handler,
       args => [],
       %% WHO MAY DELIVER TO THIS. Required, and there is no default
       %% (macula 18, macula#147): `members', `{org, Org}',
       %% `{nodes, [NodeId]}', or `{open, <<"why anyone may publish">>}'.
       sources => {org, <<"acme">>}}].

args is what your init/1 receives (default []). A declaration mcl_core cannot wire — no sources above all — is refused at boot, naming the topic, before your start/1 runs.

%% my_x_event_handler.erl
-module(my_x_event_handler).
-behaviour(macula_subscriber).
-export([init/1, handle_event/4]).

init(Args) -> {ok, Args}.

handle_event(_Topic, Payload, _Meta, State) ->
    %% handle it
    {noreply, State}.

For a dynamic topic set (one topic per entity your service locally owns, changing at runtime), call mcl_core_pubsub:ensure_subscriptions/1 again whenever the desired set changes — it diffs against what's currently running and starts/stops only the delta, leaving everything else untouched:

mcl_core_pubsub:ensure_subscriptions(
    [#{topic => Topic, module => my_x_event_handler, args => EntityId,
       sources => {org, <<"acme">>}} || EntityId <- my_entities()]).

A change to any part of one entry — the topic, the handler, the args, sources, or the group and admission below — restarts exactly that subscriber and no other.

You do not need to handle reconnect yourself. An ordinary link respawn (a station blip) is invisible to a subscription — macula's pool replays it automatically on the new link. mcl_core_pubsub_subscriptions also self-heals on a 30s reconcile tick independent of any caller, so a topic that couldn't start because the mesh wasn't attached yet at boot is retried automatically.

Hearing only an org's own nodes

Declare it, and the SDK enforces it before your handler runs: macula 18 takes sources on every subscription (macula#147) and drops a fact whose publisher is not one of the declared sources — counted and visible in the pool's own status, never handed to your handler. sources => {org, <<"mcl-news">>} admits only nodes that organisation delegated; {nodes, [NodeId]} names exactly the publishers you mean. members admits any realm member, and {open, Reason} is the written opt-out.

Subscribing under a sealed group

If your service publishes its facts sealed, subscribe to them sealed too (mcl_om 1.7.0, mcl-om#49). Two more keys, valid only together:

subscriptions() ->
    [#{topic     => <<"io.example/mcl-tenders/tenders/wire/tender_notice_reported_v1">>,
       module    => tender_notice_handler,
       sources   => {org, <<"mcl-tenders">>},
       %% The group's prefix. `topic' must be under it on a SEGMENT
       %% boundary, so this is not a group of `.../tenders_archive/...'.
       group     => <<"io.example/mcl-tenders/tenders">>,
       %% Called as apply/3 with exactly these arguments and nothing
       %% added. `{ok, UCAN}' admits this node to the group; `{error,
       %% Reason}' refuses the subscription.
       admission => {tender_notices_group, admission, []}}].

Where the admission gets its UCAN is your service's business — read it from your deployment's environment, as mcl-tenders does:

admission() ->
    case os:getenv("MCL_TENDERS_GROUP_UCAN") of
        false -> {error, no_admission_token};
        Ucan  -> {ok, list_to_binary(Ucan)}
    end.

mcl_core calls it once per subscribe attempt — a first start, a restart, a pool replacement, a changed declaration — and hands the token straight to the SDK beside the group. It is never called on a reconcile tick that finds your subscriber running and matching, nothing is cached, and the token is in no child spec, in no subscriber state and in no log of mcl_core's: only the function and {Module, Function, Args} are kept, and the token lives for one call. (Node-wide, the SDK keyring still holds it until macula-io/macula#189 lands.) Because the admission runs inside the reconcile server, it must not block: a wait with no deadline delays every other subscription's reconcile.

A refusal never falls back to a clear subscription. The subscriber does not start, mcl_core_pubsub_subscriptions retries on its 30s tick, and /health names the topic and the reason — {group, {admission, Reason}} for yours, or the SDK's own verdict (not_authorized, not_a_member, no_distributor) once one is presented. A refusal is reported by an ATOM only: answer {error, expired} and /health says expired; answer {error, {expired, Anything}} and it says admission_refused, because that term may hold the token you just read. A raise out of the SDK call itself is reported as subscribe_raised: its own reason is the call's arguments, and the token is one of them.

Under a group, a sealed event arrives already opened, with sealed => 1 and seal_key_id in its meta; one that cannot be opened arrives once as {macula_event_unopened, SubRef, Topic, Info} rather than as a payload your handler sees. macula's macula_pubsub:subscribe/5 documents every reason.

sources decides delivery. A handler that must decide per fact (one square's speakers out of an org's many) still asks the realm itself, because macula verifies who signed a publication (Meta's publisher, with publisher_verified), not who may publish on a topic:

handle_event(_Topic, Payload, #{publisher := Publisher, publisher_verified := true}, State) ->
    {noreply, heard(mcl_core:org_member(<<"mcl-news">>, Publisher), Payload, State)};
handle_event(_Topic, _Payload, _UnverifiedMeta, State) ->
    {noreply, State}.

heard({ok, _ExpiresAt}, Payload, State)          -> act_on(Payload, State);
heard({error, {not_a_member, _}}, _Payload, State) -> State;  %% not that org's node
heard({error, {unavailable, _}}, _Payload, State)  -> State.  %% could not find out

A node is a member once Raf admits it on the Providers desk, and stops being one within 30 minutes of a revocation. Answers are cached, so a member costs no lookup per fact and a stranger publishing in a loop costs one lookup a minute. Decide for yourself what unavailable means for your service: it is not a refusal, and a station roll produces it for under a minute.

The escape hatch

The three publish modes above cover every real call site surveyed across the workspace, but not everything — e.g. retry-with-backoff on a failed publish, fully decoupled from any caller. start_publisher/3,4,5 resolves mesh_handles/0 exactly like publish/2,3, then hands full callback control to a caller-supplied module implementing -behaviour(macula_publisher) yourself:

{ok, _Pid} = mcl_core_pubsub:start_publisher(my_retry_coordinator,
                                              Topic, Payload).

mcl_core has no say over what your module's callback does with the outcome — reach for this only when publish/2,3's three fixed modes genuinely don't fit.

Chapter 4: How to Upload/Download files over the mesh

Share and get: call macula directly

mcl_core does not wrap content. It had a wrapper, mcl_core_content (piece E), removed in 0.30.0: no service used it, and macula 12.6.0 (D27) made the SDK's own calls the simple shape a service wants. They need macula 12.6.0 or later; mcl_core 0.31 requires 12.7.0, so every service on it has them. Use them with the handles mcl_core:mesh_handles/0 returns:

{ok, Pool, Realm} = mcl_core:mesh_handles(),
{ok, Mcid}  = macula:share_content(Pool, Realm, Bytes, #{org => mcl_core_identity:org()}),
{ok, Bytes} = macula:get_content(Pool, Realm, Mcid),
ok          = macula:unshare_content(Pool, Realm, Mcid).

This is content-addressed storage, not a destination-addressed file transfer. share_content takes no filename, path or recipient: this node keeps the bytes and serves them, and returns an MCID (a codec byte plus a hash). get_content fetches by that identifier from a node that shares it, and verifies the bytes. Share with #{org => Org}: the content is then served on <org>/content_v1_<node hex>, which the delegation the service already holds authorizes. Without org it is served on ~<node hex>/content_v1, which needs macula-station 0.6.4 or later. A node serves what it shares until it unshares it or stops, so unshare what you no longer need. The supervised forms, macula_feeder and macula_download, remain for a caller that wants the outcome delivered to a callback module. See macula's docs/guides/content/CONTENT_GUIDE.md.

If you actually need "send this to a specific recipient"

Content sharing is deliberately not what you want if the real requirement is "push these bytes at a service that's already expecting them" rather than "store this somewhere content-addressed for whoever asks later." That's a genuinely different, and already supervised, macula primitive pair: macula_upload (recipient) / macula_pusher (sender).

mcl_core does not wrap this pair. Not "not yet" in the sense chapter 5's streaming gap is — no service in this workspace has needed it at all, so there's no real usage to design a facade from. Call the supervised behaviours directly, resolving mcl_core:mesh_handles/0 and mcl_core:identity_key/0 yourself — this is the supervised macula API, with no mcl_core-level layer on top of it.

%% Recipient: advertise an upload procedure, same advertise_direct
%% shape as chapter 2's RPC providers.
-module(my_x_upload_handler).
-behaviour(macula_upload).
-export([init/1, handle_open/2, handle_chunk/2, handle_eof/1]).

init(_Args) -> {ok, []}.
handle_open(_UploadArgs, State) -> {ok, State}.
handle_chunk(Bytes, State) -> {ok, [Bytes | State]}.
handle_eof(State) -> {reply, {ok, iolist_to_binary(lists:reverse(State))}, State}.

register() ->
    {ok, Pool, Realm} = mcl_core:mesh_handles(),
    {ok, NodeKey}     = mcl_core:identity_key(),
    macula_upload:advertise_direct(Pool, Realm, <<"my_x.receive_report">>,
                                   ?MODULE, [], NodeKey,
                                   %% who may upload to it: no default
                                   %% (macula 18, macula#147).
                                   #{auth => {callers, members}}).
%% Sender: push bytes at that specific, already-known recipient.
{ok, Pool, Realm} = mcl_core:mesh_handles(),
{ok, _PusherPid} = macula_pusher:start_link(my_x_push_result_handler,
                                            Pool, Realm,
                                            <<"my_x.receive_report">>, Bytes).

macula_pusher:start_link/5,6,7 and macula_upload:advertise_direct/7 are the same kind of supervised, callback-driven primitive as every other call in this guide — mcl_core just hasn't grown a mesh_handles-resolving facade over this specific pair yet.

Chapter 5: How to stream media over the mesh

mcl_core does not wrap streaming. macula_streamer (provider) and macula_stream_sink (consumer) are real, supervised OTP behaviours in the SDK — that layer is done, by macula. What's missing is the second layer this guide's other chapters have: a mcl_core- level facade that resolves mesh_handles/0 for you and picks a default callback shape. It doesn't exist because exactly one service in the whole workspace survey uses streaming at all (macula-services/mcl-tube, for video), and its callback logic — chunking a specific video file off disk — is genuinely service-specific in a way a generic wrapper can't cleanly generalize from a single example. A second real exemplar would make building one worth it.

Until then, call macula_streamer/macula_stream_sink directly — still the supervised API, not the raw wire protocol — resolving your own pool/realm/node key via mcl_core:mesh_handles()/ mcl_core:identity_key() exactly the way every wrapper in this guide does internally.

Serving a stream

%% Real example: mcl-tube's stream_video_clip_by_id.erl, trimmed.
-module(stream_video_clip_by_id).
-behaviour(macula_streamer).
-export([init/1, handle_open/2]).

init(_Args) -> {ok, undefined}.

handle_open(#{clip_id := ClipId}, State) ->
    open_from(project_tube_store:get_clip(ClipId), ClipId, State);
handle_open(_StreamArgs, State) ->
    {stop, bad_request, State}.

open_from({ok, #{status := <<"published">>, local_ref := LocalRef}}, _ClipId, State) ->
    %% spawn a sender process that reads the file in chunks and calls
    %% macula_streamer:send/2,3 on this streamer's own pid, then
    %% macula_streamer:close/1 when done
    {ok, State};
open_from(_NotFoundOrUnpublished, _ClipId, State) ->
    {stop, not_found, State}.

init/1 and handle_open/2 are the required callbacks; sending is push-based and driven from outside them once handle_open/2 has returned {ok, State} — any process holding the streamer's pid calls macula_streamer:send/2,3/close/1 on it, so a natural shape is spawning a dedicated sender process from inside handle_open/2 itself (as mcl-tube does), not sending inline.

Registering this as callable — the supervised call, not a hand-rolled wire-level ADVERTISE — is macula_streamer:advertise_direct/7, the same shape chapter 2's macula_response:advertise_direct/7 uses for plain RPC handlers, calling the auth policy too:

{ok, Pool, Realm} = mcl_core:mesh_handles(),
{ok, NodeKey}     = mcl_core:identity_key(),
{ok, _Sup} = macula_streamer:advertise_direct(Pool, Realm,
                                              <<"my_x.watch_clip">>,
                                              stream_video_clip_by_id, [],
                                              NodeKey,
                                              #{auth => {callers, members}}).

Re-advertise this periodically (a station's wire-level registration doesn't survive a connection replacement, same as chapter 2's RPC providers) by tracking the returned supervisor pid and passing it back in as advertise_direct/7's reuse_sup option on each tick — the exact pattern mcl_core_capabilities already runs for macula_response; read that module's do_advertise/2 for the mechanism to copy.

Consuming a stream

macula_stream_sink:start_link/5,6 is the supervised consumer-side call — not macula:call_stream/5, which hands back a raw stream pid you'd otherwise have to hand-write your own recv loop around. start_link/5,6 opens the stream, runs that loop for you in a linked reader process (so a slow peer never blocks your gen_server's own mailbox), and calls Module:handle_chunk/2 once per item, Module:handle_close/2 when the stream ends or errors:

-module(my_x_clip_consumer).
-behaviour(macula_stream_sink).
-export([init/1, handle_chunk/2, handle_close/2]).

init(Args) -> {ok, Args}.

handle_chunk(Bytes, State) ->
    %% do something with this chunk
    {ok, State}.

handle_close(_Reason, State) ->
    {stop, normal, State}.
{ok, Pool, Realm} = mcl_core:mesh_handles(),
{ok, _SinkPid} = macula_stream_sink:start_link(my_x_clip_consumer, Pool,
                                               Realm, <<"my_x.watch_clip">>,
                                               #{clip_id => ClipId}).

Testing your service's mesh code

Three techniques, in order of how much you should reach for them (cheapest first):

  1. Pure functions. If your handler has any decision logic (resolve_realm/2-shaped, resolve_mode/1-shaped), export it and test it directly — no mesh at all. Every wrapper module in this library follows this convention; match it in your own handler modules.

  2. Zero-seed real pool. macula_client:connect([], #{}) boots a genuinely real pool with no station to reach, so every mesh call against it resolves to a real, deterministic SDK error ({error, {transient, no_healthy_station}}) fast and locally — no network, no mocking macula itself. This is the right tool for "does my code degrade correctly with no mesh," which is most of what needs covering.

  3. A real station. The only way to prove a success path — a capability genuinely answers a call, a subscription genuinely receives a published event, content genuinely round-trips. macula .io's demo fleet (station-de-frankfurt.macula.io) is documented, disposable dev infra safe to hit directly in tests. Every real bug pieces A–H's own tests found (a DHT key mismatch, a missing TLS trust triad, a nonexistent supervisor:stop/1, a race in a retry-inside-a-dying-callback design) was only found this way — budget for at least one test per mesh-facing feature that actually round-trips through a real station, not just a mocked one.

If a test needs technique 3, put it in test_live/, not test/ — excluded from the default rebar3 eunit/CI gate on purpose, since a station blip must never block an unrelated merge. See any file in this repo's own test_live/ for the pattern, and this repo's .github/workflows/lint-and-test.yml for how CI runs it separately and non-blocking.

Where to look next

  • service_anatomy.md — the boot lifecycle this guide assumes.
  • identity_model.md — why a service has its own identity, not the operator's.
  • read_model_services.md — if your subscription (chapter 3) is feeding a queryable local read model rather than just triggering a side effect: the Listener/Policy/Projection split that keeps it from serving stale entries forever, and the discovery-at- scale reasoning behind relying on the subscription rather than a find_records_by_type crawl.
  • macula-services/mcl-tube — the fullest real exemplar of a service using every primitive in this guide, including the two chapters 4–5 note mcl_core does not wrap (content and streaming) — built directly against the SDK, and the source this whole plan was derived from.