From 0396d6a56f180050aa7308102cb5e059bb28206b Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Thu, 3 Dec 2026 05:12:19 +0000 Subject: [PATCH] perf(playground): skip staging for disposable ZIP plugin mounts --- docs/recipe-contract.md | 5 ++ packages/cli/src/commands/recipe-run.ts | 16 +++-- .../cli/src/commands/recipe-runtime-setup.ts | 1 + packages/cli/src/recipe-sources.ts | 6 ++ packages/cli/src/zip-source.ts | 21 ++++-- .../runtime-core/src/runtime-contracts.ts | 2 + .../src/mount-materialization.ts | 14 ++-- .../src/playground-runtime.ts | 10 +-- tests/playground-readonly-mounts.test.ts | 17 +++++ tests/recipe-extra-plugin-local-zip.test.ts | 8 +++ ...pe-extra-plugin-mounts.integration.test.ts | 67 +++++++++++++++++++ 11 files changed, 146 insertions(+), 21 deletions(-) create mode 100644 tests/recipe-extra-plugin-mounts.integration.test.ts diff --git a/docs/recipe-contract.md b/docs/recipe-contract.md index 61596796..156600ce 100644 --- a/docs/recipe-contract.md +++ b/docs/recipe-contract.md @@ -323,6 +323,11 @@ subpath that resolves outside the root through a symlink is rejected. Without a containing `sourceRoot`, the plugin directory is the boundary. Escaping, dangling, and cyclic symlinks are skipped and reported in runtime evidence. +On Playground, caller-owned plugin directories are staged so runtime writes do +not change the source. ZIP plugins extracted into a run-owned tree of regular +files and directories mount directly from that tree, which is discarded after +runtime teardown. ZIPs containing symlinks still use readonly staging. + External HTTPS zip downloads are gated by `WP_CODEBOX_ALLOW_NETWORK_DOWNLOADS=1`. Local paths are resolved relative to the recipe file. diff --git a/packages/cli/src/commands/recipe-run.ts b/packages/cli/src/commands/recipe-run.ts index ae56fa64..e5b266e5 100644 --- a/packages/cli/src/commands/recipe-run.ts +++ b/packages/cli/src/commands/recipe-run.ts @@ -235,14 +235,14 @@ export async function runRecipe(options: RecipeRunOptions, interruption?: Recipe await managedServices.release() managedServicesReleased = true } - let runtimeDestroyed = false + let runtimeDestruction: Promise | undefined const destroyActiveRuntime = async (): Promise => { - if (!runtime || runtimeDestroyed) { + if (!runtime || runtimeDestruction) { return } - runtimeDestroyed = true - await bestEffortTimeout(runtime.destroy(), 2_000) + runtimeDestruction = runtime.destroy() + await bestEffortTimeout(runtimeDestruction, 2_000) } const phaseExecutor = new RecipeRunPhaseExecutor({ context, timeoutMs: options.timeoutMs, interruption, destroyActiveRuntime }) const phaseTracker = phaseExecutor.tracker @@ -647,7 +647,13 @@ export async function runRecipe(options: RecipeRunOptions, interruption?: Recipe cleanupEvidence = await runManagedServiceCleanup(runRegistry, runRecord, serviceEvidence, true, async () => { await releaseManagedServices() - await cleanupRecipePreparedSources(workspaceMounts, extraPlugins, stagedFiles, overlays, dependencyOverlays, extraThemes) + const disposablePlugins = runtimeDestruction ? extraPlugins.filter((plugin) => plugin.disposableExtraction) : [] + if (disposablePlugins.length > 0 && runtimeDestruction) { + // The best-effort shutdown wait may time out while Playground still has these mounts open. + const cleanup = () => cleanupRecipePreparedSources([], disposablePlugins) + await bestEffortTimeout(runtimeDestruction.then(cleanup, cleanup), 2_000) + } + await cleanupRecipePreparedSources(workspaceMounts, extraPlugins.filter((plugin) => !disposablePlugins.includes(plugin)), stagedFiles, overlays, dependencyOverlays, extraThemes) await cleanupInputMountBaselines(inputMountBaselinePaths) }) runRecord = await runRegistry.read(runRecord.runId) diff --git a/packages/cli/src/commands/recipe-runtime-setup.ts b/packages/cli/src/commands/recipe-runtime-setup.ts index 792b1fa5..60c798ab 100644 --- a/packages/cli/src/commands/recipe-runtime-setup.ts +++ b/packages/cli/src/commands/recipe-runtime-setup.ts @@ -468,6 +468,7 @@ function preparedExtraPluginMounts(plugins: PreparedExtraPlugin[]): MountSpec[] type: "directory", source: plugin.source, ...(plugin.sourceRoot !== undefined ? { sourceRoot: plugin.sourceRoot } : {}), + ...(plugin.disposableExtraction ? { sourceOwnership: "run-disposable" as const } : {}), target: plugin.target, mode: "readonly", ...(plugin.metadata?.phase === "pre-install" ? { phase: "pre-install" as const } : {}), diff --git a/packages/cli/src/recipe-sources.ts b/packages/cli/src/recipe-sources.ts index 9d719aa9..65ba8775 100644 --- a/packages/cli/src/recipe-sources.ts +++ b/packages/cli/src/recipe-sources.ts @@ -60,6 +60,7 @@ export interface RecipeSourceProvenance { } interface PreparedExternalSource { + disposableExtraction?: boolean source: string sourceRoot?: string cleanupPaths: string[] @@ -67,6 +68,7 @@ interface PreparedExternalSource { } export interface PreparedExtraPlugin { + disposableExtraction?: boolean source: string sourceRoot?: string slug: string @@ -320,6 +322,7 @@ export async function prepareExtraPlugins(plugins: readonly WorkspaceRecipeExtra const prepared = await prepareComposerAutoloadForPlugin(pluginResolved, slug, sourceRef, plugin.composer, resolved.source) await assertPreparedPluginFileExists(prepared.source, pluginFile.slice(slug.length + 1), sourceRef) preparedPlugins.push({ + ...(resolved.disposableExtraction && prepared.source === pluginResolved.source ? { disposableExtraction: true } : {}), source: prepared.source, ...(prepared.sourceRoot !== undefined ? { sourceRoot: prepared.sourceRoot } : {}), slug, @@ -981,6 +984,7 @@ async function preserveComposerDependencyReference(consumer: PreparedExtraPlugin await cp(copyRoot, stagedRoot, { recursive: true, verbatimSymlinks: consumer.sourceRoot !== undefined }) if (consumer.sourceRoot !== undefined) await assertExtraPluginSourceWithinRoot(stagedSource, stagedRoot) consumer.source = stagedSource + delete consumer.disposableExtraction if (consumer.sourceRoot !== undefined) consumer.sourceRoot = stagedRoot stagedConsumers.add(consumer) } @@ -1749,6 +1753,7 @@ async function prepareRecipeSource(sourceRef: string, recipeDirectory: string, s const preparedZip = await prepareLocalZipSource(localPath, slug, source.expectedSha256) return { source: await extractedPluginSourceDirectory(preparedZip.extractDirectory, slug), + disposableExtraction: preparedZip.plainTree, cleanupPaths: [preparedZip.root], provenance: { ...recipeSourceProvenance(source, recipeDirectory), @@ -1772,6 +1777,7 @@ async function prepareRecipeSource(sourceRef: string, recipeDirectory: string, s return { source: await extractedPluginSourceDirectory(preparedZip.extractDirectory, slug), + disposableExtraction: preparedZip.plainTree, cleanupPaths: [preparedZip.root], provenance: { ...recipeSourceProvenance(source, recipeDirectory), diff --git a/packages/cli/src/zip-source.ts b/packages/cli/src/zip-source.ts index 50b7009f..93efa106 100644 --- a/packages/cli/src/zip-source.ts +++ b/packages/cli/src/zip-source.ts @@ -17,6 +17,7 @@ export interface PreparedZipSource { zipPath: string extractDirectory: string digest: string + plainTree: boolean } export type RedirectSourceResolver = (source: TSource, finalSourceRef: string, headers?: Headers) => TSource @@ -29,9 +30,9 @@ export async function prepareZipSource(sourc const digest = await downloadZipSource(source, zipPath, redirectSource) await assertSafeZipEntries(zipPath) await executeManagedHostCommand({ command: "unzip", args: ["-q", zipPath, "-d", extractDirectory], cwd: root, allowedCwdRoots: [root], label: "extract recipe source zip" }) - await assertExtractedSourceBounds(extractDirectory) + const plainTree = await assertExtractedSourceBounds(extractDirectory) - return { root, zipPath, extractDirectory, digest } + return { root, zipPath, extractDirectory, digest, plainTree } } export async function prepareLocalZipSource(sourcePath: string, slug: string, expectedSha256?: string): Promise { @@ -52,8 +53,8 @@ export async function prepareLocalZipSource(sourcePath: string, slug: string, ex await mkdir(extractDirectory, { recursive: true }) await assertSafeZipEntries(zipPath) await executeManagedHostCommand({ command: "unzip", args: ["-q", zipPath, "-d", extractDirectory], cwd: root, allowedCwdRoots: [root], label: "extract recipe source zip" }) - await assertExtractedSourceBounds(extractDirectory) - return { root, zipPath, extractDirectory, digest } + const plainTree = await assertExtractedSourceBounds(extractDirectory) + return { root, zipPath, extractDirectory, digest, plainTree } } catch (error) { await rm(root, { recursive: true, force: true }) throw error @@ -107,7 +108,7 @@ async function assertSafeZipEntries(zipPath: string): Promise { } } -async function assertExtractedSourceBounds(directory: string): Promise { +async function assertExtractedSourceBounds(directory: string): Promise { const totals = await directoryTotals(directory) if (totals.files > maxExtractedFiles()) { throw new Error(`Recipe source extraction contains too many files: ${totals.files}`) @@ -115,22 +116,28 @@ async function assertExtractedSourceBounds(directory: string): Promise { if (totals.bytes > maxExtractedBytes()) { throw new Error(`Recipe source extraction exceeds ${maxExtractedBytes()} bytes: ${totals.bytes}`) } + return totals.plainTree } -async function directoryTotals(directory: string): Promise<{ files: number; bytes: number }> { +async function directoryTotals(directory: string): Promise<{ files: number; bytes: number; plainTree: boolean }> { let files = 0 let bytes = 0 + let plainTree = true for (const entry of await readdir(directory, { withFileTypes: true })) { const path = join(directory, entry.name) if (entry.isDirectory()) { const child = await directoryTotals(path) files += child.files bytes += child.bytes + plainTree &&= child.plainTree } else if (entry.isFile()) { const result = await stat(path) files += 1 bytes += result.size + } else { + // Keep readonly staging's containment checks for archives with links. + plainTree = false } } - return { files, bytes } + return { files, bytes, plainTree } } diff --git a/packages/runtime-core/src/runtime-contracts.ts b/packages/runtime-core/src/runtime-contracts.ts index a3bc1e67..b0c4e090 100644 --- a/packages/runtime-core/src/runtime-contracts.ts +++ b/packages/runtime-core/src/runtime-contracts.ts @@ -858,6 +858,8 @@ export interface MountSpec { source: string /** Optional host containment boundary for readonly symlinks. Must contain the resolved source. */ sourceRoot?: string + /** An isolated source safe to mount directly, even if readonly. Its owner keeps it alive through runtime teardown. */ + sourceOwnership?: "run-disposable" target: string mode: "readonly" | "readwrite" captureArtifacts?: boolean diff --git a/packages/runtime-playground/src/mount-materialization.ts b/packages/runtime-playground/src/mount-materialization.ts index 4759908d..b79a616f 100644 --- a/packages/runtime-playground/src/mount-materialization.ts +++ b/packages/runtime-playground/src/mount-materialization.ts @@ -58,13 +58,17 @@ interface ReadonlyMountSourceGeneration { files: number } +function needsReadonlySnapshot(mount: MountSpec): boolean { + return mount.mode === "readonly" && mount.sourceOwnership !== "run-disposable" +} + /** * Playground's Node filesystem mount handler is writable. Snapshot readonly - * inputs into a runtime-owned directory before handing them to that handler. + * inputs unless the caller already owns an isolated, disposable copy. */ export async function stageReadonlyPlaygroundMounts(mounts: MountSpec[]): Promise { - const readonlyMounts = mounts.filter((mount) => mount.mode === "readonly") - if (readonlyMounts.length === 0) { + const snapshotCount = mounts.filter(needsReadonlySnapshot).length + if (snapshotCount === 0) { return { mounts, diagnostics: [], @@ -76,7 +80,7 @@ export async function stageReadonlyPlaygroundMounts(mounts: MountSpec[]): Promis const root = await mkdtemp(join(tmpdir(), "wp-codebox-readonly-mounts-")) try { const stagedMountResults = await Promise.allSettled(mounts.map(async (mount, index) => { - if (mount.mode !== "readonly") { + if (!needsReadonlySnapshot(mount)) { return { mount, diagnostics: [] } } const source = join(root, `${index}-${basename(mount.source) || "mount"}`) @@ -115,7 +119,7 @@ export async function stageReadonlyPlaygroundMounts(mounts: MountSpec[]): Promis return { mounts: stagedMounts, diagnostics, - phaseResult: readonlyMountStagingPhaseResult(readonlyMounts.length, diagnostics, preparations), + phaseResult: readonlyMountStagingPhaseResult(snapshotCount, diagnostics, preparations), async [Symbol.asyncDispose]() { await rm(root, { recursive: true, force: true }) }, diff --git a/packages/runtime-playground/src/playground-runtime.ts b/packages/runtime-playground/src/playground-runtime.ts index 7076e284..22099fb8 100644 --- a/packages/runtime-playground/src/playground-runtime.ts +++ b/packages/runtime-playground/src/playground-runtime.ts @@ -254,6 +254,7 @@ class PlaygroundRuntime implements Runtime { private readonly artifactRoot: string private readonly hostTools?: HostToolRegistry private cliServerPromise?: Promise + private destroyPromise?: Promise private readonly activeExecutionAbortControllers = new Set() private readonly executionSignals = new AsyncLocalStorage() private readonly requestWorkerExecutions = new AsyncLocalStorage>() @@ -702,11 +703,12 @@ class PlaygroundRuntime implements Runtime { return server.playground.readFileAsText(path) } - async destroy(): Promise { - if (this.status === "destroyed") { - return - } + destroy(): Promise { + this.destroyPromise ??= this.destroyPlayground() + return this.destroyPromise + } + private async destroyPlayground(): Promise { this.status = "destroyed" for (const controller of this.activeExecutionAbortControllers) { controller.abort() diff --git a/tests/playground-readonly-mounts.test.ts b/tests/playground-readonly-mounts.test.ts index cdb752d3..895ac2b1 100644 --- a/tests/playground-readonly-mounts.test.ts +++ b/tests/playground-readonly-mounts.test.ts @@ -98,6 +98,23 @@ try { { source: pluginSource, target: "/wordpress/wp-content/plugins/tracked-symlink-plugin", mode: "readonly" }, ]) const stagedPlugin = staging.mounts[0].source + const disposableSource = join(root, "disposable") + await mkdir(disposableSource) + await writeFile(join(disposableSource, "plugin.php"), "disposable bytes") + const disposable = { source: disposableSource, target: "/disposable", mode: "readonly", sourceOwnership: "run-disposable" } as const + const mixed = await stageReadonlyPlaygroundMounts([ + disposable, + { source: readonlySource, target: "/readonly", mode: "readonly", type: "file" }, + ]) + try { + assert.equal(mixed.mounts[0], disposable) + assert.notEqual(mixed.mounts[1].source, readonlySource) + assert.equal(mixed.phaseResult.metadata?.mounts, 1) + assert.equal((mixed.phaseResult.metadata?.preparation as { bytes?: number }).bytes, readonlyBytes.length) + } finally { + await mixed[Symbol.asyncDispose]() + } + await access(disposableSource) assert.match(await readFile(join(stagedPlugin, "plugin.php"), "utf8"), /Plugin Name: Tracked Symlink Fixture/, "the plugin entrypoint remains available") assert.equal(await readFile(join(stagedPlugin, "includes", "runtime.php"), "utf8"), " { assert.deepEqual(nested.provenance.digest, { sha256: digest, expected: digest, verified: true }) assert.equal(nested.provenance.kind, "local") assert.equal(nested.cleanupPaths.length, 1) + assert.equal(nested.disposableExtraction, true) await cleanupRecipePreparedSources([], [nested]) await writeFile(join(recipeDirectory, "flat-plugin.php"), " { assert.deepEqual(await validateWorkspaceRecipeSemantics(flatRecipe, join(recipeDirectory, "flat.json")), []) const [flat] = await prepareRecipeExtraPlugins(flatRecipe, recipeDirectory) assert.equal((await stat(join(flat.source, "flat-plugin.php"))).isFile(), true) + assert.equal(flat.disposableExtraction, true) await cleanupRecipePreparedSources([], [flat]) + await symlink("flat-plugin.php", join(recipeDirectory, "linked.php")) + await execFileAsync("zip", ["-qy", "linked.zip", "flat-plugin.php", "linked.php"], { cwd: recipeDirectory }) + const [linked] = await prepareRecipeExtraPlugins(recipe("linked.zip", "flat-plugin"), recipeDirectory) + assert.equal(linked.disposableExtraction, undefined, "archives containing symlinks still need readonly staging") + await cleanupRecipePreparedSources([], [linked]) + await assert.rejects(() => prepareRecipeExtraPlugins(recipe("nested.zip", "nested-plugin", "0".repeat(64)), recipeDirectory), /sha256 mismatch/) }) diff --git a/tests/recipe-extra-plugin-mounts.integration.test.ts b/tests/recipe-extra-plugin-mounts.integration.test.ts new file mode 100644 index 00000000..d158b3d2 --- /dev/null +++ b/tests/recipe-extra-plugin-mounts.integration.test.ts @@ -0,0 +1,67 @@ +import assert from "node:assert/strict" +import { execFile } from "node:child_process" +import { createHash } from "node:crypto" +import { access, mkdir, readFile, writeFile } from "node:fs/promises" +import { join } from "node:path" +import { promisify } from "node:util" + +import type { BrowserStartupProgressEvent, LifecycleEvent, MaterializationPhaseResult, MountSpec } from "../packages/runtime-core/src/index.js" +import type { RecipeRunOutput } from "../packages/cli/src/commands/recipe-run-types.js" +import { withTempDir } from "../scripts/test-kit.js" + +const execFileAsync = promisify(execFile) + +await withTempDir("wp-codebox-extra-plugin-mounts-", async (root) => { + const plugin = "mount-test" + const pluginFile = `${plugin}/${plugin}.php` + const source = join(root, plugin) + const contents = " JSON.parse(line) as LifecycleEvent) + const progress = events.find((event) => event.type === "runtime.browser-startup-progress" && (event.data?.event as BrowserStartupProgressEvent)?.phase === "preview:materializing-mounts") + const staging = (progress?.data?.event as BrowserStartupProgressEvent | undefined)?.detail?.materialization as MaterializationPhaseResult | undefined + assert.equal((staging?.metadata?.preparation as { bytes?: number } | undefined)?.bytes, stagedBytes, input) + assert.equal(staging?.metadata?.mounts, stagedBytes === 0 ? 0 : 1, input) + assert.equal(await readFile(join(root, pluginFile), "utf8"), contents) + assert.deepEqual(await readFile(join(root, "plugin.zip")), archive) + + if (stagedBytes === 0) { + const mountEvent = events.find((event) => event.type === "runtime.mounted" && (event.data?.mount as MountSpec)?.target === `/wordpress/wp-content/plugins/${plugin}`) + const mount = mountEvent?.data?.mount as MountSpec | undefined + assert.equal(mount?.sourceOwnership, "run-disposable") + assert.ok(mount?.source) + await assert.rejects(access(mount.source), { code: "ENOENT" }) + } + } +}) + +console.log("recipe extra plugin mount isolation ok")