aboutsummaryrefslogtreecommitdiffstats
path: root/lib/assets/javascripts/cable/connection_monitor.js.coffee
blob: cf36b2a4570428d2c4773b0a0b2b85c091eeae53 (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
class Cable.ConnectionMonitor
  MAX_CONNECTION_INTERVAL: 5 * 1000
  PING_STALE_INTERVAL: 8 * 1000

  identifier: Cable.PING_IDENTIFIER

  constructor: (@consumer) ->
    @reset()
    @consumer.subscribers.add(this)
    @pollConnection()

  connected: ->
    @reset()
    @pingedAt = now()

  received: ->
    @pingedAt = now()

  reset: ->
    @connectionAttempts = 1

  pollConnection: ->
    setTimeout =>
      @reconnect() if @connectionIsStale()
      @pollConnection()
    , @getPollTimeout()

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

  connectionIsStale: ->
    @pingedAt? and (now() - @pingedAt) > @PING_STALE_INTERVAL

  reconnect: ->
    console.log "Ping took too long to arrive. Reconnecting.."
    @connectionAttempts += 1
    @consumer.connection.connect()

  now = ->
    new Date().getTime()