diff --git a/src/ipc.gleam b/src/ipc.gleam new file mode 100644 index 0000000..a35bf8b --- /dev/null +++ b/src/ipc.gleam @@ -0,0 +1,59 @@ +import gleam/bytes_tree + +pub type Socket + +// https://www.erlang.org/doc/apps/kernel/inet#t:address_family/0 +// local socket +type Local { + Local(socket_path: String) +} + +type ModeValue { + Binary +} + +type IPCOption { + Active(Bool) + Mode(ModeValue) +} + +pub type IPCError { + IPCError(reason: String) +} + +pub fn connect(socket_path: String) -> Result(Socket, IPCError) { + let options = [Mode(Binary), Active(False)] + + // timeout in ms + let timeout = 1000 + + gen_tcp_connect(Local(socket_path), 0, options, timeout) +} + +pub fn send(socket: Socket, message: String) -> Result(Nil, IPCError) { + gen_tcp_send(socket, bytes_tree.from_string(message)) +} + +pub fn close(socket: Socket) -> Nil { + gen_tcp_close(socket) +} + +// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#connect/4 +@external(erlang, "gen_tcp", "connect") +fn gen_tcp_connect( + address: Local, + port: Int, + options: List(IPCOption), + timeout: Int, +) -> Result(Socket, IPCError) + +// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#send/2 +@external(erlang, "ipc_ffi", "send") +fn gen_tcp_send( + socket: Socket, + packet: bytes_tree.BytesTree, +) -> Result(Nil, IPCError) + +// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#close/1 +@external(erlang, "gen_tcp", "close") +fn gen_tcp_close(socket: Socket) -> Nil diff --git a/src/ipc_ffi.erl b/src/ipc_ffi.erl new file mode 100644 index 0000000..6c303c2 --- /dev/null +++ b/src/ipc_ffi.erl @@ -0,0 +1,8 @@ +-module(ipc_ffi). +-export([send/2]). + +send(Socket, Packet) -> + case gen_tcp:send(Socket, Packet) of + ok -> {ok, nil}; + Res -> Res + end. \ No newline at end of file