-
-
Notifications
You must be signed in to change notification settings - Fork 794
/
RubyRunner.js
118 lines (95 loc) · 2.49 KB
/
RubyRunner.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
import { EOL, platform } from 'os'
import { relative, resolve } from 'path'
import execa from 'execa'
const { parse, stringify } = JSON
const { cwd } = process
const { has } = Reflect
export default class RubyRunner {
#env = null
#handlerName = null
#handlerPath = null
#allowCache = false
constructor(funOptions, env, allowCache) {
const { handlerName, handlerPath } = funOptions
this.#env = env
this.#handlerName = handlerName
this.#handlerPath = handlerPath
this.#allowCache = allowCache
}
// no-op
// () => void
cleanup() {}
_parsePayload(value) {
for (const item of value.split(EOL)) {
let json
// first check if it's JSON
try {
json = parse(item)
// nope, it's not JSON
} catch (err) {
// no-op
}
// now let's see if we have a property __offline_payload__
if (
json &&
typeof json === 'object' &&
has(json, '__offline_payload__')
) {
return json.__offline_payload__
}
}
return undefined
}
// invokeLocalRuby, loosely based on:
// https://github.com/serverless/serverless/blob/v1.50.0/lib/plugins/aws/invokeLocal/index.js#L556
// invoke.rb, copy/pasted entirely as is:
// https://github.com/serverless/serverless/blob/v1.50.0/lib/plugins/aws/invokeLocal/invoke.rb
async run(event, context) {
const runtime = platform() === 'win32' ? 'ruby.exe' : 'ruby'
// https://docs.aws.amazon.com/lambda/latest/dg/ruby-context.html
// https://docs.aws.amazon.com/lambda/latest/dg/ruby-context.html
// exclude callbackWaitsForEmptyEventLoop, don't mutate context
const { callbackWaitsForEmptyEventLoop, ..._context } = context
const input = stringify({
context: _context,
event,
allowCache: this.#allowCache,
})
// console.log(input)
const ruby = execa(
runtime,
[
resolve(__dirname, 'invoke.rb'),
relative(cwd(), this.#handlerPath),
this.#handlerName,
],
{
env: this.#env,
input,
// shell: true,
},
)
let result
try {
result = await ruby
} catch (err) {
// TODO
console.log(err)
throw err
}
const { stderr, stdout } = result
if (stderr) {
// TODO
console.log(stderr)
return stderr
}
try {
return this._parsePayload(stdout)
} catch (err) {
// TODO
console.log('No JSON')
// TODO return or re-throw?
return err
}
}
}