/
connection.ex
649 lines (582 loc) · 20.3 KB
/
connection.ex
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
defmodule DBConnection.ConnectionError do
defexception [:message]
def exception(message), do: %DBConnection.ConnectionError{message: message}
end
defmodule DBConnection.Connection do
@moduledoc """
A `DBConnection.Pool` with a single connection, the default pool.
### Options
* `:sync_connect` - Whether to block the caller of `start_link` to
carry out an initial connection attempt (boolean, default: `false`)
"""
@behaviour DBConnection.Pool
use Connection
require Logger
alias DBConnection.Backoff
@pool_timeout 5_000
@timeout 15_000
@idle_timeout 1_000
## DBConnection.Pool API
@doc false
def ensure_all_started(_opts, _type) do
{:ok, []}
end
@doc false
def start_link(mod, opts) do
start_link(mod, opts, :connection)
end
@doc false
def child_spec(mod, opts, child_opts \\ []) do
child_spec(mod, opts, :connection, child_opts)
end
@doc false
def checkout(pool, opts) do
pool_timeout = opts[:pool_timeout] || @pool_timeout
queue? = Keyword.get(opts, :queue, true)
timeout = opts[:timeout] || @timeout
ref = make_ref()
try do
Connection.call(pool, {:checkout, ref, queue?, timeout}, pool_timeout)
catch
:exit, {_, {_, :call, [pool | _]}} = reason ->
cancel(pool, ref)
exit(reason)
end
end
@doc false
def checkin({pid, ref}, state, _) do
Connection.cast(pid, {:checkin, ref, state})
end
@doc false
def disconnect({pid, ref}, err, state, _) do
Connection.cast(pid, {:disconnect, ref, err, state})
end
@doc false
def stop({pid, ref}, err, state, _) do
Connection.cast(pid, {:stop, ref, err, state})
end
@doc false
def sync_stop({pid, ref}, err, state, opts) do
timeout = Keyword.get(opts, :pool_timeout, @pool_timeout)
{_, mref} = spawn_monitor(fn() ->
sync_stop(pid, ref, err, state, timeout)
end)
# The reason is not important as long as the process exited
# before trying to checkin
receive do
{:DOWN, ^mref, _, _, _} -> :ok
end
end
## Internal API
@doc false
def start_link(mod, opts, mode, info \\ nil) do
start_opts = start_opts(mode, opts)
Connection.start_link(__MODULE__, {mod, opts, mode, info}, start_opts)
end
@doc false
def child_spec(mod, opts, mode, child_opts) do
Supervisor.Spec.worker(__MODULE__, [mod, opts, mode], child_opts)
end
## Connection API
@doc false
def init({mod, opts, mode, info}) do
queue = if mode == :sojourn, do: :broker, else: :queue.new()
broker = if mode == :sojourn, do: elem(info, 0)
regulator = if mode == :sojourn, do: elem(info, 1)
idle = if mode == :sojourn, do: :passive, else: get_idle(opts)
after_timeout = if mode == :poolboy, do: :stop, else: :backoff
s = %{mod: mod, opts: opts, state: nil, client: :closed, broker: broker,
regulator: regulator, lock: nil, queue: queue, timer: nil,
backoff: Backoff.new(opts),
after_connect: Keyword.get(opts, :after_connect),
after_connect_timeout: Keyword.get(opts, :after_connect_timeout,
@timeout), idle: idle,
idle_timeout: Keyword.get(opts, :idle_timeout, @idle_timeout),
idle_time: 0, after_timeout: after_timeout}
if mode == :connection and Keyword.get(opts, :sync_connect, false) do
connect(:init, s)
else
{:connect, :init, s}
end
end
@doc false
def connect(_, %{regulator: regulator, lock: nil} = s)
when is_pid(regulator) do
{:await, ref, _} = :sregulator.async_ask(regulator, {self(), make_ref()})
{:ok, %{s | client: {ref, :regulator}}}
end
def connect(_, s) do
%{mod: mod, opts: opts, backoff: backoff, after_connect: after_connect,
idle: idle, idle_timeout: idle_timeout, regulator: regulator,
lock: lock} = s
case apply(mod, :connect, [opts]) do
{:ok, state} when after_connect != nil ->
ref = make_ref()
Connection.cast(self(), {:after_connect, ref})
{:ok, %{s | state: state, client: {ref, :connect}}}
{:ok, state} when idle == :passive ->
backoff = backoff && Backoff.reset(backoff)
ref = make_ref()
Connection.cast(self(), {:connected, ref})
{:ok, %{s | state: state, client: {ref, :connect}, backoff: backoff}}
{:ok, state} when idle == :active ->
backoff = backoff && Backoff.reset(backoff)
{:ok, %{s | state: state, client: nil, backoff: backoff}, idle_timeout}
{:error, err} when is_nil(backoff) ->
raise err
{:error, err} ->
Logger.error(fn() ->
[inspect(mod), ?\s, ?(, inspect(self()), ") failed to connect: " |
Exception.format_banner(:error, err, [])]
end)
done_lock(regulator, lock)
{timeout, backoff} = Backoff.backoff(backoff)
{:backoff, timeout, %{s | lock: nil, backoff: backoff}}
end
end
@doc false
def disconnect({log, err}, %{mod: mod} = s) do
case log do
:nolog ->
:ok
:log ->
_ = Logger.error(fn() ->
[inspect(mod), ?\s, ?(, inspect(self()),
") disconnected: " | Exception.format_banner(:error, err, [])]
end)
:ok
end
%{state: state, client: client, timer: timer, regulator: regulator,
lock: lock, queue: queue, backoff: backoff} = s
demonitor(client)
cancel_timer(timer)
done_lock(regulator, lock)
queue = clear_queue(queue)
:ok = apply(mod, :disconnect, [err, state])
s = %{s | state: nil, client: :closed, timer: nil, lock: nil, queue: queue}
case client do
_ when backoff == :nil ->
{:stop, {:shutdown, err}, s}
{_, :after_connect} ->
{timeout, backoff} = Backoff.backoff(backoff)
{:backoff, timeout, %{s | backoff: backoff}}
_ ->
{:connect, :disconnect, s}
end
end
@doc false
def handle_call({:checkout, ref, queue?, timeout}, {pid, _} = from, s) do
case s do
%{queue: :broker} ->
exit(:bad_checkout)
%{client: nil, idle: :passive, mod: mod, state: state} ->
Connection.reply(from, {:ok, {self(), ref}, mod, state})
client = {ref, Process.monitor(pid)}
timer = start_timer(pid, timeout)
{:noreply, %{s | client: client, timer: timer}}
%{client: {_, :connect}, after_connect: nil, idle: :passive,
state: state} ->
mon = Process.monitor(pid)
handle_checkout({ref, mon}, timeout, from, state, s)
%{client: nil, idle: :active, state: state} ->
mon = Process.monitor(pid)
handle_checkout({ref, mon}, timeout, from, state, s)
%{client: :closed} ->
message = "connection not available because of disconnection"
err = DBConnection.ConnectionError.exception(message)
{:reply, {:error, err}, s}
%{queue: queue} when queue? == true ->
client = {ref, Process.monitor(pid)}
queue = :queue.in({client, timeout, from}, queue)
{:noreply, %{s | queue: queue}}
_ when queue? == false ->
message = "connection not available and queuing is disabled"
err = DBConnection.ConnectionError.exception(message)
{:reply, {:error, err}, s}
end
end
def handle_call({:stop, ref, _, _} = stop, from, %{client: {ref, _}} = s) do
Connection.reply(from, :ok)
handle_cast(stop, s)
end
def handle_call({:stop, _, _, _}, _, s) do
{:reply, :error, s}
end
@doc false
def handle_cast({:checkin, ref, state}, %{client: {ref, _}} = s) do
handle_next(state, s)
end
def handle_cast({:disconnect, ref, err, state}, %{client: {ref, _}} = s) do
{:disconnect, {:log, err}, %{s | state: state}}
end
def handle_cast({:stop, ref, err, state}, %{client: {ref, _}} = s) do
## Terrible hack so the stacktrace points here and we get the new
## state in logs
{_, stack} = :erlang.process_info(self(), :current_stacktrace)
{:stop, {err, stack}, %{s | state: state}}
end
def handle_cast({:cancel, _}, %{queue: :broker}) do
exit(:bad_cancel)
end
def handle_cast({:cancel, ref}, %{client: {ref, _}, state: state} = s) do
handle_next(state, s)
end
def handle_cast({:cancel, ref}, %{queue: queue} = s) do
cancel =
fn({{ref2, mon}, _, _}) ->
if ref === ref2 do
Process.demonitor(mon, [:flush])
false
else
true
end
end
handle_timeout(%{s | queue: :queue.filter(cancel, queue)})
end
def handle_cast({:checkin, _, _}, s) do
handle_timeout(s)
end
def handle_cast({tag, _, _, _}, s) when tag in [:disconnect, :stop] do
handle_timeout(s)
end
def handle_cast({:after_connect, ref}, %{client: {ref, :connect}} = s) do
%{mod: mod, state: state, after_connect: after_connect,
after_connect_timeout: timeout, opts: opts} = s
case apply(mod, :checkout, [state]) do
{:ok, state} ->
opts = [timeout: timeout] ++ opts
{pid, ref} =
DBConnection.Task.run_child(mod, after_connect, state, opts)
timer = start_timer(pid, timeout)
s = %{s | client: {ref, :after_connect}, timer: timer, state: state}
{:noreply, s}
{:disconnect, err, state} ->
{:disconnect, {:log, err}, %{s | state: state}}
end
end
def handle_cast({:after_connect, _}, s) do
{:noreply, s}
end
def handle_cast({:connected, ref}, %{client: {ref, :connect}} = s) do
%{mod: mod, state: state, queue: queue, broker: broker} = s
case apply(mod, :checkout, [state]) do
{:ok, state} when queue == :broker ->
info = {self(), mod, state}
{:await, ^ref, _} = :sbroker.async_ask_r(broker, info, {self(), ref})
{:noreply, %{s | client: {ref, :broker}, state: state}}
{:ok, state} ->
handle_next(state, %{s | client: nil})
{:disconnect, err, state} ->
{:disconnect, {:log, err}, %{s | state: state}}
end
end
def handle_cast({:connected, _}, %{idle: :passive} = s) do
{:noreply, s}
end
@doc false
def handle_info({:DOWN, ref, _, pid, reason},
%{client: {ref, :after_connect}} = s) do
message = "client #{inspect pid} exited: " <> Exception.format_exit(reason)
err = DBConnection.ConnectionError.exception(message)
{:disconnect, {down_log(reason), err}, %{s | client: {nil, :after_connect}}}
end
def handle_info({:DOWN, mon, _, pid, reason}, %{client: {ref, mon}} = s) do
message = "client #{inspect pid} exited: " <> Exception.format_exit(reason)
err = DBConnection.ConnectionError.exception(message)
{:disconnect, {down_log(reason), err}, %{s | client: {ref, nil}}}
end
def handle_info({:DOWN, _, :process, _, _} = msg, %{queue: :broker} = s) do
do_handle_info(msg, s)
end
def handle_info({:DOWN, ref, :process, _, _} = msg, %{queue: queue} = s) do
len = :queue.len(queue)
down = fn({{_, mon}, _, _}) -> ref != mon end
queue = :queue.filter(down, queue)
case :queue.len(queue) do
^len ->
do_handle_info(msg, s)
_ ->
{:noreply, %{s | queue: queue}}
end
end
def handle_info({:timeout, timer, {__MODULE__, pid, timeout}},
%{timer: timer} = s) when is_reference(timer) do
message = "client #{inspect pid} timed out because " <>
"it checked out the connection for longer than #{timeout}ms"
exception = DBConnection.ConnectionError.exception(message)
case s do
# Client timed out and using poolboy. Disable backoff to cause an exit so
# that poolboy starts a new process immediately. Otherwise this worker
# doesn't get used until the client checks in. This is equivalent to the
# other pools because because poolboy does unlimited restarts and no
# backoff required as connection is active.
%{after_timeout: :stop, client: {_, mon}} when is_reference(mon) ->
{:disconnect, {:log, exception}, %{s | timer: nil, backoff: nil}}
_ ->
{:disconnect, {:log, exception}, %{s | timer: nil}}
end
end
def handle_info(:timeout, %{client: nil, broker: nil} = s) do
%{mod: mod, state: state} = s
case apply(mod, :ping, [state]) do
{:ok, state} ->
handle_timeout(%{s | state: state})
{:disconnect, err, state} ->
{:disconnect, {:log, err}, %{s | state: state}}
end
end
def handle_info({ref, msg}, %{client: {ref, :broker}} = s) do
handle_broker(msg, s)
end
def handle_info({ref, msg}, %{client: {ref, :regulator}} = s) do
handle_regulator(msg, s)
end
def handle_info(msg, %{client: nil} = s) do
do_handle_info(msg, s)
end
def handle_info(msg, %{client: {_, :connect}} = s) do
do_handle_info(msg, s)
end
def handle_info(msg, %{mod: mod} = s) do
Logger.info(fn() ->
[inspect(mod), ?\s, ?(, inspect(self()), ") missed message: " |
inspect(msg)]
end)
{:noreply, s}
end
@doc false
def format_status(info, [_, %{client: :closed, mod: mod}]) do
case info do
:normal -> [{:data, [{'Module', mod}]}]
:terminate -> mod
end
end
def format_status(info, [pdict, %{mod: mod, state: state}]) do
case function_exported?(mod, :format_status, 2) do
true when info == :normal ->
normal_status(mod, pdict, state)
false when info == :normal ->
normal_status_default(mod, state)
true when info == :terminate ->
{mod, terminate_status(mod, pdict, state)}
false when info == :terminate ->
{mod, state}
end
end
## Helpers
defp start_opts(:connection, opts) do
Keyword.take(opts, [:debug, :name, :timeout, :spawn_opt])
end
defp start_opts(mode, opts) when mode in [:poolboy, :sojourn] do
Keyword.take(opts, [:debug, :spawn_opt])
end
defp cancel(pool, ref) do
try do
Connection.cast(pool, {:cancel, ref})
rescue
ArgumentError ->
:ok
end
end
defp sync_stop(pid, ref, err, state, timeout) do
mref = Process.monitor(pid)
case Connection.call(pid, {:stop, ref, err, state}, timeout) do
:ok ->
# The reason is not important as long as the process exited
# before trying to checkin
receive do: ({:DOWN, ^mref, _, _, _} -> :ok)
:error ->
exit(:normal)
end
end
defp get_idle(opts) do
case Keyword.get(opts, :idle, :passive) do
:passive -> :passive
:active -> :active
end
end
defp handle_checkout({ref, _} = client, timeout, {pid, _} = from, state, s) do
%{mod: mod} = s
case apply(mod, :checkout, [state]) do
{:ok, state} ->
Connection.reply(from, {:ok, {self(), ref}, mod, state})
timer = start_timer(pid, timeout)
{:noreply, %{s | client: client, timer: timer, state: state}}
{:disconnect, err, state} ->
{:disconnect, {:log, err}, %{s | state: state}}
end
end
defp handle_next(state, %{client: {_, :after_connect} = client} = s) do
%{backoff: backoff} = s
backoff = backoff && Backoff.reset(backoff)
demonitor(client)
handle_next(state, %{s | client: nil, backoff: backoff})
end
defp handle_next(state, %{queue: :broker} = s) do
%{client: client, timer: timer, mod: mod, broker: broker} = s
demonitor(client)
cancel_timer(timer)
info = {self(), mod, state}
{:await, ref, _} = :sbroker.async_ask_r(broker, info, {self(), make_ref()})
{:noreply, %{s | state: state, client: {ref, :broker}, timer: nil}}
end
defp handle_next(state, s) do
%{client: client, timer: timer, queue: queue, idle: idle} = s
demonitor(client)
cancel_timer(timer)
{item, queue} = :queue.out(queue)
s = %{s | client: nil, timer: nil, queue: queue}
case item do
{:value, {{ref, pid} = new_client, timeout, from}} ->
%{mod: mod} = s
Connection.reply(from, {:ok, {self(), ref}, mod, state})
timer = start_timer(pid, timeout)
{:noreply, %{s | client: new_client, timer: timer, state: state}}
:empty when idle == :passive ->
handle_timeout(%{s | state: state})
:empty when idle == :active ->
handle_checkin(state, s)
end
end
defp handle_checkin(state, %{mod: mod} = s) do
case apply(mod, :checkin, [state]) do
{:ok, state} ->
handle_timeout(%{s | state: state})
{:disconnect, err, state} ->
{:disconnect, {:log, err}, %{s | state: state}}
end
end
defp down_log(:normal), do: :nolog
defp down_log(:shutdown), do: :nolog
defp down_log({:shutdown, _}), do: :nolog
defp down_log(_), do: :log
defp handle_broker({:go, ref, {pid, timeout}, _, _}, s) do
mon = Process.monitor(pid)
timer = start_timer(pid, timeout)
{:noreply, %{s | idle_time: 0, client: {ref, mon}, timer: timer}}
end
defp handle_broker({:drop, queue_time}, s) do
%{regulator: regulator, lock: lock} = s
case :sregulator.continue(regulator, lock) do
{:go, ^lock, _, _, continue_time} ->
idle_native = queue_time + continue_time
idle = :erlang.convert_time_unit(idle_native, :native, :milli_seconds)
continue(idle, s)
{:stop, _} ->
msg = "regulator #{inspect regulator} did not allow connection to continue"
err = DBConnection.SojournError.exception(msg)
{:disconnect, {:nolog, err}, %{s | idle_time: 0, lock: nil}}
end
end
defp continue(idle, s) do
%{idle_time: idle_time, idle_timeout: idle_timeout} = s
case idle_time + idle do
idle_time when idle_time < idle_timeout ->
continue_ask(%{s | idle_time: idle_time})
_ ->
continue_ping(s)
end
end
defp continue_ask(s) do
%{mod: mod, state: state, broker: broker, client: {ref, :broker}} = s
info = {self(), mod, state}
{:await, ^ref, _} = :sbroker.async_ask_r(broker, info, {self(), ref})
{:noreply, s}
end
defp continue_ping(%{mod: mod, state: state} = s) do
case apply(mod, :ping, [state]) do
{:ok, state} ->
continue_ask(%{s | idle_time: 0, state: state})
{:disconnect, err, state} ->
{:disconnect, {:log, err}, %{s | idle_time: 0, state: state}}
end
end
defp handle_regulator({:go, lock, _, _, _}, s) do
{:connect, :go, %{s | client: nil, lock: lock}}
end
defp handle_regulator({:drop, _}, s) do
{:stop, :drop, %{s| client: nil}}
end
defp do_handle_info(msg, %{mod: mod, state: state} = s) do
case apply(mod, :handle_info, [msg, state]) do
{:ok, state} ->
handle_timeout(%{s | state: state})
{:disconnect, err, state} ->
{:disconnect, {:log, err}, %{s | state: state}}
end
end
defp handle_timeout(%{client: nil, idle_timeout: idle_timeout} = s) do
{:noreply, s, idle_timeout}
end
defp handle_timeout(s), do: {:noreply, s}
defp demonitor({_, mon}) when is_reference(mon) do
Process.demonitor(mon, [:flush])
end
defp demonitor({mon, :after_connect}) when is_reference(mon) do
Process.demonitor(mon, [:flush])
end
defp demonitor({_, _}), do: true
defp demonitor(nil), do: true
defp start_timer(_, :infinity), do: nil
defp start_timer(pid, timeout) do
:erlang.start_timer(timeout, self(), {__MODULE__, pid, timeout})
end
defp cancel_timer(nil), do: :ok
defp cancel_timer(timer) do
case :erlang.cancel_timer(timer) do
false -> flush_timer(timer)
_ -> :ok
end
end
defp flush_timer(timer) do
receive do
{:timeout, ^timer, {__MODULE__, _, _}} ->
:ok
after
0 ->
raise ArgumentError, "timer #{inspect(timer)} does not exist"
end
end
defp clear_queue(:broker), do: :broker
defp clear_queue(queue) do
clear =
fn({{_, mon}, _, from}) ->
Process.demonitor(mon, [:flush])
message = "connection not available because of disconnection"
err = DBConnection.ConnectionError.exception(message)
Connection.reply(from, {:error, err})
false
end
:queue.filter(clear, queue)
end
defp done_lock(_, nil), do: :ok
defp done_lock(regulator, lock) do
{:stop, _} = :sregulator.done(regulator, lock, :infinity)
:ok
end
defp normal_status(mod, pdict, state) do
try do
mod.format_status(:normal, [pdict, state])
catch
_, _ ->
normal_status_default(mod, state)
else
status ->
status
end
end
defp normal_status_default(mod, state) do
[{:data, [{'Module', mod}, {'State', state}]}]
end
defp terminate_status(mod, pdict, state) do
try do
mod.format_status(:terminate, [pdict, state])
catch
_, _ ->
state
else
status ->
status
end
end
end