-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
69 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
defmodule Explorer.Chain.Events.Listener do | ||
@moduledoc """ | ||
Listens and publishes events from PG | ||
""" | ||
|
||
use GenServer | ||
|
||
alias Postgrex.Notifications | ||
|
||
def start_link(_) do | ||
GenServer.start_link(__MODULE__, "chain_event") | ||
end | ||
|
||
def init(channel) do | ||
{:ok, pid} = | ||
:explorer | ||
|> Application.get_env(Explorer.Repo) | ||
|> Notifications.start_link() | ||
|
||
ref = Notifications.listen!(pid, channel) | ||
|
||
{:ok, {pid, ref, channel}} | ||
end | ||
|
||
def handle_info({:notification, _pid, _ref, _topic, payload}, state) do | ||
payload | ||
|> decode_payload!() | ||
|> broadcast() | ||
|
||
{:noreply, state} | ||
end | ||
|
||
defp decode_payload!(payload) do | ||
payload | ||
|> Base.decode64!() | ||
|> :erlang.binary_to_term() | ||
end | ||
|
||
defp broadcast({:chain_event, event_type} = event) do | ||
Registry.dispatch(Registry.ChainEvents, event_type, fn entries -> | ||
for {pid, _registered_val} <- entries do | ||
send(pid, event) | ||
end | ||
end) | ||
end | ||
|
||
defp broadcast({:chain_event, event_type, broadcast_type, _data} = event) do | ||
Registry.dispatch(Registry.ChainEvents, {event_type, broadcast_type}, fn entries -> | ||
for {pid, _registered_val} <- entries do | ||
send(pid, event) | ||
end | ||
end) | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters