subscription
This commit is contained in:
		
							parent
							
								
									32727b2ab8
								
							
						
					
					
						commit
						3e066fd23a
					
				
					 1 changed files with 36 additions and 0 deletions
				
			
		
							
								
								
									
										36
									
								
								app/lib/prymn/messaging/subscription.ex
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								app/lib/prymn/messaging/subscription.ex
									
									
									
									
									
										Normal 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
 | 
				
			||||||
		Loading…
	
		Reference in a new issue