defmodule Prymn.Messaging.Connection do use GenServer require Logger @dialyzer {:nowarn_function, init: 1} def start_link(%{name: name} = init_arg) do GenServer.start_link(__MODULE__, init_arg, name: name) end def publish(server, subject, payload) do GenServer.call(server, {:pub, subject, payload}) end def subscribe(server, subject, reply) do GenServer.call(server, {:sub, subject, reply}) end @impl true def init(_init_arg) do Process.flag(:trap_exit, true) connect_opts = %{ host: "localhost", username: "prymn_admin", password: "prymn_admin", auth_required: true } case Gnat.start_link(connect_opts) do {:ok, pid} -> {:ok, pid} {:error, reason} -> # Let the supervisor restart the Connection after a short delay Logger.info("Initial NATS connection failed. Restarting...") Process.sleep(1000) {:stop, reason} end end @impl true def handle_call({:pub, subject, payload}, _from, conn_pid) do :ok = Gnat.pub(conn_pid, subject, payload) {:reply, :ok, conn_pid} end def handle_call({:sub, subject, reply}, _from, conn_pid) do {:ok, cons_pid} = GenServer.start_link(Prymn.Messaging.FooConsumer, reply) {:ok, sub} = Gnat.sub(conn_pid, cons_pid, subject) {:reply, {:ok, sub}, conn_pid} end @impl true def handle_info({:EXIT, pid, reason}, conn_pid) when conn_pid == pid do Logger.info("NATS connection lost (#{reason})") {:stop, {:shutdown, :connection_closed}, conn_pid} end end