-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathconnection.ex
More file actions
944 lines (753 loc) · 30 KB
/
connection.ex
File metadata and controls
944 lines (753 loc) · 30 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
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
defmodule Connection do
@moduledoc ~S"""
A behaviour module for implementing connection processes.
> #### Deprecation Warning {: .warning}
>
> With the inclusion of [`gen_statem`](https://www.erlang.org/doc/man/gen_statem.html)
in Erlang/OTP, this project is no longer necessary.
>
> See the following pull request as examples
of replacing `Connection` by `gen_statem` in existing projects:
> * https://github.com/elixir-ecto/postgrex/pull/643
> * https://github.com/elixir-ecto/postgrex/pull/644
> * https://github.com/elixir-ecto/db_connection/pull/275
>
> We may release new versions if necessary to keep compatibility with Erlang/OTP and
Elixir but otherwise this package is no longer recommended for new projects.
The `Connection` behaviour is a superset of the `GenServer` behaviour. The
additional return values and callbacks are designed to aid building a
connection process that can handle a peer being (temporarily) unavailable.
An example `Connection` process:
defmodule TCPConnection do
use Connection
def start_link(host, port, opts, timeout \\ 5000) do
Connection.start_link(__MODULE__, {host, port, opts, timeout})
end
def send(conn, data) do
Connection.call(conn, {:send, data})
end
def recv(conn, bytes, timeout \\ 3000) do
Connection.call(conn, {:recv, bytes, timeout})
end
def close(conn), do: Connection.call(conn, :close)
def init({host, port, opts, timeout}) do
s = %{host: host, port: port, opts: opts, timeout: timeout, sock: nil}
{:connect, :init, s}
end
def connect(_, %{sock: nil, host: host, port: port, opts: opts, timeout: timeout} = s) do
case :gen_tcp.connect(host, port, [active: false] ++ opts, timeout) do
{:ok, sock} ->
{:ok, %{s | sock: sock}}
{:error, _} ->
{:backoff, 1000, s}
end
end
def disconnect(info, %{sock: sock} = s) do
:ok = :gen_tcp.close(sock)
case info do
{:close, from} ->
Connection.reply(from, :ok)
{:error, :closed} ->
:error_logger.format("Connection closed~n", [])
{:error, reason} ->
reason = :inet.format_error(reason)
:error_logger.format("Connection error: ~s~n", [reason])
end
{:connect, :reconnect, %{s | sock: nil}}
end
def handle_call(_, _, %{sock: nil} = s) do
{:reply, {:error, :closed}, s}
end
def handle_call({:send, data}, _, %{sock: sock} = s) do
case :gen_tcp.send(sock, data) do
:ok ->
{:reply, :ok, s}
{:error, _} = error ->
{:disconnect, error, error, s}
end
end
def handle_call({:recv, bytes, timeout}, _, %{sock: sock} = s) do
case :gen_tcp.recv(sock, bytes, timeout) do
{:ok, _} = ok ->
{:reply, ok, s}
{:error, :timeout} = timeout ->
{:reply, timeout, s}
{:error, _} = error ->
{:disconnect, error, error, s}
end
end
def handle_call(:close, from, s) do
{:disconnect, {:close, from}, s}
end
end
The example above follows a common pattern. Try to connect immediately, if
that fails backoff and retry after a delay. If a retry fails make another
attempt after another delay. If the process disconnects a reconnection attempt
is made immediately, if that fails backoff begins.
Importantly when backing off requests will still be received by the process,
which will need to be handled. In the above example the process replies with
`{:error, :closed}` when it is disconnected.
"""
@behaviour :gen_server
@doc """
Called when the connection process is first started. `start_link/3` will block
until it returns.
Returning `{:ok, state}` will cause `start_link/3` to return
`{:ok, pid}` and the process to enter its loop with state `state` without
calling `connect/2`.
This return value is useful when the process connects inside `init/1` so that
`start_link/3` blocks until a connection is established.
Returning `{:ok, state, timeout}` is similar to `{:ok, state}`
except `handle_info(:timeout, state)` will be called after `timeout` if no
message arrives.
Returning `{:ok, state, :hibernate}` is similar to
`{:ok, state}` except the process is hibernated awaiting a message.
Returning `{:connect, info, state}` will cause `start_link/3` to return
`{:ok, pid}` and `connect(info, state)` will be called immediately - even if
messages are in the processes message queue. `state` contains the state of the
process and `info` should contain any information not contained in the state
that is needed to connect.
This return value is very useful because connecting in `connect/2` will not
block the parent process and a connection attempt is guaranteed to occur
before any messages are handled, which is not possible when using a
`GenServer`.
Returning `{:backoff, timeout, state}` will cause `start_link/3` to return
`{:ok, pid}` and the process to enter its normal loop with state `state`.
`connect(:backoff, state)` is called after `timeout` if `connect/2` or
`disconnect/2` is not called within the timeout.
This return value can be used to delay or stagger the initial connection
attempt.
Returning `{:backoff, timeout, state, timeout2}` is similar to
`{:backoff, timeout, state}` except `handle_info(:timeout, state)` will be
called after `timeout2` if no message arrives.
Returning `{:backoff, timeout, state, :hibernate}` is similar to
`{:backoff, timeout, state}` except the process hibernates.
Returning `:ignore` will cause `start_link/3` to return `:ignore` and the
process will exit normally without entering the loop or calling
`terminate/2`.
Returning `{:stop, reason}` will cause `start_link/3` to return
`{:error, reason}` and the process to exit with reason `reason` without
entering the loop or calling `terminate/2`.
"""
@callback init(any) ::
{:ok, any}
| {:ok, any, timeout | :hibernate}
| {:connect, any, any}
| {:backoff, timeout, any}
| {:backoff, timeout, any, timeout | :hibernate}
| :ignore
| {:stop, any}
@doc """
Called when the process should try to connect. The first argument will either
be the `info` term from `{:connect, info, state}` or
`{:connect, info, reply, state}`, or `:backoff` if the connection attempt is
triggered by backing off.
It might be beneficial to do handshaking in this callback if connecting is
successful.
Returning `{:ok, state}` or `{:ok, state, timeout | :hibernate}` will cause
the process to continue its loop. This should be returned when the connection
attempt was successful. In the later case `handle_info(:timeout, state)` is
called after `timeout` if no message has been received, if the third element
is a timeout. Otherwise if the third element is `:hibernate` the process
hibernates.
Returning `{:backoff, timeout, state}` will cause the process to continue
its loop but `connect(:backoff, state)` will be called after `timeout` if
`connect/2` or `disconnect/2` is not called before that point.
This return value is used when a connection attempt fails but another attempt
should be made after a delay. It might be beneficial to increase the delay
up to a maximum if successive attempts fail to prevent unnecessary work. If
several connection processes are connecting to the same peer it may also be
beneficial to add some jitter (randomness) to the delays. This spreads out the
connection attempts and helps prevent many attempts occurring at the same time.
Returning `{:backoff, timeout, state, timeout2 | :hibernate}` is similar to
`{:backoff, timeout, state}` except `handle_info(:timeout, state)` is called
after `timeout2` if no message has been received, or if `:hibernate`, the
process hibernates.
Returning `{:stop, reason, state}` will terminate the loop and call
`terminate(reason, state)` before the process exits with reason `reason`.
"""
@callback connect(any, any) ::
{:ok, any}
| {:ok, any, timeout | :hibernate}
| {:backoff, timeout, any}
| {:backoff, timeout, any, timeout | :hibernate}
| {:stop, any, any}
@doc """
Called when the process should disconnect. The first argument will either
be the `info` term from `{:disconnect, info, state}` or
`{:disconnect, info, reply, state}`. This callback should do any cleaning up
required to disconnect the connection and update the state of the process.
Returning `{:connect, info, state}` will call `connect(info, state)`
immediately - even if there are messages in the message queue.
Returning `{:backoff, timeout, state}` or
`{:backoff, timeout, state, timeout2 | :hibernate}` starts a backoff timer and
behaves the same as when returned from `connect/2`. See the `connect/2`
callback for more information.
Returning `{:noconnect, state}` or `{:noconnect, state, timeout | :hibernate}`
will cause the process to continue is loop (and NOT call `connect/2` to
try to reconnect). In the later case a timeout is started or the process
hibernates.
Returning `{:stop, reason, state}` will terminate the loop and call
`terminate(reason, state)` before the process exits with reason `reason`.
"""
@callback disconnect(any, any) ::
{:connect, any, any}
| {:backoff, timeout, any}
| {:backoff, timeout, any, timeout | :hibernate}
| {:noconnect, any}
| {:noconnect, any, timeout | :hibernate}
| {:stop, any, any}
@doc """
Called when the process receives a call message sent by `call/3`. This
callback has the same arguments as the `GenServer` equivalent and the
`:reply`, `:noreply` and `:stop` return tuples behave the same. However
there are a few additional return values:
Returning `{:connect, info, reply, state}` will reply to the call with `reply`
and immediately call `connect(info, state)`. Similarly for
`{:disconnect, info, reply, state}`, except `disconnect/2` is called.
Returning `{:connect, info, state}` or `{:disconnect, info, state}` will
call the relevant callback immediately without replying to the call. This
might be useful when the call should block until the process has connected,
failed to connect or disconnected. The second argument passed to this callback
can be included in the `info` or `state` terms and a reply sent in the next
or a later callback using `reply/2`.
"""
@callback handle_call(any, {pid, any}, any) ::
{:reply, any, any}
| {:reply, any, any, timeout | :hibernate}
| {:noreply, any}
| {:noreply, any, timeout | :hibernate}
| {:disconnect | :connect, any, any, any}
| {:disconnect | :connect, any, any}
| {:stop, any, any}
| {:stop, any, any, any}
@doc """
Called when the process receives a cast message sent by `cast/3`. This
callback has the same arguments as the `GenServer` equivalent and the
`:noreply` and `:stop` return tuples behave the same. However
there are two additional return values:
Returning `{:connect, info, state}` will immediately call
`connect(info, state)`. Similarly for `{:disconnect, info, state}`,
except `disconnect/2` is called.
"""
@callback handle_cast(any, any) ::
{:noreply, any}
| {:noreply, any, timeout | :hibernate}
| {:disconnect | :connect, any, any}
| {:stop, any, any}
@doc """
Called when the process receives a message that is not a call or cast. This
callback has the same arguments as the `GenServer` equivalent and the `:noreply`
and `:stop` return tuples behave the same. However there are two additional
return values:
Returning `{:connect, info, state}` will immediately call
`connect(info, state)`. Similarly for `{:disconnect, info, state}`,
except `disconnect/2` is called.
"""
@callback handle_info(any, any) ::
{:noreply, any}
| {:noreply, any, timeout | :hibernate}
| {:disconnect | :connect, any, any}
| {:stop, any, any}
@doc """
This callback is the same as the `GenServer` equivalent and is used to change
the state when loading a different version of the callback module.
"""
@callback code_change(any, any, any) :: {:ok, any}
@doc """
This callback is the same as the `GenServer` equivalent and is called when the
process terminates. The first argument is the reason the process is about
to exit with.
"""
@callback terminate(any, any) :: any
defmacro __using__(_) do
quote location: :keep do
@behaviour Connection
# The default implementations of init/1, handle_call/3, handle_info/2,
# handle_cast/2, terminate/2 and code_change/3 have been taken verbatim
# from Elixir's GenServer default implementation.
@doc false
def init(args) do
{:ok, args}
end
@doc false
def handle_call(msg, _from, state) do
# We do this to trick dialyzer to not complain about non-local returns.
reason = {:bad_call, msg}
case :erlang.phash2(1, 1) do
0 -> exit(reason)
1 -> {:stop, reason, state}
end
end
@doc false
def handle_info(_msg, state) do
{:noreply, state}
end
@doc false
def handle_cast(msg, state) do
# We do this to trick dialyzer to not complain about non-local returns.
reason = {:bad_cast, msg}
case :erlang.phash2(1, 1) do
0 -> exit(reason)
1 -> {:stop, reason, state}
end
end
@doc false
def terminate(_reason, _state) do
:ok
end
@doc false
def code_change(_old, state, _extra) do
{:ok, state}
end
@doc false
def connect(info, state) do
reason = {:bad_connect, info}
case :erlang.phash2(1, 1) do
0 -> exit(reason)
1 -> {:stop, reason, state}
end
end
@doc false
def disconnect(info, state) do
reason = {:bad_disconnect, info}
case :erlang.phash2(1, 1) do
0 -> exit(reason)
1 -> {:stop, reason, state}
end
end
defoverridable init: 1,
handle_call: 3,
handle_info: 2,
handle_cast: 2,
terminate: 2,
code_change: 3,
connect: 2,
disconnect: 2
end
end
@doc """
Starts a `Connection` process linked to the current process.
This function is used to start a `Connection` process in a supervision tree.
The process will be started by calling `init/1` in the callback module with
the given argument.
This function will return after `init/1` has returned in the spawned process.
The return values are controlled by the `init/1` callback.
See `GenServer.start_link/3` for more information.
"""
@spec start_link(module, any, GenServer.options()) :: GenServer.on_start()
def start_link(mod, args, opts \\ []) do
start(mod, args, opts, :link)
end
@doc """
Starts a `Connection` process without links (outside of a supervision tree).
See `start_link/3` for more information.
"""
@spec start(module, any, GenServer.options()) :: GenServer.on_start()
def start(mod, args, opts \\ []) do
start(mod, args, opts, :nolink)
end
@doc """
Sends a synchronous call to the `Connection` process and waits for a reply.
See `GenServer.call/2` for more information.
"""
defdelegate call(conn, req), to: :gen_server
@doc """
Sends a synchronous request to the `Connection` process and waits for a reply.
See `GenServer.call/3` for more information.
"""
defdelegate call(conn, req, timeout), to: :gen_server
@doc """
Sends a asynchronous request to the `Connection` process.
See `GenServer.cast/2` for more information.
"""
defdelegate cast(conn, req), to: GenServer
@doc """
Sends a reply to a request sent by `call/3`.
See `GenServer.reply/2` for more information.
"""
defdelegate reply(from, response), to: :gen_server
defstruct [:mod, :backoff, :raise, :mod_state]
## :gen callback
@doc false
def init_it(starter, _, name, mod, args, opts) do
Process.put(:"$initial_call", {mod, :init, 1})
try do
apply(mod, :init, [args])
catch
:exit, reason ->
init_stop(starter, name, reason)
:error, reason ->
init_stop(starter, name, {reason, __STACKTRACE__})
:throw, value ->
reason = {{:nocatch, value}, __STACKTRACE__}
init_stop(starter, name, reason)
else
{:ok, mod_state} ->
:proc_lib.init_ack(starter, {:ok, self()})
enter_loop(mod, nil, mod_state, name, opts, :infinity)
{:ok, mod_state, timeout} ->
:proc_lib.init_ack(starter, {:ok, self()})
enter_loop(mod, nil, mod_state, name, opts, timeout)
{:connect, info, mod_state} ->
:proc_lib.init_ack(starter, {:ok, self()})
enter_connect(mod, info, mod_state, name, opts)
{:backoff, backoff_timeout, mod_state} ->
backoff = start_backoff(backoff_timeout)
:proc_lib.init_ack(starter, {:ok, self()})
enter_loop(mod, backoff, mod_state, name, opts, :infinity)
{:backoff, backoff_timeout, mod_state, timeout} ->
backoff = start_backoff(backoff_timeout)
:proc_lib.init_ack(starter, {:ok, self()})
enter_loop(mod, backoff, mod_state, name, opts, timeout)
:ignore ->
_ = unregister(name)
:proc_lib.init_ack(starter, :ignore)
exit(:normal)
{:stop, reason} ->
init_stop(starter, name, reason)
other ->
init_stop(starter, name, {:bad_return_value, other})
end
end
## :proc_lib callback
@doc false
def enter_loop(mod, backoff, mod_state, name, opts, :hibernate) do
args = [mod, backoff, mod_state, name, opts, :infinity]
:proc_lib.hibernate(__MODULE__, :enter_loop, args)
end
def enter_loop(mod, backoff, mod_state, name, opts, timeout)
when name === self() do
s = %Connection{mod: mod, backoff: backoff, mod_state: mod_state, raise: nil}
:gen_server.enter_loop(__MODULE__, opts, s, timeout)
end
def enter_loop(mod, backoff, mod_state, name, opts, timeout) do
s = %Connection{mod: mod, backoff: backoff, mod_state: mod_state, raise: nil}
:gen_server.enter_loop(__MODULE__, opts, s, name, timeout)
end
@doc false
def init(_) do
{:stop, __MODULE__}
end
@doc false
def handle_call(request, from, %{mod: mod, mod_state: mod_state} = s) do
try do
apply(mod, :handle_call, [request, from, mod_state])
catch
:throw, value ->
:erlang.raise(:error, {:nocatch, value}, __STACKTRACE__)
else
{:noreply, mod_state} = noreply ->
put_elem(noreply, 1, %{s | mod_state: mod_state})
{:noreply, mod_state, _} = noreply ->
put_elem(noreply, 1, %{s | mod_state: mod_state})
{:reply, _, mod_state} = reply ->
put_elem(reply, 2, %{s | mod_state: mod_state})
{:reply, _, mod_state, _} = reply ->
put_elem(reply, 2, %{s | mod_state: mod_state})
{:connect, info, mod_state} ->
connect(info, mod_state, s)
{:connect, info, reply, mod_state} ->
reply(from, reply)
connect(info, mod_state, s)
{:disconnect, info, mod_state} ->
disconnect(info, mod_state, s)
{:disconnect, info, reply, mod_state} ->
reply(from, reply)
disconnect(info, mod_state, s)
{:stop, _, mod_state} = stop ->
put_elem(stop, 2, %{s | mod_state: mod_state})
{:stop, _, _, mod_state} = stop ->
put_elem(stop, 3, %{s | mod_state: mod_state})
other ->
{:stop, {:bad_return_value, other}, %{s | mod_state: mod_state}}
end
end
@doc false
def handle_cast(request, s) do
handle_async(:handle_cast, request, s)
end
@doc false
def handle_info(
{:timeout, backoff, __MODULE__},
%{backoff: backoff, mod_state: mod_state} = s
) do
connect(:backoff, mod_state, %{s | backoff: nil})
end
def handle_info(msg, s) do
handle_async(:handle_info, msg, s)
end
@doc false
def code_change(old_vsn, %{mod: mod, mod_state: mod_state} = s, extra) do
try do
apply(mod, :code_change, [old_vsn, mod_state, extra])
catch
:throw, value ->
exit({{:nocatch, value}, __STACKTRACE__})
else
{:ok, mod_state} ->
{:ok, %{s | mod_state: mod_state}}
end
end
@doc false
def format_status(:normal, [pdict, %{mod: mod, mod_state: mod_state}]) do
try do
apply(mod, :format_status, [:normal, [pdict, mod_state]])
catch
_, _ ->
[{:data, [{~c"State", mod_state}]}]
else
mod_status ->
mod_status
end
end
def format_status(:terminate, [pdict, %{mod: mod, mod_state: mod_state}]) do
try do
apply(mod, :format_status, [:terminate, [pdict, mod_state]])
catch
_, _ ->
mod_state
else
mod_state ->
mod_state
end
end
@doc false
def terminate(reason, %{mod: mod, mod_state: mod_state, raise: nil}) do
apply(mod, :terminate, [reason, mod_state])
end
def terminate(stop, %{raise: {class, reason, stack}} = s) do
%{mod: mod, mod_state: mod_state} = s
try do
apply(mod, :terminate, [stop, mod_state])
catch
:throw, value ->
:erlang.raise(:error, {:nocatch, value}, __STACKTRACE__)
else
_ when stop in [:normal, :shutdown] ->
:ok
_ when tuple_size(stop) == 2 and elem(stop, 0) == :shutdown ->
:ok
_ ->
:erlang.raise(class, reason, stack)
end
end
# start helpers
defp start(mod, args, options, link) do
case Keyword.pop(options, :name) do
{nil, opts} ->
:gen.start(__MODULE__, link, mod, args, opts)
{atom, opts} when is_atom(atom) ->
:gen.start(__MODULE__, link, {:local, atom}, mod, args, opts)
{{:global, _} = name, opts} ->
:gen.start(__MODULE__, link, name, mod, args, opts)
{{:via, _, _} = name, opts} ->
:gen.start(__MODULE__, link, name, mod, args, opts)
end
end
# init helpers
defp init_stop(starter, name, reason) do
_ = unregister(name)
:proc_lib.init_ack(starter, {:error, reason})
exit(reason)
end
defp unregister(name) when name === self(), do: :ok
defp unregister({:local, name}), do: Process.unregister(name)
defp unregister({:global, name}), do: :global.unregister_name(name)
defp unregister({:via, mod, name}), do: apply(mod, :unregister_name, [name])
defp enter_connect(mod, info, mod_state, name, opts) do
try do
apply(mod, :connect, [info, mod_state])
catch
:exit, reason ->
report_reason = {:EXIT, {reason, __STACKTRACE__}}
enter_terminate(mod, mod_state, name, reason, report_reason)
:error, reason ->
reason = {reason, __STACKTRACE__}
enter_terminate(mod, mod_state, name, reason, {:EXIT, reason})
:throw, value ->
reason = {{:nocatch, value}, __STACKTRACE__}
enter_terminate(mod, mod_state, name, reason, {:EXIT, reason})
else
{:ok, mod_state} ->
enter_loop(mod, nil, mod_state, name, opts, :infinity)
{:ok, mod_state, timeout} ->
enter_loop(mod, nil, mod_state, name, opts, timeout)
{:backoff, backoff_timeout, mod_state} ->
backoff = start_backoff(backoff_timeout)
enter_loop(mod, backoff, mod_state, name, opts, :infinity)
{:backoff, backoff_timeout, mod_state, timeout} ->
backoff = start_backoff(backoff_timeout)
enter_loop(mod, backoff, mod_state, name, opts, timeout)
{:stop, reason, mod_state} ->
enter_terminate(mod, mod_state, name, reason, {:stop, reason})
other ->
reason = {:bad_return_value, other}
enter_terminate(mod, mod_state, name, reason, {:stop, reason})
end
end
defp enter_terminate(mod, mod_state, name, reason, report_reason) do
try do
apply(mod, :terminate, [reason, mod_state])
catch
:exit, reason ->
report_reason = {:EXIT, {reason, __STACKTRACE__}}
enter_stop(mod, mod_state, name, reason, report_reason)
:error, reason ->
reason = {reason, __STACKTRACE__}
enter_stop(mod, mod_state, name, reason, {:EXIT, reason})
:throw, value ->
reason = {{:nocatch, value}, __STACKTRACE__}
enter_stop(mod, mod_state, name, reason, {:EXIT, reason})
else
_ ->
enter_stop(mod, mod_state, name, reason, report_reason)
end
end
defp enter_stop(_, _, _, :normal, {:stop, :normal}), do: exit(:normal)
defp enter_stop(_, _, _, :shutdown, {:stop, :shutdown}), do: exit(:shutdown)
defp enter_stop(_, _, _, {:shutdown, reason} = shutdown, {:stop, {:shutdown, reason}}) do
exit(shutdown)
end
defp enter_stop(mod, mod_state, name, reason, {_, reason2}) do
s = %{mod: mod, backoff: nil, mod_state: mod_state}
mod_state = format_status(:terminate, [Process.get(), s])
## No last message
format =
~c"** Generic server ~p terminating \n" ++
~c"** Last message in was ~p~n" ++
~c"** When Server state == ~p~n" ++
~c"** Reason for termination == ~n** ~p~n"
args = [report_name(name), nil, mod_state, report_reason(reason2)]
:error_logger.format(format, args)
exit(reason)
end
defp report_name(name) when name === self(), do: name
defp report_name({:local, name}), do: name
defp report_name({:global, name}), do: name
defp report_name({:via, _, name}), do: name
defp report_reason({:undef, [{mod, fun, args, _} | _] = stack} = reason) do
cond do
:code.is_loaded(mod) === false ->
{:"module could not be loaded", stack}
not function_exported?(mod, fun, length(args)) ->
{:"function not exported", stack}
true ->
reason
end
end
defp report_reason(reason) do
reason
end
## backoff helpers
defp start_backoff(:infinity), do: nil
defp start_backoff(timeout) do
:erlang.start_timer(timeout, self(), __MODULE__)
end
defp cancel_backoff(%{backoff: nil} = s), do: s
defp cancel_backoff(%{backoff: backoff} = s) do
case :erlang.cancel_timer(backoff) do
false ->
flush_backoff(backoff)
_ ->
:ok
end
%{s | backoff: nil}
end
defp flush_backoff(backoff) do
receive do
{:timeout, ^backoff, __MODULE__} ->
:ok
after
0 ->
:ok
end
end
## GenServer helpers
defp connect(info, mod_state, %{mod: mod} = s) do
s = cancel_backoff(s)
try do
apply(mod, :connect, [info, mod_state])
catch
class, reason ->
stack = __STACKTRACE__
callback_stop(class, reason, stack, %{s | mod_state: mod_state})
else
{:ok, mod_state} ->
{:noreply, %{s | mod_state: mod_state}}
{:ok, mod_state, timeout} ->
{:noreply, %{s | mod_state: mod_state}, timeout}
{:backoff, backoff_timeout, mod_state} ->
backoff = start_backoff(backoff_timeout)
{:noreply, %{s | backoff: backoff, mod_state: mod_state}}
{:backoff, backoff_timeout, mod_state, timeout} ->
backoff = start_backoff(backoff_timeout)
{:noreply, %{s | backoff: backoff, mod_state: mod_state}, timeout}
{:stop, _, mod_state} = stop ->
put_elem(stop, 2, %{s | mod_state: mod_state})
other ->
{:stop, {:bad_return_value, other}, %{s | mod_state: mod_state}}
end
end
defp disconnect(info, mod_state, %{mod: mod} = s) do
s = cancel_backoff(s)
try do
apply(mod, :disconnect, [info, mod_state])
catch
class, reason ->
stack = __STACKTRACE__
callback_stop(class, reason, stack, %{s | mod_state: mod_state})
else
{:connect, info, mod_state} ->
connect(info, mod_state, s)
{:noconnect, mod_state} ->
{:noreply, %{s | mod_state: mod_state}}
{:noconnect, mod_state, timeout} ->
{:noreply, %{s | mod_state: mod_state}, timeout}
{:backoff, backoff_timeout, mod_state} ->
backoff = start_backoff(backoff_timeout)
{:noreply, %{s | backoff: backoff, mod_state: mod_state}}
{:backoff, backoff_timeout, mod_state, timeout} ->
backoff = start_backoff(backoff_timeout)
{:noreply, %{s | backoff: backoff, mod_state: mod_state}, timeout}
{:stop, _, mod_state} = stop ->
put_elem(stop, 2, %{s | mod_state: mod_state})
other ->
{:stop, {:bad_return_value, other}, %{s | mod_state: mod_state}}
end
end
# In order to have new mod_state in terminate/2 must return the exit reason.
# However to get the correct GenServer report (exit with stacktrace),
# include stacktrace in reason and re-raise after calling mod.terminate/2 if
# it does not raise.
defp callback_stop(:throw, value, stack, s) do
callback_stop(:error, {:nocatch, value}, stack, s)
end
defp callback_stop(class, reason, stack, s) do
raise = {class, reason, stack}
{:stop, stop_reason(class, reason, stack), %{s | raise: raise}}
end
defp stop_reason(:error, reason, stack), do: {reason, stack}
defp stop_reason(:exit, reason, _), do: reason
defp handle_async(fun, msg, %{mod: mod, mod_state: mod_state} = s) do
try do
apply(mod, fun, [msg, mod_state])
catch
:throw, value ->
:erlang.raise(:error, {:nocatch, value}, __STACKTRACE__)
else
{:noreply, mod_state} = noreply ->
put_elem(noreply, 1, %{s | mod_state: mod_state})
{:noreply, mod_state, _} = noreply ->
put_elem(noreply, 1, %{s | mod_state: mod_state})
{:connect, info, mod_state} ->
connect(info, mod_state, s)
{:disconnect, info, mod_state} ->
disconnect(info, mod_state, s)
{:stop, _, mod_state} = stop ->
put_elem(stop, 2, %{s | mod_state: mod_state})
other ->
{:stop, {:bad_return_value, other}, %{s | mod_state: mod_state}}
end
end
end