-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathPhoenix.elm
1087 lines (800 loc) · 38 KB
/
Phoenix.elm
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
effect module Phoenix where { command = MyCmd, subscription = MySub } exposing (connect, push)
{-| An Elm client for [Phoenix](http://www.phoenixframework.org) Channels.
This package makes it easy to connect to Phoenix Channels, but in a more declarative manner than the Phoenix Socket Javascript library. Simply provide a `Socket` and a list of `Channel`s you want to join and this library handles the tedious parts like opening a connection, joining channels, reconnecting after a network error and registering event handlers.
#Connect with Phoenix
@docs connect
# Push messages
@docs push
-}
import Json.Encode as Encode exposing (Value)
import WebSocket.LowLevel as WS
import Dict exposing (Dict)
import Task exposing (Task)
import Process
import Phoenix.Internal.Channel as InternalChannel exposing (InternalChannel)
import Phoenix.Internal.Helpers as Helpers exposing ((&>), (<&>))
import Phoenix.Internal.Message as Message exposing (Message)
import Phoenix.Internal.Presence as InternalPresence
import Phoenix.Internal.Socket as InternalSocket exposing (InternalSocket)
import Phoenix.Channel as Channel exposing (Channel)
import Phoenix.Socket as Socket exposing (Socket)
import Phoenix.Push as Push exposing (Push)
-- SUBSCRIPTIONS
type MySub msg
= Connect (Socket msg) (List (Channel msg))
{-| Declare a socket you want to connect to and the channels you want to join. The effect manager will open the socket connection, join the channels. See `Phoenix.Socket` and `Phoenix.Channel` for more configuration and behaviour details.
import Phoenix.Socket as Socket
import Phoenix.Channel as Channel
type Msg = NewMsg Value | ...
socket =
Socket.init "ws://localhost:4000/socket/websocket"
channel =
Channel.init "room:lobby"
-- register a handler for messages
-- with a "new_msg" event
|> Channel.on "new_msg" NewMsg
subscriptions model =
connect socket [channel]
**Note**: An empty channel list keeps the socket connection open.
-}
connect : Socket msg -> List (Channel msg) -> Sub msg
connect socket channels =
subscription (Connect socket channels)
-- COMMANDS
type MyCmd msg
= Send Endpoint (Push msg)
{-| Pushes a `Push` message to a particular socket address. The address has to be the same as with which you initalized the `Socket` in the `connect` subscription.
payload =
Json.Encode.object [("msg", "Hello Phoenix")]
message =
Push.init "room:lobby" "new_msg"
|> Push.withPayload payload
push "ws://localhost:4000/socket/websocket" message
**Note**: The message will be queued until you successfully joined a channel to the topic of the message.
-}
push : String -> Push msg -> Cmd msg
push endpoint push_ =
command (Send endpoint push_)
cmdMap : (a -> b) -> MyCmd a -> MyCmd b
cmdMap func cmd =
case cmd of
Send endpoint push_ ->
Send endpoint (Push.map func push_)
-- SUB MAP
subMap : (a -> b) -> MySub a -> MySub b
subMap func sub =
case sub of
Connect socket channels ->
Connect
(socket |> Socket.map func)
(channels |> List.map (Channel.map func))
type alias Message =
Message.Message
-- INTERNALS
type alias State msg =
{ sockets : InternalSocketsDict msg
, channels : InternalChannelsDict msg
, selfCallbacks : SelfCallbackDict msg
, channelQueues : ChannelQueuesDict msg
}
type alias InternalSocketsDict msg =
Dict Endpoint (InternalSocket msg)
type alias InternalChannelsDict msg =
Dict Endpoint (Dict Topic (InternalChannel msg))
type alias ChannelsDict msg =
Dict Endpoint (Dict Topic (Channel msg))
type alias SubsDict msg =
Dict Endpoint (EndpointSubsDict msg)
type alias EndpointSubsDict msg =
Dict Topic (Dict Event (List (Callback msg)))
type alias ChannelQueuesDict msg =
Dict Endpoint (Dict Topic (List ( Message, Maybe (SelfCallback msg) )))
type alias SelfCallbackDict msg =
Dict ( Ref, Endpoint ) (SelfCallback msg)
type alias Callback msg =
Value -> msg
type alias Endpoint =
String
type alias Topic =
String
type alias Event =
String
type alias Ref =
Int
-- INIT
init : Task Never (State msg)
init =
Task.succeed (State Dict.empty Dict.empty Dict.empty Dict.empty)
-- HANDLE APP MESSAGES
onEffects :
Platform.Router msg (Msg msg)
-> List (MyCmd msg)
-> List (MySub msg)
-> State msg
-> Task Never (State msg)
onEffects router cmds subs state =
let
definedSockets =
buildSocketsDict subs
definedChannels =
buildChannelsDict subs Dict.empty
updateState newState =
let
getNewChannels =
handleChannelsUpdate router definedChannels newState.channels
getNewSockets =
handleSocketsUpdate router definedSockets newState.sockets
in
Task.map2 (\newSockets newChannels -> { newState | sockets = newSockets, channels = newChannels })
getNewSockets
getNewChannels
in
sendPushsHelp cmds state <&> \newState -> updateState newState
-- BUILD SOCKETS
buildSocketsDict : List (MySub msg) -> Dict String (Socket msg)
buildSocketsDict subs =
let
insert sub dict =
case sub of
Connect socket _ ->
Dict.insert socket.endpoint socket dict
in
List.foldl insert Dict.empty subs
-- BUILD CHANNELS
buildChannelsDict : List (MySub msg) -> InternalChannelsDict msg -> InternalChannelsDict msg
buildChannelsDict subs dict =
case subs of
[] ->
dict
(Connect { endpoint } channels) :: rest ->
let
internalChan chan =
(InternalChannel InternalChannel.Closed Dict.empty chan)
build chan dict_ =
buildChannelsDict rest (Helpers.insertIn endpoint chan.topic (internalChan chan) dict_)
in
List.foldl build dict channels
sendPushsHelp : List (MyCmd msg) -> State msg -> Task x (State msg)
sendPushsHelp cmds state =
case cmds of
[] ->
Task.succeed state
(Send endpoint push) :: rest ->
let
message =
Message.fromPush push
in
pushSocket endpoint message (Just <| PushResponse push) state
<&> sendPushsHelp rest
handleSocketsUpdate : Platform.Router msg (Msg msg) -> Dict String (Socket msg) -> InternalSocketsDict msg -> Task Never (InternalSocketsDict msg)
handleSocketsUpdate router definedSockets stateSockets =
let
-- addedSocketsStep: endpoints where we have to open a new socket connection
addedSocketsStep endpoint definedSocket taskChain =
let
socket =
(InternalSocket.internalSocket definedSocket)
in
taskChain
<&> \addedSockets ->
attemptOpen router 0 socket
<&> \pid ->
Task.succeed (Dict.insert endpoint (InternalSocket.opening 0 pid socket) addedSockets)
-- we update the authentication parameters
retainedSocketsStep endpoint definedSocket stateSocket taskChain =
taskChain |> Task.map (Dict.insert endpoint <| InternalSocket.update definedSocket stateSocket)
removedSocketsStep endpoint stateSocket taskChain =
InternalSocket.close stateSocket &> taskChain
in
Dict.merge addedSocketsStep retainedSocketsStep removedSocketsStep definedSockets stateSockets (Task.succeed Dict.empty)
handleChannelsUpdate : Platform.Router msg (Msg msg) -> InternalChannelsDict msg -> InternalChannelsDict msg -> Task Never (InternalChannelsDict msg)
handleChannelsUpdate router nextChannels previousChannels =
let
addedChannelsStep endpoint definedEndpointChannels taskChain =
let
sendJoin =
Dict.values definedEndpointChannels
|> List.foldl (\channel task -> task &> sendJoinChannel router endpoint channel)
(Task.succeed ())
insert newChannels =
Task.succeed (Dict.insert endpoint definedEndpointChannels newChannels)
in
sendJoin &> taskChain <&> insert
retainedChannelsStep endpoint definedEndpointChannels stateEndpointChannels taskChain =
let
getEndpointChannels =
handleEndpointChannelsUpdate router endpoint definedEndpointChannels stateEndpointChannels
in
Task.map2 (\endpointChannels newChannels -> Dict.insert endpoint endpointChannels newChannels)
getEndpointChannels
taskChain
removedChannelsStep endpoint stateEndpointChannels taskChain =
let
sendLeave =
Dict.values stateEndpointChannels
|> List.foldl (\channel task -> task &> sendLeaveChannel router endpoint channel)
(Task.succeed ())
in
sendLeave &> taskChain
in
Dict.merge addedChannelsStep retainedChannelsStep removedChannelsStep nextChannels previousChannels (Task.succeed Dict.empty)
handleEndpointChannelsUpdate : Platform.Router msg (Msg msg) -> Endpoint -> Dict Topic (InternalChannel msg) -> Dict Topic (InternalChannel msg) -> Task Never (Dict Topic (InternalChannel msg))
handleEndpointChannelsUpdate router endpoint definedChannels stateChannels =
let
leftStep topic defined getNewChannels =
(sendJoinChannel router endpoint defined) &> Task.map (Dict.insert topic defined) getNewChannels
bothStep topic defined state getNewChannels =
let
channel =
state
|> InternalChannel.updatePayload defined.channel.payload
|> InternalChannel.updateOn defined.channel.on
in
Task.map (Dict.insert topic channel) getNewChannels
rightStep topic state getNewChannels =
(sendLeaveChannel router endpoint state) &> getNewChannels
in
Dict.merge leftStep bothStep rightStep definedChannels stateChannels (Task.succeed Dict.empty)
sendLeaveChannel : Platform.Router msg (Msg msg) -> Endpoint -> InternalChannel msg -> Task Never ()
sendLeaveChannel router endpoint internalChannel =
case internalChannel.state of
InternalChannel.Joined ->
Platform.sendToSelf router (LeaveChannel endpoint internalChannel)
_ ->
Task.succeed ()
sendJoinChannel : Platform.Router msg (Msg msg) -> Endpoint -> InternalChannel msg -> Task Never ()
sendJoinChannel router endpoint internalChannel =
Platform.sendToSelf router (JoinChannel endpoint internalChannel)
&> maybeNotifyApp router internalChannel.channel.onRequestJoin
-- STATE UPDATE HELPERS
updateSocket : Endpoint -> InternalSocket msg -> State msg -> State msg
updateSocket endpoint socket state =
{ state | sockets = Dict.insert endpoint socket state.sockets }
updateChannels : InternalChannelsDict msg -> State msg -> State msg
updateChannels channels state =
{ state | channels = channels }
updateSelfCallbacks : SelfCallbackDict msg -> State msg -> State msg
updateSelfCallbacks selfCallbacks state =
{ state | selfCallbacks = selfCallbacks }
removeChannelQueue : Endpoint -> Topic -> State msg -> State msg
removeChannelQueue endpoint topic state =
{ state | channelQueues = Helpers.removeIn endpoint topic state.channelQueues }
insertSocket : Endpoint -> InternalSocket msg -> State msg -> State msg
insertSocket endpoint socket state =
{ state
| sockets = Dict.insert endpoint socket state.sockets
}
insertSelfCallback : ( Ref, Endpoint ) -> Maybe (SelfCallback msg) -> State msg -> State msg
insertSelfCallback ( ref, endpoint ) maybeSelfCb state =
case maybeSelfCb of
Nothing ->
state
Just selfCb ->
{ state
| selfCallbacks = Dict.insert ( ref, endpoint ) selfCb state.selfCallbacks
}
-- HANDLE INTERN MESSAGES
type alias SelfCallback msg =
Message -> Msg msg
type Msg msg
= Receive Endpoint Message
| Die String { code : Int, reason : String, wasClean : Bool }
| GoodOpen String WS.WebSocket
| BadOpen String WS.BadOpen
| Register
| JoinChannel Endpoint (InternalChannel msg)
| LeaveChannel Endpoint (InternalChannel msg)
| ChannelLeaveReply Endpoint (InternalChannel msg) Message
| ChannelJoinReply Endpoint Topic InternalChannel.State Message
| GoodJoin Endpoint Topic
| SendHeartbeat Endpoint
| PushResponse (Push msg) Message
onSelfMsg : Platform.Router msg (Msg msg) -> Msg msg -> State msg -> Task Never (State msg)
onSelfMsg router selfMsg state =
case selfMsg of
GoodOpen endpoint ws ->
case InternalSocket.get endpoint state.sockets of
Just internalSocket ->
let
_ =
if internalSocket.socket.debug then
Debug.log "WebSocket connected with " endpoint
else
endpoint
notifyOnOpen =
maybeNotifyApp router internalSocket.socket.onOpen
state_ =
insertSocket endpoint (InternalSocket.connected ws internalSocket) state
in
notifyOnOpen
&> (heartbeat router endpoint state_)
<&> (rejoinAllChannels endpoint)
-- somehow the state is messed up
Nothing ->
Task.succeed state
BadOpen endpoint details ->
case Dict.get endpoint state.sockets of
Nothing ->
Task.succeed state
Just internalSocket ->
let
_ =
if internalSocket.socket.debug then
Debug.log ("WebSocket couldn_t connect with " ++ endpoint) details
else
details
backoffIteration =
case internalSocket.connection of
InternalSocket.Opening n _ ->
n + 1
_ ->
0
backoff =
internalSocket.socket.reconnectTimer backoffIteration
newState pid =
(updateSocket endpoint (InternalSocket.opening backoffIteration pid internalSocket)) state
in
attemptOpen router backoff internalSocket
|> Task.map newState
Die endpoint details ->
case Dict.get endpoint state.sockets of
Nothing ->
Task.succeed state
Just ({ connection, socket } as internalSocket) ->
let
backoffIteration =
case connection of
InternalSocket.Opening n _ ->
n + 1
_ ->
0
backoff =
socket.reconnectTimer backoffIteration
-- update channels because of disconnect
getNewState =
handleChannelDisconnect router endpoint state
finalNewState pid =
Task.map (updateSocket endpoint (InternalSocket.opening backoffIteration pid internalSocket)) getNewState
notifyOnClose =
socket.onClose
|> maybeAndMap (Just details)
|> maybeNotifyApp router
notifyOnNormalClose =
-- see https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent for error codes
if details.code == 1000 then
maybeNotifyApp router socket.onNormalClose
else
Task.succeed ()
notifyOnAbnormalClose =
-- see https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent for error codes
if details.code == 1006 then
socket.onAbnormalClose
|> maybeAndMap (Just { reconnectAttempt = backoffIteration, reconnectWait = backoff })
|> maybeNotifyApp router
else
Task.succeed ()
in
notifyOnClose
&> notifyOnNormalClose
&> notifyOnAbnormalClose
&> attemptOpen router backoff internalSocket
|> Task.andThen finalNewState
Receive endpoint message ->
dispatchMessage router endpoint message state.channels
&> ((handleSelfcallback router endpoint message state.selfCallbacks)
|> Task.map (\selfCbs -> updateSelfCallbacks selfCbs state)
)
<&> handlePhoenixMessage router endpoint message
ChannelJoinReply endpoint topic oldState message ->
(handleChannelJoinReply router endpoint topic message oldState state.channels)
|> Task.map (\newChannels -> updateChannels newChannels state)
JoinChannel endpoint internalChannel ->
case Dict.get endpoint state.sockets of
Nothing ->
Task.succeed state
Just internalSocket ->
case internalSocket.connection of
InternalSocket.Connected _ _ ->
pushSocket_ endpoint (InternalChannel.joinMessage internalChannel) (Just <| ChannelJoinReply endpoint internalChannel.channel.topic internalChannel.state) state
-- Nothing to do GoodOpen will handle the join
_ ->
Task.succeed state
LeaveChannel endpoint internalChannel ->
case Dict.get endpoint state.sockets of
Nothing ->
Task.succeed state
Just _ ->
case internalChannel.state of
InternalChannel.Joined ->
pushSocket_ endpoint (InternalChannel.leaveMessage internalChannel) (Just <| ChannelLeaveReply endpoint internalChannel) state
_ ->
Task.succeed state
ChannelLeaveReply endpoint { channel } message ->
case Helpers.decodeReplyPayload message.payload of
Nothing ->
Task.succeed state
Just reply ->
case reply of
Err error ->
case channel.onLeaveError of
Nothing ->
Task.succeed state
Just onLeaveError ->
Platform.sendToApp router (onLeaveError error) &> Task.succeed state
Ok ok ->
case channel.onLeave of
Nothing ->
Task.succeed state
Just onLeave ->
Platform.sendToApp router (onLeave ok) &> Task.succeed state
SendHeartbeat endpoint ->
(heartbeat router endpoint state)
GoodJoin endpoint topic ->
case Helpers.getIn endpoint topic state.channelQueues of
Nothing ->
Task.succeed state
Just queuedMessages ->
processQueue endpoint queuedMessages state
|> Task.map (removeChannelQueue endpoint topic)
PushResponse push_ message ->
case Helpers.decodeReplyPayload message.payload of
Nothing ->
Task.succeed state
Just reply ->
case reply of
Err error ->
case push_.onError of
Nothing ->
Task.succeed state
Just onError ->
Platform.sendToApp router (onError error) &> Task.succeed state
Ok ok ->
case push_.onOk of
Nothing ->
Task.succeed state
Just onOk ->
Platform.sendToApp router (onOk ok) &> Task.succeed state
_ ->
Task.succeed state
handleSelfcallback : Platform.Router msg (Msg msg) -> Endpoint -> Message -> SelfCallbackDict msg -> Task x (SelfCallbackDict msg)
handleSelfcallback router endpoint message selfCallbacks =
case message.ref of
Nothing ->
Task.succeed selfCallbacks
Just ref ->
case Dict.get ( ref, endpoint ) selfCallbacks of
Nothing ->
Task.succeed selfCallbacks
Just selfCb ->
Platform.sendToSelf router (selfCb message)
&> Task.succeed (Dict.remove ( ref, endpoint ) selfCallbacks)
processQueue : Endpoint -> List ( Message, Maybe (SelfCallback msg) ) -> State msg -> Task x (State msg)
processQueue endpoint messages state =
case messages of
[] ->
Task.succeed state
( message, maybeSelfCb ) :: rest ->
pushSocket endpoint message maybeSelfCb state
<&> processQueue endpoint rest
handlePhoenixMessage : Platform.Router msg (Msg msg) -> Endpoint -> Message -> State msg -> Task x (State msg)
handlePhoenixMessage router endpoint message state =
case message.event of
"presence_state" ->
case Helpers.getIn endpoint message.topic state.channels of
Nothing ->
Task.succeed state
Just internalChannel ->
let
newPresenceState =
case InternalPresence.decodePresenceState message.payload of
Ok presenceState ->
presenceState
Err err ->
internalChannel.presenceState
updatedChannel =
InternalChannel.updatePresenceState newPresenceState internalChannel
updatedChannels =
Helpers.insertIn endpoint internalChannel.channel.topic updatedChannel state.channels
sendToApp =
case internalChannel.channel.presence of
Nothing ->
Task.succeed ()
Just presence ->
case presence.onChange of
Just onChange ->
Platform.sendToApp router (onChange <| InternalPresence.getPresenceState newPresenceState)
Nothing ->
Task.succeed ()
in
sendToApp &> Task.succeed (updateChannels updatedChannels state)
"presence_diff" ->
case Helpers.getIn endpoint message.topic state.channels of
Nothing ->
Task.succeed state
Just internalChannel ->
let
diffResult =
case InternalPresence.decodePresenceDiff message.payload of
Ok presenceDiff ->
let
newState =
InternalPresence.syncPresenceDiff presenceDiff internalChannel.presenceState
in
{ newState = newState, joins = Just presenceDiff.joins, leaves = Just presenceDiff.leaves }
Err err ->
{ newState = internalChannel.presenceState, joins = Nothing, leaves = Nothing }
updatedChannel =
InternalChannel.updatePresenceState diffResult.newState internalChannel
updatedChannels =
Helpers.insertIn endpoint internalChannel.channel.topic updatedChannel state.channels
sendToApp =
case internalChannel.channel.presence of
Nothing ->
Task.succeed ()
Just presence ->
let
sendOnJoins =
case ( presence.onJoins, diffResult.joins ) of
( Just onJoins, Just joins ) ->
Platform.sendToApp router (onJoins <| InternalPresence.getPresenceState joins)
( _, _ ) ->
Task.succeed ()
sendOnLeaves =
case ( presence.onLeaves, diffResult.leaves ) of
( Just onLeaves, Just leaves ) ->
Platform.sendToApp router (onLeaves <| InternalPresence.getPresenceState leaves)
( _, _ ) ->
Task.succeed ()
sendOnChange =
case presence.onChange of
Just onChange ->
Platform.sendToApp router (onChange <| InternalPresence.getPresenceState diffResult.newState)
Nothing ->
Task.succeed ()
in
sendOnJoins &> sendOnLeaves &> sendOnChange
in
sendToApp &> Task.succeed (updateChannels updatedChannels state)
"phx_error" ->
case Helpers.getIn endpoint message.topic state.channels of
Nothing ->
Task.succeed state
Just internalChannel ->
let
newChannel =
InternalChannel.updateState InternalChannel.Errored internalChannel
sendToApp =
case internalChannel.channel.onError of
Nothing ->
Task.succeed ()
Just onError ->
Platform.sendToApp router onError
in
sendToApp &> sendJoinHelper endpoint [ newChannel ] state
-- TODO do we have to do something here?
"phx_close" ->
Task.succeed state
_ ->
Task.succeed state
dispatchMessage : Platform.Router msg (Msg msg) -> Endpoint -> Message -> InternalChannelsDict msg -> Task x ()
dispatchMessage router endpoint message channels =
case getEventCb endpoint message channels of
Nothing ->
Task.succeed ()
Just cb ->
Platform.sendToApp router (cb message.payload)
getEventCb : Endpoint -> Message -> InternalChannelsDict msg -> Maybe (Callback msg)
getEventCb endpoint message channels =
case Helpers.getIn endpoint message.topic channels of
Nothing ->
Nothing
Just { channel } ->
Dict.get message.event channel.on
handleChannelJoinReply : Platform.Router msg (Msg msg) -> Endpoint -> Topic -> Message -> InternalChannel.State -> InternalChannelsDict msg -> Task x (InternalChannelsDict msg)
handleChannelJoinReply router endpoint topic message prevState channels =
let
maybeChannel =
InternalChannel.get endpoint topic channels
maybePayload =
Helpers.decodeReplyPayload message.payload
newChannels state =
Task.succeed (InternalChannel.insertState endpoint topic state channels)
handlePayload { channel } payload =
case payload of
Err response ->
case channel.onJoinError of
Nothing ->
newChannels InternalChannel.Errored
Just onError ->
Platform.sendToApp router (onError response) &> newChannels InternalChannel.Errored
Ok response ->
let
join =
Platform.sendToSelf router (GoodJoin endpoint topic)
&> newChannels InternalChannel.Joined
in
case prevState of
InternalChannel.Disconnected ->
case channel.onRejoin of
Nothing ->
join
Just onRejoin ->
Platform.sendToApp router (onRejoin response) &> join
_ ->
case channel.onJoin of
Nothing ->
join
Just onJoin ->
Platform.sendToApp router (onJoin response) &> join
in
Maybe.map2 handlePayload maybeChannel maybePayload
|> Maybe.withDefault (Task.succeed channels)
handleChannelDisconnect : Platform.Router msg (Msg msg) -> Endpoint -> State msg -> Task x (State msg)
handleChannelDisconnect router endpoint state =
case Dict.get endpoint state.channels of
Nothing ->
Task.succeed state
Just endpointChannels ->
let
notifyApp { state, channel } =
case state of
InternalChannel.Joined ->
maybeNotifyApp router channel.onDisconnect
_ ->
Task.succeed ()
notify =
Dict.foldl (\_ channel task -> task &> notifyApp channel) (Task.succeed ()) endpointChannels
updateChannel _ channel =
case channel.state of
InternalChannel.Errored ->
channel
_ ->
InternalChannel.updateState InternalChannel.Disconnected channel
updatedEndpointChannels =
Dict.map updateChannel endpointChannels
in
notify
&> Task.succeed
({ state
| channels = Dict.insert endpoint updatedEndpointChannels state.channels
}
)
heartbeat : Platform.Router msg (Msg msg) -> Endpoint -> State msg -> Task x (State msg)
heartbeat router endpoint state =
case Dict.get endpoint state.sockets of
Just { socket } ->
if socket.withoutHeartbeat then
Task.succeed state
else
(Process.spawn (Process.sleep socket.heartbeatIntervall &> (Platform.sendToSelf router (SendHeartbeat endpoint))))
&> pushSocket_ endpoint heartbeatMessage Nothing state
Nothing ->
Task.succeed state
heartbeatMessage : Message
heartbeatMessage =
Message.init "phoenix" "heartbeat"
rejoinAllChannels : Endpoint -> State msg -> Task x (State msg)
rejoinAllChannels endpoint state =
case Dict.get endpoint state.channels of
Nothing ->
Task.succeed state
Just endpointChannels ->
sendJoinHelper endpoint (Dict.values endpointChannels) state
sendJoinHelper : Endpoint -> List (InternalChannel msg) -> State msg -> Task x (State msg)
sendJoinHelper endpoint channels state =
case channels of
[] ->
Task.succeed state
internalChannel :: rest ->
let
selfCb =
ChannelJoinReply endpoint internalChannel.channel.topic internalChannel.state
message =
InternalChannel.joinMessage internalChannel
newChannel =
InternalChannel.updateState InternalChannel.Joining internalChannel
newChannels =
Helpers.insertIn endpoint internalChannel.channel.topic newChannel state.channels
in
pushSocket_ endpoint message (Just selfCb) (updateChannels newChannels state)
<&> \newState -> sendJoinHelper endpoint rest newState
-- PUSH MESSAGES
{-| pushes a message to a certain socket. Ignores if the sending failes.
-}
pushSocket_ : Endpoint -> Message -> Maybe (SelfCallback msg) -> State msg -> Task x (State msg)
pushSocket_ endpoint message maybeSelfCb state =
case Dict.get endpoint state.sockets of
Nothing ->
Task.succeed state
Just socket ->
InternalSocket.push message socket
<&> \maybeRef ->
case maybeRef of
Nothing ->
Task.succeed state
Just ref ->
insertSocket endpoint (InternalSocket.increaseRef socket) state
|> insertSelfCallback ( ref, endpoint ) maybeSelfCb
|> Task.succeed
{-| pushes a message to a certain socket. Queues the message if the channel is not joined.
-}
pushSocket : Endpoint -> Message -> Maybe (SelfCallback msg) -> State msg -> Task x (State msg)
pushSocket endpoint message selfCb state =
let
queuedState =
Task.succeed
{ state
| channelQueues = Helpers.updateIn endpoint message.topic (Helpers.add ( message, selfCb )) state.channelQueues
}
afterSocketPush socket maybeRef =
case maybeRef of
Nothing ->
queuedState
Just ref ->
insertSocket endpoint (InternalSocket.increaseRef socket) state
|> insertSelfCallback ( ref, endpoint ) selfCb