|
| 1 | +""" |
| 2 | +Execution context management for PyScript. |
| 3 | +
|
| 4 | +This module handles the differences between running in the |
| 5 | +[main browser thread](https://developer.mozilla.org/en-US/docs/Glossary/Main_thread) |
| 6 | +versus running in a |
| 7 | +[Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), |
| 8 | +providing a consistent API regardless of the execution context. |
| 9 | +
|
| 10 | +Key features: |
| 11 | +
|
| 12 | +- Detects whether code is running in a worker or main thread. Read this via |
| 13 | + the boolean `pyscript.context.RUNNING_IN_WORKER`. |
| 14 | +- Parses and normalizes configuration from `polyscript.config` and adds the |
| 15 | + Python interpreter type via the `type` key in `pyscript.context.config`. |
| 16 | +- Provides appropriate implementations of `window`, `document`, and `sync`. |
| 17 | +- Sets up JavaScript module import system, including a lazy `js_import` |
| 18 | + function. |
| 19 | +- Manages `PyWorker` creation. |
| 20 | +- Provides access to the current display target via |
| 21 | + `pyscript.context.display_target`. |
| 22 | +
|
| 23 | +!!! warning |
| 24 | +
|
| 25 | + These are key differences between the main thread and worker contexts: |
| 26 | +
|
| 27 | + Main thread context: |
| 28 | +
|
| 29 | + - `window` and `document` are available directly. |
| 30 | + - `PyWorker` can be created to spawn worker threads. |
| 31 | + - `sync` is not available (raises `NotSupported`). |
| 32 | +
|
| 33 | + Worker context: |
| 34 | +
|
| 35 | + - `window` and `document` are proxied from main thread (if SharedArrayBuffer |
| 36 | + available). |
| 37 | + - `PyWorker` is not available (raises `NotSupported`). |
| 38 | + - `sync` utilities are available for main thread communication. |
| 39 | +""" |
| 40 | + |
| 41 | +import json |
| 42 | +import sys |
| 43 | + |
| 44 | +import js |
| 45 | +from polyscript import config as _polyscript_config |
| 46 | +from polyscript import js_modules |
| 47 | +from pyscript.util import NotSupported |
| 48 | + |
| 49 | +RUNNING_IN_WORKER = not hasattr(js, "document") |
| 50 | +"""Detect execution context: True if running in a worker, False if main thread.""" |
| 51 | + |
| 52 | +config = json.loads(js.JSON.stringify(_polyscript_config)) |
| 53 | +"""Parsed and normalized configuration.""" |
| 54 | +if isinstance(config, str): |
| 55 | + config = {} |
| 56 | + |
| 57 | +js_import = None |
| 58 | +"""Function to import JavaScript modules dynamically.""" |
| 59 | + |
| 60 | +window = None |
| 61 | +"""The `window` object (proxied if in a worker).""" |
| 62 | + |
| 63 | +document = None |
| 64 | +"""The `document` object (proxied if in a worker).""" |
| 65 | + |
| 66 | +sync = None |
| 67 | +"""Sync utilities for worker-main thread communication (only in workers).""" |
| 68 | + |
| 69 | +# Detect and add Python interpreter type to config. |
| 70 | +if "MicroPython" in sys.version: |
| 71 | + config["type"] = "mpy" |
| 72 | +else: |
| 73 | + config["type"] = "py" |
| 74 | + |
| 75 | + |
| 76 | +class _JSModuleProxy: |
| 77 | + """ |
| 78 | + Proxy for JavaScript modules imported via js_modules. |
| 79 | +
|
| 80 | + This allows Python code to import JavaScript modules using Python's |
| 81 | + import syntax: |
| 82 | +
|
| 83 | + ```python |
| 84 | + from pyscript.js_modules lodash import debounce |
| 85 | + ``` |
| 86 | +
|
| 87 | + The proxy lazily retrieves the actual JavaScript module when accessed. |
| 88 | + """ |
| 89 | + |
| 90 | + def __init__(self, name): |
| 91 | + """ |
| 92 | + Create a proxy for the named JavaScript module. |
| 93 | + """ |
| 94 | + self.name = name |
| 95 | + |
| 96 | + def __getattr__(self, field): |
| 97 | + """ |
| 98 | + Retrieve a JavaScript object/function from the proxied JavaScript |
| 99 | + module via the given `field` name. |
| 100 | + """ |
| 101 | + # Avoid Pyodide looking for non-existent special methods. |
| 102 | + if not field.startswith("_"): |
| 103 | + return getattr(getattr(js_modules, self.name), field) |
| 104 | + return None |
| 105 | + |
| 106 | + |
| 107 | +# Register all available JavaScript modules in Python's module system. |
| 108 | +# This enables: from pyscript.js_modules.xxx import yyy |
| 109 | +for module_name in js.Reflect.ownKeys(js_modules): |
| 110 | + sys.modules[f"pyscript.js_modules.{module_name}"] = _JSModuleProxy(module_name) |
| 111 | +sys.modules["pyscript.js_modules"] = js_modules |
| 112 | + |
| 113 | + |
| 114 | +# Context-specific setup: Worker vs Main Thread. |
| 115 | +if RUNNING_IN_WORKER: |
| 116 | + import polyscript |
| 117 | + |
| 118 | + # PyWorker cannot be created from within a worker. |
| 119 | + PyWorker = NotSupported( |
| 120 | + "pyscript.PyWorker", |
| 121 | + "pyscript.PyWorker works only when running in the main thread", |
| 122 | + ) |
| 123 | + |
| 124 | + # Attempt to access main thread's window and document via SharedArrayBuffer. |
| 125 | + try: |
| 126 | + window = polyscript.xworker.window |
| 127 | + document = window.document |
| 128 | + js.document = document |
| 129 | + |
| 130 | + # Create js_import function that runs imports on the main thread. |
| 131 | + js_import = window.Function( |
| 132 | + "return (...urls) => Promise.all(urls.map((url) => import(url)))" |
| 133 | + )() |
| 134 | + |
| 135 | + except: |
| 136 | + # SharedArrayBuffer not available - window/document cannot be proxied. |
| 137 | + sab_error_message = ( |
| 138 | + "Unable to use `window` or `document` in worker. " |
| 139 | + "This requires SharedArrayBuffer support. " |
| 140 | + "See: https://docs.pyscript.net/latest/faq/#sharedarraybuffer" |
| 141 | + ) |
| 142 | + js.console.warn(sab_error_message) |
| 143 | + window = NotSupported("pyscript.window", sab_error_message) |
| 144 | + document = NotSupported("pyscript.document", sab_error_message) |
| 145 | + |
| 146 | + # Worker-specific utilities for main thread communication. |
| 147 | + sync = polyscript.xworker.sync |
| 148 | + |
| 149 | + def current_target(): |
| 150 | + """ |
| 151 | + Get the current output target in worker context. |
| 152 | + """ |
| 153 | + return polyscript.target |
| 154 | + |
| 155 | +else: |
| 156 | + # Main thread context setup. |
| 157 | + import _pyscript |
| 158 | + from _pyscript import PyWorker as _PyWorker |
| 159 | + from pyscript.ffi import to_js |
| 160 | + |
| 161 | + js_import = _pyscript.js_import |
| 162 | + |
| 163 | + def PyWorker(url, **options): |
| 164 | + """ |
| 165 | + Create a Web Worker running Python code. |
| 166 | +
|
| 167 | + This spawns a new worker thread that can execute Python code |
| 168 | + found at the `url`, independently of the main thread. The |
| 169 | + `**options` can be used to configure the worker. |
| 170 | +
|
| 171 | + ```python |
| 172 | + from pyscript import PyWorker |
| 173 | +
|
| 174 | +
|
| 175 | + # Create a worker to run background tasks. |
| 176 | + # (`type` MUST be either `micropython` or `pyodide`) |
| 177 | + worker = PyWorker("./worker.py", type="micropython") |
| 178 | + ``` |
| 179 | +
|
| 180 | + PyWorker **can only be created from the main thread**, not from |
| 181 | + within another worker. |
| 182 | + """ |
| 183 | + return _PyWorker(url, to_js(options)) |
| 184 | + |
| 185 | + # Main thread has direct access to window and document. |
| 186 | + window = js |
| 187 | + document = js.document |
| 188 | + |
| 189 | + # sync is not available in main thread (only in workers). |
| 190 | + sync = NotSupported( |
| 191 | + "pyscript.sync", "pyscript.sync works only when running in a worker" |
| 192 | + ) |
| 193 | + |
| 194 | + def current_target(): |
| 195 | + """ |
| 196 | + Get the current output target in main thread context. |
| 197 | + """ |
| 198 | + return _pyscript.target |
0 commit comments