-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
82 lines (70 loc) · 2.04 KB
/
index.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
'use strict';
const ms = require('ms');
const sleep = require('util').promisify(setTimeout);
const path = require('path');
const { fork } = require('child_process');
const Executor = require('@runnerty/module-core').Executor;
class jsExecutor extends Executor {
constructor(process) {
super(process);
this.forked = fork(path.join(__dirname, 'child.js'));
this.response = '';
this.timeoutExceeded = false;
}
exec(params) {
this.forked.on('message', msg => {
this.response = msg;
});
this.forked.on('error', error => {
this.endFail(error);
});
this.forked.on('CLOSE', code => {
this.endFail('Closed', code);
});
this.forked.on('exit', code => {
if (code === 1) {
this.endFail();
} else {
const endOptions = { end: 'end' };
endOptions.data_output = this.response || '';
if (this.response instanceof Object) {
endOptions.extra_output = this.response;
}
this.end(endOptions);
}
});
const _params = {
script: path.resolve(params.script),
function: params.function || '',
parameters: params.parameters,
debug: params.debug || false
};
if (this.forked.connected) {
this.forked.send(_params);
this.startTimeout(params.timeout);
} else {
this.endFail(`Connection to ${_params.script} could not be established.`);
}
}
async startTimeout(time) {
if (ms('' + time) > 0) {
await sleep(ms('' + time));
if (this.forked.connected) {
this.timeoutExceeded = true;
this.forked.kill();
}
}
}
endFail(error) {
const endOptions = { end: 'error' };
endOptions.messageLog = error || this.response || '';
endOptions.err_output = error || this.response || '';
// Timeout Exceeded:
if (this.timeoutExceeded) {
endOptions.err_output = 'Timeout Exceeded. ' + endOptions.err_output;
endOptions.messageLog = 'Timeout Exceeded. ' + endOptions.messageLog;
}
this.end(endOptions);
}
}
module.exports = jsExecutor;