-module(dispatch_http).
-export([make_dispatch_fn/2,
dispatch/3,
inbox_url/2,
resolve_peer_url/2,
content_type/0]).
%% Live HTTP dispatch for delivery_worker — Step 8f per design §13.4.
%%
%% delivery_worker takes an opaque `dispatch_fn :: fun(Activity) ->
%% ok | {ok, _} | {error, Reason}`. For tests we wire a fake one
%% that records calls; for live federation we wire the closure this
%% module produces — a 1-arity fun that encodes the activity with
%% term_codec, looks up the peer's URL base, and POSTs to
%% `/actors//inbox` via httpc:request/4 (the BIF
%% wrapper Step 8e landed in lib/erlang/runtime.sx around the
%% native http-request primitive from fed-prims).
%%
%% Cfg shape (composable, priority order):
%% {peer_url, [{PeerId, BaseUrl::binary}, ...]}
%% Static map; tests + small static deployments. PeerId is
%% the actor atom (alice / bob / ...).
%% {peer_url_fn, fun((PeerId) -> {ok, BaseUrl} | not_found)}
%% Dynamic lookup; used when peer_actors gen_server caches a
%% discovery result (Step 10c will plumb this).
%%
%% BaseUrl is the scheme+host+port of the peer's HTTP server, e.g.
%% <<"http://127.0.0.1:8123">>. The inbox URL is built by
%% appending /actors//inbox so callers don't have to know the
%% wire path layout.
%%
%% Dispatch outcome:
%% 2xx -> ok (delivery_worker drops the entry)
%% non-2xx -> {error, {status, N}}
%% resolver miss -> {error, no_peer_url}
%% transport -> {error, Reason} (BIF-raised, caught here)
%% ── content-type ─────────────────────────────────────────────
%% "application/vnd.fed-sx.activity" — picked to be distinct from
%% the existing http_server content types (text/json/sx/cbor) since
%% the wire bytes are term_codec's custom netstring-ish format, not
%% any of them. The receiver's handle_inbox_post/3 in
%% http_server.erl doesn't gate on content-type yet; it just hands
%% the body to term_codec:decode. We still send a real MIME so
%% intermediaries (proxies, load balancers, logs) see something
%% honest. Substrate Note: M2 doesn't add a content_type_for/1
%% clause to http_server because that's serving outbound responses
%% (the dispatch direction is FROM us; the receiver shapes its
%% own response).
content_type() ->
%% "application/vnd.fed-sx.activity"
<<97,112,112,108,105,99,97,116,105,111,110,47,
118,110,100,46,102,101,100,45,115,120,46,97,99,
116,105,118,105,116,121>>.
%% ── public API ───────────────────────────────────────────────
make_dispatch_fn(PeerId, Cfg) ->
fun (Activity) ->
case resolve_peer_url(PeerId, Cfg) of
{error, R} ->
{error, R};
{ok, BaseUrl} ->
Url = inbox_url(BaseUrl, PeerId),
dispatch(Url, Activity, Cfg)
end
end.
dispatch(Url, Activity, _Cfg) ->
Body = term_codec:encode(Activity),
Headers = [{<<99,111,110,116,101,110,116,45,116,121,112,101>>,
content_type()}],
%% This port's try/catch needs a literal class atom (not Class:R).
%% The BIF wrapper raises error:{network, _} on transport failure
%% and error:badarg on shape failure; both reach us as `error`.
try httpc:request(Url, post, Headers, Body) of
{ok, Status, _H, _B} when Status >= 200, Status < 300 -> ok;
{ok, Status, _H, _B} -> {error, {status, Status}};
Other -> {error, {bad_response, Other}}
catch
error:Reason -> {error, Reason}
end.
%% inbox_url/2 — concatenate BaseUrl + "/actors/" + PeerId + "/inbox".
%% PeerId is the actor atom; rendered to a binary via its name.
inbox_url(BaseUrl, PeerId) when is_atom(PeerId) ->
PeerBin = list_to_binary(atom_to_list(PeerId)),
%% "/actors/" — 47,97,99,116,111,114,115,47
Prefix = <<47,97,99,116,111,114,115,47>>,
%% "/inbox" — 47,105,110,98,111,120
Suffix = <<47,105,110,98,111,120>>,
<>.
%% resolve_peer_url/2 — static :peer_url map first (tests), then
%% :peer_url_fn closure (Step 10c will hand one in once peer_actors
%% caches discovered URLs).
resolve_peer_url(PeerId, Cfg) ->
case envelope:get_field(peer_url, Cfg) of
{ok, Map} when is_list(Map) ->
case lookup_peer(PeerId, Map) of
{ok, U} -> {ok, U};
_ -> try_fn(PeerId, Cfg)
end;
_ -> try_fn(PeerId, Cfg)
end.
try_fn(PeerId, Cfg) ->
case envelope:get_field(peer_url_fn, Cfg) of
{ok, Fn} when is_function(Fn, 1) ->
case Fn(PeerId) of
{ok, U} when is_binary(U) -> {ok, U};
_ -> {error, no_peer_url}
end;
_ -> {error, no_peer_url}
end.
lookup_peer(_PeerId, []) -> not_found;
lookup_peer(PeerId, [{PeerId, Url} | _]) -> {ok, Url};
lookup_peer(PeerId, [_ | Rest]) -> lookup_peer(PeerId, Rest).