-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
167 lines (160 loc) · 4.66 KB
/
index.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
const uWS = require('uWebSockets.js')
const bytes = require('bytes')
const ServerError = require('./errors')
const Routes = require('./routes')
const render = require('./render')
const constants = require('./constants')
const Logger = require('./logger')
const utils = require('./utils')
class fastWS extends Routes {
constructor (options) {
super()
let {
ssl = null,
verbose = false,
cache = false,
templateRender = render,
bodySize = '4mb',
forceStopTimeout = 5000,
keepHeaderCase = false,
logLevel = 'info'
} = options || {}
if (typeof keepHeaderCase !== 'boolean') {
throw new ServerError({
code: 'SERVER_INVALID_OPTIONS',
message: 'The option `keepHeaderCase` is invalid.'
})
}
if (!['error', 'warn', 'info', 'verbose'].includes(logLevel)) {
throw new ServerError({
code: 'SERVER_INVALID_OPTIONS',
message: 'The option `logLevel` must be in ["error", "warn", "info", "verbose"].'
})
}
try {
bodySize = bytes.parse(bodySize)
} catch (e) {
throw new ServerError({
code: 'SERVER_INVALID_OPTIONS',
message: 'The body size format is invalid.',
originError: e
})
}
if (typeof templateRender !== 'function') {
throw new ServerError({
code: 'SERVER_INVALID_OPTIONS',
message: 'The option `templateRender` must be function.'
})
}
if (typeof cache === 'object') {
if (typeof cache.has !== 'function' || typeof cache.set !== 'function' || typeof cache.get !== 'function') {
throw new ServerError({
code: 'SERVER_INVALID_OPTIONS',
message: 'The option `cache` is invalid.'
})
}
} else if (cache === false) {
// disable cache
cache = {
has: (key) => false,
set: () => false
}
} else {
throw new ServerError({
code: 'SERVER_INVALID_OPTIONS',
message: 'The option `cache` is invalid.'
})
}
this._createTime = Date.now()
this.ssl = ssl
this.forceStopTimeout = forceStopTimeout
this._server = null
this._socket = null
this.log = new Logger(verbose ? 'verbose' : logLevel)
this.params = {
[constants.keepHeaderCase]: keepHeaderCase,
[constants.maxBodySize]: bodySize,
[constants.templateEngine]: templateRender,
[constants.cache]: cache,
[constants.trustProxy]: utils.createCidrMatcher(['loopback'])
}
process.on('SIGINT', () => this.gracefulStop(true))
process.on('SIGTERM', () => this.gracefulStop(true))
process.on('SIGHUP', () => this.reload())
}
listen (hostOrPort, portOrCallback, callback) {
let host, port
if (typeof hostOrPort === 'number' && typeof portOrCallback === 'function') {
port = hostOrPort
callback = portOrCallback
} else if (typeof hostOrPort === 'string' && typeof portOrCallback === 'number') {
host = hostOrPort
port = portOrCallback
}
if (!port) {
if (this._listenTo) {
[host, port] = this._listenTo
} else {
throw new ServerError({
code: 'INVALID_ARG',
message: 'Invalid arguments'
})
}
} else {
this._listenTo = [host, port]
}
// init app
this._server = this.ssl ? uWS.SSLApp(this.ssl) : uWS.App()
super.build()
.forEach(([method, path, callback]) => {
this._server[method](path, callback)
})
// ready to listen
const listenCallback = (listenSocket) => {
this._socket = listenSocket
if (listenSocket) {
this.log.verbose(`Started in ${Date.now() - this._createTime} ms`)
} else {
this.log.error('Bind failed!')
}
if (callback) {
callback(listenSocket)
}
}
this.gracefulStop(false)
if (host) {
this._server.listen(host, port, listenCallback)
} else {
this._server.listen(port, listenCallback)
}
}
gracefulStop (canForceExit = true) {
if (this._socket) {
const forceStop = canForceExit && setTimeout(() => {
this.log.verbose('Force stop')
process.exit(0)
}, this.forceStopTimeout)
this.log.verbose('Shutting down...')
uWS.us_listen_socket_close(this._socket)
clearTimeout(forceStop)
this._socket = null
}
}
reload () {
if (this._server) {
this.log.verbose('Reloading...')
this.listen()
}
}
getParam (key, defaultValue = null) {
return this.params[key] || defaultValue
}
setParam (key, value) {
if (key === constants.trustProxy) {
this.params[key] = utils.createCidrMatcher(value)
} else {
this.params[key] = value
}
}
}
module.exports = fastWS