diff --git a/CLAUDE.md b/CLAUDE.md index 006cec3..e243d73 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -348,6 +348,10 @@ like synchronous JS errors; pyodide compatible: `.name` / `.message`, e.g. before python starts) / `Module.unpackArchive({url, path})` (later, then `importlib.invalidate_caches()`); paths resolved against `path` (never the cwd), directory entries not listed, paths outside `path` rejected. + `cache: true` (5.1, opt-in: archive URLs may change content) caches an + archive like a package: unpacked tar in `pyjs-packages-v2` + bytecode, + key = URL + `?pyjs-archive-path=` (`loadArchive` / `installArchive` + in `runtime.ts`); bypassed with `verifySha256` + sha256. Tests: `tests/npm/test_archives.py` with archives the driver generates (`pyjs_test_driver/test_archives.py`); the npm / bundler pages pass one in `archives`. @@ -365,6 +369,12 @@ like synchronous JS errors; pyodide compatible: `.name` / `.message`, e.g. unknown paths with index.html) -> `cdnUrl` (default jsDelivr, exact version, baked in via esbuild `define`) unless `cdnFallback: false`. Self-hosting: `npx copy-assets ` (`npm/bin/pyjs.mjs`). + The runtime wasm (~14 MB) is fetched normally, caching is left to the + browser's HTTP cache (deliberately not in Cache Storage). A dev server + without ETag / cache headers answers 200 on every reload (seen in webgym: + once per page with `compileRuntime`); CDN / `immutable` headers give a + cache hit. A Cache Storage copy would need the package version in its key + (`copy-assets` paths are not versioned). Bundler pitfalls handled in `build.mjs`: no `new URL("", import.meta.url)` (Parcel fails on directories), the runtime `import(url)` lives in the unminified `dist/load-runtime.js` (esbuild's minifier drops diff --git a/CMakeLists.txt b/CMakeLists.txt index 8f0bdfa..78423cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 4.0) -project(pyjs VERSION 5.0.0 DESCRIPTION "pyjs") +project(pyjs VERSION 5.1.0 DESCRIPTION "pyjs") # cmake module directory diff --git a/docs/npm.md b/docs/npm.md index 70eb4ef..e797b44 100644 --- a/docs/npm.md +++ b/docs/npm.md @@ -102,6 +102,11 @@ accepts both, specs and pinned packages. Python checks each `.pyc` against the modification time + size of its source (kept from the archive), a stale one is compiled again. `bytecodeCache: false` turns it off. +* **Archives** are not cached by default (an archive URL may change its + content). `{url, path, cache: true}` caches one like a package: its + unpacked files and the bytecode of its `.py` files, by URL + `path`. Only + for URLs whose content never changes, e.g. with a content hash in the file + name: a cached archive is not downloaded again. * **sha256:** not checked by default (hashing large packages costs time); `verifySha256: true` checks every package / archive that has a `sha256` (such packages are then always downloaded: the cached layout cannot be @@ -170,7 +175,7 @@ JavaScript modules, so bundlers do not copy them; two ways to deploy them: |---|---|---| | `packages` | `[]` | conda package specs, solved and installed before Python starts | | `urls` | `[]` | pinned conda packages (`{url, sha256?}` or URL strings), no solver | -| `archives` | `[]` | archives (`{url, path, sha256?}`) unpacked before Python starts, see below | +| `archives` | `[]` | archives (`{url, path, sha256?, cache?}`) unpacked before Python starts, see below | | `files` | `[]` | files (`{path, data}` or `{path, url}`) written before Python starts | | `channels` | emscripten-forge 6x, conda-forge | channels the specs are solved against (also self-hosted ones, see below) | | `cache` | `true` | package cache in Cache Storage (`false`, or a cache name) | @@ -224,6 +229,14 @@ await pyjs.addFiles([{ path: "/data/extra.csv", url: "extra.csv" }]); pyjs.exec("import sys; sys.path.insert(0, '/examples')"); ``` +A filtered package (stripped of tests, headers, docs, ...) as an archive with +a content hash in its name gets the package caches with `cache: true`: a +small first download, and later visits only untar and load cached bytecode: + +```js +archives: [{ url: "packages-3f9a1c2e.tar.gz", path: "/", cache: true }], +``` + ## wasm32 or wasm64? wasm32 is the default and works in all browsers. wasm64 (memory64) allows @@ -231,6 +244,11 @@ more than 4 GB of memory (pyjs is linked with up to 16 GB) but needs a browser with memory64 support. Extra packages are taken from the matching channel subdir (`emscripten-wasm32` / `emscripten-wasm64`). +## Changes in 5.1 + +* Archives can be cached like packages: `{url, path, cache: true}` (unpacked + files + bytecode), see Caching above. + ## Changes in 5.0 * `extraPackages` / `extra_packages` → `packages`. diff --git a/npm/README.md b/npm/README.md index 6c225f3..3ff74c5 100644 --- a/npm/README.md +++ b/npm/README.md @@ -65,7 +65,7 @@ The returned object is the pyjs runtime (the emscripten `Module`): `exec`, |---|---|---| | `packages` | `[]` | conda package specs, solved + installed before python starts | | `urls` | `[]` | pinned conda packages (`{url, sha256?}` / URL strings), no solver | -| `archives` | `[]` | archives (`{url, path}`: tar / zip, gzip / bzip2 / zstd) unpacked before python starts | +| `archives` | `[]` | archives (`{url, path, cache?}`: tar / zip, gzip / bzip2 / zstd) unpacked before python starts; `cache: true` caches them like packages (immutable URLs only) | | `files` | `[]` | files (`{path, data}` / `{path, url}`) written before python starts | | `channels` | emscripten-forge 6x, conda-forge | channels the specs are solved against | | `cache` | `true` | package cache in Cache Storage (`false`, or a cache name) | diff --git a/npm/src/install.ts b/npm/src/install.ts index c508151..5f0d01c 100644 --- a/npm/src/install.ts +++ b/npm/src/install.ts @@ -142,10 +142,19 @@ export function installExtracted(Module: any, extracted: IExtractedPackage): { f return { files: result.files, sharedLibs: result.sharedLibs }; } -/** extract any archive below `dest` -> its files and shared libraries */ -export function extractArchive(Module: any, bytes: Uint8Array, dest: string): { files: string[]; sharedLibs: string[] } { - const result: IExtracted = Module._extract_archive(bytes, dest, {}); - return { files: result.files, sharedLibs: result.sharedLibs }; +/** + * extract any archive below `dest` -> its files and shared libraries; with + * `keep`, also what was written as an uncompressed tar (paths relative to + * `dest`) for the archive cache + */ +export function extractArchive( + Module: any, + bytes: Uint8Array, + dest: string, + keep = false +): { files: string[]; sharedLibs: string[]; tar?: Uint8Array } { + const result: IExtracted = Module._extract_archive(bytes, dest, { tar: keep }); + return { files: result.files, sharedLibs: result.sharedLibs, tar: keep ? result.tar : undefined }; } /** remove the files of a package (replaced / removed) */ diff --git a/npm/src/runtime.ts b/npm/src/runtime.ts index bffdf03..b6d94ef 100644 --- a/npm/src/runtime.ts +++ b/npm/src/runtime.ts @@ -315,12 +315,62 @@ function solve(state: IState, specs: string[], channels: string[], logger: ILogg }); } -/** archives / files with a URL: their downloads (started at once) */ +/** an archive to unpack: from the archive cache (its unpacked files as tar) or downloaded */ +interface ILoadedArchive { + archive: IArchive; + url: string; + /** the cache key (`cache: true` only): the URL + the destination */ + key?: string; + extracted?: Uint8Array; + bytes?: Uint8Array; + bytecode?: Uint8Array; +} + +/** + * an archive with `cache: true` is cached like a package (its unpacked files + * and their bytecode, by URL + destination: the URL must change when the + * content does); without, it is downloaded (sha256 checked when asked) + */ +async function loadArchive(state: IState, archive: IArchive): Promise { + const url = new URL(archive.url.toString(), pageUrl()).href; + const checked = state.verify && !!archive.sha256; + if (!archive.cache || !state.cacheName || checked) { + const bytes = await fetchBytes(url, { item: url, sha256: archive.sha256, verify: state.verify, onProgress: state.onProgress }); + return { archive, url, bytes }; + } + const key = `${url}${url.includes("?") ? "&" : "?"}pyjs-archive-path=${encodeURIComponent(archive.path)}`; + const bytecode = state.bytecode?.read(key); + const cached = await readExtracted(state.cacheName, key); + if (cached) { + state.onProgress?.({ item: url, phase: "cached", done: cached.tar.length, total: cached.tar.length }); + return { archive, url, key, extracted: cached.tar, bytecode: await bytecode }; + } + const bytes = await fetchBytes(url, { item: url, onProgress: state.onProgress }); + return { archive, url, key, bytes, bytecode: await bytecode }; +} + +/** archives: their downloads / cache reads (started at once) */ function downloadArchives(state: IState, archives: IArchive[]) { - return archives.map((a) => { - const url = new URL(a.url.toString(), pageUrl()).href; - return { archive: a, bytes: deferred(fetchBytes(url, { item: url, sha256: a.sha256, verify: state.verify, onProgress: state.onProgress })) }; - }); + return archives.map((archive) => ({ archive, loaded: deferred(loadArchive(state, archive)) })); +} + +/** unpack a loaded archive below its path (cached: stored in the background) -> its files and shared libraries */ +function installArchive(state: IState, loaded: ILoadedArchive): { files: string[]; sharedLibs: string[] } { + const { archive, key } = loaded; + let result: { files: string[]; sharedLibs: string[]; tar?: Uint8Array }; + if (loaded.extracted) { + result = extractArchive(state.Module, loaded.extracted, archive.path); + } else { + result = extractArchive(state.Module, loaded.bytes as Uint8Array, archive.path, !!key); + if (key && result.tar) { + storeExtracted(state.cacheName, key, result.tar, []); // (not awaited: the next visit uses it) + } + } + if (key) { + state.bytecode?.add(`archive:${key}`, key, result.files, loaded.bytecode); + } + state.onProgress?.({ item: loaded.url, phase: "extract", done: 1, total: 1 }); + return { files: result.files, sharedLibs: result.sharedLibs }; } function downloadFiles(state: IState, files: IFile[]) { return files.map((f) => { @@ -443,8 +493,13 @@ export async function initialize(arch: Arch, options: IInitializeOptions = {}): add("waitSolve", t); const installed = await installDownloaded(state, packageDownloads, onProgress); sharedLibs.push(...installed.sharedLibs); - for (const { archive, bytes } of archives) { - sharedLibs.push(...extractArchive(Module, await bytes, archive.path).sharedLibs); + for (const { loaded } of archives) { + t = performance.now(); + const archive = await loaded; + add("waitDownloads", t); + t = performance.now(); + sharedLibs.push(...installArchive(state, archive).sharedLibs); + add("extractArchives", t); } for (const { file, data } of files) { writeFile(Module, file.path, await data); @@ -525,8 +580,7 @@ function attachInstallers(state: IState): void { Module.unpackArchive = (archive: IArchive) => enqueue(state, async () => { - const [download] = downloadArchives(state, [archive]); - const result = extractArchive(Module, await download.bytes, archive.path); + const result = installArchive(state, await loadArchive(state, archive)); await linkSharedLibs(state, result.sharedLibs, state.onProgress); invalidateCaches(); return result.files; diff --git a/npm/src/types.ts b/npm/src/types.ts index 691bd6a..df46429 100644 --- a/npm/src/types.ts +++ b/npm/src/types.ts @@ -44,6 +44,13 @@ export interface IArchive { path: string; /** checked only with `verifySha256: true` */ sha256?: string; + /** + * cache the archive like a package (default: false): its unpacked files + * and python's bytecode of its `.py` files, by URL + `path`. Only for + * URLs whose content never changes (e.g. a content hash in the file + * name): a cached archive is not downloaded again + */ + cache?: boolean; } /** A file written into the emscripten file system: its content or a URL. */ diff --git a/tests/npm/test_archives.py b/tests/npm/test_archives.py index b703986..f5747dc 100644 --- a/tests/npm/test_archives.py +++ b/tests/npm/test_archives.py @@ -1,3 +1,6 @@ +import asyncio +import importlib +import importlib.util import os import sys @@ -43,3 +46,62 @@ async def test_unpack_archive_at_runtime(): finally: sys.path.remove("/unpacked/at/runtime") assert unpacked_runtime_pkg.VALUE == "runtime" + + +ARCHIVE_URL = "/test-data/archive_runtime.tar.bz2" + + +def _archive(path, cache): + """an archive option for `unpackArchive` (JS object)""" + return pyjs.js.Function( + "url", "path", "cache", "return {url: url, path: path, cache: cache}" + )(ARCHIVE_URL, path, cache) + + +def _cache_key(path): + """the key of an archive in the caches: its absolute URL + the destination""" + url = str(pyjs.js.URL.new(ARCHIVE_URL, pyjs.js.location.href).href) + return f"{url}?pyjs-archive-path={pyjs.js.encodeURIComponent(path)}" + + +async def _cached(cache_name, key): + """the cache entry, waiting up to ~5 s (written in the background)""" + cache = await pyjs.js.caches.open(cache_name) + for _ in range(100): + if await cache.match(key) is not None: + return True + await asyncio.sleep(0.05) + return False + + +async def test_archive_cache(): + """`cache: true`: the unpacked files and their bytecode are cached by URL + + path; unpacking it again needs no download and brings back both. Without + it (the default) nothing is cached.""" + if not pyjs.js.Function("return typeof caches !== 'undefined'")(): + return # (no Cache Storage here) + path = "/cached/archive" + module_file = f"{path}/unpacked_runtime_pkg/__init__.py" + await pyjs_core._module.unpackArchive(_archive(path, True)) + sys.modules.pop("unpacked_runtime_pkg", None) # (imported from another path before) + sys.path.insert(0, path) + try: + import unpacked_runtime_pkg as cached_pkg # (writes its .pyc) + finally: + sys.path.remove(path) + assert cached_pkg.__file__ == module_file + pyc = importlib.util.cache_from_source(module_file) + assert os.path.exists(pyc) + await pyjs_core._module.saveBytecode() + assert await _cached("pyjs-packages-v2", _cache_key(path)) + assert await _cached("pyjs-packages-v2-bytecode", _cache_key(path)) + # (the earlier test unpacked it without `cache`) + assert await (await pyjs.js.caches.open("pyjs-packages-v2")).match(_cache_key("/unpacked/at/runtime")) is None + + os.unlink(module_file) + os.unlink(pyc) + pyjs.js.performance.clearResourceTimings() + await pyjs_core._module.unpackArchive(_archive(path, True)) + fetched = pyjs.to_py(pyjs.js.Function("return performance.getEntriesByType('resource').map((e) => e.name)")()) + assert not any(ARCHIVE_URL in u for u in fetched), fetched + assert os.path.exists(module_file) and os.path.exists(pyc)