From 3fb27518a3e820d799f3a6fb31bdd86c38880bfb Mon Sep 17 00:00:00 2001 From: DerThorsten Date: Wed, 25 Nov 2026 14:57:54 +0100 Subject: [PATCH 1/3] 4.0.0: run on the JavaScript of the pyjs npm package (pyjs >= 6) The runner broke with pyjs 5.2 (the classic init API it used is gone). It now drives pyjs through the npm package's JavaScript (`initializePyjsRuntime`), with the same surface API (`pyjs_code_runner run script ...`, `run(...)`), so pytester keeps working unchanged. Where pyjs and python come from: - `--conda-env`: an emscripten-forge env with pyjs >= 6. Its runtime and the npm JavaScript (lib_js/pyjs/npm, shipped by the pyjs conda package) are used and the env is packed with empack: exactly what is installed runs, e.g. a python, pyjs and package that were just built locally. - `--pyjs-npm `: the npm package with its own runtime and environment; extra conda packages via `--package` (repeatable), `--arch`. Simplified: one browser backend (playwright, main thread or worker, stdlib http server; web/index.html, worker.js, run.js) instead of the per-backend html / js / servers; the node backend and appdirs are gone. Uncaught errors and unhandled rejections in the page end the run instead of hanging. Co-Authored-By: Claude Opus 5.5 --- README.md | 23 +- pyjs_code_runner/backend/backend.py | 17 +- pyjs_code_runner/backend/backend_base.py | 15 - pyjs_code_runner/backend/browser.py | 108 +++++++ .../backend/browser_main/__init__.py | 0 .../backend/browser_main/browser_main.py | 96 ------ .../backend/browser_main/server.py | 37 --- .../backend/browser_worker/__init__.py | 0 .../backend/browser_worker/browser_worker.py | 151 --------- pyjs_code_runner/backend/node/__init__.py | 0 pyjs_code_runner/backend/node/node.py | 104 ------ pyjs_code_runner/backend/node/node_main.js | 112 ------- pyjs_code_runner/cli/run.py | 54 +++- pyjs_code_runner/constants.py | 7 - pyjs_code_runner/get_cache_dir.py | 8 +- pyjs_code_runner/html/__init__.py | 0 pyjs_code_runner/html/browser_main.html | 13 - pyjs_code_runner/html/browser_worker.html | 48 --- pyjs_code_runner/js/__init__.py | 0 pyjs_code_runner/js/utils.js | 99 ------ pyjs_code_runner/js/worker.js | 1 - pyjs_code_runner/run.py | 298 +++++++++++------- pyjs_code_runner/version.py | 2 +- pyjs_code_runner/web/index.html | 38 +++ pyjs_code_runner/web/run.js | 72 +++++ pyjs_code_runner/web/worker.js | 16 + pyjs_code_runner/work_dir_context.py | 12 - pyproject.toml | 1 - test/conftest.py | 8 +- 29 files changed, 490 insertions(+), 850 deletions(-) delete mode 100644 pyjs_code_runner/backend/backend_base.py create mode 100644 pyjs_code_runner/backend/browser.py delete mode 100644 pyjs_code_runner/backend/browser_main/__init__.py delete mode 100644 pyjs_code_runner/backend/browser_main/browser_main.py delete mode 100644 pyjs_code_runner/backend/browser_main/server.py delete mode 100644 pyjs_code_runner/backend/browser_worker/__init__.py delete mode 100644 pyjs_code_runner/backend/browser_worker/browser_worker.py delete mode 100644 pyjs_code_runner/backend/node/__init__.py delete mode 100644 pyjs_code_runner/backend/node/node.py delete mode 100644 pyjs_code_runner/backend/node/node_main.js delete mode 100644 pyjs_code_runner/html/__init__.py delete mode 100644 pyjs_code_runner/html/browser_main.html delete mode 100644 pyjs_code_runner/html/browser_worker.html delete mode 100644 pyjs_code_runner/js/__init__.py delete mode 100644 pyjs_code_runner/js/utils.js delete mode 100644 pyjs_code_runner/js/worker.js create mode 100644 pyjs_code_runner/web/index.html create mode 100644 pyjs_code_runner/web/run.js create mode 100644 pyjs_code_runner/web/worker.js delete mode 100644 pyjs_code_runner/work_dir_context.py diff --git a/README.md b/README.md index 563522b..3266b08 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,22 @@ A driver to run python code in a wasm environment, almost like running vanilla python code. -## Motivation - -Debugging, experimenting and testing python code from a dedicated conda environment -in browser environment is a complex process with a lot of (complicated) steps. - -* create the environment for emscripten -* pack the environemtn +## How it works + +The script runs in a browser (playwright, main thread or web worker), driven by +the JavaScript of the pyjs npm package. Where pyjs and python come from: + +* **a conda env** (`--conda-env`): an emscripten-forge env with **pyjs >= 6**. + Its runtime and the npm JavaScript (`lib_js/pyjs/npm`, shipped by the pyjs + conda package) are used, and the env is packed with empack. So exactly what + is installed there runs, e.g. a python, pyjs and a package that were just + built locally. This is what `pytester` (emscripten-forge recipe tests) uses. +* **an npm package** (`--pyjs-npm @scope/pyjs@6.0.0`, or a local package + directory / `.tgz`): its own runtime and environment; extra conda packages + with `--package ` (repeatable) are installed at runtime. + +Directories are mounted with `--mount :`. +pyjs < 6 envs are not supported anymore (use pyjs-code-runner 3.x). ## Installation diff --git a/pyjs_code_runner/backend/backend.py b/pyjs_code_runner/backend/backend.py index f2acd90..4d6c3ca 100644 --- a/pyjs_code_runner/backend/backend.py +++ b/pyjs_code_runner/backend/backend.py @@ -90,17 +90,10 @@ def ensure_playwright_imports(): def get_backend_cls(backend_type): if backend_type == BackendType.node: - raise RuntimeError( - "the node backend is currently disabled as its not (yet) working with empack>=3.0.0" - ) - - elif backend_type == BackendType.browser_main: - ensure_playwright_imports() - from .browser_main.browser_main import BrowserMainBackend + raise RuntimeError("the node backend is not supported: use browser-main or browser-worker") + ensure_playwright_imports() + from .browser import BrowserMainBackend, BrowserWorkerBackend + if backend_type == BackendType.browser_main: return BrowserMainBackend - elif backend_type == BackendType.browser_worker: - ensure_playwright_imports() - from .browser_worker.browser_worker import BrowserWorkerBackend - - return BrowserWorkerBackend + return BrowserWorkerBackend diff --git a/pyjs_code_runner/backend/backend_base.py b/pyjs_code_runner/backend/backend_base.py deleted file mode 100644 index 3c9dcef..0000000 --- a/pyjs_code_runner/backend/backend_base.py +++ /dev/null @@ -1,15 +0,0 @@ -from ..constants import JS_DIR, HTML_DIR - - -class BackendBase(object): - def __init__(self, host_work_dir, work_dir, script, async_main): - self.host_work_dir = host_work_dir - self.script = script - self.work_dir = work_dir - self.async_main = async_main - - def js_utils(self): - with open(JS_DIR / "utils.js") as f: - content = f.read() - - return content diff --git a/pyjs_code_runner/backend/browser.py b/pyjs_code_runner/backend/browser.py new file mode 100644 index 0000000..522df63 --- /dev/null +++ b/pyjs_code_runner/backend/browser.py @@ -0,0 +1,108 @@ +"""Run the prepared directory (see run.py) in a browser with playwright: serve +it, open index.html (main thread) or index.html?worker (web worker), print +what the page prints, and wait for its result.""" + +import asyncio +import json +import socket +import threading +from contextlib import closing, contextmanager +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer + +from playwright.async_api import async_playwright + +from .backend import BrowserType, launch_browser + +# how long the page may take (also the timeout of every playwright call that +# waits); recipes with long test suites raise it by patching +# Page.set_default_timeout +TIMEOUT_MS = 4 * 60 * 1000 + + +def find_free_port(): + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: + s.bind(("", 0)) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + return s.getsockname()[1] + + +@contextmanager +def serve(directory, port): + """serve `directory` at http://127.0.0.1: while in the context""" + + class Handler(SimpleHTTPRequestHandler): + # (ES modules / module workers need a JavaScript mime type) + extensions_map = { + **SimpleHTTPRequestHandler.extensions_map, + ".js": "text/javascript", + ".mjs": "text/javascript", + ".wasm": "application/wasm", + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, directory=str(directory), **kwargs) + + def log_message(self, fmt, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", port), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{port}" + finally: + server.shutdown() + thread.join() + + +class BrowserBackend: + """runs the script in the page's main thread (`worker` False) or in a web + worker""" + + worker = False + + def __init__( + self, + host_work_dir, + port=None, + headless=True, + slow_mo=None, + browser=BrowserType.chromium, + ): + self.host_work_dir = host_work_dir + self.port = port if port is not None else find_free_port() + self.headless = headless + self.slow_mo = slow_mo + self.browser = BrowserType(browser) + + def run(self): + with serve(self.host_work_dir, self.port) as url: + page_url = f"{url}/index.html" + ("?worker" if self.worker else "") + result = asyncio.run(self._run(page_url)) + if "error" in result: + raise RuntimeError(f"pyjs-code-runner: {result['error']}") + if result["code"] != 0: + raise RuntimeError(f"return_code != 0 ({result['code']})") + + async def _run(self, page_url): + async with async_playwright() as p: + browser = await launch_browser(p, self.browser, headless=self.headless, slow_mo=self.slow_mo) + try: + page = await browser.new_page() + page.set_default_timeout(TIMEOUT_MS) + page.on("console", lambda message: print(message.text, flush=True)) + page.on("pageerror", lambda error: print(f"page error: {error}", flush=True)) + await page.goto(page_url) + # (the page sets globalThis.result: {code} or {error}) + await page.wait_for_function("() => globalThis.result !== undefined", polling=200) + return json.loads(await page.evaluate("() => JSON.stringify(globalThis.result)")) + finally: + await browser.close() + + +class BrowserMainBackend(BrowserBackend): + worker = False + + +class BrowserWorkerBackend(BrowserBackend): + worker = True diff --git a/pyjs_code_runner/backend/browser_main/__init__.py b/pyjs_code_runner/backend/browser_main/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/pyjs_code_runner/backend/browser_main/browser_main.py b/pyjs_code_runner/backend/browser_main/browser_main.py deleted file mode 100644 index afef30a..0000000 --- a/pyjs_code_runner/backend/browser_main/browser_main.py +++ /dev/null @@ -1,96 +0,0 @@ -import os -import asyncio -from ..backend_base import BackendBase -from ..backend import BrowserType, launch_browser -from ...constants import JS_DIR, HTML_DIR -from .server import server_context, find_free_port -from playwright.async_api import async_playwright -from pathlib import Path -import shutil - - -THIS_DIR = os.path.dirname(os.path.realpath(__file__)) - - -class BrowserMainBackend(BackendBase): - def __init__( - self, - host_work_dir, - work_dir, - script, - async_main, - port, - headless, - slow_mo, - browser=BrowserType.chromium, - ): - super().__init__( - host_work_dir=host_work_dir, - work_dir=work_dir, - script=script, - async_main=async_main, - ) - if port is None: - port = find_free_port() - self.port = port - self.headless = headless - self.slow_mo = slow_mo - self.browser = BrowserType(browser) - - def run(self): - browser_main_html = "browser_main.html" - main = HTML_DIR / browser_main_html - shutil.copyfile(main, self.host_work_dir / browser_main_html) - - with server_context(work_dir=self.host_work_dir, port=self.port) as ( - server, - url, - ): - page_url = f"{url}/{browser_main_html}" - ret = asyncio.run(self.playwright_run_in_main_thread(page_url=page_url)) - if ret != 0: - raise RuntimeError("return_code != 0") - - async def playwright_run_in_main_thread(self, page_url): - async with async_playwright() as p: - browser = await launch_browser( - p, self.browser, headless=self.headless, slow_mo=self.slow_mo - ) - page = await browser.new_page() - await page.goto(page_url) - # n min = n_min * 60 * 1000 ms - n_min = 4 - page.set_default_timeout(n_min * 60 * 1000) - - async def handle_console(msg): - txt = str(msg) - print(txt) - - page.on("console", handle_console) - - # await page.goto(page_url) - status = await page.evaluate( - f"""async () => {{ - - {self.js_utils()} - - - var collected_prints = "" - const print = (text) => {{ - console.log(text) - collected_prints += text; - collected_prints += "\\n"; - }} - - var pyjs = await make_pyjs(print,print, true); - - var r = globalThis.eval_main_script(pyjs, "{self.work_dir}","{self.script}"); - if({int(self.async_main)}){{ - r = r || await run_async_python_main(pyjs); - }} - return r; - - }}""" - ) - return_code = int(status) - return return_code diff --git a/pyjs_code_runner/backend/browser_main/server.py b/pyjs_code_runner/backend/browser_main/server.py deleted file mode 100644 index d59d22d..0000000 --- a/pyjs_code_runner/backend/browser_main/server.py +++ /dev/null @@ -1,37 +0,0 @@ -import socket -import threading - -from contextlib import closing, contextmanager -from http.server import HTTPServer, SimpleHTTPRequestHandler - - -def find_free_port(): - with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: - s.bind(("", 0)) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - return s.getsockname()[1] - - -def start_server(work_dir, port): - class Handler(SimpleHTTPRequestHandler): - def __init__(self, *args, **kwargs): - super().__init__(*args, directory=work_dir, **kwargs) - - def log_message(self, fmt, *args): - return - - httpd = HTTPServer(("127.0.0.1", port), Handler) - - thread = threading.Thread(target=httpd.serve_forever) - thread.start() - return thread, httpd - - -@contextmanager -def server_context(work_dir, port): - thread, server = start_server(work_dir=work_dir, port=port) - try: - yield server, f"http://127.0.0.1:{port}" - finally: - server.shutdown() - thread.join() diff --git a/pyjs_code_runner/backend/browser_worker/__init__.py b/pyjs_code_runner/backend/browser_worker/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/pyjs_code_runner/backend/browser_worker/browser_worker.py b/pyjs_code_runner/backend/browser_worker/browser_worker.py deleted file mode 100644 index 353ceb6..0000000 --- a/pyjs_code_runner/backend/browser_worker/browser_worker.py +++ /dev/null @@ -1,151 +0,0 @@ -import os -import asyncio -from ..backend_base import BackendBase -from ..backend import BrowserType, launch_browser -from ...constants import JS_DIR, HTML_DIR -from ..browser_main.server import server_context, find_free_port -from playwright.async_api import async_playwright -from playwright.async_api import Error as PlaywrightError -from pathlib import Path -import shutil - - -def _is_target_closed_error(e): - # TargetClosedError is not part of playwright's public api (and older - # versions raise a plain Error with a "Target closed" message) - msg = str(e) - return ( - type(e).__name__ == "TargetClosedError" - or "Target closed" in msg - or "has been closed" in msg - ) - - -class BrowserWorkerBackend(BackendBase): - def __init__( - self, - host_work_dir, - work_dir, - script, - async_main, - port, - headless, - slow_mo, - preload_shared_libs=True, - browser=BrowserType.chromium, - ): - super().__init__( - host_work_dir=host_work_dir, - work_dir=work_dir, - script=script, - async_main=async_main, - ) - if port is None: - port = find_free_port() - self.port = port - self.headless = headless - self.slow_mo = slow_mo - self.browser = BrowserType(browser) - self.preload_shared_libs = preload_shared_libs - - def run(self): - # copy html - browser_worker_html = "browser_worker.html" - main = HTML_DIR / browser_worker_html - shutil.copyfile(main, self.host_work_dir / browser_worker_html) - - # copy worker - worker_js = "worker.js" - main = JS_DIR / worker_js - shutil.copyfile(main, self.host_work_dir / worker_js) - - with server_context(work_dir=self.host_work_dir, port=self.port) as ( - server, - url, - ): - page_url = f"{url}/{browser_worker_html}" - ret = asyncio.run(self.playwright_run_in_worker_thread(page_url=page_url)) - if ret != 0: - raise RuntimeError("return_code != 0") - - async def playwright_run_in_worker_thread(self, page_url): - async with async_playwright() as p: - browser = await launch_browser( - p, self.browser, headless=self.headless, slow_mo=self.slow_mo - ) - page = await browser.new_page() - - # n min = n_min * 60 * 1000 ms - n_min = 4 - page.set_default_timeout(n_min * 60 * 1000) - - async def handle_worker(worker): - try: - await self._run_in_worker(worker) - except PlaywrightError as e: - if not _is_target_closed_error(e): - raise - # the page terminates the worker as soon as the worker has - # posted its result (see browser_worker.html), which may - # happen before playwright receives the evaluate result. - # The return code is read from the page below. - pass - - page.on("worker", handle_worker) - - async def handle_console(msg): - txt = str(msg) - if txt.startswith( - "warning: Browser does not support creating object URLs" - ): - pass - else: - print(txt) - - page.on("console", handle_console) - await page.goto(page_url) - await page.wait_for_function("() => globalThis.done") - - test_output = await page.evaluate_handle( - """ - () => - { - return globalThis.test_output - } - """ - ) - return_code = int(str(await test_output.get_property("return_code"))) - return return_code - - async def _run_in_worker(self, worker): - test_output = await worker.evaluate_handle( - f"""async () => - {{ - - {self.js_utils()} - - var collected_prints = "" - const print = (text) => {{ - console.log(text) - collected_prints += text; - collected_prints += "\\n"; - }} - - - var pyjs = await make_pyjs(print, print, {str(self.preload_shared_libs).lower()}); - - var r = eval_main_script(pyjs, "{self.work_dir}","{self.script}"); - if({int(self.async_main)}){{ - r = r || await run_async_python_main(pyjs); - }} - - msg = {{ - return_code : r, - collected_prints : collected_prints - }} - self.postMessage(msg) - return r - }}""" - ) - if int(str(test_output)) != 0: - raise RuntimeError(f"tests failed with return code: {test_output}") diff --git a/pyjs_code_runner/backend/node/__init__.py b/pyjs_code_runner/backend/node/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/pyjs_code_runner/backend/node/node.py b/pyjs_code_runner/backend/node/node.py deleted file mode 100644 index 0278f8c..0000000 --- a/pyjs_code_runner/backend/node/node.py +++ /dev/null @@ -1,104 +0,0 @@ -import subprocess -from pathlib import Path -import os -import shutil -import json -import sys -import shutil -from ..backend_base import BackendBase -from subprocess import Popen, PIPE, STDOUT -import textwrap - -THIS_DIR = os.path.dirname(os.path.realpath(__file__)) - - -class NodeBackend(BackendBase): - def __init__(self, host_work_dir, work_dir, script, async_main, node_binary): - super().__init__( - host_work_dir=host_work_dir, - work_dir=work_dir, - script=script, - async_main=async_main, - ) - if node_binary is None: - shutil_node_binary = shutil.which("node") - if shutil_node_binary is None: - raise RuntimeError( - textwrap.dedent( - """\n - pyjs-code-runner error: - - * Cannot find node - - - to use the node backend `node`/`nodejs` needs to be installed. - - Install playwight with: - - * conda: - - conda install -c conda-forge nodejs - - * mamba: - - mamba install -c conda-forge nodejs - - * micromamba: - - micromamb install -c conda-forge nodejs - - """ - ) - ) - else: - node_binary = shutil_node_binary - self.node_binary = node_binary - - def supports_flag_no_experimental_fetch(self): - probe_cmd = [self.node_binary, "--no-experimental-fetch", "--version"] - ret_code = subprocess.call( - probe_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL - ) - return ret_code == 0 - - def run(self): - main_name = "node_main.js" - main = Path(THIS_DIR) / main_name - shutil.copyfile(main, self.host_work_dir / main_name) - - cmd = [self.node_binary] - if self.supports_flag_no_experimental_fetch(): - cmd.append("--no-experimental-fetch") - - cmd.extend( - [ - main_name, - self.work_dir, - self.script, - str(int(self.async_main)), - self.host_work_dir, - ] - ) - - process = subprocess.Popen(cmd, stdout=subprocess.PIPE) - # Poll process.stdout to show stdout live - while True: - output = process.stdout.readline() - if process.poll() is not None: - break - if output: - print(output.decode().strip()) - rc = process.poll() - if process.returncode != 0: - raise RuntimeError( - f"node return with returncode: {process.returncode} rc {rc}" - ) - - result_path = self.host_work_dir / "_node_result.json" - if result_path.exists(): - with open(result_path, "r") as f: - results = json.load(f) - if results["return_code"] != 0: - raise RuntimeError(results["error"]) - else: - raise RuntimeError("internal error in pyjs-code-runner") diff --git a/pyjs_code_runner/backend/node/node_main.js b/pyjs_code_runner/backend/node/node_main.js deleted file mode 100644 index 73f845e..0000000 --- a/pyjs_code_runner/backend/node/node_main.js +++ /dev/null @@ -1,112 +0,0 @@ - -const fs = require('fs'); -var path = require('path'); - -console.log(process.argv); -work_dir = process.argv[2]; -script_path = process.argv[3]; -async_main = parseInt(process.argv[4]); -host_work_dir =process.argv[5]; - -node_result_json = path.join(host_work_dir, '_node_result.json'); - - -function report_error(e){ - let data = JSON.stringify({ - error: e, - return_code: 1 - }); - fs.writeFileSync(node_result_json, data); -} - -function report_no_run(){ - let data = JSON.stringify({ - error: "unknown error, code did not run properly", - return_code: 1 - }); - fs.writeFileSync(node_result_json, data); -} - -function report_success(e){ - let data = JSON.stringify({ - return_code: 0 - }); - fs.writeFileSync(node_result_json, data); -} -// a proper run will overwrite this -report_no_run(); -(async () => { - try { - const { default: createModule } = await import("./pyjs_runtime_node.js") - - - var pyjs = await createModule() - var EmscriptenForgeModule = pyjs - global.EmscriptenForgeModule = pyjs - global.pyjs = pyjs - - - const { default: importPackages } = await import("./packed_env.js") - await importPackages(); - - const { default: importMounts } = await import("./packed_mounts.js") - await importMounts(); - - await pyjs.init() - - try{ - pyjs.exec(`import os;os.chdir("${work_dir}")`) - pyjs.eval_file(`${script_path}`); - } - catch(e){ - console.error("error while evaluating main file:",e) - report_error(e); - return; - } - if(async_main) - { - - pyjs.exec(`\n -import asyncio -_async_done_ = [False] -_ret_code = [0] -async def main_runner(): - try: - ret = await main() - if ret is None: - ret = 0 - _ret_code[0] = ret - except Exception as e: - _ret_code[0] = 1 - print("EXCEPTION",e) - finally: - global _async_done_ - _async_done_[0] = True -asyncio.ensure_future(main_runner()) - `) - - - while(true) - { - await new Promise(resolve => setTimeout(resolve, 100)); - const _async_done_ = pyjs.eval("_async_done_[0]") - if(_async_done_) - { - break; - } - } - let ret_code = pyjs.eval("_ret_code[0]"); - if(ret_code != 0) - { - // process.exit(ret_code); - report_error(Error("python_return_code!= 0")); - return; - } - } - } catch (e) { - console.error(e) - report_error(e); - return; - } - report_success() -})(); \ No newline at end of file diff --git a/pyjs_code_runner/cli/run.py b/pyjs_code_runner/cli/run.py index ea3519e..6d291f2 100644 --- a/pyjs_code_runner/cli/run.py +++ b/pyjs_code_runner/cli/run.py @@ -44,9 +44,27 @@ def parse_mounts(mounts): return parsed_mounts -conda_env_option = require_option( +conda_env_option = typer.Option( + None, *make_names("conda-env"), - help="host location of the conda environment in which to run the code", + help="host location of the conda environment (with pyjs >= 6) in which to run the code; " + "required unless --pyjs-npm is given", +) +pyjs_npm_option = typer.Option( + None, + "--pyjs-npm", + help="run with a pyjs npm package instead of a conda env: @ from the npm " + "registry, or a local package directory / .tgz", +) +packages_option = typer.Option( + None, + "--package", + help="(with --pyjs-npm) conda package spec to install at runtime, repeatable", +) +arch_option = typer.Option( + "wasm32", + "--arch", + help="(with --pyjs-npm) wasm32 or wasm64", ) script_option = require_option( *make_names("script"), help="path of script inside the virtual fileystem to run" @@ -122,7 +140,7 @@ def parse_mounts(mounts): @script_app.command() def browser_main( - conda_env: Path = conda_env_option, + conda_env: Optional[Path] = conda_env_option, script: Path = script_option, async_main: bool = async_main_option, mounts: List[str] = mounts_option, @@ -137,6 +155,9 @@ def browser_main( headless: bool = headless_option, slow_mo: Optional[int] = slowmo_option, browser: BrowserType = browser_option, + pyjs_npm: Optional[str] = pyjs_npm_option, + packages: Optional[List[str]] = packages_option, + arch: str = arch_option, ): run_script( backend_type=BackendType.browser_main, @@ -151,15 +172,16 @@ def browser_main( cache_dir=cache_dir, use_cache=cache, host_work_dir=host_work_dir, - backend_kwargs=dict( - port=port, headless=headless, slow_mo=slow_mo, browser=browser - ), + backend_kwargs=dict(port=port, headless=headless, slow_mo=slow_mo, browser=browser), + pyjs_npm=pyjs_npm, + packages=packages, + arch=arch, ) @script_app.command() def browser_worker( - conda_env: Path = conda_env_option, + conda_env: Optional[Path] = conda_env_option, script: Path = script_option, async_main: bool = async_main_option, mounts: List[str] = mounts_option, @@ -174,6 +196,9 @@ def browser_worker( headless: bool = headless_option, slow_mo: Optional[int] = slowmo_option, browser: BrowserType = browser_option, + pyjs_npm: Optional[str] = pyjs_npm_option, + packages: Optional[List[str]] = packages_option, + arch: str = arch_option, ): run_script( backend_type=BackendType.browser_worker, @@ -188,9 +213,10 @@ def browser_worker( cache_dir=cache_dir, use_cache=cache, host_work_dir=host_work_dir, - backend_kwargs=dict( - port=port, headless=headless, slow_mo=slow_mo, browser=browser - ), + backend_kwargs=dict(port=port, headless=headless, slow_mo=slow_mo, browser=browser), + pyjs_npm=pyjs_npm, + packages=packages, + arch=arch, ) @@ -247,9 +273,14 @@ def run_script( cache_dir, use_cache, backend_kwargs=None, + pyjs_npm=None, + packages=None, + arch="wasm32", ): if backend_kwargs is None: backend_kwargs = dict() + if conda_env is None and pyjs_npm is None: + exit_with_err("either --conda-env or --pyjs-npm is required") mounts = parse_mounts(mounts) if use_cache: cache_dir = get_cache_dir(cache_dir=cache_dir) @@ -271,4 +302,7 @@ def run_script( use_cache=use_cache, host_work_dir=host_work_dir, backend_kwargs=backend_kwargs, + pyjs_npm=pyjs_npm, + packages=packages, + arch=arch, ) diff --git a/pyjs_code_runner/constants.py b/pyjs_code_runner/constants.py index 569e8fc..8de1e91 100644 --- a/pyjs_code_runner/constants.py +++ b/pyjs_code_runner/constants.py @@ -1,8 +1 @@ -from pathlib import Path -import os - EMSCRIPTEN_HOME = "/home/web_user" -_THIS_DIR = Path(os.path.dirname(os.path.realpath(__file__))) - -JS_DIR = _THIS_DIR / "js" -HTML_DIR = _THIS_DIR / "html" diff --git a/pyjs_code_runner/get_cache_dir.py b/pyjs_code_runner/get_cache_dir.py index 218a974..d2a0b5c 100644 --- a/pyjs_code_runner/get_cache_dir.py +++ b/pyjs_code_runner/get_cache_dir.py @@ -1,10 +1,12 @@ -import appdirs - +import os from pathlib import Path def get_appdir(): - path = Path(appdirs.user_data_dir("pyjs_code_runner", "ThorstenBeier")) + """the default cache directory: $XDG_CACHE_HOME/pyjs_code_runner, else + ~/.cache/pyjs_code_runner""" + root = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache" + path = Path(root) / "pyjs_code_runner" path.mkdir(parents=True, exist_ok=True) return path diff --git a/pyjs_code_runner/html/__init__.py b/pyjs_code_runner/html/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/pyjs_code_runner/html/browser_main.html b/pyjs_code_runner/html/browser_main.html deleted file mode 100644 index 1db07c2..0000000 --- a/pyjs_code_runner/html/browser_main.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - TEST_TITLE - - - - - - - - diff --git a/pyjs_code_runner/html/browser_worker.html b/pyjs_code_runner/html/browser_worker.html deleted file mode 100644 index 5f0e1b7..0000000 --- a/pyjs_code_runner/html/browser_worker.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - TEST_TITLE - - - - - - - diff --git a/pyjs_code_runner/js/__init__.py b/pyjs_code_runner/js/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/pyjs_code_runner/js/utils.js b/pyjs_code_runner/js/utils.js deleted file mode 100644 index f576f62..0000000 --- a/pyjs_code_runner/js/utils.js +++ /dev/null @@ -1,99 +0,0 @@ -async function fetchMount(pyjs, mount){ - let url = `./${mount}`; - let filename = `/mount_tarballs/${mount}`; - let byte_array = await pyjs._fetch_byte_array(url, filename); - pyjs.FS.writeFile(filename, byte_array); - pyjs._untar_from_python(filename, "/"); -} - -async function fetchMounts(pyjs) { - let response = await fetch("./mounts.json"); - if (!response.ok) { - throw new Error(`HTTP error while fetching ./mounts.json! status: ${response.status}`); - } - let mounts = await response.json(); - pyjs.FS.mkdir("/mount_tarballs"); - await Promise.all(mounts.map(mount => fetchMount(pyjs, mount))); - -} - -async function make_pyjs(print, error, preload_load_shared_libs=true) { - var pyjs = await createModule({ print: print, error: print }) - - await pyjs.bootstrap_from_empack_packed_environment( - `./empack_env_meta.json`, /* packages_json_url */ - ".", /* package_tarballs_root_url */ - false, /* verbose */ - !preload_load_shared_libs /* skip_loading_shared_libs */ - ); - globalThis.pyjs = pyjs - return pyjs -} - -globalThis.make_pyjs = make_pyjs - -function eval_main_script(pyjs, workdir, filename) { - try { - pyjs.exec("import os;from os.path import exists") - pyjs.exec(`os.chdir("${workdir}")`) - pyjs.eval_file(filename); - return 0; - } - catch (e) { - if (typeof e === "number") { - const msg = pyjs.extract_exception_message(e); - console.error("error while evaluating main file:", msg) - } - else { - console.error("error while evaluating main file:", e) - } - return 1; - } - return 0 -} -globalThis.eval_main_script = eval_main_script - -async function run_async_python_main(pyjs) { - - - pyjs.exec(` -import asyncio -_async_done_ = [False] -_ret_code = [0] -async def main_runner(): - try: - ret = await main() - if ret is None: - ret = 0 - _ret_code[0] = ret - except Exception as e: - _ret_code[0] = 1 - print("EXCEPTION",e) - finally: - global _async_done_ - _async_done_[0] = True -asyncio.ensure_future(main_runner()) - `) - - while (true) { - await new Promise(resolve => setTimeout(resolve, 100)); - const _async_done_ = pyjs.eval("_async_done_[0]") - if (_async_done_) { - break; - } - } - return pyjs.eval("_ret_code[0]") - -} -globalThis.run_async_python_main = run_async_python_main - - -if (typeof exports === 'object' && typeof module === 'object') { - module.exports = make_pyjs; -} -else if (typeof define === 'function' && define['amd']) { - define([], function () { return make_pyjs; }); -} -else if (typeof exports === 'object') { - exports["make_pyjs"] = make_pyjs; -} diff --git a/pyjs_code_runner/js/worker.js b/pyjs_code_runner/js/worker.js deleted file mode 100644 index d454866..0000000 --- a/pyjs_code_runner/js/worker.js +++ /dev/null @@ -1 +0,0 @@ -importScripts('./pyjs_runtime_browser.js') \ No newline at end of file diff --git a/pyjs_code_runner/run.py b/pyjs_code_runner/run.py index f01d783..a771eec 100644 --- a/pyjs_code_runner/run.py +++ b/pyjs_code_runner/run.py @@ -1,81 +1,163 @@ -from .backend.backend import BackendType, get_backend_type_family, get_backend_cls -from .work_dir_context import work_dir_context -from .get_cache_dir import get_cache_dir - -import tempfile -from pathlib import Path -from empack.pack import pack_env, pack_directory,add_tarfile_to_env_meta -from empack.pack import DEFAULT_CONFIG_PATH as EMPACK_DEFAULT_CONFIG_PATH -from empack.file_patterns import pkg_file_filter_from_yaml +"""Prepare a directory with everything a browser needs to run a python script +with pyjs, and run it there (backend/browser.py). + +The page (web/) is driven by the JavaScript of the pyjs npm package. Where +pyjs and the python environment come from: + +* a conda env (`conda_env`, the default; what pytester uses): an + emscripten-forge env with pyjs >= 6 in it. Its runtime + (lib_js/pyjs/pyjs_runtime_browser.{js,wasm}) and the npm package's + JavaScript (lib_js/pyjs/npm) are used, and the whole env is packed with + empack. So what runs is exactly what is installed there, e.g. a python, + pyjs and some package that were just built locally. +* an npm package (`pyjs_npm`): a pyjs npm package (a version from the npm + registry, or a local package directory / .tgz) with its own runtime and + environment; `packages` are installed at runtime from the conda channels + by the package's installer. + +The directory served to the browser: + + index.html, worker.js, run.js the page (web/) + config.json what to run, read by run.js + pyjs/ the pyjs npm package (at least dist/) + assets// conda env mode: runtime + packed env + mount_.tar.gz the mounts +""" -from contextlib import contextmanager +import json import os import shutil -import json - - -def pack_mounts(mounts, host_work_dir, backend_type): - mount_js_files = [] - for mount_index, (host_path, em_path) in enumerate(mounts): - mount_filename = f"mount_{mount_index}.tar.gz" - mount_js_files.append(mount_filename) - if host_path.is_dir(): - pack_directory( - host_dir=host_path, - mount_dir=em_path, - outname=mount_filename, - outdir=host_work_dir, - compresslevel=1, - ) +import tarfile +import tempfile +import urllib.request +from contextlib import contextmanager +from pathlib import Path - elif host_path.is_file(): - raise RuntimeError("packing files is not yet supported") - else: - raise RuntimeError( - f"host_path (={host_path}) in mounts is neither dir nor file" - ) - with open(Path(host_work_dir) / "mounts.json", "w") as f: - json.dump(mount_js_files, f, indent=4) - return mount_js_files +from empack.file_patterns import pkg_file_filter_from_yaml +from empack.pack import DEFAULT_CONFIG_PATH as EMPACK_DEFAULT_CONFIG_PATH +from empack.pack import pack_directory, pack_env +from .backend.backend import BackendType, get_backend_cls +from .get_cache_dir import get_cache_dir -def conda_env_to_cache_name(conda_env, backend_type): - env_name = str(conda_env).replace(os.path.sep, "_") - folder_name = ( - f"{env_name}__backend_family__{get_backend_type_family(backend_type).value}" +WEB_DIR = Path(__file__).resolve().parent / "web" +NPM_REGISTRY = "https://registry.npmjs.org" + + +def env_arch(conda_env): + """"wasm32" or "wasm64": the platform of the packages in `conda_env`""" + for meta in sorted((Path(conda_env) / "conda-meta").glob("*.json")): + subdir = json.loads(meta.read_text()).get("subdir", "") + if subdir.startswith("emscripten-"): + return subdir.split("-", 1)[1] + raise RuntimeError(f"{conda_env} has no emscripten-wasm32 / emscripten-wasm64 packages") + + +def install_runtime(source_dir, target_dir): + """the runtime as the npm package wants it in assets/: the wasm + and the emscripten glue as ES module (the conda package installs it as + classic script: the module is the same text + an export)""" + target_dir.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source_dir / "pyjs_runtime_browser.wasm", target_dir / "pyjs_runtime_browser.wasm") + glue = (source_dir / "pyjs_runtime_browser.js").read_text() + (target_dir / "pyjs_runtime_browser.mjs").write_text(glue + "\nexport default createModule;\n") + + +def prepare_from_conda_env(conda_env, relocate_prefix, pyjs_dir, file_filter, use_cache, cache_dir, out): + """conda env mode (see the module docstring); returns (arch, config)""" + arch = env_arch(conda_env) + # pyjs_dir: a directory like lib_js/pyjs of the env (runtime + npm/) + pyjs_dir = Path(pyjs_dir) if pyjs_dir is not None else Path(conda_env) / "lib_js" / "pyjs" + if not (pyjs_dir / "npm" / "dist" / "index.js").exists(): + raise RuntimeError( + f"{pyjs_dir} has no npm/dist/index.js: pyjs-code-runner needs pyjs >= 6 in the env " + "(its conda package ships the JavaScript of the npm package in lib_js/pyjs/npm)" + ) + shutil.copytree(pyjs_dir / "npm", out / "pyjs") + assets = out / "assets" / arch + install_runtime(pyjs_dir, assets) + pack_env( + env_prefix=conda_env, + relocate_prefix=relocate_prefix, + file_filters=file_filter, + use_cache=use_cache, + cache_dir=cache_dir, + outdir=assets, + compresslevel=1, ) - return folder_name - - -def copy_pyjs(conda_env, backend_type, pyjs_dir, outdir): - if backend_type == BackendType.node: - files = ["pyjs_runtime_node.js", "pyjs_runtime_node.wasm"] + return arch, dict(pyjs="pyjs", assets="assets", packages=[]) + + +def split_npm_spec(spec): + """"@scope/name@1.2.3" -> ("@scope/name", "1.2.3"); without a version: + "latest". (A scoped name starts with an @ of its own.)""" + scope = "@" if spec.startswith("@") else "" + name, _, version = spec[len(scope):].partition("@") + return scope + name, version or "latest" + + +def npm_package_dir(spec, cache_dir): + """The directory of the npm package `spec`: a local package directory, a + local .tgz, or "@" from the npm registry (downloaded once + into the cache).""" + path = Path(spec) + if path.is_dir(): + return path + if path.is_file(): + target = Path(cache_dir) / "npm" / path.name + archive = path else: - files = ["pyjs_runtime_browser.js", "pyjs_runtime_browser.wasm"] - - # if user specified pyjs dir we prefer this - if pyjs_dir is not None: - source_dir = Path(pyjs_dir) - else: - source_dir = Path(conda_env) / "lib_js/pyjs/" - if not source_dir.exists(): - raise RuntimeError( - f"{conda_env} does not contain pyjs. use pyjs-dir argument or install pyjs in env" - ) - - for file in files: - shutil.copyfile(Path(source_dir) / file, Path(outdir) / file) + name, version = split_npm_spec(spec) + with urllib.request.urlopen(f"{NPM_REGISTRY}/{name}/{version}") as response: + meta = json.load(response) + target = Path(cache_dir) / "npm" / f"{meta['name'].replace('/', '_')}-{meta['version']}" + archive = target.with_suffix(".tgz") + if not (target / "package").is_dir(): + target.parent.mkdir(parents=True, exist_ok=True) + print(f"downloading {meta['name']}@{meta['version']}", flush=True) + urllib.request.urlretrieve(meta["dist"]["tarball"], archive) + if not (target / "package").is_dir(): + with tarfile.open(archive) as tar: + tar.extractall(target, filter="data") + return target / "package" + + +def prepare_from_npm(spec, arch, packages, cache_dir, out): + """npm mode (see the module docstring); returns (arch, config)""" + package = npm_package_dir(spec, cache_dir) + shutil.copytree(package, out / "pyjs") + if not (out / "pyjs" / "assets" / arch).is_dir(): + raise RuntimeError(f"the npm package {spec} has no runtime for {arch}") + return arch, dict(pyjs="pyjs", assets="pyjs/assets", packages=list(packages or [])) + + +def pack_mounts(mounts, out): + """each (host directory, path in the virtual file system) as tarball; + returns the `archives` entries of the npm package's initialize()""" + archives = [] + for index, (host_path, em_path) in enumerate(mounts): + host_path = Path(host_path) + if not host_path.is_dir(): + raise RuntimeError(f"mount {host_path}: only directories can be mounted") + name = f"mount_{index}.tar.gz" + pack_directory(host_dir=host_path, mount_dir=str(em_path), outname=name, outdir=out, compresslevel=1) + # (the entries are relative to "/": "home/web_user/...") + archives.append(dict(url=name, path="/")) + return archives @contextmanager def host_work_dir_context(host_work_dir=None): if host_work_dir is None: with tempfile.TemporaryDirectory() as temp_dir: - with work_dir_context(temp_dir): - yield Path(temp_dir) + yield Path(temp_dir) else: - with work_dir_context(host_work_dir): - yield host_work_dir + host_work_dir = Path(host_work_dir) + # (filled from scratch: copytree needs the targets to not exist) + for entry in ["pyjs", "assets"]: + shutil.rmtree(host_work_dir / entry, ignore_errors=True) + host_work_dir.mkdir(parents=True, exist_ok=True) + yield host_work_dir def run( @@ -92,68 +174,46 @@ def run( use_cache=False, host_work_dir=None, backend_kwargs=None, + pyjs_npm=None, + packages=None, + arch="wasm32", ): - relocate_prefix = str(relocate_prefix) - if host_work_dir is not None: - host_work_dir = Path(host_work_dir) - + """Run the python file `script` (path in the virtual file system, relative + to `work_dir`) with pyjs in a browser; raises if it fails. + + conda env mode: `conda_env` (an emscripten-forge env with pyjs >= 6). + npm mode: `pyjs_npm` ("@", a package directory or .tgz), + `packages` (conda specs installed at runtime) and `arch`; `conda_env` + is not used then (None). + `mounts`: (host directory, directory in the virtual file system) pairs. + `async_main`: after running the script, await its `main()`. + `backend_kwargs`: port, headless, slow_mo, browser, preload_shared_libs. + """ if pkg_file_filter is None: pkg_file_filter = pkg_file_filter_from_yaml(EMPACK_DEFAULT_CONFIG_PATH) - - if backend_kwargs is None: - backend_kwargs = dict() - if cache_dir is None: cache_dir = get_cache_dir(cache_dir=None) + backend_kwargs = dict(backend_kwargs or {}) - # create a temporary host work directory - with host_work_dir_context(host_work_dir) as host_work_dir: - # copy pyjs-runtime to host-work-dir - copy_pyjs( - conda_env=conda_env, - backend_type=backend_type, - pyjs_dir=pyjs_dir, - outdir=host_work_dir, - ) - - # pack the environment itself - pack_env( - env_prefix=conda_env, - relocate_prefix=relocate_prefix, - file_filters=pkg_file_filter, - use_cache=use_cache, - cache_dir=cache_dir, - outdir=host_work_dir, - compresslevel=9, - ) - env_meta_filename = Path(host_work_dir) / "empack_env_meta.json" - - - - #raise RuntimeError("stop here") - # pack all the mounts - mount_files = pack_mounts( - mounts=mounts, - backend_type=backend_type, - host_work_dir=host_work_dir, - ) - for mount_file in mount_files: - print(f"mount_file: {mount_file}") - try: - add_tarfile_to_env_meta( - env_meta_filename=env_meta_filename, tarfile=mount_file - ) - except shutil.SameFileError: - pass - - # get the backend where the wasm code runs (ie node/browser-main/browser-worker) - backend = get_backend_cls(backend_type=backend_type)( - host_work_dir=host_work_dir, - work_dir=work_dir, - script=script, - async_main=async_main, - **backend_kwargs, + with host_work_dir_context(host_work_dir) as out: + if pyjs_npm is not None: + arch, config = prepare_from_npm(pyjs_npm, arch, packages, cache_dir, out) + else: + arch, config = prepare_from_conda_env( + conda_env, str(relocate_prefix), pyjs_dir, pkg_file_filter, use_cache, cache_dir, out + ) + config.update( + arch=arch, + archives=pack_mounts(mounts, out), + work_dir=str(work_dir), + script=str(script), + async_main=bool(async_main), + # (default as before: preloaded, also in a worker) + preload_shared_libs=bool(backend_kwargs.pop("preload_shared_libs", True)), ) + (out / "config.json").write_text(json.dumps(config, indent=2)) + for name in ["index.html", "worker.js", "run.js"]: + shutil.copyfile(WEB_DIR / name, out / name) - # run + backend = get_backend_cls(backend_type=backend_type)(host_work_dir=out, **backend_kwargs) backend.run() diff --git a/pyjs_code_runner/version.py b/pyjs_code_runner/version.py index 88c513e..ce1305b 100644 --- a/pyjs_code_runner/version.py +++ b/pyjs_code_runner/version.py @@ -1 +1 @@ -__version__ = "3.3.0" +__version__ = "4.0.0" diff --git a/pyjs_code_runner/web/index.html b/pyjs_code_runner/web/index.html new file mode 100644 index 0000000..e407b66 --- /dev/null +++ b/pyjs_code_runner/web/index.html @@ -0,0 +1,38 @@ + + + + + pyjs-code-runner + + + + + diff --git a/pyjs_code_runner/web/run.js b/pyjs_code_runner/web/run.js new file mode 100644 index 0000000..51a174d --- /dev/null +++ b/pyjs_code_runner/web/run.js @@ -0,0 +1,72 @@ +// Runs the user's script with pyjs, in the main thread (index.html) or in a +// worker (worker.js). Everything comes from the directory this file is +// served from, prepared by pyjs_code_runner/run.py. `config.json` says what +// to run and where things are: +// +// arch, work_dir, script, async_main, preload_shared_libs +// pyjs the directory of the pyjs npm package (its dist/*.js) +// assets the `assetsUrl`: / with the runtime +// (pyjs_runtime_browser.{mjs,wasm}) and a packed environment +// packages conda packages to install at runtime (npm mode) +// archives the mounts: tarballs unpacked into the file system +// +// The two sources (see run.py): a conda env (its runtime, its npm JS from +// lib_js/pyjs/npm, the env packed by empack: what pytester uses), or an npm +// package (its own JS, runtime and environment, + `packages`). +// +// Returns the exit code of the script: 0 if it ran through (and, with +// async_main, its `main()` returned None or 0), else non-zero. + +// The python side: run the script as `python