forked from rooseveltframework/roosevelt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroosevelt.js
executable file
·272 lines (232 loc) · 7.74 KB
/
roosevelt.js
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
require('colors')
const http = require('http')
const https = require('https')
const express = require('express')
const cluster = require('cluster')
const path = require('path')
const os = require('os')
const fs = require('fs')
const fsr = require('./lib/tools/fsr')()
module.exports = function (params) {
params = params || {} // ensure params are an object
// appDir is either specified by the user or sourced from the parent require
params.appDir = params.appDir || path.dirname(module.parent.filename)
let app = express() // initialize express
let logger
let appName
let appEnv
let httpServer
let httpsServer
let httpsOptions
let keyPath
let ca
let cafile
let passphrase
let numCPUs = 1
let servers = []
let i
let connections = {}
let initialized = false
let faviconPath
let flags
// expose initial vars
app.set('express', express)
app.set('params', params)
// source user supplied params
app = require('./lib/sourceParams')(app)
logger = require('./lib/tools/logger')(app)
appName = app.get('appName')
appEnv = app.get('env')
flags = app.get('flags')
logger.log('💭', `Starting ${appName} in ${appEnv} mode...`.bold)
// let's try setting up the servers with user-supplied params
if (!app.get('params').https.httpsOnly) {
httpServer = http.Server(app)
httpServer.on('connection', mapConnections)
}
if (app.get('params').https.enable) {
httpsOptions = {
requestCert: app.get('params').https.requestCert,
rejectUnauthorized: app.get('params').https.rejectUnauthorized
}
ca = app.get('params').https.ca
cafile = app.get('params').https.cafile !== false
passphrase = app.get('params').https.passphrase
keyPath = app.get('params').https.keyPath
if (keyPath) {
if (app.get('params').https.pfx) {
httpsOptions.pfx = fs.readFileSync(keyPath.pfx)
} else {
httpsOptions.key = fs.readFileSync(keyPath.key)
httpsOptions.cert = fs.readFileSync(keyPath.cert)
}
if (passphrase) {
httpsOptions.passphrase = passphrase
}
if (ca) {
// Are we using a CA file, or are we sending the CA directly?
if (cafile) {
// String or array
if (typeof ca === 'string') {
httpsOptions.ca = fs.readFileSync(ca)
} else if (ca instanceof Array) {
httpsOptions.ca = []
ca.forEach(function (val, index, array) {
httpsOptions.ca.push(fs.readFileSync(val))
})
}
} else {
httpsOptions.ca = ca
}
}
}
httpsServer = https.Server(httpsOptions, app)
httpsServer.on('connection', mapConnections)
}
app.httpServer = httpServer
app.httpsServer = httpsServer
// enable gzip compression
app.use(require('compression')())
// enable cookie parsing
app.use(require('cookie-parser')())
// enable favicon support
if (app.get('params').favicon !== 'none' && app.get('params').favicon !== null) {
faviconPath = path.join(app.get('appDir'), app.get('params').staticsRoot, app.get('params').favicon)
if (fsr.fileExists(faviconPath)) {
app.use(require('serve-favicon')(faviconPath))
} else {
logger.warn(`Favicon ${app.get('params').favicon} does not exist. Please ensure the "favicon" param is configured correctly.`.yellow)
}
}
// bind user-defined middleware which fires at the beginning of each request if supplied
if (params.onReqStart && typeof params.onReqStart === 'function') {
app.use(params.onReqStart)
}
// configure express
app = require('./lib/setExpressConfigs')(app)
// fire user-defined onServerInit event
if (params.onServerInit && typeof params.onServerInit === 'function') {
params.onServerInit(app)
}
// assign individual keys to connections when opened so they can be destroyed gracefully
function mapConnections (conn) {
let key = conn.remoteAddress + ':' + conn.remotePort
connections[key] = conn
// once the connection closes, remove
conn.on('close', function () {
delete connections[key]
})
}
// Initialize Roosevelt app middleware and prepare static css,js
function initServer (cb) {
if (initialized) {
return cb()
}
initialized = true
preprocessCss()
function preprocessCss () {
require('./lib/preprocessCss')(app, bundleJs)
}
function bundleJs () {
require('./lib/jsBundler')(app, compileJs)
}
function compileJs () {
require('./lib/jsCompiler')(app, validateHTML)
}
function validateHTML () {
require('./lib/htmlValidator')(app, mapRoutes)
}
require('./lib/htmlMinify')(app)
function mapRoutes () {
// map routes
app = require('./lib/mapRoutes')(app)
// custom error page
app = require('./lib/500ErrorPage.js')(app)
if (cb && typeof cb === 'function') {
cb()
}
}
}
// start server
function startHttpServer () {
// determine number of CPUs to use
const max = os.cpus().length
let cores = flags.cores
if (cores) {
if (cores === 'max') {
numCPUs = max
} else if (cores <= max && cores > 0) {
numCPUs = cores
} else {
logger.warn(`Invalid value "${cores}" supplied to --cores command line argument. Defaulting to 1 core.`.yellow)
}
}
function gracefulShutdown () {
let key
function exitLog () {
logger.log('✔️', `${appName} successfully closed all connections and shut down gracefully.`.magenta)
process.exit()
}
app.set('roosevelt:state', 'disconnecting')
logger.log('\n💭 ', `${appName} received kill signal, attempting to shut down gracefully.`.magenta)
servers[0].close(function () {
if (servers.length > 1) {
servers[1].close(exitLog)
} else {
exitLog()
}
})
// destroy connections when server is killed
for (key in connections) {
connections[key].destroy()
}
setTimeout(function () {
logger.error(`${appName} could not close all connections in time; forcefully shutting down.`.red)
process.exit(1)
}, app.get('params').shutdownTimeout)
}
let lock = {}
let startupCallback = function (proto, port) {
return function () {
logger.log('🎧', `${appName} ${proto.trim()} server listening on port ${port} (${appEnv} mode)`.bold)
if (!Object.isFrozen(lock)) {
Object.freeze(lock)
// fire user-defined onServerStart event
if (params.onServerStart && typeof params.onServerStart === 'function') {
params.onServerStart(app)
}
}
}
}
if (cluster.isMaster && numCPUs > 1) {
for (i = 0; i < numCPUs; i++) {
cluster.fork()
}
cluster.on('exit', function (worker, code, signal) {
logger.log('⚰️', `${appName} thread ${worker.process.pid} died`.magenta)
})
} else {
if (!app.get('params').https.httpsOnly) {
servers.push(httpServer.listen(app.get('port'), (params.localhostOnly && appEnv !== 'development' ? 'localhost' : null), startupCallback(' HTTP', app.get('port'))))
}
if (app.get('params').https.enable) {
servers.push(httpsServer.listen(app.get('params').https.httpsPort, (params.localhostOnly && appEnv !== 'development' ? 'localhost' : null), startupCallback(' HTTPS', app.get('params').https.httpsPort)))
}
process.on('SIGTERM', gracefulShutdown)
process.on('SIGINT', gracefulShutdown)
}
}
function startServer () {
if (!initialized) {
return initServer(startHttpServer)
}
startHttpServer()
}
return {
httpServer: httpServer,
httpsServer: httpsServer,
expressApp: app,
initServer: initServer,
startServer: startServer
}
}