Refactor how py-script are executed, kill scriptQueue store, introduce pyExec (#881)

Yet another refactoring to untangle the old mess.
Highlights:

base.ts, pyscript.ts and pyrepl.ts were a tangled mess of code, in which each of them interacted with the others in non-obvious ways. Now PyScript is no longer a subclass of BaseEvalElement and it is much simpler. I removed code for handling the attributes std-out and std-err because they are no longer needed with the new display() logic.

The logic for executing python code is now in pyexec.ts: so we are decoupling the process of "finding" the python code (handled by the py-script web component) and the logic to actually execute it. This has many advantages, including the fact that it will be more easily usable by other components (e.g. pyrepl). Also, note that it's called pyexec and not pyeval: in the vast majority of cases in Python you have statements to execute, and almost never expressions to evaluate.

I killed the last remaining global store, scriptQueue tada. As a bonus effect, now we automatically do the correct thing when a <py-script> tag is dynamically added to the DOM (I added a test for it). I did not remove svelte from packages.json, because I don't fully understand the implications: there are various options which mention svelte in rollup.js and tsconfig.json, so it's probably better to kill it in its own PR.

pyexec.ts is also responsible of handling the default target for display() and correct handling/visualization of exceptions. I fixed/improved/added display/output tests in the process.
I also found a problem though, see issue #878, so I improved the test and marked it as xfail.

I removed BaseEvalElement as the superclass of most components. Now the only class which inherits from it is PyRepl. In a follow-up PR, I plan to merge them into a single class and do more cleanup.

During the refactoring, I killed guidGenerator: now instead of generating random py-* IDs which are very hard to read for humans, we generated py-internal-X IDs, where X is 0, 1, 2, 3, etc. This makes writing tests and debugging much easier.

I improved a lot our test machinery: it turns out that PR #829 broke the ability to use/view sourcemaps inside the playwright browser (at least on my machine).
For some reason chromium is unable to find sourcemaps if you use playwrights internal routing. So I reintroduced the http_server fixture which was removed by that PR, and added a pytest option --no-fake-server to use it instead, useful for debugging. By default we are still using the fakeserver though (which is faster and parallelizable).

Similarly, I added --dev which implies --headed and also automatically open chrome dev tools.
This commit is contained in:
Antonio Cuni
2022-10-23 23:31:50 +02:00
committed by GitHub
parent d9b8b48972
commit f9194cc833
23 changed files with 379 additions and 389 deletions

View File

@@ -3,23 +3,16 @@ import './styles/pyscript_base.css';
import { loadConfigFromElement } from './pyconfig';
import type { AppConfig } from './pyconfig';
import type { Runtime } from './runtime';
import { PyScript, initHandlers, mountElements } from './components/pyscript';
import { make_PyScript, initHandlers, mountElements } from './components/pyscript';
import { PyLoader } from './components/pyloader';
import { PyodideRuntime } from './pyodide';
import { getLogger } from './logger';
import { scriptsQueue } from './stores';
import { handleFetchError, showError, globalExport } from './utils'
import { createCustomElements } from './components/elements';
const logger = getLogger('pyscript/main');
let scriptsQueue_: PyScript[];
scriptsQueue.subscribe((value: PyScript[]) => {
scriptsQueue_ = value;
});
/* High-level overview of the lifecycle of a PyScript App:
@@ -37,7 +30,8 @@ scriptsQueue.subscribe((value: PyScript[]) => {
6. setup the environment, install packages
7. run user scripts
7. connect the py-script web component. This causes the execution of all the
user scripts
8. initialize the rest of web components such as py-button, py-repl, etc.
@@ -58,11 +52,11 @@ class PyScriptApp {
config: AppConfig;
loader: PyLoader;
runtime: Runtime;
PyScript: any; // XXX would be nice to have a more precise type for the class itself
// lifecycle (1)
main() {
this.loadConfig();
customElements.define('py-script', PyScript);
this.showLoader();
this.loadRuntime();
}
@@ -129,7 +123,6 @@ class PyScriptApp {
//
// Invariant: this.config and this.loader are set and available.
async afterRuntimeLoad(runtime: Runtime): Promise<void> {
// XXX what is the JS/TS standard way of doing asserts?
console.assert(this.config !== undefined);
console.assert(this.loader !== undefined);
@@ -195,11 +188,53 @@ class PyScriptApp {
// lifecycle (7)
executeScripts(runtime: Runtime) {
for (const script of scriptsQueue_) {
void script.evaluate(runtime);
}
scriptsQueue.set([]);
this.register_importmap(runtime);
this.PyScript = make_PyScript(runtime);
customElements.define('py-script', this.PyScript);
}
async register_importmap(runtime: Runtime) {
// make importmap ES modules available from python using 'import'.
//
// XXX: this code can probably be improved because errors are silently
// ignored. Moreover at the time of writing we don't really have a test
// for it and this functionality is used only by the d3 example. We
// might want to rethink the whole approach at some point. E.g., maybe
// we should move it to py-config?
//
// Moreover, it's also wrong because it's async and currently we don't
// await the module to be fully registered before executing the code
// inside py-script. It's also unclear whether we want to wait or not
// (or maybe only wait only if we do an actual 'import'?)
for (const node of document.querySelectorAll("script[type='importmap']")) {
const importmap = (() => {
try {
return JSON.parse(node.textContent);
} catch {
return null;
}
})();
if (importmap?.imports == null) continue;
for (const [name, url] of Object.entries(importmap.imports)) {
if (typeof name != 'string' || typeof url != 'string') continue;
let exports: object;
try {
// XXX: pyodide doesn't like Module(), failing with
// "can't read 'name' of undefined" at import time
exports = { ...(await import(url)) };
} catch {
logger.warn(`failed to fetch '${url}' for '${name}'`);
continue;
}
runtime.registerJsModule(name, exports);
}
}
}
}
function pyscript_get_config() {