-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathclient.ex
More file actions
202 lines (164 loc) · 5.53 KB
/
client.ex
File metadata and controls
202 lines (164 loc) · 5.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
defmodule Absinthe.GraphqlWS.Client do
use GenServer
alias Absinthe.GraphqlWS.Uuid
require Logger
defstruct [
:gun,
:gun_process_monitor,
:gun_stream_ref,
:monitor,
:transport,
listeners: %{},
queries: %{}
]
def start(endpoint, init_payload \\ %{}) do
{:ok, client} = GenServer.start(__MODULE__, endpoint: endpoint)
{:ok, %{"type" => "connection_ack"}} = push(client, %{type: "connection_init", payload: init_payload})
{:ok, client}
end
def init(endpoint: endpoint) do
init(endpoint: endpoint, monitor: Process, transport: :gun)
end
def init(endpoint: endpoint, monitor: monitor, transport: transport) do
uri = URI.parse(endpoint)
with {:ok, gun_pid} <- transport.open(uri.host |> to_charlist(), uri.port, %{protocols: [:http]}),
{:ok, _protocol} <- transport.await_up(gun_pid, :timer.seconds(5)),
stream_ref <- transport.ws_upgrade(gun_pid, uri.path),
:ok <- wait_for_upgrade() do
ref = monitor.monitor(gun_pid)
{:ok,
__struct__(
gun: gun_pid,
gun_process_monitor: ref,
gun_stream_ref: stream_ref,
monitor: monitor,
transport: transport
)}
end
end
def close(pid) do
:ok = GenServer.call(pid, :close)
GenServer.stop(pid, :normal)
end
def handle_call({:push, %{type: "connection_init"} = message}, from, state) do
send_and_cache("connection_init", from, message, state)
end
def handle_call({:push, %{id: id} = message}, from, state) do
send_and_cache(id, from, message, state)
end
def handle_call({:query, gql, variables}, from, state) do
id = Uuid.generate()
send_and_cache(id, from, make_message(id, gql, variables), state)
end
def handle_call(:close, _from, state) do
state.monitor.demonitor(state.gun_process_monitor)
:ok = state.transport.close(state.gun)
{:reply, :ok, state}
end
def handle_call({:subscribe, gql, variables, handler}, _from, %{listeners: listeners} = state) do
id = Uuid.generate()
state.transport.ws_send(state.gun, {:text, Jason.encode!(make_message(id, gql, variables))})
listeners = Map.put(listeners, id, handler)
state = Map.put(state, :listeners, listeners)
{:reply, {:ok, id}, state}
end
def handle_info({:DOWN, _ref, :process, pid, reason}, state) do
warn("Process went down: #{inspect(pid)}")
{:stop, reason, state}
end
def handle_info({:gun_error, _pid, _stream_ref, reason}, state) do
{:stop, reason, state}
end
def handle_info({:gun_ws, _pid, _stream_ref, {:text, payload}}, state) do
message = Jason.decode!(payload)
new_listeners =
case message do
%{"id" => id, "type" => "complete"} ->
state.listeners |> Map.delete(id)
_ ->
state.listeners
end
new_queries =
case message do
%{"id" => id, "type" => "complete"} ->
state.queries |> Map.delete(id)
%{"id" => id} ->
# IO.inspect(message, label: "INBOUND")
dispatch(id, message, state)
%{"type" => "connection_ack"} ->
ref = Map.fetch!(state.queries, "connection_init")
GenServer.reply(ref, {:ok, message})
state.queries |> Map.delete("connection_init")
_ ->
state.queries
end
{:noreply, %{state | queries: new_queries, listeners: new_listeners}}
end
def handle_info({:gun_ws, _pid, _stream_ref, {:close, code, payload}}, state) do
Map.values(state.queries)
|> Enum.each(fn ref -> GenServer.reply(ref, {:error, code, payload}) end)
{:stop, :server_closed, %{state | queries: %{}}}
end
def handle_info(msg, state) do
warn("unhandled handle_info: #{inspect(msg)}")
{:noreply, state}
end
defp dispatch(id, message, state) do
cond do
Map.has_key?(state.listeners, id) ->
handler = Map.get(state.listeners, id)
send(handler, {:subscription, id, message["payload"]})
# handler.(message)
state.queries
Map.has_key?(state.queries, id) ->
ref = Map.fetch!(state.queries, id)
GenServer.reply(ref, {:ok, message})
state.queries
end
end
defp make_message(id, gql, variables) do
%{
id: id,
type: "subscribe",
payload: %{
query: gql,
variables: Map.new(variables)
}
}
end
def push(pid, message), do: GenServer.call(pid, {:push, message})
def query(pid, gql, variables \\ %{}) do
case GenServer.call(pid, {:query, gql, variables}) do
{:ok, %{"payload" => payload}} -> {:ok, payload}
result -> result
end
end
defp send_and_cache(id, from, message, %{queries: queries} = state) do
# IO.inspect(message, label: "OUTBOUND")
state.transport.ws_send(state.gun, {:text, Jason.encode!(message)})
queries = Map.put(queries, id, from)
state = Map.put(state, :queries, queries)
{:noreply, state}
end
def subscribe(pid, gql, variables, handler) do
case GenServer.call(pid, {:subscribe, gql, variables, handler}) do
{:ok, %{"id" => id}} -> {:ok, id}
result -> result
end
end
defp wait_for_upgrade do
receive do
{:gun_upgrade, _pid, _stream_ref, ["websocket"], _headers} ->
:ok
{:gun_response, _pid, _stream_ref, _, status, _headers} ->
{:error, status}
{:gun_error, _pid, _stream_ref, reason} ->
{:error, reason}
after
1000 ->
exit(:timeout)
end
end
# defp debug(msg), do: Logger.debug("[client@#{inspect(self())}] #{msg}")
defp warn(msg), do: Logger.warning("[client@#{inspect(self())}] #{msg}")
end