subscription

This commit is contained in:
Nikos Papadakis 2024-02-03 13:11:31 +02:00
parent 32727b2ab8
commit 3e066fd23a
Signed by untrusted user who does not match committer: nikos
GPG key ID: 78871F9905ADFF02

View file

@ -0,0 +1,36 @@
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