Spaces:
Running
Running
File size: 2,157 Bytes
e43bb93 |
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 |
import PyodideWorker from '$lib/pyodide/pyodideKernel.worker?worker';
export type CellState = {
id: string;
status: 'idle' | 'running' | 'completed' | 'error';
result: any;
stdout: string;
stderr: string;
};
export class PyodideKernel {
private worker: Worker;
private listeners: Map<string, (data: any) => void>;
constructor() {
this.worker = new PyodideWorker();
this.listeners = new Map();
// Listen to messages from the worker
this.worker.onmessage = (event) => {
const { type, id, ...data } = event.data;
if ((type === 'stdout' || type === 'stderr') && this.listeners.has(id)) {
this.listeners.get(id)?.({ type, id, ...data });
} else if (type === 'result' && this.listeners.has(id)) {
this.listeners.get(id)?.({ type, id, ...data });
// Remove the listener once the result is delivered
this.listeners.delete(id);
} else if (type === 'kernelState') {
this.listeners.forEach((listener) => listener({ type, ...data }));
}
};
// Initialize the worker
this.worker.postMessage({ type: 'initialize' });
}
async execute(id: string, code: string): Promise<CellState> {
return new Promise((resolve, reject) => {
// Set up the listener for streaming and execution result
const state: CellState = {
id,
status: 'running',
result: null,
stdout: '',
stderr: ''
};
this.listeners.set(id, (data) => {
if (data.type === 'stdout') {
state.stdout += data.message;
} else if (data.type === 'stderr') {
state.stderr += data.message;
} else if (data.type === 'result') {
// Final result
const { state: finalState } = data;
resolve(finalState);
}
});
// Send execute request to the worker
this.worker.postMessage({ type: 'execute', id, code });
});
}
async getState() {
return new Promise<Record<string, CellState>>((resolve) => {
this.worker.postMessage({ type: 'getState' });
this.listeners.set('kernelState', (data) => {
if (data.type === 'kernelState') {
resolve(data.state);
}
});
});
}
terminate() {
this.worker.postMessage({ type: 'terminate' });
this.worker.terminate();
}
}
|