mcl_core_pubsub_subscriptions (mcl_core v1.0.0)
View SourceReconciles the desired subscription set against mcl_core_pubsub_sup's actual running children (piece D, guides/mesh_native_services.md).
One supervised macula_subscriber per declared subscription not already running as declared; any running one whose declaration no longer matches is stopped and started again. Same "declare it, reconcile on a timer" shape as mcl_core_capabilities's 30s republish -- and for the same reason: the desired set may be declared before the mesh is attached, so the tick also retries anything that couldn't start yet, and it's the backstop for the one scenario let-it-crash alone doesn't cover -- a full pool replacement (not just a link respawn) drops every subscription's Pool pid at once, and if the supervisor's own restart budget is exhausted before mcl_core_identity reconnects, nothing else would ever retry.
A DECLARATION IS COMPARED WHOLE (mcl-om#41). The child's own start args carry everything the service asked for -- handler module, args and sources beside the topic -- so what is running is read back from supervisor:get_childspec/2 rather than remembered here: changing one subscription's sources restarts that subscriber and no other, and a change that reached the running child by any other route is undone on the next tick rather than silently kept.
A CHILD THAT STOPPED IS NOT A CHILD THAT IS RUNNING. The children are transient: a subscription that ends normally (macula_subscriber passes a handler's {stop, normal, State} straight through) keeps its child spec and no process, and OTP never restarts it -- so the next tick deletes that spec and starts the subscriber again, /health never lists it as running, and diff/2 is not fooled by a spec that still reads back as the declaration it was made from.
A SUBSCRIPTION THAT CANNOT START IS NOT FORGOTTEN. The reason is logged once at warning and kept per topic, /health reports it, and the verdict is degraded until the same topic starts -- the facts that subscriber exists to react to are not arriving, which a service answering ok would otherwise hide. A declaration macula would refuse anyway (sources missing, say: macula 18 does not default it, macula#147) is refused by validate/1 before anything is attempted, so the mistake is named at boot rather than discovered from a log.
A SUBSCRIPTION UNDER A SEALED GROUP NAMES THE ADMISSION THAT OPENS IT (mcl-om#49). A declaration may carry group (the group's prefix) and admission ({M, F, A}), and then mcl_core gives the subscriber a subscribe function of its own instead of macula's default: at each subscribe attempt it calls the admission, and hands the token it answers straight to macula:subscribe/5 beside the group. The token is therefore in no child spec, no subscriber state and no log of mcl_core's -- the spec carries the fun and the {M, F, A}, and the fun's own frame is the only place a token ever exists. NODE-wide that holds only once macula-io/macula#189 lands: the SDK's keyring keeps the ucan in its own state and macula_node_keys:redacted/1 does not redact ucan / ucan_token, so a crash report or sys:get_status of the keyring can still show one, which is macula's to fix and not this.
An admission that refuses (or raises) starts nothing: the topic is recorded as failed, /health names it and the reason, and the next tick tries again. What it ANSWERS is not reported as itself: an atom is passed through (no_admission_token), anything else becomes admission_refused, and a raise admission_raised. Nor is a raise from macula:subscribe/5 passed on as itself -- that reason is the call's own arguments, the token among them, so it is reported as subscribe_raised. There is no fallback to a clear subscription.
AN ADMISSION MUST NOT BLOCK. It is called from this server's own reconcile (through supervisor:start_child/2), so a subscription whose admission waits for something -- a network call with no deadline, say -- holds up the reconcile of EVERY other subscription and the /health report with it. Read what you need before the fun is handed over, or bound the wait; what the admission itself does to get a token in under a second is then nobody else's delay.
Reconnect handling that is deliberately NOT here: no macula_event_gone listening, no resubscribe-on-DOWN. Confirmed live (macula_link_respawn_replay_tests.erl) that an ordinary link respawn is invisible to a subscriber -- macula_client_replay already replays it one layer down. Building that in here would reintroduce the exact hand-rolled machinery this piece exists to make unnecessary.
Summary
Functions
What an admission answered, as a token or a reason safe to report.
The child a declaration becomes. Split out so a test can hold the spec itself -- above all, to show that a token is in it nowhere: the admission is NOT called here, so the only thing a sealed-group subscription puts in its spec is the fun and the {M, F, A}.
The subscription supervisor's children, as {Topic, Pid}: Pid is a pid while the child runs, restarting while the supervisor is bringing it back, and undefined when only its spec is left. That third state is the one worth knowing about: a transient child that stops NORMALLY -- a handler answering {stop, normal, State} to an event, say -- is left with its spec and no process, and is never restarted.
The topics the supervisor is restarting right now. Neither running nor dead: the next tick sees how it ended.
The topics whose child is gone and whose spec is still there: not running, and not restartable in place.
The declaration a running child was started with, read back from its own child spec: macula_subscriber:start_link/6's start args are Module, Pool, Realm, Topic, Args, Opts, and sources lives in Opts -- as do group and admission, when the declaration named them. Anything else running under the subscription supervisor is reported as unknown, which matches no declaration -- so it is stopped rather than kept as a subscriber nothing asked for.
The delta between what's desired and what's running, compared declaration by declaration: {ToStart, ToStop}. ToStart is every desired subscription a running child does not already match (a missing topic, or one whose module, args or sources changed); ToStop is every running declaration no desired one matches -- which is exactly the set that changed or is no longer wanted.
Declare the desired subscription set. Safe to call repeatedly whenever it changes at runtime -- e.g. a federation_inbox-shaped service adding one topic per newly-registered entity -- diffs against what is currently running and touches only the delta.
The failed list a report carries: one #{topic, reason} per topic with a recorded failure, the reason printed so the body stays JSON-encodable.
What is declared, what is running and what last failed, for /health and for an operator: desired and running are topics, failed is one #{topic, reason} per topic whose last start attempt failed, the reason printed so the body stays JSON-encodable.
The topics with a process behind them. A spec with no process is not running, whatever it declares.
What supervisor:start_child/2 answered, as a failure to record or none. A start function's own refusal comes back wrapped {error, {Reason, Child}} -- Child being the supervisor's own record, whose tag is child -- a duplicate id as {error, {already_started, Pid}}, and a spec left behind by a child that stopped as {error, already_present}.
The subscribe function macula_subscriber is started with for a sealed-group subscription: the admission is called HERE, at each subscribe attempt (a first start, a restart, a pool replacement, a changed declaration -- never a reconcile tick that finds the subscriber running), and its token goes straight to macula:subscribe/5 beside the group. Nothing caches it: once the group is joined, a later epoch pull is macula's keyring's business.
The options macula:subscribe/5 is finally given: the declaration's own (sources, delivery and the like), group, and the token. admission is dropped -- it is mcl_core's declaration key, not an option macula knows.
Is this something mcl_core can wire? Pure, so a service's boot can ask before it starts anything, and so every refusal is testable without a mesh. Refused: sources missing; a source class macula does not know; open with no written reason, or a reason that is not text; an empty or malformed {nodes, _} / {org, _}; a non-binary topic; a non-atom module; the same topic twice; group without admission or the other way round, a grouptopic is not under on a segment boundary, an admission that is not {atom, atom, list}, and an M:F/arity that is not exported; and anything that is not a map at all.
The verdict a report contributes to /health: ok while nothing is failing, {degraded, #{subscriptions => Failed}} otherwise.
Types
Functions
What an admission answered, as a token or a reason safe to report.
NOTHING AN ADMISSION SAYS IS REPORTED AS ITSELF (mcl-om#49). Whatever this returns is echoed to a log line, to /health and to a supervisor's crash report, so the only thing passed through is an ATOM: a reason an operator can act on (no_admission_token) and that cannot carry anything. An admission that answers a term, a tuple, or a list is reported by the fixed atom admission_refused, and one that raises by admission_raised. An admission reads a token and can fail holding it -- {error, {expired, Token}}, say -- and echoing that term is exactly how the token would reach a log line, /health or a crash report.
-spec child_spec(pid(), binary(), mcl_core_service:subscription()) -> map().
The child a declaration becomes. Split out so a test can hold the spec itself -- above all, to show that a token is in it nowhere: the admission is NOT called here, so the only thing a sealed-group subscription puts in its spec is the fun and the {M, F, A}.
The subscription supervisor's children, as {Topic, Pid}: Pid is a pid while the child runs, restarting while the supervisor is bringing it back, and undefined when only its spec is left. That third state is the one worth knowing about: a transient child that stops NORMALLY -- a handler answering {stop, normal, State} to an event, say -- is left with its spec and no process, and is never restarted.
The topics the supervisor is restarting right now. Neither running nor dead: the next tick sees how it ended.
The topics whose child is gone and whose spec is still there: not running, and not restartable in place.
-spec declaration(binary(), term()) -> declaration().
The declaration a running child was started with, read back from its own child spec: macula_subscriber:start_link/6's start args are Module, Pool, Realm, Topic, Args, Opts, and sources lives in Opts -- as do group and admission, when the declaration named them. Anything else running under the subscription supervisor is reported as unknown, which matches no declaration -- so it is stopped rather than kept as a subscriber nothing asked for.
-spec diff([mcl_core_service:subscription()], [declaration()]) -> {[mcl_core_service:subscription()], [binary()]}.
The delta between what's desired and what's running, compared declaration by declaration: {ToStart, ToStop}. ToStart is every desired subscription a running child does not already match (a missing topic, or one whose module, args or sources changed); ToStop is every running declaration no desired one matches -- which is exactly the set that changed or is no longer wanted.
A declaration that changed appears in both lists, and the reconcile stops before it starts, so the child id is free by the time it is started again.
-spec ensure([mcl_core_service:subscription()]) -> ok.
Declare the desired subscription set. Safe to call repeatedly whenever it changes at runtime -- e.g. a federation_inbox-shaped service adding one topic per newly-registered entity -- diffs against what is currently running and touches only the delta.
A declaration mcl_core cannot wire raises {mcl_core_subscription_invalid, #{topic := Topic, reason := Reason}} in the CALLER, before anything is stopped or started: a service whose subscriptions/0 is wrong fails its own boot naming the topic, instead of leaving a subscriber macula will refuse to make.
The failed list a report carries: one #{topic, reason} per topic with a recorded failure, the reason printed so the body stays JSON-encodable.
-spec report() -> #{desired := [binary()], running := [binary()], failed := failure_report()}.
What is declared, what is running and what last failed, for /health and for an operator: desired and running are topics, failed is one #{topic, reason} per topic whose last start attempt failed, the reason printed so the body stays JSON-encodable.
READ LOCK-FREE, never through this server (mcl_core_capabilities`s grant and liveness tables are read the same way): a /health request must not queue behind a reconcile that is subscribing, and subscribing is network I/O. The report is written once per reconcile, which is the only thing that can change it.
Never raises: before boot, or in a test that started only part of the tree, the table does not exist and the answer is an empty report.
The topics with a process behind them. A spec with no process is not running, whatever it declares.
What supervisor:start_child/2 answered, as a failure to record or none. A start function's own refusal comes back wrapped {error, {Reason, Child}} -- Child being the supervisor's own record, whose tag is child -- a duplicate id as {error, {already_started, Pid}}, and a spec left behind by a child that stopped as {error, already_present}.
-spec start_subscriber(pid(), binary(), mcl_core_service:subscription(), map()) -> map().
-spec subscribe(binary(), {module(), atom(), [term()]}) -> fun((pid(), binary(), binary(), pid(), map()) -> {ok, reference()} | {error, term()}).
The subscribe function macula_subscriber is started with for a sealed-group subscription: the admission is called HERE, at each subscribe attempt (a first start, a restart, a pool replacement, a changed declaration -- never a reconcile tick that finds the subscriber running), and its token goes straight to macula:subscribe/5 beside the group. Nothing caches it: once the group is joined, a later epoch pull is macula's keyring's business.
The options macula:subscribe/5 is finally given: the declaration's own (sources, delivery and the like), group, and the token. admission is dropped -- it is mcl_core's declaration key, not an option macula knows.
Is this something mcl_core can wire? Pure, so a service's boot can ask before it starts anything, and so every refusal is testable without a mesh. Refused: sources missing; a source class macula does not know; open with no written reason, or a reason that is not text; an empty or malformed {nodes, _} / {org, _}; a non-binary topic; a non-atom module; the same topic twice; group without admission or the other way round, a grouptopic is not under on a segment boundary, an admission that is not {atom, atom, list}, and an M:F/arity that is not exported; and anything that is not a map at all.
-spec verdict(map()) -> ok | {degraded, #{subscriptions := failure_report()}}.
The verdict a report contributes to /health: ok while nothing is failing, {degraded, #{subscriptions => Failed}} otherwise.