forked from codecombat/codecombat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.coffee
56 lines (50 loc) · 1.69 KB
/
server.coffee
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
require 'newrelic' if process.env.NEW_RELIC_LICENSE_KEY?
do (setupLodash = this) ->
GLOBAL._ = require 'lodash'
_.str = require 'underscore.string'
_.mixin _.str.exports()
express = require 'express'
http = require 'http'
log = require 'winston'
serverSetup = require './server_setup'
co = require 'co'
config = require './server_config'
{ runHealthcheck } = require './server/middleware/healthcheck'
Promise = require 'bluebird'
module.exports.startServer = (done) ->
app = createAndConfigureApp()
httpServer = http.createServer(app).listen app.get('port'), -> done?()
log.info('Express SSL server listening on port ' + app.get('port'))
runHealthcheckForever() if config.isProduction
{app, httpServer}
runHealthcheckForever = ->
log.info('Running healthchecks forever')
co ->
sleep = (time, result=null) -> new Promise((resolve) -> setTimeout((-> resolve(result)), time))
failures = 0
yield sleep(15000) # give server time to start up
while true
passed = yield Promise.race([
runHealthcheck()
new sleep(5000, false)
])
if passed
failures = 0
yield sleep(15000)
else
failures += 1
log.warn("Healthcheck failure ##{failures}.")
if failures >= 3
log.error('Three healthcheck failures in a row. Killing self.')
process.exit(1)
createAndConfigureApp = module.exports.createAndConfigureApp = ->
serverSetup.setupLogging()
serverSetup.connectToDatabase()
app = express()
if config.forceCompression
compression = require('compression')
app.use(compression())
serverSetup.setExpressConfigurationOptions app
serverSetup.setupMiddleware app
serverSetup.setupRoutes app
app