aboutsummaryrefslogtreecommitdiffstats
path: root/lib/assets/javascripts/cable/connection.js.coffee
blob: e987c227c6d101b1f7e510e1164772dddf57c445 (plain) (blame)
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
class Cable.Connection
  MAX_CONNECTION_INTERVAL: 5 * 1000
  PING_STALE_INTERVAL: 8

  constructor: (@cable) ->
    @resetPingTime()
    @resetConnectionAttemptsCount()
    @connect()

  send: (data) ->
    if @isConnected()
      @websocket.send(JSON.stringify(data))
      true
    else
      false

  connect: ->
    @websocket = @createWebSocket()

  createWebSocket: ->
    ws = new WebSocket(@cable.url)
    ws.onmessage = @onMessage
    ws.onopen    = @onConnect
    ws.onclose   = @onClose
    ws.onerror   = @onError
    ws

  onMessage: (message) =>
    data = JSON.parse message.data

    if data.identifier is '_ping'
      @pingReceived(data.message)
    else
      @cable.subscribers.notify(data.identifier, "received", data.message)

  onConnect: =>
    @startWaitingForPing()
    @resetConnectionAttemptsCount()
    @cable.subscribers.reload()

  onClose: =>
    @reconnect()

  onError: =>
    @reconnect()

  isConnected: ->
    @websocket?.readyState is 1

  disconnect: ->
    @removeExistingConnection()
    @resetPingTime()
    @cable.subscribers.notifyAll("disconnected")

  reconnect: ->
    @disconnect()

    setTimeout =>
      @incrementConnectionAttemptsCount()
      @connect()
    , @generateReconnectInterval()

  removeExistingConnection: ->
    if @websocket?
      @clearPingWaitTimeout()

      @websocket.onclose = -> # no-op
      @websocket.onerror = -> # no-op
      @websocket.close()
      @websocket = null

  resetConnectionAttemptsCount: ->
    @connectionAttempts = 1

  incrementConnectionAttemptsCount: ->
    @connectionAttempts += 1

  generateReconnectInterval: () ->
    interval = (Math.pow(2, @connectionAttempts) - 1) * 1000
    if interval > @MAX_CONNECTION_INTERVAL then @MAX_CONNECTION_INTERVAL else interval

  startWaitingForPing: ->
    @clearPingWaitTimeout()

    @waitForPingTimeout = setTimeout =>
      console.log "Ping took too long to arrive. Reconnecting.."
      @reconnect()
    , @PING_STALE_INTERVAL * 1000

  clearPingWaitTimeout: ->
    clearTimeout(@waitForPingTimeout)

  resetPingTime: ->
    @lastPingTime = null

  pingReceived: (timestamp) ->
    if @lastPingTime? and (timestamp - @lastPingTime) > @PING_STALE_INTERVAL
      console.log "Websocket connection is stale. Reconnecting.."
      @reconnect()
    else
      @startWaitingForPing()
      @lastPingTime = timestamp