Repository navigation
Expand file tree
/
Copy pathwebsockex.ex
More file actions
1401 lines (1114 loc) · 43.7 KB
/
Copy pathwebsockex.ex
File metadata and controls
1401 lines (1114 loc) · 43.7 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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule WebSockex do
alias WebSockex.{Utils}
@handshake_guid "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
@moduledoc ~S"""
A client handles negotiating the connection, then sending frames, receiving
frames, closing, and reconnecting that connection.
A simple client implementation would be:
```
defmodule WsClient do
use WebSockex
def start_link(url, state) do
WebSockex.start_link(url, __MODULE__, state)
end
def handle_frame({:text, msg}, state) do
IO.puts "Received a message: #{msg}"
{:ok, state}
end
def handle_cast({:send, {type, msg} = frame}, state) do
IO.puts "Sending #{type} frame with payload: #{msg}"
{:reply, frame, state}
end
end
```
## Closing Connections
WebSockex connections can be closed gracefully by returning close tuples from
callback functions. The following callbacks support close returns:
- `c:handle_frame/2`
- `c:handle_cast/2`
- `c:handle_info/2`
- `c:handle_ping/2`
- `c:handle_pong/2`
### Basic Close
Return `{:close, state}` to close with the default close code (1000):
```
def handle_frame({:text, "quit"}, state) do
{:close, state}
end
```
### Close with Custom Code
Return `{:close, {close_code, message}, state}` to specify a close code and reason:
```
def handle_frame({:text, "error"}, state) do
{:close, {4000, "Application error"}, state}
end
```
Close codes are integers in specific ranges:
- `1000-1015` - Standard protocol codes (e.g., 1000 = normal, 1001 = going away, 1002 = protocol error, 1003 = unsupported data)
- `3000-3999` - Reserved for use by libraries, frameworks, and applications (registered with IANA)
- `4000-4999` - Private use for applications
Common standard codes include:
- `1000` - Normal closure
- `1001` - Going away
- `1002` - Protocol error
- `1003` - Unsupported data
## Supervision
WebSockex is implemented as an OTP Special Process and as a result will fit
into supervision trees.
WebSockex also supports the Supervisor children format introduced in Elixir
1.5. Meaning that a child specification could be `{ClientModule, [state]}`.
However, since there is a possibility that you would like to provide a
`t:WebSockex.Conn/0` or a url as well as the state, there are two versions of
the `child_spec` function. If you need functionality beyond that it is
recommended that you override the function or define your own.
Just remember to use the version that corresponds with your `start_link`'s
arity.
"""
@type client :: pid | atom | {:via, module, term} | {:global, term}
@type frame ::
:ping
| :pong
| {:ping | :pong, nil | (message :: binary)}
| {:text | :binary, message :: binary}
@typedoc """
The frame sent when the negotiating a connection closure.
"""
@type close_frame :: {close_code, message :: binary}
@typedoc """
An integer between 1000 and 4999 that specifies the reason for closing the connection.
"""
@type close_code :: integer
@typedoc """
Debug options to be parsed by `:sys.debug_options/1`.
These options can also be set after the process is running using the functions in
the Erlang `:sys` module.
"""
@type debug_opts :: [
:trace
| :log
| {:log, log_depth :: pos_integer}
| :statistics
| {:log_to_file, Path.t()}
]
@type options :: [option]
@typedoc """
Options values for `start_link`.
- `:async` - Replies with `{:ok, pid}` before establishing the connection.
This is useful for when attempting to connect indefinitely, this way the
process doesn't block trying to establish a connection.
- `:handle_initial_conn_failure` - When set to `true` a connection failure
while establishing the initial connection won't immediately return an error
and instead will invoke the `c:handle_disconnect/2` callback. This option
only matters during process initialization. The `handle_disconnect`
callback is always invoked if an established connection is lost.
- `:debug` - Options to set the debug options for `:sys.handle_debug`.
- `:name` - An atom that the registers the process with name locally.
Can also be a `{:via, module, term}` or `{:global, term}` tuple.
Other possible option values include: `t:WebSockex.Conn.connection_option/0`
"""
@type option ::
WebSockex.Conn.connection_option()
| {:async, boolean}
| {:debug, debug_opts}
| {:name, atom | {:global, term} | {:via, module, term}}
| {:handle_initial_conn_failure, boolean}
@typedoc """
The reason a connection was closed.
A `:normal` reason is the same as a `1000` reason with no payload.
If the peer closes the connection abruptly without a close frame then the
close reason is `{:remote, :closed}`.
"""
@type close_reason ::
{:remote | :local, :normal}
| {:remote | :local, close_code, message :: binary}
| {:remote, :closed}
| {:error, term}
@typedoc """
The error returned when a connection fails to be established.
"""
@type close_error ::
%WebSockex.RequestError{}
| %WebSockex.ConnError{}
| %WebSockex.InvalidFrameError{}
| %WebSockex.FrameEncodeError{}
@typedoc """
A map that contains information about the failure to connect.
This map contains the error, attempt number, and the `t:WebSockex.Conn.t/0`
that was used to attempt the connection.
"""
@type connection_status_map :: %{
reason: close_reason | close_error,
attempt_number: integer,
conn: WebSockex.Conn.t()
}
@doc """
Invoked after a connection is established.
This is invoked after both the initial connection and a reconnect.
"""
@callback handle_connect(conn :: WebSockex.Conn.t(), state :: term) :: {:ok, new_state :: term}
@doc """
Invoked on the reception of a frame on the socket.
The control frames have possible payloads, when they don't have a payload
then the frame will have `nil` as the payload. e.g. `{:ping, nil}`
"""
@callback handle_frame(frame, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked to handle asynchronous `cast/2` messages.
"""
@callback handle_cast(msg :: term, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked to handle all other non-WebSocket messages.
"""
@callback handle_info(msg :: term, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked when the WebSocket disconnects from the server.
This callback is only invoked in the event of a connection failure. In cases
of crashes or other errors the process will terminate immediately
skipping this callback.
If the `handle_initial_conn_failure: true` option is provided during process
startup, then this callback will be invoked if the process fails to establish
an initial connection.
If a connection is established by reconnecting, the `c:handle_connect/2`
callback will be invoked.
The possible returns for this callback are:
- `{:ok, state}` will continue the process termination.
- `{:reconnect, state}` will attempt to reconnect instead of terminating.
- `{:reconnect, conn, state}` will attempt to reconnect with the connection
data in `conn`. `conn` is expected to be a `t:WebSockex.Conn.t/0`.
"""
@callback handle_disconnect(connection_status_map, state :: term) ::
{:ok, new_state}
| {:reconnect, new_state}
| {:reconnect, new_conn :: WebSockex.Conn.t(), new_state}
when new_state: term
@doc """
Invoked when the Websocket receives a ping frame
"""
@callback handle_ping(ping_frame :: :ping | {:ping, binary}, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked when the Websocket receives a pong frame.
"""
@callback handle_pong(pong_frame :: :pong | {:pong, binary}, state :: term) ::
{:ok, new_state}
| {:reply, frame, new_state}
| {:close, new_state}
| {:close, close_frame, new_state}
when new_state: term
@doc """
Invoked when the process is terminating.
"""
@callback terminate(close_reason, state :: term) :: any
@doc """
Invoked when a new version the module is loaded during runtime.
"""
@callback code_change(old_vsn :: term | {:down, term}, state :: term, extra :: term) ::
{:ok, new_state :: term}
| {:error, reason :: term}
@doc """
Invoked to retrieve a formatted status of the state in a WebSockex process.
This optional callback is used when you want to edit the values returned when
invoking `:sys.get_status`.
The second argument is a two-element list with the order of `[pdict, state]`.
"""
@callback format_status(:normal, [process_dictionary | state]) :: status :: term
when process_dictionary: [{key :: term, val :: term}], state: term
@optional_callbacks format_status: 2
defmacro __using__(opts) do
quote location: :keep do
@behaviour WebSockex
if Kernel.function_exported?(Supervisor, :child_spec, 2) do
@doc false
def child_spec(conn_info, state) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [conn_info, state]}
}
|> Supervisor.child_spec(unquote(Macro.escape(opts)))
end
@doc false
def child_spec(state) do
%{
id: __MODULE__,
start: {__MODULE__, :start_link, [state]}
}
|> Supervisor.child_spec(unquote(Macro.escape(opts)))
end
defoverridable child_spec: 2, child_spec: 1
end
@doc false
def handle_connect(_conn, state) do
{:ok, state}
end
@doc false
def handle_frame(frame, _state) do
raise "No handle_frame/2 clause in #{__MODULE__} provided for #{inspect(frame)}"
end
@doc false
def handle_cast(message, _state) do
raise "No handle_cast/2 clause in #{__MODULE__} provided for #{inspect(message)}"
end
@doc false
def handle_info(message, state) do
require Logger
Logger.error("No handle_info/2 clause in #{__MODULE__} provided for #{inspect(message)}")
{:ok, state}
end
@doc false
def handle_disconnect(_connection_status_map, state) do
{:ok, state}
end
@doc false
def handle_ping(:ping, state) do
{:reply, :pong, state}
end
def handle_ping({:ping, msg}, state) do
{:reply, {:pong, msg}, state}
end
@doc false
def handle_pong(:pong, state), do: {:ok, state}
def handle_pong({:pong, _}, state), do: {:ok, state}
@doc false
def terminate(_close_reason, _state), do: :ok
@doc false
def code_change(_old_vsn, state, _extra), do: {:ok, state}
defoverridable handle_connect: 2,
handle_frame: 2,
handle_cast: 2,
handle_info: 2,
handle_ping: 2,
handle_pong: 2,
handle_disconnect: 2,
terminate: 2,
code_change: 3
end
end
@doc """
Starts a `WebSockex` process.
Acts like `start_link/4`, except doesn't link the current process.
See `start_link/4` for more information.
"""
@spec start(url :: String.t() | WebSockex.Conn.t(), module, term, options) ::
{:ok, pid} | {:error, term}
def start(conn_info, module, state, opts \\ [])
def start(%WebSockex.Conn{} = conn, module, state, opts) do
Utils.spawn(:no_link, conn, module, state, opts)
end
def start(url, module, state, opts) do
case WebSockex.Conn.new(url, opts) do
%WebSockex.Conn{} = conn ->
start(conn, module, state, opts)
{:error, _} = error ->
error
end
end
@doc """
Starts a `WebSockex` process linked to the current process.
For available option values see `t:option/0`.
If a `WebSockex.Conn.t` is used in place of a url string, then the options
available in `t:WebSockex.Conn.connection_option/0` have effect.
The callback `c:handle_connect/2` is invoked after the connection is
established.
"""
@spec start_link(url :: String.t() | WebSockex.Conn.t(), module, term, options) ::
{:ok, pid} | {:error, term}
def start_link(conn_info, module, state, opts \\ [])
def start_link(conn = %WebSockex.Conn{}, module, state, opts) do
Utils.spawn(:link, conn, module, state, opts)
end
def start_link(url, module, state, opts) do
case WebSockex.Conn.new(url, opts) do
%WebSockex.Conn{} = conn ->
start_link(conn, module, state, opts)
{:error, _} = error ->
error
end
end
@doc """
Asynchronously sends a message to a client that is handled by `c:handle_cast/2`.
"""
@spec cast(client, term) :: :ok
def cast(client, message) do
Utils.send(client, {:"$websockex_cast", message})
:ok
end
@doc """
Sends a frame through the WebSocket.
If the connection is either connecting or closing then this will return an
error tuple with a `WebSockex.NotConnectedError` exception struct as the
second element.
If a connection failure is discovered while sending then it will return an
error tuple with a `WebSockex.ConnError` exception struct as the second
element.
"""
@spec send_frame(client, frame, timeout) ::
:ok
| {:error,
%WebSockex.FrameEncodeError{}
| %WebSockex.ConnError{}
| %WebSockex.NotConnectedError{}
| %WebSockex.InvalidFrameError{}}
| none
def send_frame(client, frame, timeout \\ 5_000)
def send_frame(client, _, _) when client == self() do
raise %WebSockex.CallingSelfError{function: :send_frame}
end
def send_frame(client, frame, timeout) do
try do
{:ok, res} = :gen.call(client, :"$websockex_send", frame, timeout)
res
catch
_, reason ->
exit({reason, {__MODULE__, :call, [client, frame]}})
end
end
@doc """
Sends a close frame to signal that no more data will be sent, but continues
receiving data from the remote side.
This implements the WebSocket half-close pattern (similar to TCP shutdown).
After calling this function:
- No more frames can be sent (send_frame will return an error)
- Incoming frames are still processed normally via callbacks
- When the remote sends its close frame, the connection completes closing
This is useful when you need to signal "I'm done sending" while still waiting
for a response from the remote side.
## Options
- `:timeout` - Timeout for the operation (default: 5000 ms)
## Examples
# Signal done sending, wait for response
:ok = WebSockex.close_output(client)
# Connection will now only receive frames until remote closes
# With custom close code and message
:ok = WebSockex.close_output(client, {1000, "Done sending"})
"""
@spec close_output(client, close_frame | nil, timeout) ::
:ok
| {:error,
%WebSockex.ConnError{}
| %WebSockex.NotConnectedError{}}
def close_output(client, close_frame \\ nil, timeout \\ 5_000)
def close_output(client, _, _) when client == self() do
raise %WebSockex.CallingSelfError{function: :close_output}
end
def close_output(client, close_frame, timeout) do
try do
{:ok, res} = :gen.call(client, :"$websockex_close_output", close_frame, timeout)
res
catch
_, reason ->
exit({reason, {__MODULE__, :call, [client, close_frame]}})
end
end
@doc false
@spec init(pid, WebSockex.Conn.t(), module, term, options) :: {:ok, pid} | {:error, term}
def init(parent, conn, module, module_state, opts) do
do_init(parent, self(), conn, module, module_state, opts)
end
@spec init(pid, atom, WebSockex.Conn.t(), module, term, options) :: {:ok, pid} | {:error, term}
def init(parent, name, conn, module, module_state, opts) do
case Utils.register(name) do
true ->
do_init(parent, name, conn, module, module_state, opts)
{:error, _} = error ->
:proc_lib.init_ack(parent, error)
end
end
## OTP Stuffs
@doc false
def system_continue(parent, debug, %{connection_status: :connected} = state) do
websocket_loop(parent, debug, Map.delete(state, :connection_status))
end
def system_continue(parent, debug, %{connection_status: :connecting} = state) do
open_loop(parent, debug, Map.delete(state, :connection_status))
end
def system_continue(parent, debug, %{connection_status: {:closing, reason}} = state) do
close_loop(reason, parent, debug, Map.delete(state, :connection_status))
end
def system_continue(parent, debug, %{connection_status: :output_closed} = state) do
websocket_loop(parent, debug, Map.delete(state, :connection_status))
end
@doc false
@spec system_terminate(term, pid, any, any) :: no_return
def system_terminate(reason, parent, debug, state) do
terminate(reason, parent, debug, state)
end
@doc false
def system_get_state(%{module_state: module_state}) do
{:ok, module_state}
end
@doc false
def system_replace_state(fun, state) do
new_module_state = fun.(state.module_state)
{:ok, new_module_state, %{state | module_state: new_module_state}}
end
@doc false
def system_code_change(state, _mod, old_vsn, extra) do
case apply(state.module, :code_change, [old_vsn, state.module_state, extra]) do
{:ok, new_module_state} ->
{:ok, %{state | module_state: new_module_state}}
other ->
other
end
catch
other -> other
end
@doc false
def format_status(opt, [pdict, sys_state, parent, debug, state]) do
log = Utils.sys_log(debug)
module_misc = module_status(opt, state.module, pdict, state.module_state)
[
{:header, ~c"Status for WebSockex process #{inspect(self())}"},
{:data,
[
{"Status", sys_state},
{"Parent", parent},
{"Log", log},
{"Connection Status", state.connection_status},
{"Socket Buffer", state.buffer},
{"Socket Module", state.module}
]}
| module_misc
]
end
defp module_status(opt, module, pdict, module_state) do
default = [{:data, [{"State", module_state}]}]
if function_exported?(module, :format_status, 2) do
result = try_callback(module, :format_status, [opt, [pdict, module_state]])
case result do
{:"$EXIT", _} ->
require Logger
Logger.error("There was an error while invoking #{module}.format_status/2")
default
other when is_list(other) ->
other
other ->
[other]
end
else
default
end
end
# Internals! Yay
defp do_init(parent, name, conn, module, module_state, opts) do
# OTP stuffs
debug = Utils.parse_debug_options(self(), opts)
reply_fun =
case Keyword.get(opts, :async, false) do
true ->
:proc_lib.init_ack(parent, {:ok, self()})
&async_init_fun/1
false ->
&sync_init_fun(parent, &1)
end
state = %{
conn: conn,
module: module,
module_state: module_state,
name: name,
reply_fun: reply_fun,
buffer: <<>>,
fragment: nil,
output_closed_reason: nil
}
handle_conn_failure = Keyword.get(opts, :handle_initial_conn_failure, false)
case open_connection(parent, debug, state) do
{:ok, new_state} ->
debug = Utils.sys_debug(debug, :connected, state)
module_init(parent, debug, new_state)
{:error, error, new_state} when handle_conn_failure == true ->
init_conn_failure(error, parent, debug, new_state)
{:error, error, _} ->
state.reply_fun.({:error, error})
end
end
# Loops
defp open_loop(parent, debug, state) do
%{task: %{ref: ref}} = state
receive do
{:system, from, req} ->
state = Map.put(state, :connection_status, :connecting)
:sys.handle_system_msg(req, from, parent, __MODULE__, debug, state)
{:"$websockex_send", from, _frame} ->
:gen.reply(from, {:error, %WebSockex.NotConnectedError{connection_state: :opening}})
open_loop(parent, debug, state)
{:"$websockex_close_output", from, _frame} ->
:gen.reply(from, {:error, %WebSockex.NotConnectedError{connection_state: :opening}})
open_loop(parent, debug, state)
{:EXIT, ^parent, reason} ->
case state do
%{reply_fun: reply_fun} ->
reply_fun.(reason)
exit(reason)
_ ->
terminate(reason, parent, debug, state)
end
{^ref, {:ok, new_conn}} ->
Process.demonitor(ref, [:flush])
new_state =
Map.delete(state, :task)
|> Map.put(:conn, new_conn)
{:ok, new_state}
{^ref, {:error, reason}} ->
Process.demonitor(ref, [:flush])
new_state = Map.delete(state, :task)
{:error, reason, new_state}
end
end
defp websocket_loop(parent, debug, state) do
output_closed? = Map.get(state, :output_closed_reason) != nil
case WebSockex.Frame.parse_frame(state.buffer) do
{:ok, frame, buffer} ->
debug = Utils.sys_debug(debug, {:in, :frame, frame}, state)
execute_telemetry([:websockex, :frame, :received], state, %{frame: frame})
handle_frame(frame, parent, debug, %{state | buffer: buffer})
:incomplete ->
transport = state.conn.transport
socket = state.conn.socket
receive do
{:system, from, req} ->
connection_status = if output_closed?, do: :output_closed, else: :connected
state = Map.put(state, :connection_status, connection_status)
:sys.handle_system_msg(req, from, parent, __MODULE__, debug, state)
{:"$websockex_cast", msg} ->
debug = Utils.sys_debug(debug, {:in, :cast, msg}, state)
common_handle({:handle_cast, msg}, parent, debug, state)
{:"$websockex_send", from, frame} ->
if output_closed? do
:gen.reply(
from,
{:error, %WebSockex.NotConnectedError{connection_state: :output_closed}}
)
websocket_loop(parent, debug, state)
else
sync_send(frame, from, parent, debug, state)
end
{:"$websockex_close_output", from, close_frame} ->
if output_closed? do
# Already closed output
:gen.reply(from, :ok)
websocket_loop(parent, debug, state)
else
handle_close_output(close_frame, from, parent, debug, state)
end
{^transport, ^socket, message} ->
buffer = read_all_data(transport, socket, [message, state.buffer])
websocket_loop(parent, debug, %{state | buffer: buffer})
{:tcp_closed, ^socket} ->
handle_close({:remote, :closed}, parent, debug, state)
{:ssl_closed, ^socket} ->
handle_close({:remote, :closed}, parent, debug, state)
{:EXIT, ^parent, reason} ->
terminate(reason, parent, debug, state)
msg ->
debug = Utils.sys_debug(debug, {:in, :msg, msg}, state)
common_handle({:handle_info, msg}, parent, debug, state)
end
end
end
defp read_all_data(transport, socket, buffer) do
receive do
{^transport, ^socket, message} ->
read_all_data(transport, socket, [message | buffer])
after
0 ->
:lists.reverse(buffer)
|> join_bitstrings()
end
end
defp join_bitstrings([a, b]), do: <<a::bitstring, b::bitstring>>
defp join_bitstrings([a]), do: a
defp join_bitstrings([]), do: <<>>
defp join_bitstrings(rest) do
{a, b} = Enum.split(rest, div(length(rest), 2))
a = join_bitstrings(a)
b = join_bitstrings(b)
<<a::bitstring, b::bitstring>>
end
# Handle close_output request - send close frame but keep receiving
defp handle_close_output(close_frame, from, parent, debug, state) do
close_reason = build_close_reason(close_frame)
debug = Utils.sys_debug(debug, {:close_output, close_reason}, state)
case send_close_frame(close_reason, state.conn) do
:ok ->
debug = Utils.sys_debug(debug, {:socket_out, :close, close_reason}, state)
:gen.reply(from, :ok)
# Mark output as closed and continue in websocket_loop
websocket_loop(parent, debug, %{state | output_closed_reason: close_reason})
{:error, %WebSockex.ConnError{original: reason}} when reason in [:closed, :einval] ->
:gen.reply(from, {:error, %WebSockex.NotConnectedError{connection_state: :closing}})
handle_close({:remote, :closed}, parent, debug, state)
{:error, reason} ->
:gen.reply(from, {:error, reason})
websocket_loop(parent, debug, state)
end
end
defp build_close_reason(nil), do: {:local, :normal}
defp build_close_reason({code, message}), do: {:local, code, message}
defp close_loop(reason, parent, debug, %{conn: conn, timer_ref: timer_ref} = state) do
transport = state.conn.transport
socket = state.conn.socket
receive do
{:system, from, req} ->
state = Map.put(state, :connection_status, {:closing, reason})
:sys.handle_system_msg(req, from, parent, __MODULE__, debug, state)
{:EXIT, ^parent, reason} ->
terminate(reason, parent, debug, state)
{^transport, ^socket, _} ->
close_loop(reason, parent, debug, state)
{:"$websockex_send", from, _frame} ->
:gen.reply(from, {:error, %WebSockex.NotConnectedError{connection_state: :closing}})
close_loop(reason, parent, debug, state)
{:"$websockex_close_output", from, _frame} ->
:gen.reply(from, {:error, %WebSockex.NotConnectedError{connection_state: :closing}})
close_loop(reason, parent, debug, state)
{close_mod, ^socket} when close_mod in [:tcp_closed, :ssl_closed] ->
new_conn = %{conn | socket: nil}
debug = Utils.sys_debug(debug, :closed, state)
purge_timer(timer_ref, :websockex_close_timeout)
state = Map.delete(state, :timer_ref)
on_disconnect(reason, parent, debug, %{state | conn: new_conn})
:"$websockex_close_timeout" ->
new_conn = WebSockex.Conn.close_socket(conn)
debug = Utils.sys_debug(debug, :timeout_closed, state)
on_disconnect(reason, parent, debug, %{state | conn: new_conn})
end
end
# Frame Handling
defp handle_frame(:ping, parent, debug, state) do
common_handle({:handle_ping, :ping}, parent, debug, state)
end
defp handle_frame({:ping, msg}, parent, debug, state) do
common_handle({:handle_ping, {:ping, msg}}, parent, debug, state)
end
defp handle_frame(:pong, parent, debug, state) do
common_handle({:handle_pong, :pong}, parent, debug, state)
end
defp handle_frame({:pong, msg}, parent, debug, state) do
common_handle({:handle_pong, {:pong, msg}}, parent, debug, state)
end
defp handle_frame(:close, parent, debug, %{output_closed_reason: reason} = state)
when not is_nil(reason) do
complete_half_close(reason, parent, debug, state)
end
defp handle_frame(:close, parent, debug, state) do
handle_close({:remote, :normal}, parent, debug, state)
end
defp handle_frame(
{:close, _code, _reason},
parent,
debug,
%{output_closed_reason: reason} = state
)
when not is_nil(reason) do
complete_half_close(reason, parent, debug, state)
end
defp handle_frame({:close, code, reason}, parent, debug, state) do
handle_close({:remote, code, reason}, parent, debug, state)
end
defp handle_frame({:fragment, _, _} = fragment, parent, debug, state) do
handle_fragment(fragment, parent, debug, state)
end
defp handle_frame({:continuation, _} = fragment, parent, debug, state) do
handle_fragment(fragment, parent, debug, state)
end
defp handle_frame({:finish, _} = fragment, parent, debug, state) do
handle_fragment(fragment, parent, debug, state)
end
defp handle_frame(frame, parent, debug, state) do
common_handle({:handle_frame, frame}, parent, debug, state)
end
defp handle_fragment({:fragment, type, part}, parent, debug, %{fragment: nil} = state) do
websocket_loop(parent, debug, %{state | fragment: {type, part}})
end
defp handle_fragment({:fragment, _, _}, parent, debug, state) do
handle_close(
{:local, 1002, "Endpoint tried to start a fragment without finishing another"},
parent,
debug,
state
)
end
defp handle_fragment({:continuation, _}, parent, debug, %{fragment: nil} = state) do
handle_close(
{:local, 1002, "Endpoint sent a continuation frame without starting a fragment"},
parent,
debug,
state
)
end
defp handle_fragment({:continuation, next}, parent, debug, %{fragment: {type, part}} = state) do
websocket_loop(parent, debug, %{state | fragment: {type, <<part::binary, next::binary>>}})
end
defp handle_fragment({:finish, next}, parent, debug, %{fragment: {type, part}} = state) do
frame = {type, <<part::binary, next::binary>>}
debug = Utils.sys_debug(debug, {:in, :completed_fragment, frame}, state)
handle_frame(frame, parent, debug, %{state | fragment: nil})
end
defp handle_close({:remote, :closed} = reason, parent, debug, state) do
debug = Utils.sys_debug(debug, {:close, :remote, :unexpected}, state)
new_conn = %{state.conn | socket: nil}
on_disconnect(reason, parent, debug, %{state | conn: new_conn})
end
defp handle_close({:remote, _} = reason, parent, debug, state) do
handle_remote_close(reason, parent, debug, state)
end
defp handle_close({:remote, _, _} = reason, parent, debug, state) do
handle_remote_close(reason, parent, debug, state)
end
defp handle_close({:local, _} = reason, parent, debug, state) do
handle_local_close(reason, parent, debug, state)
end
defp handle_close({:local, _, _} = reason, parent, debug, state) do
handle_local_close(reason, parent, debug, state)
end
defp handle_close({:error, _} = reason, parent, debug, state) do
handle_error_close(reason, parent, debug, state)
end
defp common_handle({function, msg}, parent, debug, state) do
output_closed? = Map.get(state, :output_closed_reason) != nil
result = try_callback(state.module, function, [msg, state.module_state])
case result do
{:ok, new_state} ->
websocket_loop(parent, debug, %{state | module_state: new_state})
{:reply, frame, new_state} ->
# RFC 6455 forbids data frames after a local Close, but a Pong is still
# required until a Close has been received.
if output_closed? and not pong_frame?(frame) do
debug = Utils.sys_debug(debug, {:reply_ignored, function}, state)
websocket_loop(parent, debug, %{state | module_state: new_state})
else
# A `with` that includes `else` clause isn't tail recursive (elixir-lang/elixir#6251)
res =