36 lines
1,015 B
Elixir
36 lines
1,015 B
Elixir
defmodule Prymn.Messaging.Subscription do
|
|
use GenServer
|
|
|
|
alias Prymn.Messaging
|
|
|
|
def start_link(%{agent_id: agent_id, subject: subject} = init_arg) do
|
|
name = {:via, Registry, {Prymn.Messaging.SubscriptionRegistry, agent_id <> subject}}
|
|
GenServer.start_link(__MODULE__, init_arg, name: name)
|
|
end
|
|
|
|
@impl true
|
|
def init(%{agent_id: agent_id, subject: subject, gnat: gnat, reply: reply}) do
|
|
Process.monitor(reply)
|
|
subject = "agents.v1.#{agent_id}.#{subject}"
|
|
{:ok, sub} = Gnat.sub(gnat, self(), subject)
|
|
|
|
{:ok, %{reply: reply, sub: sub, gnat: gnat}}
|
|
end
|
|
|
|
@impl true
|
|
def handle_info({:msg, %{body: body, topic: subject}}, %{reply: reply} = state) do
|
|
msg = Messaging.Messages.handle_message(subject, body)
|
|
send(reply, msg)
|
|
|
|
{:noreply, state}
|
|
end
|
|
|
|
def handle_info({:DOWN, _ref, :process, _object, _reason}, state) do
|
|
{:stop, {:shutdown, :gone}, state}
|
|
end
|
|
|
|
@impl true
|
|
def terminate({:shutdown, _}, state) do
|
|
Gnat.unsub(state.gnat, state.sub)
|
|
end
|
|
end
|