Skip to content

Commit 325abd4

Browse files
committed
Use pg instead if available
1 parent dac31fa commit 325abd4

File tree

3 files changed

+45
-6
lines changed

3 files changed

+45
-6
lines changed

lib/phoenix/pubsub/application.ex

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
defmodule Phoenix.PubSub.Application do
2+
use Application
3+
4+
def start(_, _) do
5+
children = pg_children()
6+
Supervisor.start_link(children, strategy: :one_for_one)
7+
end
8+
9+
if Code.ensure_loaded?(:pg) do
10+
defp pg_children() do
11+
[%{id: :pg, start: {:pg, :start_link, [Phoenix.PubSub]}}]
12+
end
13+
else
14+
defp pg_children() do
15+
[]
16+
end
17+
end
18+
end

lib/phoenix/pubsub/pg2.ex

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
defmodule Phoenix.PubSub.PG2 do
22
@moduledoc """
3-
Phoenix PubSub adapter based on `:pg2`.
3+
Phoenix PubSub adapter based on `:pg`/`:pg2`.
44
55
It runs on Distributed Erlang and is the default adapter.
66
"""
@@ -15,7 +15,7 @@ defmodule Phoenix.PubSub.PG2 do
1515

1616
@impl true
1717
def broadcast(adapter_name, topic, message, dispatcher) do
18-
case :pg2.get_members(pg2_namespace(adapter_name)) do
18+
case pg_members(adapter_name) do
1919
{:error, {:no_such_group, _}} ->
2020
{:error, :no_such_group}
2121

@@ -51,12 +51,11 @@ defmodule Phoenix.PubSub.PG2 do
5151

5252
@impl true
5353
def init({name, adapter_name}) do
54-
pg2_group = pg2_namespace(adapter_name)
55-
:ok = :pg2.create(pg2_group)
56-
:ok = :pg2.join(pg2_group, self())
54+
:ok = pg_join(adapter_name)
5755
{:ok, name}
5856
end
5957

58+
@impl true
6059
def handle_info({:forward_to_local, topic, message, dispatcher}, pubsub) do
6160
Phoenix.PubSub.local_broadcast(pubsub, topic, message, dispatcher)
6261
{:noreply, pubsub}
@@ -67,5 +66,26 @@ defmodule Phoenix.PubSub.PG2 do
6766
{:noreply, pubsub}
6867
end
6968

70-
defp pg2_namespace(server_name), do: {:phx, server_name}
69+
if Code.ensure_loaded?(:pg) do
70+
defp pg_members(adapter_name) do
71+
:pg.get_members(Phoenix.PubSub, adapter_name)
72+
end
73+
74+
defp pg_join(adapter_name) do
75+
:ok = :pg.join(Phoenix.PubSub, adapter_name, self())
76+
end
77+
else
78+
defp pg_members(adapter_name) do
79+
:pg2.get_members(pg2_namespace(adapter_name))
80+
end
81+
82+
defp pg_join(adapter_name) do
83+
namespace = pg2_namespace(adapter_name)
84+
:ok = :pg2.create(namespace)
85+
:ok = :pg2.join(namespace, self())
86+
:ok
87+
end
88+
89+
defp pg2_namespace(adapter_name), do: {:phx, adapter_name}
90+
end
7191
end

mix.exs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ defmodule Phoenix.PubSub.Mixfile do
2222

2323
def application do
2424
[
25+
mod: {Phoenix.PubSub.Application, []},
2526
applications: [:logger, :crypto],
2627
]
2728
end

0 commit comments

Comments
 (0)