-
-
Notifications
You must be signed in to change notification settings - Fork 793
/
LambdaFunction.js
289 lines (245 loc) · 7.95 KB
/
LambdaFunction.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 { tmpdir } from 'os'
import { dirname, join, resolve, sep } from 'path'
import { emptyDir, ensureDir, readFile, remove, writeFile } from 'fs-extra'
import { performance } from 'perf_hooks'
import jszip from 'jszip'
import HandlerRunner from './handler-runner/index.js'
import LambdaContext from './LambdaContext.js'
import serverlessLog from '../serverlessLog.js'
import resolveJoins from '../utils/resolveJoins.js'
import {
DEFAULT_LAMBDA_MEMORY_SIZE,
DEFAULT_LAMBDA_RUNTIME,
DEFAULT_LAMBDA_TIMEOUT,
supportedRuntimes,
} from '../config/index.js'
import { createUniqueId, splitHandlerPathAndName } from '../utils/index.js'
const { keys } = Object
const { ceil } = Math
export default class LambdaFunction {
#artifact = null
#clientContext = null
#codeDir = null
#event = null
#executionTimeEnded = null
#executionTimeStarted = null
#functionKey = null
#functionName = null
#handlerRunner = null
#idleTimeStarted = null
#initialized = false
#lambdaContext = null
#lambdaDir = null
#memorySize = null
#region = null
#runtime = null
#timeout = null
status = 'IDLE' // can be 'BUSY' or 'IDLE'
constructor(functionKey, functionDefinition, serverless, options) {
const {
service,
config: { serverlessPath, servicePath },
service: { provider, package: servicePackage = {} },
} = serverless
// TEMP options.location, for compatibility with serverless-webpack:
// https://github.com/dherault/serverless-offline/issues/787
// TODO FIXME look into better way to work with serverless-webpack
const _servicePath = resolve(servicePath, options.location || '')
const { handler, name, package: functionPackage = {} } = functionDefinition
const [handlerPath, handlerName] = splitHandlerPathAndName(handler)
const memorySize =
functionDefinition.memorySize ||
provider.memorySize ||
DEFAULT_LAMBDA_MEMORY_SIZE
const runtime =
functionDefinition.runtime || provider.runtime || DEFAULT_LAMBDA_RUNTIME
const timeout =
(functionDefinition.timeout ||
provider.timeout ||
DEFAULT_LAMBDA_TIMEOUT) * 1000
// this._executionTimeout = null
this.#functionKey = functionKey
this.#functionName = name
this.#memorySize = memorySize
this.#region = provider.region
this.#runtime = runtime
this.#timeout = timeout
this._verifySupportedRuntime()
const env = this._getEnv(
resolveJoins(provider.environment),
functionDefinition.environment,
handler,
)
this.#artifact = functionDefinition.package?.artifact
if (!this.#artifact) {
this.#artifact = service.package?.artifact
}
if (this.#artifact) {
// lambda directory contains code and layers
this.#lambdaDir = join(
tmpdir(),
'serverless-offline',
'services',
service.service,
functionKey,
createUniqueId(),
)
}
this.#codeDir = this.#lambdaDir
? resolve(this.#lambdaDir, 'code')
: _servicePath
// TEMP
const funOptions = {
functionKey,
handler,
handlerName,
codeDir: this.#codeDir,
handlerPath: resolve(this.#codeDir, handlerPath),
runtime,
serverlessPath,
servicePath: _servicePath,
timeout,
functionName: name,
servicePackage: servicePackage.artifact
? resolve(_servicePath, servicePackage.artifact)
: undefined,
functionPackage: functionPackage.artifact
? resolve(_servicePath, functionPackage.artifact)
: undefined,
}
this.#handlerRunner = new HandlerRunner(funOptions, options, env)
this.#lambdaContext = new LambdaContext(name, memorySize)
}
_startExecutionTimer() {
this.#executionTimeStarted = performance.now()
// this._executionTimeout = this.#executionTimeStarted + this.#timeout * 1000
}
_stopExecutionTimer() {
this.#executionTimeEnded = performance.now()
}
_startIdleTimer() {
this.#idleTimeStarted = performance.now()
}
_verifySupportedRuntime() {
// print message but keep working (don't error out or exit process)
if (!supportedRuntimes.has(this.#runtime)) {
// this.printBlankLine(); // TODO
console.log('')
serverlessLog(
`Warning: found unsupported runtime '${this.#runtime}' for function '${
this.#functionKey
}'`,
)
}
}
// based on:
// https://github.com/serverless/serverless/blob/v1.50.0/lib/plugins/aws/invokeLocal/index.js#L108
_getAwsEnvVars() {
return {
AWS_DEFAULT_REGION: this.#region,
AWS_LAMBDA_FUNCTION_MEMORY_SIZE: this.#memorySize,
AWS_LAMBDA_FUNCTION_NAME: this.#functionName,
AWS_LAMBDA_FUNCTION_VERSION: '$LATEST',
// https://github.com/serverless/serverless/blob/v1.50.0/lib/plugins/aws/lib/naming.js#L123
AWS_LAMBDA_LOG_GROUP_NAME: `/aws/lambda/${this.#functionName}`,
AWS_LAMBDA_LOG_STREAM_NAME:
'2016/12/02/[$LATEST]f77ff5e4026c45bda9a9ebcec6bc9cad',
AWS_REGION: this.#region,
LAMBDA_RUNTIME_DIR: '/var/runtime',
LAMBDA_TASK_ROOT: '/var/task',
LANG: 'en_US.UTF-8',
LD_LIBRARY_PATH:
'/usr/local/lib64/node-v4.3.x/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib',
NODE_PATH: '/var/runtime:/var/task:/var/runtime/node_modules',
}
}
_getEnv(providerEnv, functionDefinitionEnv, handler) {
return {
...this._getAwsEnvVars(),
...providerEnv,
...functionDefinitionEnv,
_HANDLER: handler, // TODO is this available in AWS?
}
}
setClientContext(clientContext) {
this.#clientContext = clientContext
}
setEvent(event) {
this.#event = event
}
// () => Promise<void>
async cleanup() {
// TODO console.log('lambda cleanup')
await this.#handlerRunner.cleanup()
if (this.#lambdaDir) {
await remove(this.#lambdaDir)
}
}
_executionTimeInMillis() {
return this.#executionTimeEnded - this.#executionTimeStarted
}
// rounds up to the nearest 100 ms
_billedExecutionTimeInMillis() {
return (
ceil((this.#executionTimeEnded - this.#executionTimeStarted) / 100) * 100
)
}
// extractArtifact, loosely based on:
// https://github.com/serverless/serverless/blob/v1.57.0/lib/plugins/aws/invokeLocal/index.js#L312
async _extractArtifact() {
if (!this.#artifact) {
return null
}
emptyDir(this.#codeDir)
const data = await readFile(this.#artifact)
const zip = await jszip.loadAsync(data)
return Promise.all(
keys(zip.files).map(async (filename) => {
const fileData = await zip.files[filename].async('nodebuffer')
if (filename.endsWith(sep)) {
return Promise.resolve()
}
await ensureDir(join(this.#codeDir, dirname(filename)))
return writeFile(join(this.#codeDir, filename), fileData, {
mode: zip.files[filename].unixPermissions,
})
}),
)
}
async _initialize() {
await this._extractArtifact()
this.#initialized = true
}
get idleTimeInMinutes() {
return (performance.now() - this.#idleTimeStarted) / 1000 / 60
}
get functionName() {
return this.#functionName
}
async runHandler() {
this.status = 'BUSY'
if (!this.#initialized) {
await this._initialize()
}
const requestId = createUniqueId()
this.#lambdaContext.setRequestId(requestId)
this.#lambdaContext.setClientContext(this.#clientContext)
const context = this.#lambdaContext.create()
this._startExecutionTimer()
const result = await this.#handlerRunner.run(this.#event, context)
this._stopExecutionTimer()
// TEMP TODO FIXME find better solution
if (!this.#handlerRunner.isDockerRunner()) {
serverlessLog(
`(λ: ${
this.#functionKey
}) RequestId: ${requestId} Duration: ${this._executionTimeInMillis().toFixed(
2,
)} ms Billed Duration: ${this._billedExecutionTimeInMillis()} ms`,
)
}
this.status = 'IDLE'
this._startIdleTimer()
return result
}
}