Gleam + Relm4 foreign node POC over Erlang distribution
1%% Minimal distribution helpers for the gleamtk POC.
2-module(gleamtk_ffi).
3-export([
4 ping/1,
5 send_to/3,
6 register_name/1,
7 self_pid/0,
8 node_name/0,
9 nodes/0,
10 receive_any/1,
11 atom/1,
12 tuple2_atom_binary/2,
13 tuple2_atom_int/2,
14 hello_with_self/0
15]).
16
17%% Gleam PingResult constructors → atoms pong | pang
18ping(Node) when is_atom(Node) ->
19 net_adm:ping(Node).
20
21%% Gleam Nil → atom nil
22send_to(Name, Node, Msg) when is_atom(Name), is_atom(Node) ->
23 {Name, Node} ! Msg,
24 nil.
25
26%% Gleam Result(Nil, Nil) → {ok, nil} | {error, nil}
27register_name(Name) when is_atom(Name) ->
28 case catch erlang:register(Name, self()) of
29 true ->
30 {ok, nil};
31 {'EXIT', _} ->
32 case erlang:whereis(Name) of
33 Pid when Pid =:= self() -> {ok, nil};
34 _ -> {error, nil}
35 end
36 end.
37
38self_pid() -> self().
39
40node_name() -> node().
41
42nodes() -> nodes(connected).
43
44%% Gleam Result(Term, Nil) → {ok, Msg} | {error, nil}
45receive_any(TimeoutMs) when is_integer(TimeoutMs), TimeoutMs >= 0 ->
46 receive
47 Msg -> {ok, Msg}
48 after TimeoutMs ->
49 {error, nil}
50 end.
51
52atom(Bin) when is_binary(Bin) ->
53 binary_to_atom(Bin, utf8).
54
55tuple2_atom_binary(AtomBin, Str) when is_binary(AtomBin), is_binary(Str) ->
56 {binary_to_atom(AtomBin, utf8), Str}.
57
58tuple2_atom_int(AtomBin, N) when is_binary(AtomBin), is_integer(N) ->
59 {binary_to_atom(AtomBin, utf8), N}.
60
61%% `{hello, self()}` so the foreign node can SEND replies to our pid.
62hello_with_self() ->
63 {hello, self()}.