-
Notifications
You must be signed in to change notification settings - Fork 30
/
index.js
219 lines (197 loc) · 6.76 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
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
'use strict';
let Promise = require('bluebird');
let path = require('path');
let child_process = Promise.promisifyAll(require('child_process'));
const PYTHON_BRIDGE_SCRIPT = path.join(__dirname, 'node_python_bridge.py');
function pythonBridge(opts) {
// default options
let intepreter = opts && opts.python || 'python';
let stdio = opts && opts.stdio || ['pipe', process.stdout, process.stderr];
let options = {
cwd: opts && opts.cwd,
env: opts && opts.env,
uid: opts && opts.uid,
gid: opts && opts.gid,
stdio: stdio.concat(['ipc'])
};
// create process bridge
let ps = child_process.spawn(intepreter, [PYTHON_BRIDGE_SCRIPT], options);
let queue = singleQueue();
function sendPythonCommand(type, enqueue, self) {
function wrapper() {
self = self || wrapper;
let code = json.apply(this, arguments);
if (!(this && this.connected || self.connected)) {
return Promise.reject(new PythonBridgeNotConnected());
}
return enqueue(() => new Promise((resolve, reject) => {
ps.send({type: type, code: code});
ps.once('message', onMessage);
ps.once('close', onClose);
function onMessage(data) {
ps.removeListener('close', onClose);
if (data && data.type && data.type === 'success') {
resolve(eval(`(${data.value})`));
} else if (data && data.type && data.type === 'exception') {
reject(new PythonException(data.value));
} else {
reject(data);
}
}
function onClose(exit_code, message) {
ps.removeListener('message', onMessage);
if (!message) {
reject(new Error(`Python process closed with exit code ${exit_code}`));
} else {
reject(new Error(`Python process closed with exit code ${exit_code} and message: ${message}`));
}
}
}));
}
return wrapper;
}
function setupLock(enqueue) {
return f => {
return enqueue(() => {
let lock_queue = singleQueue();
let lock_python = sendPythonCommand('evaluate', lock_queue);
lock_python.ex = sendPythonCommand('execute', lock_queue, lock_python);
lock_python.lock = setupLock(lock_queue);
lock_python.connected = true;
lock_python.__proto__ = python;
return f(lock_python);
});
};
}
// API
let python = sendPythonCommand('evaluate', queue);
python.ex = sendPythonCommand('execute', queue, python);
python.lock = setupLock(queue);
python.pid = ps.pid;
python.connected = true;
python.Exception = PythonException;
python.isException = isPythonException;
python.disconnect = () => {
python.connected = false;
return queue(() => {
ps.disconnect();
});
};
python.end = python.disconnect;
python.kill = signal => {
python.connected = false;
ps.kill(signal);
};
python.stdin = ps.stdin;
python.stdout = ps.stdout;
python.stderr = ps.stderr;
return python;
}
class PythonException extends Error {
constructor(exc) {
if (exc && exc.format) {
super(exc.format.join(''));
} else if (exc && exc.error) {
super(`Python exception: ${exc.error}`);
} else {
super('Unknown Python exception');
}
this.error = exc.error;
this.exception = exc.exception;
this.traceback = exc.traceback;
this.format = exc.format;
}
}
class PythonBridgeNotConnected extends Error {
constructor() {
super('Python bridge is no longer connected.');
}
}
function isPythonException(name, exc) {
const thunk = exc => (
exc instanceof PythonException &&
exc.exception &&
exc.exception.type.name === name
);
if (exc === undefined) {
return thunk;
}
return thunk(exc);
}
function singleQueue() {
let last = Promise.resolve();
return function enqueue(f) {
let wait = last;
let done;
last = new Promise(resolve => {
done = resolve;
});
return new Promise((resolve, reject) => {
wait.finally(() => {
Promise.try(f).then(resolve, reject);
});
}).finally(() => done());
};
}
function dedent(code) {
// dedent text
let lines = code.split('\n');
let offset = null;
// remove extra blank starting line
if (!lines[0].trim()) {
lines.shift();
}
for (let line of lines) {
let trimmed = line.trimLeft();
if (trimmed) {
offset = (line.length - trimmed.length) + 1;
break;
}
}
if (!offset) {
return code;
}
let match = new RegExp('^' + new Array(offset).join('\\s?'));
return lines.map(line => line.replace(match, '')).join('\n');
}
function json(text_nodes) {
let values = Array.prototype.slice.call(arguments, 1);
return dedent(text_nodes.reduce((cur, acc, i) => {
return cur + serializePython(values[i - 1]) + acc;
}));
}
function serializePython(value) {
if (value === null || typeof value === 'undefined') {
return 'None';
} else if (value === true) {
return 'True';
} else if (value === false) {
return 'False';
} else if (value === Infinity) {
return "float('inf')";
} else if (value === -Infinity) {
return "float('-inf')";
} else if (value instanceof Array) {
return `[${value.map(serializePython).join(', ')}]`;
} else if (typeof value === 'number') {
if (isNaN(value)) {
return "float('nan')";
}
return JSON.stringify(value);
} else if (typeof value === 'string') {
return JSON.stringify(value);
} else if (value instanceof Map) {
const props = Array.from(value.entries()).map(kv => `${serializePython(kv[0])}: ${serializePython(kv[1])}`);
return `{${props.join(', ')}}`;
} else {
const props = Object.keys(value).map(k => `${serializePython(k)}: ${serializePython(value[k])}`);
return `{${props.join(', ')}}`;
}
}
pythonBridge.pythonBridge = pythonBridge;
pythonBridge.PythonException = PythonException;
pythonBridge.PythonBridgeNotConnected = PythonBridgeNotConnected;
pythonBridge.isPythonException = isPythonException;
pythonBridge.json = json;
pythonBridge.serializePython = serializePython;
module.exports = pythonBridge.pythonBridge = pythonBridge;