Add Pyodide worker, Python cell runner and worker client

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-14 22:04:13 +02:00
parent b7abd9f3ca
commit 62c03246cb
4 changed files with 370 additions and 0 deletions
+157
View File
@@ -0,0 +1,157 @@
// Client du worker Python, côté thread principal : seule frontière qui parle à Python.
// Protocole des messages : voir app/js/workers/python-worker.js.
const SIGINT = 2;
// Délai après lequel une interruption qui n'aboutit pas est remplacée par un terminate().
const INTERRUPT_GRACE_MS = 2000;
export class PyodideWorkerClient {
#workerUrl;
#indexURL;
#worker = null;
#interruptView = null;
#interruptible = false;
#ready = null;
#readyHandlers = null;
#pending = new Map();
#nextId = 1;
#graceTimer = null;
/**
* @param {object} options
* @param {string} options.indexURL Dossier de Pyodide vendorisé, avec slash final.
* @param {URL|string} [options.workerUrl] Script du worker.
*/
constructor({ indexURL, workerUrl = new URL('../workers/python-worker.js', import.meta.url) }) {
this.#indexURL = indexURL;
this.#workerUrl = workerUrl;
}
/** Vrai si l'arrêt propre (SharedArrayBuffer) est disponible. */
get interruptible() {
return this.#interruptible;
}
/** Démarre le worker (idempotent). Résout quand Pyodide est prêt. */
start() {
if (!this.#ready) {
this.#ready = this.#spawn();
}
return this.#ready;
}
/**
* Exécute une cellule.
* @param {string} code
* @param {object} [options]
* @param {string[]} [options.collect] Variables à relire après l'exécution.
* @param {(text: string) => void} [options.onStdout]
* @param {(text: string) => void} [options.onStderr]
* @returns {Promise<{ok: boolean, error: object|null, variables: object}>}
*/
async run(code, { collect = [], onStdout = () => {}, onStderr = () => {} } = {}) {
await this.start();
const id = this.#nextId++;
return new Promise((resolve) => {
this.#pending.set(id, { resolve, onStdout, onStderr });
this.#worker.postMessage({ type: 'run_code', id, code, collect });
});
}
/** Vide l'espace de noms Python. */
async reset() {
await this.start();
this.#worker.postMessage({ type: 'reset' });
}
/** Interrompt la cellule en cours (boucle infinie, etc.). Sans effet si rien ne tourne. */
interrupt() {
if (this.#pending.size === 0) {
return;
}
if (!this.#interruptible) {
this.#hardRestart();
return;
}
this.#interruptView[0] = SIGINT;
// Filet de sécurité : si Python ne réagit pas, on repart d'un worker neuf.
clearTimeout(this.#graceTimer);
this.#graceTimer = setTimeout(() => this.#hardRestart(), INTERRUPT_GRACE_MS);
}
/** Arrête définitivement le worker. */
dispose() {
clearTimeout(this.#graceTimer);
this.#worker?.terminate();
this.#worker = null;
this.#ready = null;
this.#failPending();
}
#spawn() {
// SharedArrayBuffer n'existe que si la page est isolée (COOP/COEP).
const canShare = typeof SharedArrayBuffer !== 'undefined' && globalThis.crossOriginIsolated === true;
const buffer = canShare ? new SharedArrayBuffer(1) : null;
this.#interruptView = buffer ? new Uint8Array(buffer) : null;
this.#worker = new Worker(this.#workerUrl, { type: 'module' });
this.#worker.addEventListener('message', (event) => this.#onMessage(event.data));
this.#worker.addEventListener('error', (event) => this.#readyHandlers?.reject(new Error(event.message)));
return new Promise((resolve, reject) => {
this.#readyHandlers = { resolve, reject };
this.#worker.postMessage({ type: 'init', indexURL: this.#indexURL, interruptBuffer: buffer });
});
}
#onMessage(message) {
switch (message.type) {
case 'ready':
this.#interruptible = message.interruptible;
this.#readyHandlers?.resolve({ interruptible: message.interruptible });
break;
case 'init_error':
this.#ready = null;
this.#readyHandlers?.reject(new Error(message.message));
break;
case 'stdout':
this.#pending.get(message.id)?.onStdout(message.text);
break;
case 'stderr':
this.#pending.get(message.id)?.onStderr(message.text);
break;
case 'result': {
const entry = this.#pending.get(message.id);
if (entry) {
this.#pending.delete(message.id);
const { type, id, ...result } = message;
entry.resolve(result);
}
if (this.#pending.size === 0) {
clearTimeout(this.#graceTimer);
}
break;
}
}
}
/** Termine le worker, rejoue les cellules en attente comme interrompues, puis le recrée. */
#hardRestart() {
clearTimeout(this.#graceTimer);
this.#worker?.terminate();
this.#failPending();
// L'espace de noms Python est perdu : le prochain run() repart de zéro.
this.#ready = null;
this.#worker = null;
this.#interruptible = false;
this.start().catch(() => {});
}
#failPending() {
const error = { type: 'KeyboardInterrupt', message: '', lineno: null, traceback: 'KeyboardInterrupt' };
for (const { resolve } of this.#pending.values()) {
resolve({ ok: false, error, variables: {} });
}
this.#pending.clear();
}
}
+127
View File
@@ -0,0 +1,127 @@
// Worker du moteur Python : charge Pyodide (vendorisé) et exécute le code des cellules.
//
// Protocole (messages entrants) :
// { type: 'init', indexURL, interruptBuffer? } charge Pyodide ; répond 'ready' ou 'init_error'
// { type: 'run_code', id, code, collect? } exécute une cellule ; répond 'result'
// { type: 'reset' } vide l'espace de noms Python
//
// Messages sortants :
// { type: 'ready', interruptible }
// { type: 'init_error', message }
// { type: 'stdout' | 'stderr', id, text } flux brut, au fil de l'exécution
// { type: 'result', id, ok, error, variables } error = { type, message, lineno, traceback }
//
// Interruption : pas de message 'interrupt'. Pendant qu'une cellule tourne, le worker est
// occupé et ne lirait pas ses messages ; le client écrit donc 2 (SIGINT) directement dans le
// SharedArrayBuffer fourni à 'init'. Python lève alors KeyboardInterrupt dans la cellule.
const SIGINT = 2;
class PythonWorker {
#pyodide = null;
#runner = null;
#interruptView = null;
#currentId = null;
#ready = null;
constructor() {
self.addEventListener('message', (event) => this.#onMessage(event.data));
}
#onMessage(message) {
switch (message.type) {
case 'init':
this.#ready = this.#init(message);
break;
case 'run_code':
this.#run(message);
break;
case 'reset':
this.#reset();
break;
}
}
async #init({ indexURL, interruptBuffer }) {
try {
// Import dynamique : le worker est de type module, Pyodide est servi en local (COEP).
const { loadPyodide } = await import(`${indexURL}pyodide.mjs`);
this.#pyodide = await loadPyodide({ indexURL });
// La sortie arrive en octets bruts : on garde les retours à la ligne exacts,
// indispensables pour le test stdout_equals.
this.#pyodide.setStdout({ write: (bytes) => this.#emit('stdout', bytes) });
this.#pyodide.setStderr({ write: (bytes) => this.#emit('stderr', bytes) });
// input() n'est pas supporté en synchrone : lecture immédiate de fin de fichier.
this.#pyodide.setStdin({ stdin: () => null });
const source = await (await fetch(new URL('../../python/pyquest_runner.py', import.meta.url))).text();
this.#pyodide.FS.mkdirTree('/pyquest');
this.#pyodide.FS.writeFile('/pyquest/pyquest_runner.py', source);
this.#pyodide.runPython("import sys; sys.path.insert(0, '/pyquest')");
this.#runner = this.#pyodide.pyimport('pyquest_runner');
// Sans SharedArrayBuffer (page non isolée), pas d'interruption propre :
// le client doit alors se rabattre sur worker.terminate().
let interruptible = false;
if (interruptBuffer instanceof SharedArrayBuffer) {
this.#interruptView = new Uint8Array(interruptBuffer);
this.#pyodide.setInterruptBuffer(this.#interruptView);
interruptible = true;
}
self.postMessage({ type: 'ready', interruptible });
} catch (error) {
self.postMessage({ type: 'init_error', message: String(error?.message ?? error) });
throw error;
}
}
#emit(stream, bytes) {
// `stream: true` gère les caractères UTF-8 coupés entre deux écritures.
const decoder = this.#decoders[stream];
const text = decoder.decode(bytes, { stream: true });
if (text !== '') {
self.postMessage({ type: stream, id: this.#currentId, text });
}
return bytes.length;
}
#decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
async #run({ id, code, collect = [] }) {
try {
await this.#ready;
} catch {
self.postMessage({ type: 'result', id, ok: false, variables: {}, error: this.#internalError('Pyodide not ready') });
return;
}
this.#currentId = id;
// Remet le tampon à zéro : une interruption tardive ne doit pas tuer la cellule suivante.
if (this.#interruptView) {
this.#interruptView[0] = 0;
}
try {
const raw = this.#runner.run_cell(code, JSON.stringify(collect));
self.postMessage({ type: 'result', id, ...JSON.parse(raw) });
} catch (error) {
// Erreur hors du code de l'apprenant (bug du runner ou de Pyodide).
self.postMessage({ type: 'result', id, ok: false, variables: {}, error: this.#internalError(error) });
} finally {
if (this.#interruptView) {
this.#interruptView[0] = 0;
}
this.#currentId = null;
}
}
#reset() {
this.#ready?.then(() => this.#runner.reset_namespace()).catch(() => {});
}
#internalError(error) {
const message = String(error?.message ?? error);
return { type: 'InternalError', message, lineno: null, traceback: message };
}
}
new PythonWorker();
+86
View File
@@ -0,0 +1,86 @@
"""Exécuteur de cellules PyQuest.
Chargé dans Pyodide par le worker. Compile et exécute le code de l'apprenant dans un espace de
noms persistant (comme un notebook), puis renvoie un résultat structuré sous forme de JSON.
"""
from __future__ import annotations
import json
import linecache
import math
import traceback
from typing import Any
CELL_FILENAME = "<cell>"
_namespace: dict[str, Any] = {}
def reset_namespace() -> None:
"""Repart d'un espace de noms vierge (changement de niveau, bouton « Recommencer »)."""
_namespace.clear()
_namespace["__name__"] = "__main__"
def _describe(value: Any) -> dict[str, Any]:
"""Décrit une valeur : nom du type, repr, et valeur JSON si elle est « simple »."""
description: dict[str, Any] = {
"type": type(value).__name__,
"repr": repr(value),
"value": None,
}
if isinstance(value, float) and not math.isfinite(value):
return description
if value is None or isinstance(value, (str, int, float, bool)):
description["value"] = value
return description
def _error_info(exc: BaseException, code: str) -> dict[str, Any]:
"""Construit la description d'une erreur sans exposer les cadres internes du runner."""
# Le premier cadre est celui de run_cell lui-même : on l'écarte.
tb = exc.__traceback__.tb_next if exc.__traceback__ else None
lineno: int | None = None
if isinstance(exc, SyntaxError):
lineno = exc.lineno
else:
for frame in traceback.extract_tb(tb):
if frame.filename == CELL_FILENAME:
lineno = frame.lineno
return {
"type": type(exc).__name__,
"message": str(exc),
"lineno": lineno,
"traceback": "".join(traceback.format_exception(type(exc), exc, tb)),
}
def run_cell(code: str, collect_json: str = "[]") -> str:
"""Exécute `code` et renvoie un JSON : {ok, error, variables}.
`collect_json` est une liste JSON de noms de variables à relire après l'exécution.
"""
collect: list[str] = json.loads(collect_json)
error: dict[str, Any] | None = None
# Permet aux tracebacks d'afficher la ligne de code fautive.
linecache.cache[CELL_FILENAME] = (
len(code),
None,
code.splitlines(keepends=True),
CELL_FILENAME,
)
try:
compiled = compile(code, CELL_FILENAME, "exec")
exec(compiled, _namespace)
except BaseException as exc: # noqa: BLE001 - KeyboardInterrupt et SystemExit inclus
error = _error_info(exc, code)
variables = {
name: _describe(_namespace[name]) for name in collect if name in _namespace
}
return json.dumps({"ok": error is None, "error": error, "variables": variables})
reset_namespace()