Add real input() support via SharedArrayBuffer and level 03

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-14 22:43:39 +02:00
parent cd59bbbf5f
commit 5a41231861
20 changed files with 595 additions and 35 deletions
+47 -4
View File
@@ -2,6 +2,11 @@
// Protocole des messages : voir app/js/workers/python-worker.js.
const SIGINT = 2;
// Zone de réponse à input() : 8 octets d'en-tête (état, longueur) puis le texte UTF-8.
const INPUT_HEADER_BYTES = 8;
const INPUT_MAX_BYTES = 4096;
const INPUT_STATE_ANSWER = 1;
const INPUT_STATE_EOF = 2;
// Délai après lequel une interruption qui n'aboutit pas est remplacée par un terminate().
const INTERRUPT_GRACE_MS = 2000;
@@ -10,6 +15,8 @@ export class PyodideWorkerClient {
#indexURL;
#worker = null;
#interruptView = null;
#inputControl = null;
#inputData = null;
#interruptible = false;
#ready = null;
#readyHandlers = null;
@@ -47,14 +54,17 @@ export class PyodideWorkerClient {
* @param {string[]} [options.collect] Variables à relire après l'exécution.
* @param {(text: string) => void} [options.onStdout]
* @param {(text: string) => void} [options.onStderr]
* @param {(prompt: string) => Promise<string|null>} [options.onInput] Répond à input() ;
* null ou absent = fin de saisie (EOFError côté Python).
* @param {boolean} [options.isolated] Exécute sur une copie de l'état, sans le modifier.
* @returns {Promise<{ok: boolean, error: object|null, variables: object}>}
*/
async run(code, { collect = [], onStdout = () => {}, onStderr = () => {} } = {}) {
async run(code, { collect = [], onStdout = () => {}, onStderr = () => {}, onInput = null, isolated = false } = {}) {
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 });
this.#pending.set(id, { resolve, onStdout, onStderr, onInput });
this.#worker.postMessage({ type: 'run_code', id, code, collect, isolated });
});
}
@@ -93,6 +103,9 @@ export class PyodideWorkerClient {
const canShare = typeof SharedArrayBuffer !== 'undefined' && globalThis.crossOriginIsolated === true;
const buffer = canShare ? new SharedArrayBuffer(1) : null;
this.#interruptView = buffer ? new Uint8Array(buffer) : null;
const inputBuffer = canShare ? new SharedArrayBuffer(INPUT_HEADER_BYTES + INPUT_MAX_BYTES) : null;
this.#inputControl = inputBuffer ? new Int32Array(inputBuffer, 0, 2) : null;
this.#inputData = inputBuffer ? new Uint8Array(inputBuffer, INPUT_HEADER_BYTES) : null;
this.#worker = new Worker(this.#workerUrl, { type: 'module' });
this.#worker.addEventListener('message', (event) => this.#onMessage(event.data));
@@ -100,7 +113,7 @@ export class PyodideWorkerClient {
return new Promise((resolve, reject) => {
this.#readyHandlers = { resolve, reject };
this.#worker.postMessage({ type: 'init', indexURL: this.#indexURL, interruptBuffer: buffer });
this.#worker.postMessage({ type: 'init', indexURL: this.#indexURL, interruptBuffer: buffer, inputBuffer });
});
}
@@ -120,6 +133,9 @@ export class PyodideWorkerClient {
case 'stderr':
this.#pending.get(message.id)?.onStderr(message.text);
break;
case 'input_request':
this.#answerInput(message);
break;
case 'result': {
const entry = this.#pending.get(message.id);
if (entry) {
@@ -135,6 +151,33 @@ export class PyodideWorkerClient {
}
}
/** Transmet la réponse de l'apprenant au worker bloqué dans input(). */
async #answerInput({ id, prompt }) {
const worker = this.#worker;
const handler = this.#pending.get(id)?.onInput;
let answer = null;
try {
answer = handler ? await handler(prompt) : null;
} catch {
answer = null;
}
// Le worker a pu être remplacé (interruption forcée) pendant l'attente.
if (worker !== this.#worker || !this.#inputControl) {
return;
}
let length = 0;
if (answer !== null) {
// encodeInto refuse une vue sur SharedArrayBuffer (navigateurs) : on encode d'abord en
// mémoire locale, en ne gardant que des caractères entiers, puis on recopie.
const local = new Uint8Array(INPUT_MAX_BYTES);
length = new TextEncoder().encodeInto(answer, local).written;
this.#inputData.set(local.subarray(0, length));
}
Atomics.store(this.#inputControl, 1, length);
Atomics.store(this.#inputControl, 0, answer === null ? INPUT_STATE_EOF : INPUT_STATE_ANSWER);
Atomics.notify(this.#inputControl, 0);
}
/** Termine le worker, rejoue les cellules en attente comme interrompues, puis le recrée. */
#hardRestart() {
clearTimeout(this.#graceTimer);