-
Notifications
You must be signed in to change notification settings - Fork 23
/
worker.ts
489 lines (434 loc) · 13.7 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import type Pyodide from 'pyodide';
import type { DriveFS } from '@jupyterlite/contents';
import type { IPyodideWorkerKernel } from './tokens';
export class PyodideRemoteKernel {
constructor() {
this._initialized = new Promise((resolve, reject) => {
this._initializer = { resolve, reject };
});
}
/**
* Accept the URLs from the host
**/
async initialize(options: IPyodideWorkerKernel.IOptions): Promise<void> {
this._options = options;
if (options.location.includes(':')) {
const parts = options.location.split(':');
this._driveName = parts[0];
this._localPath = parts[1];
} else {
this._driveName = '';
this._localPath = options.location;
}
await this.initRuntime(options);
await this.initFilesystem(options);
await this.initPackageManager(options);
await this.initKernel(options);
await this.initGlobals(options);
this._initializer?.resolve();
}
protected async initRuntime(options: IPyodideWorkerKernel.IOptions): Promise<void> {
const { pyodideUrl, indexUrl } = options;
let loadPyodide: typeof Pyodide.loadPyodide;
if (pyodideUrl.endsWith('.mjs')) {
// note: this does not work at all in firefox
const pyodideModule: typeof Pyodide = await import(
/* webpackIgnore: true */ pyodideUrl
);
loadPyodide = pyodideModule.loadPyodide;
} else {
importScripts(pyodideUrl);
loadPyodide = (self as any).loadPyodide;
}
this._pyodide = await loadPyodide({ indexURL: indexUrl });
}
protected async initPackageManager(
options: IPyodideWorkerKernel.IOptions,
): Promise<void> {
if (!this._options) {
throw new Error('Uninitialized');
}
const { pipliteWheelUrl, disablePyPIFallback, pipliteUrls } = this._options;
await this._pyodide.loadPackage(['micropip']);
// get piplite early enough to impact pyodide dependencies
await this._pyodide.runPythonAsync(`
import micropip
await micropip.install('${pipliteWheelUrl}', keep_going=True)
import piplite.piplite
piplite.piplite._PIPLITE_DISABLE_PYPI = ${disablePyPIFallback ? 'True' : 'False'}
piplite.piplite._PIPLITE_URLS = ${JSON.stringify(pipliteUrls)}
`);
}
protected async initKernel(options: IPyodideWorkerKernel.IOptions): Promise<void> {
// from this point forward, only use piplite (but not %pip)
await this._pyodide.runPythonAsync(`
await piplite.install(['sqlite3'], keep_going=True);
await piplite.install(['ipykernel'], keep_going=True);
await piplite.install(['comm'], keep_going=True);
await piplite.install(['pyodide_kernel'], keep_going=True);
await piplite.install(['ipython'], keep_going=True);
import pyodide_kernel
`);
// cd to the kernel location
if (options.mountDrive && this._localPath) {
await this._pyodide.runPythonAsync(`
import os;
os.chdir("${this._localPath}");
`);
}
}
protected async initGlobals(options: IPyodideWorkerKernel.IOptions): Promise<void> {
const { globals } = this._pyodide;
this._kernel = globals.get('pyodide_kernel').kernel_instance.copy();
this._stdout_stream = globals.get('pyodide_kernel').stdout_stream.copy();
this._stderr_stream = globals.get('pyodide_kernel').stderr_stream.copy();
this._interpreter = this._kernel.interpreter.copy();
this._interpreter.send_comm = this.sendComm.bind(this);
}
/**
* Setup custom Emscripten FileSystem
*/
protected async initFilesystem(
options: IPyodideWorkerKernel.IOptions,
): Promise<void> {
if (options.mountDrive) {
const mountpoint = '/drive';
const { FS, PATH, ERRNO_CODES } = this._pyodide;
const { baseUrl } = options;
const { DriveFS } = await import('@jupyterlite/contents');
const driveFS = new DriveFS({
FS,
PATH,
ERRNO_CODES,
baseUrl,
driveName: this._driveName,
mountpoint,
});
FS.mkdir(mountpoint);
FS.mount(driveFS, {}, mountpoint);
FS.chdir(mountpoint);
this._driveFS = driveFS;
}
}
/**
* Recursively convert a Map to a JavaScript object
* @param obj A Map, Array, or other object to convert
*/
mapToObject(obj: any) {
const out: any = obj instanceof Array ? [] : {};
obj.forEach((value: any, key: string) => {
out[key] =
value instanceof Map || value instanceof Array
? this.mapToObject(value)
: value;
});
return out;
}
/**
* Format the response from the Pyodide evaluation.
*
* @param res The result object from the Pyodide evaluation
*/
formatResult(res: any): any {
if (!(res instanceof this._pyodide.ffi.PyProxy)) {
return res;
}
// TODO: this is a bit brittle
const m = res.toJs();
const results = this.mapToObject(m);
return results;
}
/**
* Makes sure pyodide is ready before continuing, and cache the parent message.
*/
async setup(parent: any): Promise<void> {
await this._initialized;
this._kernel._parent_header = this._pyodide.toPy(parent);
}
/**
* Execute code with the interpreter.
*
* @param content The incoming message with the code to execute.
*/
async execute(content: any, parent: any) {
await this.setup(parent);
const publishExecutionResult = (
prompt_count: any,
data: any,
metadata: any,
): void => {
const bundle = {
execution_count: prompt_count,
data: this.formatResult(data),
metadata: this.formatResult(metadata),
};
postMessage({
parentHeader: this.formatResult(this._kernel._parent_header)['header'],
bundle,
type: 'execute_result',
});
};
const publishExecutionError = (ename: any, evalue: any, traceback: any): void => {
const bundle = {
ename: ename,
evalue: evalue,
traceback: traceback,
};
postMessage({
parentHeader: this.formatResult(this._kernel._parent_header)['header'],
bundle,
type: 'execute_error',
});
};
const clearOutputCallback = (wait: boolean): void => {
const bundle = {
wait: this.formatResult(wait),
};
postMessage({
parentHeader: this.formatResult(this._kernel._parent_header)['header'],
bundle,
type: 'clear_output',
});
};
const displayDataCallback = (data: any, metadata: any, transient: any): void => {
const bundle = {
data: this.formatResult(data),
metadata: this.formatResult(metadata),
transient: this.formatResult(transient),
};
postMessage({
parentHeader: this.formatResult(this._kernel._parent_header)['header'],
bundle,
type: 'display_data',
});
};
const updateDisplayDataCallback = (
data: any,
metadata: any,
transient: any,
): void => {
const bundle = {
data: this.formatResult(data),
metadata: this.formatResult(metadata),
transient: this.formatResult(transient),
};
postMessage({
parentHeader: this.formatResult(this._kernel._parent_header)['header'],
bundle,
type: 'update_display_data',
});
};
const publishStreamCallback = (name: any, text: any): void => {
const bundle = {
name: this.formatResult(name),
text: this.formatResult(text),
};
postMessage({
parentHeader: this.formatResult(this._kernel._parent_header)['header'],
bundle,
type: 'stream',
});
};
this._stdout_stream.publish_stream_callback = publishStreamCallback;
this._stderr_stream.publish_stream_callback = publishStreamCallback;
this._interpreter.display_pub.clear_output_callback = clearOutputCallback;
this._interpreter.display_pub.display_data_callback = displayDataCallback;
this._interpreter.display_pub.update_display_data_callback =
updateDisplayDataCallback;
this._interpreter.displayhook.publish_execution_result = publishExecutionResult;
this._interpreter.input = this.input.bind(this);
this._interpreter.getpass = this.getpass.bind(this);
const res = await this._kernel.run(content.code);
const results = this.formatResult(res);
if (results['status'] === 'error') {
publishExecutionError(results['ename'], results['evalue'], results['traceback']);
}
return results;
}
/**
* Complete the code submitted by a user.
*
* @param content The incoming message with the code to complete.
*/
async complete(content: any, parent: any) {
await this.setup(parent);
const res = this._kernel.complete(content.code, content.cursor_pos);
const results = this.formatResult(res);
return results;
}
/**
* Inspect the code submitted by a user.
*
* @param content The incoming message with the code to inspect.
*/
async inspect(
content: { code: string; cursor_pos: number; detail_level: 0 | 1 },
parent: any,
) {
await this.setup(parent);
const res = this._kernel.inspect(
content.code,
content.cursor_pos,
content.detail_level,
);
const results = this.formatResult(res);
return results;
}
/**
* Check code for completeness submitted by a user.
*
* @param content The incoming message with the code to check.
*/
async isComplete(content: { code: string }, parent: any) {
await this.setup(parent);
const res = this._kernel.is_complete(content.code);
const results = this.formatResult(res);
return results;
}
/**
* Respond to the commInfoRequest.
*
* @param content The incoming message with the comm target name.
*/
async commInfo(content: any, parent: any) {
await this.setup(parent);
const res = this._kernel.comm_info(content.target_name);
const results = this.formatResult(res);
return {
comms: results,
status: 'ok',
};
}
/**
* Respond to the commOpen.
*
* @param content The incoming message with the comm open.
*/
async commOpen(content: any, parent: any) {
await this.setup(parent);
const res = this._kernel.comm_manager.comm_open(
this._pyodide.toPy(null),
this._pyodide.toPy(null),
this._pyodide.toPy(content),
);
const results = this.formatResult(res);
return results;
}
/**
* Respond to the commMsg.
*
* @param content The incoming message with the comm msg.
*/
async commMsg(content: any, parent: any) {
await this.setup(parent);
const res = this._kernel.comm_manager.comm_msg(
this._pyodide.toPy(null),
this._pyodide.toPy(null),
this._pyodide.toPy(content),
);
const results = this.formatResult(res);
return results;
}
/**
* Respond to the commClose.
*
* @param content The incoming message with the comm close.
*/
async commClose(content: any, parent: any) {
await this.setup(parent);
const res = this._kernel.comm_manager.comm_close(
this._pyodide.toPy(null),
this._pyodide.toPy(null),
this._pyodide.toPy(content),
);
const results = this.formatResult(res);
return results;
}
/**
* Resolve the input request by getting back the reply from the main thread
*
* @param content The incoming message with the reply
*/
async inputReply(content: any, parent: any) {
await this.setup(parent);
this._resolveInputReply(content);
}
/**
* Send a input request to the front-end.
*
* @param prompt the text to show at the prompt
* @param password Is the request for a password?
*/
async sendInputRequest(prompt: string, password: boolean) {
const content = {
prompt,
password,
};
postMessage({
type: 'input_request',
parentHeader: this.formatResult(this._kernel._parent_header)['header'],
content,
});
}
async getpass(prompt: string) {
prompt = typeof prompt === 'undefined' ? '' : prompt;
await this.sendInputRequest(prompt, true);
const replyPromise = new Promise((resolve) => {
this._resolveInputReply = resolve;
});
const result: any = await replyPromise;
return result['value'];
}
async input(prompt: string) {
prompt = typeof prompt === 'undefined' ? '' : prompt;
await this.sendInputRequest(prompt, false);
const replyPromise = new Promise((resolve) => {
this._resolveInputReply = resolve;
});
const result: any = await replyPromise;
return result['value'];
}
/**
* 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 sendComm(type: string, content: any, metadata: any, ident: any, buffers: any) {
postMessage({
type: type,
content: this.formatResult(content),
metadata: this.formatResult(metadata),
ident: this.formatResult(ident),
buffers: this.formatResult(buffers),
parentHeader: this.formatResult(this._kernel._parent_header)['header'],
});
}
/**
* Initialization options.
*/
protected _options: IPyodideWorkerKernel.IOptions | null = null;
/**
* A promise that resolves when all initiaization is complete.
*/
protected _initialized: Promise<void>;
private _initializer: {
reject: () => void;
resolve: () => void;
} | null = null;
protected _pyodide: Pyodide.PyodideInterface = null as any;
/** TODO: real typing */
protected _localPath = '';
protected _driveName = '';
protected _kernel: any;
protected _interpreter: any;
protected _stdout_stream: any;
protected _stderr_stream: any;
protected _resolveInputReply: any;
protected _driveFS: DriveFS | null = null;
}