/
ServerlessOffline.js
370 lines (295 loc) · 9.62 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import updateNotifier from 'update-notifier'
import debugLog from './debugLog.js'
import serverlessLog, { logWarning, setLog } from './serverlessLog.js'
import { satisfiesVersionRange } from './utils/index.js'
import {
commandOptions,
CUSTOM_OPTION,
defaultOptions,
SERVER_SHUTDOWN_TIMEOUT,
} from './config/index.js'
import pkg from '../package.json'
export default class ServerlessOffline {
#cliOptions = null
#http = null
#options = null
#schedule = null
#webSocket = null
#lambda = null
#serverless = null
constructor(serverless, cliOptions) {
this.#cliOptions = cliOptions
this.#serverless = serverless
setLog((...args) => serverless.cli.log(...args))
this.commands = {
offline: {
// add start nested options
commands: {
start: {
lifecycleEvents: ['init', 'ready', '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:ready': this.ready.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() {
// Put here so available everywhere, not just in handlers
process.env.IS_OFFLINE = true
// check if update is available
updateNotifier({ pkg }).notify()
this._verifyServerlessVersionCompatibility()
this._mergeOptions()
const {
httpEvents,
lambdas,
scheduleEvents,
webSocketEvents,
} = this._getEvents()
// if (lambdas.length > 0) {
await this._createLambda(lambdas)
// }
const eventModules = []
if (httpEvents.length > 0) {
eventModules.push(this._createHttp(httpEvents))
}
if (scheduleEvents.length > 0) {
eventModules.push(this._createSchedule(scheduleEvents))
}
if (webSocketEvents.length > 0) {
eventModules.push(this._createWebSocket(webSocketEvents))
}
await Promise.all(eventModules)
}
async ready() {
if (process.env.NODE_ENV !== 'test') {
await this._listenForTermination()
}
}
async end(skipExit) {
// TEMP FIXME
if (process.env.NODE_ENV === 'test' && skipExit === undefined) {
return
}
serverlessLog('Halting offline server')
const eventModules = []
if (this.#lambda) {
eventModules.push(this.#lambda.cleanup())
eventModules.push(this.#lambda.stop(SERVER_SHUTDOWN_TIMEOUT))
}
if (this.#http) {
eventModules.push(this.#http.stop(SERVER_SHUTDOWN_TIMEOUT))
}
// if (this.#schedule) {
// eventModules.push(this.#schedule.stop())
// }
if (this.#webSocket) {
eventModules.push(this.#webSocket.stop(SERVER_SHUTDOWN_TIMEOUT))
}
await Promise.all(eventModules)
if (!skipExit) {
process.exit(0)
}
}
/**
* 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()
await this.ready()
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 _createLambda(lambdas, skipStart) {
const { default: Lambda } = await import('./lambda/index.js')
this.#lambda = new Lambda(this.#serverless, this.#options)
this.#lambda.create(lambdas)
if (!skipStart) {
await this.#lambda.start()
}
}
async _createHttp(events, skipStart) {
const { default: Http } = await import('./events/http/index.js')
this.#http = new Http(this.#serverless, this.#options, this.#lambda)
await this.#http.registerPlugins()
this.#http.create(events)
// HTTP Proxy defined in Resource
this.#http.createResourceRoutes()
// 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.#http.create404Route()
if (!skipStart) {
await this.#http.start()
}
}
async _createSchedule(events) {
const { default: Schedule } = await import('./events/schedule/index.js')
this.#schedule = new Schedule(
this.#lambda,
this.#serverless.service.provider.region,
)
this.#schedule.create(events)
}
async _createWebSocket(events) {
const { default: WebSocket } = await import('./events/websocket/index.js')
this.#webSocket = new WebSocket(
this.#serverless,
this.#options,
this.#lambda,
)
this.#webSocket.create(events)
return this.#webSocket.start()
}
_mergeOptions() {
const {
service: { custom = {}, provider },
} = this.#serverless
const customOptions = custom[CUSTOM_OPTION]
// merge options
// order of Precedence: command line options, custom options, defaults.
this.#options = {
...defaultOptions,
...customOptions,
...this.#cliOptions,
}
// 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: ${provider.stage}/${provider.region}.`)
debugLog('options:', this.#options)
}
_getEvents() {
const { service } = this.#serverless
const httpEvents = []
const lambdas = []
const scheduleEvents = []
const webSocketEvents = []
const functionKeys = service.getAllFunctions()
let hasPrivateHttpEvent = false
functionKeys.forEach((functionKey) => {
const functionDefinition = service.getFunction(functionKey)
lambdas.push({ functionKey, functionDefinition })
const events = service.getAllEventsInFunction(functionKey) || []
events.forEach((event) => {
const { http, httpApi, schedule, websocket } = event
if ((http || httpApi) && functionDefinition.handler) {
const httpEvent = {
functionKey,
handler: functionDefinition.handler,
http: http || httpApi,
}
// this is here to allow rawHttpEventDefinition to be a string
// the problem is that events defined as
// httpApi: '*'
// will not have the isHttpApi flag set. This will need to be addressed
// when adding support for HttpApi 2.0 payload types.
if (httpApi && typeof httpApi === 'object') {
httpEvent.http = { ...httpApi, isHttpApi: true }
}
if (http && http.private) {
hasPrivateHttpEvent = true
}
httpEvents.push(httpEvent)
}
if (schedule) {
scheduleEvents.push({
functionKey,
schedule,
})
}
if (websocket) {
webSocketEvents.push({
functionKey,
websocket,
})
}
})
})
// for simple API Key authentication model
if (hasPrivateHttpEvent) {
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')
}
}
return {
httpEvents,
lambdas,
scheduleEvents,
webSocketEvents,
}
}
// TEMP FIXME quick fix to expose gateway server for testing, look for better solution
getApiGatewayServer() {
return this.#http.getServer()
}
// TODO: missing tests
_verifyServerlessVersionCompatibility() {
const currentVersion = this.#serverless.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 contains bugs.
To avoid any issues update serverless to a later version.
`,
)
}
}
}