1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Establish WebSocket connection when first subscription is created. Fixes #24026

* More intention revealing than connecting on the first call to Connection#send
* Fixes that calls to Connection#send would attempt to open a connection when the WebSocket's state is CONNECTING
This commit is contained in:
Javan Makhmali 2016-03-03 17:33:56 -05:00
parent daeaac7027
commit 82a1bf268d
3 changed files with 10 additions and 9 deletions

View file

@ -8,9 +8,6 @@ class ActionCable.Connection
constructor: (@consumer) -> constructor: (@consumer) ->
send: (data) -> send: (data) ->
unless @isOpen()
@open()
if @isOpen() if @isOpen()
@webSocket.send(JSON.stringify(data)) @webSocket.send(JSON.stringify(data))
true true
@ -18,7 +15,7 @@ class ActionCable.Connection
false false
open: => open: =>
if @isAlive() if @isActive()
ActionCable.log("Attemped to open WebSocket, but existing socket is #{@getState()}") ActionCable.log("Attemped to open WebSocket, but existing socket is #{@getState()}")
throw new Error("Existing connection must be closed before opening") throw new Error("Existing connection must be closed before opening")
else else
@ -33,7 +30,7 @@ class ActionCable.Connection
reopen: -> reopen: ->
ActionCable.log("Reopening WebSocket, current state is #{@getState()}") ActionCable.log("Reopening WebSocket, current state is #{@getState()}")
if @isAlive() if @isActive()
try try
@close() @close()
catch error catch error
@ -47,10 +44,10 @@ class ActionCable.Connection
isOpen: -> isOpen: ->
@isState("open") @isState("open")
# Private isActive: ->
@isState("open", "connecting")
isAlive: -> # Private
@webSocket? and not @isState("closing", "closed")
isState: (states...) -> isState: (states...) ->
@getState() in states @getState() in states

View file

@ -23,3 +23,7 @@ class ActionCable.Consumer
send: (data) -> send: (data) ->
@connection.send(data) @connection.send(data)
ensureActiveConnection: ->
unless @connection.isActive()
@connection.open()

View file

@ -19,6 +19,7 @@ class ActionCable.Subscriptions
add: (subscription) -> add: (subscription) ->
@subscriptions.push(subscription) @subscriptions.push(subscription)
@consumer.ensureActiveConnection()
@notify(subscription, "initialized") @notify(subscription, "initialized")
@sendCommand(subscription, "subscribe") @sendCommand(subscription, "subscribe")
@ -59,4 +60,3 @@ class ActionCable.Subscriptions
sendCommand: (subscription, command) -> sendCommand: (subscription, command) ->
{identifier} = subscription {identifier} = subscription
@consumer.send({command, identifier}) @consumer.send({command, identifier})