-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexecutor.js
283 lines (225 loc) · 7.29 KB
/
executor.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
'use strict'
const wrapper = require('./util/result-wrapper')
const logger = require('../../../util/logger')
const timeoutRejector = require('../../../util/promise').timeoutRejector
const wrapResult = require('./result').wrapResult
const Backendless = require('backendless')
const path = require('path')
const SHUTDOWN_CODE = 32768
const SHUTDOWN_ACTION = 'SHUTDOWN'
const GLOBAL_LOGGER_NAME = 'Global logger'
const Modes = {
PRODUCTION : 'PRODUCTION',
MARKETPLACE: 'MARKETPLACE',
DEBUG : 'DEBUG'
}
/**
* @typedef {Object} InitAppData
* @property {string} secretKey
* @property {string} url
*/
/**
* @typedef {Object} CodeRunnerTask
* @property {String} id
* @property {String} ___jsonclass
* @property {String} applicationId;
* @property {InitAppData} initAppData;
* @property {Number} timeout
* @property {String} relativePath
* @property {String} codePath
* @property {String} mode
*/
const executor = module.exports = {}
executor.RMI = 'com.backendless.coderunner.commons.protocol.RequestMethodInvocation'
executor.RAI = 'com.backendless.coderunner.commons.protocol.RequestActionInvocation'
executor.RSI = 'com.backendless.coderunner.commons.protocol.RequestServiceInvocation'
const executors = {
[executor.RMI]: './invoke-handler',
[executor.RAI]: './invoke-action',
[executor.RSI]: './invoke-service'
}
const CACHEABLE_EXECUTORS = [
executor.RMI,
executor.RSI,
]
executor.isTaskCacheable = task => {
return CACHEABLE_EXECUTORS.includes(task.___jsonclass)
}
/**
* @param {CodeRunnerTask} task
* @returns {Function} task executor
*/
function getTaskExecutor(task) {
const taskClass = task.___jsonclass
if (!executors[taskClass]) {
throw new Error(`Unknown task [${ taskClass }]`)
}
return require(executors[taskClass])
}
function executeTask(task, model) {
const taskExecutor = getTaskExecutor(task)
if (task.timeout < 0) {
return taskExecutor(task, model)
}
const timeoutPromise = timeoutRejector(task.timeout, 'Task execution is aborted due to timeout')
return Promise
.race([
taskExecutor(task, model),
timeoutPromise
])
.then(result => {
timeoutPromise.cancel()
return result
})
}
/**
* @param {CodeRunnerTask} task
* @param {Object} opts
*/
function initClientSdk(task, opts) {
if (task.initAppData) {
if (!Backendless.Config) {
Backendless.Config = {}
}
Object.assign(Backendless.Config, opts.backendless.public)
const loggers = task.loggers || []
const logLevels = loggers.reduce((map, logConfig) => {
map[logConfig.name] = logConfig.level.toLowerCase()
return map
}, {})
Backendless.initApp({
serverURL : task.initAppData.url,
automationServerURL: opts.automation && opts.automation.internalAddress,
appId : task.applicationId,
apiKey : task.initAppData.apiKey || task.initAppData.secretKey,
logging : {
loadLevels : false,
globalLevel: logLevels[GLOBAL_LOGGER_NAME] || 'all',
levels : logLevels
}
})
if (opts.backendless.forwardableHeaders) {
applyTransferringHeaders(task, opts.backendless.forwardableHeaders)
}
}
}
/**
* BKNDLSS-27918
*
* @param {CodeRunnerTask} task
* @param {Array<String>} forwardableHeaders
*/
function applyTransferringHeaders(task, forwardableHeaders) {
const sourceHTTPHeaders = task.invocationContextDto.httpHeaders
const targetHTTPHeaders = {}
for (const httpHeaderKey in sourceHTTPHeaders) {
if (forwardableHeaders[httpHeaderKey.toLowerCase()]) {
targetHTTPHeaders[httpHeaderKey] = sourceHTTPHeaders[httpHeaderKey]
}
}
const _nativeSend = Backendless.request.send._nativeSend || Backendless.request.send
Backendless.request.send = function(options) {
options = options ? { ...options } : {}
options.headers = options.headers ? { ...targetHTTPHeaders, ...options.headers } : { ...targetHTTPHeaders }
return _nativeSend.call(this, options)
}
Backendless.request.send._nativeSend = _nativeSend
}
/**
* @param {CodeRunnerTask} task
* @param {Object} opts
*/
function enrichTask(task, opts) {
task.codePath = opts.debugModelCodePath
? opts.debugModelCodePath
: path.resolve(opts.backendless.repoPath, task.applicationId.toLowerCase(), task.relativePath || '')
//TODO: workaround for http://bugs.backendless.com/browse/BKNDLSS-12041
if (task.___jsonclass === executor.RMI && task.eventId === SHUTDOWN_CODE) {
task.___jsonclass = executor.RAI
task.actionType = SHUTDOWN_ACTION
}
task.invocationContextDto = task.invocationContextDto || {}
task.invocationContextDto.backendless = Backendless
task.invocationContextDto.backendless.toJSON = () => ({})
task.invocationContextDto.response = {
headers: task.invocationContextDto.httpResponseHeaders || {},
cookies: [],
setCookie(cookies) {
this.cookies = Array.isArray(cookies) ? cookies : [cookies]
}
}
}
/**
* @param {CodeRunnerTask} task
* @param {Object} opts
*/
const applySandbox = (task, opts) => {
const sandboxRequired = opts.sandbox && task.mode !== Modes.MARKETPLACE
if (sandboxRequired) {
require('./sandbox').apply(task.applicationId)
}
}
/**
* @param {InvokeServiceTask|InvokeHandlerTask} task
* @param {Object} opts
* @returns {ServerCodeModel}
*/
function getServerCodeModel(task, opts) {
opts.scModels = opts.scModels || {}
if (opts.debugModelCodePath) {
if (!opts.scModels[opts.debugModelCodePath]) {
const ServerCodeModel = require('../../model')
opts.scModels[opts.debugModelCodePath] = ServerCodeModel.build(opts.debugModelCodePath, opts.app.exclude)
}
return opts.scModels[opts.debugModelCodePath]
}
if (!opts.scModels[task.codePath]) {
const ServerCodeModelDescriptor = require('../../model/descriptor')
opts.scModels[task.codePath] = ServerCodeModelDescriptor.load(task.codePath)
}
return opts.scModels[task.codePath].getModelForFile(task.provider)
}
/**
* @param {CodeRunnerTask} task
* @param {Object} opts
* @param {ServerCodeModel=} model
* @returns {Promise.<?string>} task invocation result in JSON (if any)
*/
executor.execute = async function(task, opts, model) {
let response = null
try {
enrichTask(task, opts)
initClientSdk(task, opts)
applySandbox(task, opts)
if (!model && (task.provider || opts.debugModelCodePath)) {
model = getServerCodeModel(task, opts)
}
response = await executeTask(task, model)
if (response !== undefined) {
response = wrapResult(task, null, response)
}
} catch (error) {
if (error instanceof timeoutRejector.Error) {
task.criticalError = error.message
}
response = wrapResult(task, error)
}
if (logger.verboseMode) {
logger.verbose('[TRACE.REQUEST]:', JSON.stringify(task))
logger.verbose('[TRACE.RESPONSE]:', JSON.stringify(response))
}
if (response && !response.exception) {
response.arguments = response.arguments !== undefined
? wrapper.encodeArguments(response.arguments)
: []
}
const stringifiedResponse = JSON.stringify(response)
try {
if (opts.responseSizeLimit > 0 && (stringifiedResponse.length > opts.responseSizeLimit)) {
throw new Error('Response size limit exceeded')
}
} catch (error) {
return JSON.stringify(wrapResult(task, error))
}
return stringifiedResponse
}