-
Notifications
You must be signed in to change notification settings - Fork 205
/
communication.ts
210 lines (193 loc) · 6.35 KB
/
communication.ts
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
/**
* @file This file contains methods for python-node to communicate between nodejs and python
*/
import * as zmq from 'zeromq';
import {Session} from '../types/python-object';
import {startKernel} from '../communication/connectkernel';
const nodeCleanup = require('node-cleanup');
const kernel = require('./ipker.json')
/**
* Executor class: responsible for handling sessions and ipython and exeucting python statements.
*/
export default class Executor {
static sessions: Session[] = []; // stores all current sessions in use
static latestIoPort = 55548; // default start port to use for iopub
static latestShellPort = 51314 // default start port to use for shell
/**
* open a session which is bound to a scope
*/
static openSession = async (scope: string) => {
let session:Session = Executor.sessions.find((e: any) => e.id === scope);
if (!session) {
session = await Executor.createSession(scope);
session.socketSubscriber.connect(kernel.transport + "://" + kernel.ip + ":" + session.ioPort);
session.socketDealer.connect(kernel.transport + "://" + kernel.ip + ":" + session.shellPort);
session.socketSubscriber.subscribe("stream");
Executor.handleSubscriberMsg(session.socketSubscriber);
Executor.handleDealerMsg(session.socketDealer, session);
}
}
static closeSession = async (scope: string) => {
await Executor.exit(scope);
Executor.sessions = Executor.sessions.filter((session: any) => session.id !== scope);
}
/**
* exit a session
*/
static exit = async (scope: string) => {
let session:Session = Executor.sessions.find((e: any) => e.id === scope);
await session.kernel.cleanup();
}
/**
* create a new session
*/
static createSession = async (id: string) => {
const kernel: any = await startKernel(Executor.latestShellPort, Executor.latestIoPort);
// register cleanup process. This is executed when nodejs process exit
nodeCleanup(function () {
kernel.cleanup()
.then(() => {
nodeCleanup.uninstall();
})
.catch(() => {
nodeCleanup.uninstall();
});
return false;
});
const session: Session = {
id,
parent_header: {},
last_header: {
msg_id: "init_id",
msg_type: "execute_request",
username: 'pipcook',
version: "5.0",
session: "pipcook_session"
},
dealerMsg: {},
socketDealer: new zmq.Dealer,
socketSubscriber: new zmq.Subscriber,
timer: null,
ioPort: Executor.latestIoPort,
shellPort: Executor.latestShellPort,
kernel
}
Executor.latestIoPort++;
Executor.latestShellPort++;
Executor.sessions.push(session);
return session;
}
/**
* handle subscriber message. This protocol is used to receive stdout and stderr from ipython kernel
*/
static handleSubscriberMsg = (socketSubscriber: zmq.Subscriber) => {
socketSubscriber.receive()
.then((msg: Buffer[]) => {
msg.forEach((item, index) => {
try {
const json = JSON.parse(item.toString());
if (json.name === 'stdout') {
console.log('[PYTHON: ]', json.text);
} else if (json.name === 'stderr') {
console.error('[PYTHON: ]', json.text);
}
} catch (e) {
}
});
Executor.handleSubscriberMsg(socketSubscriber);
})
.catch((err) => {
Executor.handleSubscriberMsg(socketSubscriber)
});
}
/**
* handle dealer message. This protocol is used to send codes to ipython and receive execution message
*/
static handleDealerMsg = (socketDealer: zmq.Dealer, session: Session) => {
socketDealer.receive()
.then((msg) => {
const message: any = {};
msg.forEach((item) => {
try {
const json = JSON.parse(item.toString());
if (json.msg_type === 'execute_request') {
message.requestId = json.msg_id;
}
if (json.msg_type === 'execute_reply') {
message.responseId = json.msg_id;
}
if (json.status && json.execution_count !== undefined) {
if (json.status === 'ok') {
message.status = true;
if (json.user_expressions) {
for (let key in json.user_expressions) {
if (json.user_expressions[key].status === 'ok') {
message[key] = json.user_expressions[key].data['text/plain'];
}
}
}
} else {
message.status = false;
message.traceback = json.traceback;
}
}
} catch (err) {
}
});
session.dealerMsg = message;
Executor.handleDealerMsg(socketDealer, session);
})
.catch((err) => {
console.error(err);
});
}
/**
* execute codes.
* @param scope the scope name
* @param code codes to be executed
*/
static execute = (scope:string, code: string, user_expressions?: any) => {
const session:Session = Executor.sessions.find((e: any) => e.id === scope);
if (!session) {
throw new Error('no session Found!');
}
const header = session.last_header;
const parent_header = session.parent_header;
session.parent_header = header;
const metadata = {};
const content = {
code: code,
silent: true,
user_expressions: user_expressions || {}
};
session.socketDealer.send(
["","<IDS|MSG>","",
JSON.stringify(header),
JSON.stringify(parent_header),
JSON.stringify(metadata),
JSON.stringify(content)
]
);
return new Promise((resolve, reject) => {
session.timer = setInterval(() => {
if (session.dealerMsg && session.dealerMsg.requestId === header.msg_id) {
session.last_header.msg_id = session.dealerMsg.responseId;
if (session.dealerMsg.status) {
clearInterval(session.timer);
resolve(session.dealerMsg);
} else {
if (Array.isArray(session.dealerMsg.traceback)) {
session.dealerMsg.traceback.forEach((item: string) => {
console.error(item)
})
} else {
console.error('[PYTHON: ]', session.dealerMsg.traceback);
}
clearInterval(session.timer);
reject();
}
}
}, 1);
})
}
}