-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathchild-process-worker.js
More file actions
352 lines (296 loc) · 9.78 KB
/
child-process-worker.js
File metadata and controls
352 lines (296 loc) · 9.78 KB
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
// @ts-check
'use strict'
const childProcess = require('child_process')
const assert = require('assert')
const path = require('path')
const fs = require('fs')
const os = require('os')
const tmp = os.tmpdir()
const JS_WORKER_TXT = require('./workers/js-worker-txt.js')
const PY_WORKER_TXT = require('./workers/py-worker-txt.js')
const GO_WORKER_WINDOWS_TXT = require('./workers/go-worker-windows-txt.js')
const GO_WORKER_POSIX_TXT = require('./workers/go-worker-posix-txt.js')
const WORKER_PATH = `${tmp}/fake-api-gateway-lambda/worker.js`
const PYTHON_WORKER_PATH = `${tmp}/fake-api-gateway-lambda/worker.py`
const GO_WORKER_POSIX_PATH = `${tmp}/fake-api-gateway-lambda/worker-posix.go`
const GO_WORKER_WINDOWS_PATH = `${tmp}/fake-api-gateway-lambda/worker-windows.go`
const isWindows = os.platform() === 'win32'
try {
fs.mkdirSync(path.dirname(WORKER_PATH), { recursive: true })
fs.writeFileSync(WORKER_PATH, JS_WORKER_TXT)
if (isWindows) {
fs.mkdirSync(path.dirname(GO_WORKER_WINDOWS_PATH), { recursive: true })
fs.writeFileSync(GO_WORKER_WINDOWS_PATH, GO_WORKER_WINDOWS_TXT)
} else {
fs.mkdirSync(path.dirname(GO_WORKER_POSIX_PATH), { recursive: true })
fs.writeFileSync(GO_WORKER_POSIX_PATH, GO_WORKER_POSIX_TXT)
}
fs.mkdirSync(path.dirname(PYTHON_WORKER_PATH), { recursive: true })
fs.writeFileSync(PYTHON_WORKER_PATH, PY_WORKER_TXT)
} catch (err) {
console.error('Could not copy worker.{js,py,go} into tmp', err)
}
class ChildProcessWorker {
/**
* @param {{
* stdout?: object,
* stderr?: object,
* entry: string,
* handler: string,
* env: object,
* runtime: string
* }} options
*/
constructor (options) {
assert(options.handler, 'options.handler required')
assert(options.runtime, 'options.runtime required')
assert(options.entry, 'options.entry required')
this.responses = {}
this.procs = []
this.stdout = options.stdout || process.stdout
this.stderr = options.stderr || process.stderr
this.runtime = options.runtime
this.entry = options.entry
this.handler = options.handler
this.env = options.env
// this.options = options
}
logLine (output, line, type) {
if (line === '') {
return
}
const msg = `${new Date().toISOString()} ${this.latestId} ${type} ` + line
output.write(msg)
}
/**
* @param {{
* stdout: import('stream').Readable,
* output: import('stream').Writable,
* handleMessage: (o: object) => void
* }} opts
*/
parseStdout (opts) {
const { stdout, output, handleMessage } = opts
let remainder = ''
const START_LEN = '__FAKE_LAMBDA_START__'.length
const END_LEN = '__FAKE_LAMBDA_END__'.length
stdout.on('data', (bytes) => {
const str = remainder + bytes.toString()
remainder = ''
if (str.indexOf('\n') === -1) {
return this.logLine(output, str, 'INFO')
}
const lines = str.split('\n')
for (let i = 0; i < lines.length - 1; i++) {
const line = lines[i]
const index = line.indexOf('__FAKE_LAMBDA_START__')
if (index === -1) {
if (line === '') continue
this.logLine(output, line + '\n', 'INFO')
continue
}
const start = line.slice(0, index)
this.logLine(output, start)
const endIndex = line.indexOf('__FAKE_LAMBDA_END__')
const messageStr = line.slice(index + START_LEN, endIndex)
const msgObject = JSON.parse(messageStr.trim())
handleMessage(msgObject)
const end = line.slice(endIndex + END_LEN)
if (end.length > 0) {
this.logLine(output, end + '\n', 'INFO')
}
}
const lastLine = lines[lines.length - 1]
if (lastLine.includes('__FAKE_LAMBDA_START__')) {
remainder = lastLine
} else {
this.logLine(output, remainder, 'INFO')
}
})
}
async request (id, eventObject, raw) {
this.latestId = id
this.stdout.write(
`START\tRequestId:${id}\tVersion:$LATEST\n`
)
const start = Date.now()
let proc
/** @type {string | boolean} */
let shell = true
if (process.platform !== 'win32') {
shell = os.userInfo().shell
} else {
shell = false
}
if (/node(js):?(12|14|16)/.test(this.runtime)) {
const parts = this.handler.split('.')
const handlerField = parts[parts.length - 1]
const cmd = process.platform === 'win32' ? process.execPath : 'node'
proc = childProcess.spawn(
cmd,
[WORKER_PATH, this.entry, handlerField],
{
stdio: ['pipe', 'pipe', 'pipe'],
detached: false,
shell: shell,
env: {
PATH: process.env.PATH,
...this.env
}
}
)
} else if (/python:?(3)/.test(this.runtime)) {
const parts = this.handler.split('.')
const handlerField = parts[parts.length - 1]
const cmd = process.platform === 'win32' ? 'py' : 'python3'
proc = childProcess.spawn(
cmd,
[PYTHON_WORKER_PATH, this.entry, handlerField],
{
// stdio: 'inherit',
detached: false,
shell: shell,
env: {
PATH: process.env.PATH,
...this.env
}
}
)
} else if (/go:?(1)/.test(this.runtime)) {
const workerPath = isWindows ? GO_WORKER_WINDOWS_PATH : GO_WORKER_POSIX_PATH
const workerBin = workerPath.replace('.go', '')
const buildCommand = `go build ${workerPath}`
const buildOptions = {
cwd: path.dirname(workerPath),
shell: typeof shell === 'string' ? shell : undefined,
env: {
GOCACHE: process.env.GOCACHE,
GOROOT: process.env.GOROOT,
GOPATH: process.env.GOPATH,
HOME: process.env.HOME,
PATH: process.env.PATH,
LOCALAPPDATA: process.env.LOCALAPPDATA,
...this.env
}
}
const buildResult = await new Promise((resolve) => {
childProcess.exec(buildCommand, buildOptions, (err, stderr) => resolve({ err, stderr }))
})
if (buildResult.err) {
return Promise.reject(buildResult.err)
}
if (buildResult.stderr) {
const err = new Error('Internal Server Error')
Reflect.set(err, 'errorString', buildResult.stderr)
return Promise.reject(err)
}
proc = childProcess.spawn(workerBin, ['-p', '0', '-P', this.entry], {
detached: false,
shell: shell || true,
cwd: path.dirname(workerPath),
env: {
GOCACHE: process.env.GOCACHE,
GOROOT: process.env.GOROOT,
GOPATH: process.env.GOPATH,
HOME: process.env.HOME,
PATH: process.env.PATH,
LOCALAPPDATA: process.env.LOCALAPPDATA,
...this.env
}
})
}
return new Promise((resolve, reject) => {
this.procs.push(proc)
proc.unref()
let errorString = ''
proc.stderr.on('data', (line) => {
errorString += line.toString()
this.logLine(this.stderr, line, 'ERR')
})
this.parseStdout({
stdout: proc.stdout,
output: this.stdout,
handleMessage: (msg) => {
const resultObject = this.handleMessage(msg, start)
proc.kill()
resolve(resultObject)
}
})
proc.once('exit', (code) => {
code = code || 0
if (code !== 0) {
// var err = new Error()
// err.message = error.split('\n')[0]
// err.stack = error.split('\n').slice(1).join('\n')
// const lambdaError = {
// errorType: 'Error',
// errorMessage: 'Error',
// stack: errorString.split('\n')
// }
// this.stdout.write(`${new Date(start).toISOString()}\tundefined\tERROR\t${JSON.stringify(lambdaError)}\n`)
const err = new Error('Internal Server Error')
Reflect.set(err, 'errorString', errorString)
Reflect.set(err, 'code', code)
reject(err)
// this is wrong, should not crash.
}
})
proc.on('error', function (err) {
reject(err)
})
proc.stdin.on('error', function (err) {
/**
* Sometimes we get an EPIPE exception when writing to
* stdin for a process where the command is not found.
*
* We really care boure about the command not found error
* so we swallow the EPIPE and let the other err bubble instead
*/
if (Reflect.get(err, 'code') === 'EPIPE') {
return
}
reject(err)
})
proc.stdin.write(JSON.stringify({
message: 'event',
id,
eventObject,
raw: !!raw
}) + '\n')
process.stdin.end()
})
}
handleMessage (msg, start) {
if (typeof msg !== 'object' || Object.is(msg, null)) {
throw new Error('bad data type from child process')
}
const messageType = msg.message
if (messageType !== 'result') {
throw new Error('incorrect type field from child process:' + msg.type)
}
const id = msg.id
if (typeof id !== 'string') {
throw new Error('missing id from child process:' + msg.id)
}
const resultObj = msg.result
// if (!checkResult(resultObj)) {
// throw new Error('missing result from child process:' + msg.result)
// }
const duration = Date.now() - start
// log like lambda
this.stdout.write(
`END\tRequestId: ${msg.id}\n` +
`REPORT\tRequestId: ${msg.id}\t` +
'InitDuration: 0 ms\t' +
`Duration: ${duration} ms\t` +
`BilledDuration: ${Math.round(duration)} ms\t` +
`Memory Size: NaN MB MaxMemoryUsed ${Math.round(msg.memory / (1024 * 1024))} MB\n`
)
return resultObj
}
close () {
this.procs.forEach(proc => proc.kill())
this.procs = []
}
}
module.exports = ChildProcessWorker