Separate the network polling out, ready to move to a separate module.

This commit is contained in:
Pagan Gazzard 2014-12-17 17:01:24 +00:00 committed by Pablo Carranza Vélez
parent e67de4b279
commit 1c46e1e2a4
2 changed files with 45 additions and 24 deletions

View File

@ -0,0 +1,36 @@
Promise = require 'bluebird'
request = Promise.promisifyAll require 'request'
# options: The url to check, or an object of request options.
# timeout: 10s
# gzip: true
exports.checkURL = checkURL = (options) ->
if typeof options is 'string'
options =
url: options
options.timeout ?= 10000
options.gzip ?= true
request
.getAsync(options)
.spread (response) ->
return response.statusCode in [ 200, 304 ]
.catch (e) ->
return false
# options: The url to monitor, or an object of:
# interval: The time between each check.
# checkURL options
# fn(bool connected): The function that will be called each time the state changes.
exports.monitorURL = (options, fn) ->
interval = options?.interval or 0
connectivityState = null # Used to prevent multiple messages when disconnected
_check = ->
checkURL(options)
.then (connected) ->
return if connected == connectivityState
connectivityState = connected
fn(connected)
return # Do not wait on fn if it returns a promise
.finally ->
setTimeout(_check, interval)
_check()

View File

@ -4,6 +4,7 @@ fs = Promise.promisifyAll require 'fs'
config = require './config'
mixpanel = require 'mixpanel'
request = require './request'
networkCheck = require './lib/network-check'
utils = exports
@ -64,18 +65,6 @@ exports.blink = (ms = 200) ->
.delay(ms)
.then -> fs.writeFileAsync(config.ledFile, 0)
# Helps in checking connectivity by pseudo-pinging our endpoint.
exports.checkConnectivity = ->
# We avoid using ICMP as this traffic is sometimes restricted/dropped. Good
# ol' port 80 HTTP should always be available :-)
request
.getAsync
url: config.heartbeatEndpoint
timeout: 10000
.spread (response) ->
return response.statusCode in [ 200, 304 ]
.catch ->
return false
blinkPattern = do ->
started = false
@ -105,19 +94,15 @@ blinkPattern = do ->
clearTimeout(timeout)
}
exports.connectivityCheck = do ->
connectivityState = true # Used to prevent multiple messages when disconnected
_check = ->
utils.checkConnectivity()
.then (connected) ->
return if connected == connectivityState
connectivityState = connected
if connectivityState
exports.connectivityCheck = _.once ->
networkCheck.monitorURL
url: config.heartbeatEndpoint
interval: 10 * 1000
(connected) ->
if connected
console.log('Internet Connectivity: OK')
blinkPattern.stop()
else
console.log('Waiting for connectivity...')
blinkPattern.start()
.finally ->
setTimeout(_check, 10 * 1000) # Every 10 seconds perform this check.
return _.once(_check)
blinkPattern.start()