forked from jupyterlite/jupyterlite
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathworker.ts
297 lines (260 loc) · 6.3 KB
/
worker.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/**
* Store the kernel and interpreter instances.
*/
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
let kernel: any;
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
let interpreter: any;
/**
* Load Pyodided and initialize the interpreter.
*/
async function loadPyodideAndPackages() {
// new in 0.17.0 indexURL must be provided
await loadPyodide({ indexURL });
await pyodide.loadPackage(['matplotlib']);
await pyodide.runPythonAsync(`
import micropip
await micropip.install([
'traitlets',
'${_widgetsnbextensionWheelUrl}',
'${_nbformatWheelUrl}',
'${_ipykernelWheelUrl}'
])
await micropip.install([
'${_pyoliteWheelUrl}'
]);
import pyolite
`);
kernel = pyodide.globals.get('pyolite').kernel_instance;
interpreter = kernel.interpreter;
interpreter.send_comm = sendComm;
const version = pyodide.globals.get('pyolite').__version__;
console.log('Pyolite kernel initialized, version', version);
}
/**
* Recursively convert a Map to a JavaScript object
* @param The Map object to convert
*/
function mapToObject(obj: any) {
const out: any = obj instanceof Array ? [] : {};
obj.forEach((value: any, key: string) => {
out[key] =
value instanceof Map || value instanceof Array ? mapToObject(value) : value;
});
return out;
}
/**
* Format the response from the Pyodide evaluation.
*
* @param res The result object from the Pyodide evaluation
*/
function formatResult(res: any): any {
if (!pyodide.isPyProxy(res)) {
return res;
}
// TODO: this is a bit brittle
const m = res.toJs();
const results = mapToObject(m);
return results;
}
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
const pyodideReadyPromise = loadPyodideAndPackages();
/**
* Send a comm message to the front-end.
*
* @param type The type of the comm message.
* @param content The content.
* @param metadata The metadata.
* @param ident The ident.
* @param buffers The binary buffers.
*/
async function sendComm(
type: string,
content: any,
metadata: any,
ident: any,
buffers: any
) {
postMessage({
type: type,
content: formatResult(content),
metadata: formatResult(metadata),
ident: formatResult(ident),
buffers: formatResult(buffers)
});
}
/**
* Execute code with the interpreter.
*
* @param content The incoming message with the code to execute.
*/
async function execute(content: any) {
const stdoutCallback = (stdout: string): void => {
postMessage({
parentHeader: content.parentHeader,
stdout,
type: 'stdout'
});
};
const stderrCallback = (stderr: string): void => {
postMessage({
parentHeader: content.parentHeader,
stderr,
type: 'stderr'
});
};
// TODO: support multiple
const displayCallback = (res: any): void => {
const bundle = formatResult(res);
postMessage({
parentHeader: content.parentHeader,
bundle,
type: 'display'
});
};
interpreter.stdout_callback = stdoutCallback;
interpreter.stderr_callback = stderrCallback;
kernel.display_publisher.display_callback = displayCallback;
let res;
try {
res = await interpreter.run(content.code);
} catch (error) {
postMessage({
parentheader: content.parentheader,
type: 'error',
error
});
return;
}
const reply = {
parentheader: content.parentheader,
type: 'results'
};
if (!res) {
postMessage(reply);
return;
}
try {
const results = formatResult(res);
postMessage({
...reply,
results
});
} catch (e) {
postMessage(reply);
}
}
/**
* Complete the code submitted by a user.
*
* @param content The incoming message with the code to complete.
*/
function complete(content: any) {
const res = interpreter.complete(content.code.substring(0, content.cursor_pos));
const results = formatResult(res);
const reply = {
parentheader: content.parentheader,
type: 'results',
results: {
matches: results[0],
cursor_start: results[1],
cursor_end: content.cursor_pos,
status: 'ok'
}
};
postMessage(reply);
}
/**
* Respond to the commInfoRequest.
*
* @param content The incoming message with the comm target name.
*/
function commInfo(content: any) {
const res = kernel.comm_info(content.target_name);
const results = formatResult(res);
const reply = {
parentheader: content.parentheader,
type: 'results',
results: {
comms: results,
status: 'ok'
}
};
postMessage(reply);
}
/**
* Respond to the commOpen.
*
* @param content The incoming message with the comm open.
*/
function commOpen(content: any) {
const res = kernel.comm_manager.comm_open(pyodide.toPy(content));
const results = formatResult(res);
const reply = {
parentheader: content.parentheader,
type: 'results',
results
};
postMessage(reply);
}
/**
* Respond to the commMsg.
*
* @param content The incoming message with the comm msg.
*/
function commMsg(content: any) {
const res = kernel.comm_manager.comm_msg(pyodide.toPy(content));
const results = formatResult(res);
const reply = {
parentheader: content.parentheader,
type: 'results',
results
};
postMessage(reply);
}
/**
* Respond to the commClose.
*
* @param content The incoming message with the comm close.
*/
function commClose(content: any) {
const res = kernel.comm_manager.comm_close(pyodide.toPy(content));
const results = formatResult(res);
const reply = {
parentheader: content.parentheader,
type: 'results',
results
};
postMessage(reply);
}
/**
* Process a message sent to the worker.
*
* @param event The message event to process
*/
self.onmessage = async (event: MessageEvent): Promise<void> => {
await pyodideReadyPromise;
const data = event.data;
const messageType = data.type;
const messageContent = data.data;
switch (messageType) {
case 'execute-request':
console.log('Perform execution inside worker', data);
return execute(messageContent);
case 'complete-request':
return complete(messageContent);
case 'comm-info-request':
return commInfo(messageContent);
case 'comm-open':
return commOpen(messageContent);
case 'comm-msg':
return commMsg(messageContent);
case 'comm-close':
return commClose(messageContent);
default:
break;
}
};