-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
executable file
·81 lines (68 loc) · 2.22 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
// Will pass a JSON string via stdin to the go function and will catch and relay
// back the JSON response via stdout. The go executable process will be reused
// and restarted upon faileure. This should provide lower latency after the
// first call.
// set to name of the package for local testing - buildscript will rename to 'main'
const exeName = 'aws-lambda-barcode-generator';
// It shouldn't be necessary to modify below this line
const MAX_FAILS = 4;
var child_process = require('child_process'),
go_proc = null,
done = console.log.bind(console),
fails = 0;
(function new_go_proc() {
// pipe stdin/out, blind passthru stderr
go_proc = child_process.spawn('./' + exeName, { stdio: ['pipe', 'pipe', process.stderr] });
go_proc.on('error', function(err) {
process.stderr.write("go_proc errored: "+JSON.stringify(err)+"\n");
if (++fails > MAX_FAILS) {
process.exit(1); // force container restart after too many fails
}
new_go_proc();
done(err);
});
go_proc.on('exit', function(code) {
process.stderr.write("go_proc exited prematurely with code: "+code+"\n");
if (++fails > MAX_FAILS) {
process.exit(1); // force container restart after too many fails
}
new_go_proc();
done(new Error("Exited with code "+code));
});
go_proc.stdin.on('error', function(err) {
process.stderr.write("go_proc stdin write error: "+JSON.stringify(err)+"\n");
if (++fails > MAX_FAILS) {
process.exit(1); // force container restart after too many fails
}
new_go_proc();
done(err);
});
var data = null;
go_proc.stdout.on('data', function(chunk) {
fails = 0; // reset fails
if (data === null) {
data = new Buffer(chunk);
} else {
data.write(chunk);
}
// check for newline ascii char 10
if (data.length && data[data.length-1] == 10) {
var output = JSON.parse(data.toString('UTF-8'));
data = null;
if (output.errorMessage) {
// line will be replaced with 'done(output.errorMessage, null)' by build script
done(output, null);
} else {
done(null, output);
}
};
});
})();
exports.handler = function(event, context) {
// always output to current context's done
done = context.done.bind(context);
go_proc.stdin.write(JSON.stringify({
"event": event,
"context": context
})+"\n");
}