-
-
Notifications
You must be signed in to change notification settings - Fork 793
/
ServerlessOffline.js
289 lines (241 loc) · 7.95 KB
/
ServerlessOffline.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import updateNotifier from 'update-notifier'
import debugLog from './debugLog.js'
import serverlessLog, { logWarning, setLog } from './serverlessLog.js'
import {
createDefaultApiKey,
// hasHttpEvent,
hasWebsocketEvent,
satisfiesVersionRange,
} from './utils/index.js'
import {
CUSTOM_OPTION,
defaults,
options as commandOptions,
SERVER_SHUTDOWN_TIMEOUT,
} from './config/index.js'
import pkg from '../package.json'
export default class ServerlessOffline {
constructor(serverless, options) {
this._apiGateway = null
this._apiGatewayWebSocket = null
this._lambda = null
this._config = serverless.config
this._options = options
this._provider = serverless.service.provider
this._service = serverless.service
this._version = serverless.version
setLog((...args) => serverless.cli.log(...args))
this.commands = {
offline: {
// add start nested options
commands: {
start: {
lifecycleEvents: ['init', 'end'],
options: commandOptions,
usage:
'Simulates API Gateway to call your lambda functions offline using backward compatible initialization.',
},
},
lifecycleEvents: ['start'],
options: commandOptions,
usage: 'Simulates API Gateway to call your lambda functions offline.',
},
}
this.hooks = {
'offline:start:init': this.start.bind(this),
'offline:start': this._startWithExplicitEnd.bind(this),
'offline:start:end': this.end.bind(this),
}
}
_printBlankLine() {
if (process.env.NODE_ENV !== 'test') {
console.log()
}
}
// Entry point for the plugin (sls offline) when running 'sls offline start'
async start() {
// check if update is available
updateNotifier({ pkg }).notify()
this._verifyServerlessVersionCompatibility()
this.mergeOptions()
await this._createLambda()
// TODO FIXME uncomment condition below
// we can't do this just yet, because we always create endpoints for
// lambda Invoke endpoints. we could potentially add a flag (not everyone
// uses lambda invoke) and only add lambda invoke routes if flag is set
//
// if (hasHttpEvent(this._service.functions)) {
await this._createApiGateway()
await this._apiGateway.start()
// }
if (hasWebsocketEvent(this._service.functions)) {
await this._createApiGatewayWebSocket()
await this._apiGatewayWebSocket.start()
}
this.setupEvents()
if (this._apiGateway) {
// Not found handling
// we have to create the 404 routes last, otherwise we could have
// collisions with catch all routes, e.g. any (proxy+}
this._apiGateway.create404Route()
}
if (process.env.NODE_ENV !== 'test') {
await this._listenForTermination()
}
}
/**
* Entry point for the plugin (sls offline) when running 'sls offline'
* The call to this.end() would terminate the process before 'offline:start:end' could be consumed
* by downstream plugins. When running sls offline that can be expected, but docs say that
* 'sls offline start' will provide the init and end hooks for other plugins to consume
* */
async _startWithExplicitEnd() {
await this.start()
this.end()
}
async _listenForTermination() {
const command = await new Promise((resolve) => {
process
// SIGINT will be usually sent when user presses ctrl+c
.on('SIGINT', () => resolve('SIGINT'))
// SIGTERM is a default termination signal in many cases,
// for example when "killing" a subprocess spawned in node
// with child_process methods
.on('SIGTERM', () => resolve('SIGTERM'))
})
serverlessLog(`Got ${command} signal. Offline Halting...`)
}
async _createApiGateway() {
const { default: ApiGateway } = await import(
'./events/api-gateway/index.js'
)
this._apiGateway = new ApiGateway(
this._service,
this._options,
this._config,
this._lambda,
)
await this._apiGateway.registerPlugins()
// HTTP Proxy defined in Resource
this._apiGateway.createResourceRoutes()
}
async _createApiGatewayWebSocket() {
const { default: ApiGatewayWebSocket } = await import(
'./events/api-gateway-websocket/index.js'
)
this._apiGatewayWebSocket = new ApiGatewayWebSocket(
this._service,
this._options,
this._config,
this._lambda,
)
}
async _createLambda() {
const { default: Lambda } = await import('./lambda/index.js')
this._lambda = new Lambda(this._provider, this._options, this._config)
}
mergeOptions() {
// custom options
const { [CUSTOM_OPTION]: customOptions } = this._service.custom || {}
// merge options
// order of Precedence: command line options, custom options, defaults.
this._options = {
apiKey: createDefaultApiKey(),
...defaults,
...customOptions,
...this._options,
}
// Parse CORS options
this._options.corsAllowHeaders = this._options.corsAllowHeaders
.replace(/\s/g, '')
.split(',')
this._options.corsAllowOrigin = this._options.corsAllowOrigin
.replace(/\s/g, '')
.split(',')
this._options.corsExposedHeaders = this._options.corsExposedHeaders
.replace(/\s/g, '')
.split(',')
if (this._options.corsDisallowCredentials) {
this._options.corsAllowCredentials = false
}
this._options.corsConfig = {
credentials: this._options.corsAllowCredentials,
exposedHeaders: this._options.corsExposedHeaders,
headers: this._options.corsAllowHeaders,
origin: this._options.corsAllowOrigin,
}
serverlessLog(
`Starting Offline: ${this._provider.stage}/${this._provider.region}.`,
)
debugLog('options:', this._options)
}
async end() {
serverlessLog('Halting offline server')
if (this._lambda) {
await this._lambda.cleanup()
}
if (this._apiGateway) {
await this._apiGateway.stop(SERVER_SHUTDOWN_TIMEOUT)
}
if (this._apiGatewayWebSocket) {
await this._apiGatewayWebSocket.stop(SERVER_SHUTDOWN_TIMEOUT)
}
if (process.env.NODE_ENV !== 'test') {
process.exit(0)
}
}
setupEvents() {
// for simple API Key authentication model
if (this._provider.apiKeys) {
serverlessLog(`Key with token: ${this._options.apiKey}`)
if (this._options.noAuth) {
serverlessLog(
'Authorizers are turned off. You do not need to use x-api-key header.',
)
} else {
serverlessLog('Remember to use x-api-key on the request headers')
}
}
Object.entries(this._service.functions).forEach(
([functionKey, functionObj]) => {
// TODO re-activate?
// serverlessLog(`Routes for ${functionKey}:`)
this._lambda.add(functionObj.name, functionObj)
functionObj.events.forEach((event) => {
const { http, websocket } = event
if (http) {
this._apiGateway.createRoutes(functionKey, functionObj, http)
}
if (websocket) {
this._apiGatewayWebSocket.createEvent(
functionKey,
functionObj,
websocket,
)
}
})
},
)
}
// TEMP FIXME quick fix to expose gateway server for testing, look for better solution
getApiGatewayServer() {
return this._apiGateway.getServer()
}
// TODO: missing tests
_verifyServerlessVersionCompatibility() {
const currentVersion = this._version
const requiredVersionRange = pkg.peerDependencies.serverless
const versionIsSatisfied = satisfiesVersionRange(
currentVersion,
requiredVersionRange,
)
if (!versionIsSatisfied) {
logWarning(
`serverless-offline requires serverless version ${requiredVersionRange} but found version ${currentVersion}.
Be aware that functionality might be limited or has serious bugs.
To avoid any issues update serverless to a later version.
`,
)
}
}
}