-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
118 lines (101 loc) · 2.9 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
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
var _ = require('lodash');
var crypto = require('crypto');
var net = require('net');
var path = require('path');
var Promise = require('bluebird');
var spawn = require('child_process').spawn;
var stat = Promise.promisify(require('fs').stat);
var utils = require('./utils');
var request = require('request');
module.exports = (function() {
function Babl(name, params) {
params || (params = {});
this.name = name;
this.stdin = params.stdin;
this.env = params.env;
this.seed = crypto.randomBytes(16).toString('hex');
this.endpoint = params.endpoint;
process.env.QUARTZ_SOCKET = '/tmp/quartz_' + this.seed + '.sock';
this.process = spawn(Babl.binPath(), this.binParams());
};
Babl.module = function(name, params) {
return new Babl(name, params)
.call()
.then(Babl.fetchPayload)
.then(JSON.stringify)
.then(Buffer.from);
};
Babl.call = function(name, params) {
return new Babl(name, params).call();
};
Babl.fetchPayload = function(buffer) {
return new Promise(function(resolve, reject) {
var obj = JSON.parse(buffer);
var result = obj.result;
if (result.PayloadUrl) {
request({
url: result.PayloadUrl,
method: 'get',
}, function(error, response, body) {
if (error) {
reject(error);
} else {
result.Stdout = Buffer.from(body).toString('base64');
resolve(obj);
}
})
} else {
resolve(obj);
}
});
};
Babl.binPath = function() {
var platform = (process.platform.match(/(darwin|linux)/) || []).pop();
var filename = 'babl-rpc_' + platform + '_amd64';
return path.resolve(__dirname, './bin/' + filename);
};
Babl.prototype.call = function() {
var self = this;
return new Promise(function(resolve, reject) {
utils
.retry(function() {
return stat(process.env.QUARTZ_SOCKET);
}, 1, {
if: function(reason) { return reason.code === 'ENOENT'; }
})
.timeout(10000)
.then(function() { return self; })
.then(utils.dispatch)
.then(resolve)
.catch(reject);
});
};
Babl.prototype.binParams = function() {
var result = [];
if (this.endpoint) {
result.push('-endpoint', this.endpoint);
}
return result;
};
Babl.prototype.payload = function() {
var params = this.params();
params.Stdin === null && delete params.Stdin;
params.Env === null && delete params.Env;
return {
method: 'babl.Module',
params: [params],
id: 1,
};
};
Babl.prototype.toJSON = function() {
return JSON.stringify(this.payload());
};
Babl.prototype.params = function() {
return {
Name: this.name,
Stdin: new Buffer(this.stdin ? this.stdin : '').toString('base64') || null,
Env: (!_.isEmpty(this.env) && this.env) || null,
}
};
return Babl;
})();