diff --git a/packages/runtime-playground/src/phpunit-command-handlers.ts b/packages/runtime-playground/src/phpunit-command-handlers.ts index 6446e50e..f6223600 100644 --- a/packages/runtime-playground/src/phpunit-command-handlers.ts +++ b/packages/runtime-playground/src/phpunit-command-handlers.ts @@ -1,5 +1,6 @@ import { posix } from "node:path" import { phpunitModernRunnerPhp } from "./phpunit-modern-runner.js" +import { phpunitProcessIsolationPhp } from "./phpunit-process-isolation.js" import { phpEnvAssignmentFunction, phpWpConfigDefineAppenderFunction } from "./php-snippets.js" export interface PhpunitRunCodeOptions { @@ -70,6 +71,7 @@ interface PhpunitConfigDiscoveryPhpOptions { uniqueReturnValues: boolean replaceDefaultMatchers: boolean allowMissingImplicitConfig: boolean + includeProcessIsolation?: boolean } interface PhpunitChangedTestFilterPhpOptions { @@ -113,7 +115,7 @@ function phpunitConfigDiscoveryPhp(options: PhpunitConfigDiscoveryPhpOptions): s const suffixAssignment = options.replaceDefaultMatchers ? "$suffixes = $config_suffixes;" : "$suffixes = array_merge($suffixes, $config_suffixes);" const prefixAssignment = options.replaceDefaultMatchers ? "$prefixes = $config_prefixes;" : "$prefixes = array_merge($prefixes, $config_prefixes);" - return `function ${options.functionName}($xml_path, $test_dir_default, array $selected_testsuites = array()) { + return `function ${options.functionName}($xml_path, $test_dir_default, array $selected_testsuites = array()${options.includeProcessIsolation ? ", &$process_isolation = false" : ""}) { $directories = array($test_dir_default); $suffixes = array('Test.php'); $prefixes = array('test-'); @@ -197,7 +199,7 @@ function phpunitConfigDiscoveryPhp(options: PhpunitConfigDiscoveryPhpOptions): s if (!empty($config_prefixes)) { ${prefixAssignment} } - return $return_values(); + ${options.includeProcessIsolation ? "$process_isolation = in_array((string) ($xml['processIsolation'] ?? ''), array('true', '1'), true);\n " : ""}return $return_values(); }` } @@ -898,6 +900,7 @@ function pg_run_boot_stage(array $cfg = []): ?string { if ($harness_autoload !== '' && is_readable($harness_autoload)) { pg_preload_wp_cli_namespaced_functions($harness_autoload); require_once $harness_autoload; + pg_register_phpunit_process_adapter(); } elseif ($autoload_required || $harness_autoload !== '') { throw new RuntimeException('configured PHPUnit harness autoload file is not readable: ' . $harness_autoload . '; mount the WP Codebox PHPUnit harness or clear autoload-file when using bootstrap-mode=project with a project bootstrap that loads PHPUnit.'); } else { @@ -1071,7 +1074,7 @@ function pg_skip_project_bootstrap_shell_install(): void { pg_log('NOTICE:using existing Playground install; project bootstrap shell install skipped'); } -function pg_run_project_bootstrap_stage(array $cfg): void { +function pg_run_project_bootstrap_stage(array $cfg): string { global $pg_stage_output_buffering; pg_stage_begin('project_bootstrap'); try { @@ -1096,6 +1099,7 @@ function pg_run_project_bootstrap_stage(array $cfg): void { } $pg_stage_output_buffering = false; pg_stage_ok('project_bootstrap'); + return $bootstrap_real; } catch (Throwable $e) { $pg_stage_output_buffering = false; pg_stage_fail('project_bootstrap', $e); @@ -1434,6 +1438,7 @@ if ($multisite) { $_ENV['WP_MULTISITE'] = '1'; } +${phpunitProcessIsolationPhp} $legacy_project_autoload_file = ''; if ($autoload_file_role === '' && $bootstrap_mode === 'project' && $project_autoload_file === '' && $autoload_file !== '' && $autoload_file !== '/wp-codebox-vendor/autoload.php') { $legacy_project_autoload_file = $autoload_file; @@ -1446,7 +1451,7 @@ if ($bootstrap_mode === 'project') { pg_skip_project_bootstrap_shell_install(); // Match vendor/bin/phpunit: load the explicit Composer autoloader before bootstrap. pg_run_project_autoload_stage($project_autoload_file); - pg_run_project_bootstrap_stage(array('project_bootstrap' => $project_bootstrap, 'phpunit_xml' => ${JSON.stringify(options.phpunitXml)}, 'phpunit_xml_is_default' => ${JSON.stringify(options.phpunitXmlIsDefault)})); + $phpunit_child_bootstrap = pg_run_project_bootstrap_stage(array('project_bootstrap' => $project_bootstrap, 'phpunit_xml' => ${JSON.stringify(options.phpunitXml)}, 'phpunit_xml_is_default' => ${JSON.stringify(options.phpunitXmlIsDefault)})); // A legacy autoload-file reclassified as a project autoloader still runs after bootstrap. pg_run_project_autoload_stage($legacy_project_autoload_file); } else { @@ -1572,6 +1577,10 @@ try { pg_stage_begin('verify_harness'); try { pg_ensure_phpunit_harness_loaded(); + pg_register_phpunit_process_adapter(); + if (!pg_uses_modern_phpunit()) { + pg_set_phpunit_composer_install(); + } pg_stage_ok('verify_harness'); } catch (Throwable $e) { pg_stage_fail('verify_harness', $e); @@ -1588,6 +1597,7 @@ ${phpunitConfigDiscoveryPhp({ uniqueReturnValues: false, replaceDefaultMatchers: true, allowMissingImplicitConfig: options.phpunitXmlIsDefault, + includeProcessIsolation: true, })} ${phpunitDiscoveryPhp("wp_codebox_phpunit_discover", "pg_log")} @@ -1598,7 +1608,7 @@ try { if (!is_dir($test_dir)) { throw new RuntimeException('configured PHPUnit test root is not a readable directory: ' . $test_dir); } - list($directories, $suffixes, $prefixes, $excludes, $configured_files) = wp_codebox_phpunit_parse_config(${JSON.stringify(options.phpunitXml)}, $test_dir, $selected_testsuites); + list($directories, $suffixes, $prefixes, $excludes, $configured_files) = wp_codebox_phpunit_parse_config(${JSON.stringify(options.phpunitXml)}, $test_dir, $selected_testsuites, $phpunit_args['processIsolation']); $test_files = wp_codebox_phpunit_discover($directories, $suffixes, $prefixes, $excludes, $configured_files); // The third argument must be the same base / entries in phpunit.xml were // resolved against (dirname($xml_path), phpunitConfigDiscoveryPhp's basePathExpression @@ -1641,7 +1651,7 @@ if (pg_uses_modern_phpunit()) { pg_stage_begin('run_tests'); pg_log('RUNNING ' . count($test_files) . ' TEST FILES'); try { - pg_run_modern_phpunit($test_files, $phpunit_args, ${JSON.stringify(options.phpunitXml)}, ${JSON.stringify(options.phpunitXmlIsDefault)}); + pg_run_modern_phpunit($test_files, $phpunit_args, ${JSON.stringify(options.phpunitXml)}, ${JSON.stringify(options.phpunitXmlIsDefault)}, $phpunit_child_bootstrap ?? ''); } catch (Throwable $e) { pg_log_mdi_native_diagnostic(); pg_stage_fail('run_tests', $e); diff --git a/packages/runtime-playground/src/phpunit-modern-runner.ts b/packages/runtime-playground/src/phpunit-modern-runner.ts index 07f06e28..c9a6b97d 100644 --- a/packages/runtime-playground/src/phpunit-modern-runner.ts +++ b/packages/runtime-playground/src/phpunit-modern-runner.ts @@ -4,7 +4,7 @@ export function phpunitModernRunnerPhp(prefix: "pg" | "core_pg"): string { return method_exists('PHPUnit\\Runner\\Version', 'id') && (int) PHPUnit\\Runner\\Version::id() >= 10; } -function ${prefix}_run_modern_phpunit(array $files, array $args, string $config, bool $implicit_config): void { +function ${prefix}_run_modern_phpunit(array $files, array $args, string $config, bool $implicit_config, string $child_bootstrap = ''): void { if (empty($files)) { // An empty changed-file scope must not fall back to the full XML suite. ${prefix}_log('ALL TESTS PASSED'); @@ -22,8 +22,9 @@ function ${prefix}_run_modern_phpunit(array $files, array $args, string $config, } else { $argv[] = '--no-configuration'; } - // WordPress bootstrap has already run, possibly with an explicit override. - // Use a private empty file instead of re-running the bootstrap from XML. + // Give fresh isolation workers the project bootstrap without re-running it + // in the parent. Set the Composer entry point here, after Application's + // preload phase, so it does not bypass the subprocess adapter. $scratch = '/tmp/wp-codebox-phpunit-app-' . bin2hex(random_bytes(16)); if (!mkdir($scratch, 0700)) { throw new RuntimeException('Unable to allocate PHPUnit Application scratch directory'); @@ -65,7 +66,12 @@ function ${prefix}_run_modern_phpunit(array $files, array $args, string $config, ${prefix}_stage_fail('run_tests', new RuntimeException('PHPUnit Application exited before reporting a result; see PHPUnit output')); exit(1); }); - if (file_put_contents($bootstrap_file, 'code(); + $script = $staged_script = tempnam(sys_get_temp_dir(), 'phpunit-job-') ?: null; + if ($script === null || file_put_contents($script, $code) === false) { + throw new RuntimeException('Unable to stage the PHPUnit isolation job'); + } + if (is_string($command)) { + // Insert before optional script arguments or stderr redirection. + $command = preg_replace('/(?= -- | 2>&1$|$)/', ' -f ' . escapeshellarg($script), $command, 1); + } else { + $arguments = array_search('--', $command, true); + array_splice($command, $arguments === false ? count($command) : $arguments, 0, array('-f', $script)); + } + } + $process = @proc_open($command, $descriptors, $pipes, $cwd ?? (getcwd() ?: null), array_replace(getenv(), $env ?? array())); + if (!is_resource($process)) { + throw new RuntimeException('Playground could not open the PHPUnit isolation worker'); + } + return $process; +} + +function pg_set_phpunit_composer_install(): void { + if (defined('PHPUNIT_COMPOSER_INSTALL')) { + return; + } + foreach (spl_autoload_functions() as $loader) { + if (is_array($loader) && $loader[0] instanceof Composer\Autoload\ClassLoader && $loader[0]->findFile(PHPUnit\Runner\Version::class)) { + foreach (Composer\Autoload\ClassLoader::getRegisteredLoaders() as $vendor => $registered) { + if ($registered === $loader[0]) { + define('PHPUNIT_COMPOSER_INSTALL', $vendor . '/autoload.php'); + return; + } + } + } + } +} + +function pg_register_phpunit_process_adapter(): void { + if (PHP_BINARY !== '' || PHP_SAPI !== 'cli') { + return; + } + if (!defined('WP_CODEBOX_PHPUNIT_BINARY')) { + define('WP_CODEBOX_PHPUNIT_BINARY', '/internal/shared/bin/php'); + } + static $adapter = null; + if ($adapter !== null) { + // Composer prepends new loaders; restore our priority without duplicates. + spl_autoload_unregister($adapter); + } + $adapter ??= static function (string $class): void { + if (!in_array($class, array( + 'PHPUnit\Framework\TestCase', + 'PHPUnit\Util\PHP\DefaultPhpProcess', + 'PHPUnit\Util\PHP\JobRunner', + 'SebastianBergmann\Environment\Runtime', + 'PHPUnit\Util\PHP\ExtensionSettings', + ), true)) { + return; + } + foreach (spl_autoload_functions() as $loader) { + if (!is_array($loader) || !$loader[0] instanceof Composer\Autoload\ClassLoader) { + continue; + } + $file = $loader[0]->findFile($class); + if (!$file || !is_readable($file)) { + continue; + } + $source = file_get_contents($file); + if ($source === false || !str_starts_with($source, 'startTest($this); + $result->addError($this, new \RuntimeException('Unable to preserve PHPUnit isolation globals: ' . $e->getMessage(), 0, $e), 0.0); + $result->endTest($this, 0.0); + return $result; +} +SNAPSHOT + , $source); + } + // Newer sebastian/environment also uses PHP_BINARY to probe CLI INI defaults. + $source = str_replace('use const PHP_BINARY;', 'use const WP_CODEBOX_PHPUNIT_BINARY as PHP_BINARY;', $source); + $modern = $class === 'PHPUnit\Util\PHP\JobRunner'; + if ($modern || $class === 'PHPUnit\Util\PHP\DefaultPhpProcess') { + $script = $modern ? '$temporaryFile' : '$this->tempFile'; + $error = $modern ? "new Result('', \$e->getMessage())" : "['stdout' => '', 'stderr' => \$e->getMessage()]"; + // Feed spawn errors into PHPUnit's existing child-result processor, + // which reports stderr as a test error rather than aborting the suite. + $source = preg_replace_callback('/\$process = proc_open\((.*?)\n \);/s', + static function (array $match) use ($script, $error): string { + return '$pg_staged_script = null; try { $process = \pg_phpunit_proc_open($job, ' . $script . ',' + . rtrim($match[1], " \r\n,") . ', $pg_staged_script); } catch (\Throwable $e) {' + . ' if ($pg_staged_script !== null) { @unlink($pg_staged_script); } return ' . $error . '; }'; + }, $source, 1, $adapted); + if ($adapted) { + $source = str_replace('proc_close($process);', 'proc_close($process); if ($pg_staged_script !== null) { @unlink($pg_staged_script); }', $source); + } + } + eval(substr($source, 5)); + return; + } + }; + spl_autoload_register($adapter, true, true); +} +` diff --git a/packages/runtime-playground/src/programmatic-playground-runner.ts b/packages/runtime-playground/src/programmatic-playground-runner.ts index 042f728a..28e4b84e 100644 --- a/packages/runtime-playground/src/programmatic-playground-runner.ts +++ b/packages/runtime-playground/src/programmatic-playground-runner.ts @@ -1,4 +1,5 @@ import * as PHPWasmNode from "@php-wasm/node" +import * as PHPWasmUniversal from "@php-wasm/universal" import { compileBlueprint } from "@wp-playground/blueprints" import { bootWordPressAndRequestHandler } from "@wp-playground/wordpress" import type { MountSpec, RuntimeCreateSpec } from "@automattic/wp-codebox-core" @@ -16,9 +17,17 @@ const { createNodeFsMountHandler, loadNodeRuntime } = PHPWasmNode as unknown as loadNodeRuntime(phpVersion: AllPHPVersion, options?: { followSymlinks?: boolean; emscriptenOptions?: { processId?: number }; extensions?: Array }): Promise } +const { PHP, proxyFileSystem, sandboxedSpawnHandlerFactory } = PHPWasmUniversal as unknown as { + PHP: new (runtimeId: number) => ProgrammaticPHP & { exit(): void } + proxyFileSystem(parent: ProgrammaticPHP, child: ProgrammaticPHP, paths: string[]): Promise + sandboxedSpawnHandlerFactory(getChild: () => Promise<{ php: ProgrammaticPHP; reap(): void }>): unknown +} + type AllPHPVersion = "8.5" | "8.4" | "8.3" | "8.2" | "8.1" | "8.0" | "7.4" | "5.2" interface ProgrammaticPHP { + isDir(path: string): boolean + listFiles(path: string, options: { prependPath: boolean }): string[] fileExists(path: string): boolean mkdir(path: string): void mount(vfsPath: string, mountHandler: unknown): Promise @@ -57,6 +66,7 @@ export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec, const postinstallMounts = mounts.filter((mount) => mount.phase !== "pre-install") const wpConfig = databaseBootstrapWpConfig(spec) const wordPressZip = await wordpressArchiveFile(options) + let spawningPhp: ProgrammaticPHP const requestHandler = await bootWordPressAndRequestHandler({ createPhpRuntime: () => loadNodeRuntime(phpVersion, programmaticNodeRuntimeOptions(spec, nextProcessId++)), maxPhpInstances: 1, @@ -64,6 +74,23 @@ export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec, siteUrl: playgroundRuntimeSiteUrl(spec) ?? "http://127.0.0.1", documentRoot: "/wordpress", sapiName: "cli", + spawnHandler: () => sandboxedSpawnHandlerFactory(async () => { + // The request handler has one slot, already occupied by the parent. + // A child needs its own PHP runtime, but must see the parent's VFS. + const parent = spawningPhp + const child = new PHP(await loadNodeRuntime(phpVersion, programmaticNodeRuntimeOptions(spec, nextProcessId++))) + try { + await proxyFileSystem(parent, child, [ + "/internal/shared", + ...parent.listFiles("/", { prependPath: true }).filter((path) => + !["/internal", "/dev", "/proc", "/request"].includes(path) && parent.isDir(path)), + ]) + return { php: child, reap: () => child.exit() } + } catch (error) { + child.exit() + throw error + } + }), wordpressInstallMode: options.wordpressInstallMode ?? "install-from-existing-files", ...(wordPressZip ? { wordPressZip } : {}), constants: playgroundWpConfigConstants(spec.environment.blueprint), @@ -77,6 +104,7 @@ export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec, }, async onPHPInstanceCreated(php: unknown) { const programmaticPhp = php as ProgrammaticPHP + spawningPhp = programmaticPhp if (options.wordpressDirectory) { await mountHostDirectory(programmaticPhp, "/wordpress", options.wordpressDirectory) } diff --git a/patches/@wp-playground+cli+3.1.46.patch b/patches/@wp-playground+cli+3.1.46.patch index 8b270431..6c0950a1 100644 --- a/patches/@wp-playground+cli+3.1.46.patch +++ b/patches/@wp-playground+cli+3.1.46.patch @@ -18,8 +18,17 @@ index e22c476..ed7c114 100644 followSymlinks: this.args.followSymlinks === !0, trace: this.args.experimentalTrace === !0, extensions: Ve(this.args), +diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.cjs b/node_modules/@wp-playground/cli/worker-thread-v1.cjs +index 4c193ec..ea12e09 100644 +--- a/node_modules/@wp-playground/cli/worker-thread-v1.cjs ++++ b/node_modules/@wp-playground/cli/worker-thread-v1.cjs +@@ -1,3 +1,3 @@ + "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("@php-wasm/node"),b=require("@php-wasm/progress"),n=require("@php-wasm/universal"),q=require("@php-wasm/util"),I=require("@wp-playground/common"),u=require("@wp-playground/wordpress"),W=require("tls"),P=require("worker_threads"),i=require("./run-cli-D2-Klk3s.cjs"),k=require("@php-wasm/logger");function H(r,e,...t){console.log(performance.now().toFixed(6).padStart(15,"0"),r.toString().padStart(16,"0"),q.sprintf(e,...t))}class w extends n.PHPWorker{constructor(e){super(void 0,e),this.bootedRequestHandler=!1,this.bootedWordPress=!1}async useFileLockManager(e){this.fileLockManager=await n.consumeAPISync(e)}async bootWordPress(e,t){if(this.bootedWordPress)throw new Error("WordPress already booted");this.bootedWordPress=!0;const{siteUrl:s,phpVersion:o,wordpressInstallMode:m,wordPressZip:c,sqliteIntegrationPluginZip:d,dataSqlPath:y,constants:f}=e;try{await u.bootWordPress(this.__internal_getRequestHandler(),{siteUrl:s,phpVersion:o,wordpressInstallMode:m,wordPressZip:c!==void 0?new File([c],"wordpress.zip"):void 0,sqliteIntegrationPluginZip:d!==void 0?new File([d],"sqlite-integration-plugin.zip"):void 0,createFiles:{"/internal/shared/ca-bundle.crt":W.rootCertificates.join(` +-`)},phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt","curl.cainfo":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""},dataSqlPath:y,constants:f});const a=n.consumeAPI(t);await a.applyPostInstallMountsToAllWorkers(),a[n.releaseApiProxy](),p()}catch(a){throw h(a),a}}async bootRequestHandler(e){if(this.bootedRequestHandler)throw new Error("Playground already booted");this.bootedRequestHandler=!0;try{const t=await u.bootRequestHandler({siteUrl:e.siteUrl,phpVersion:e.phpVersion,maxPhpInstances:1,createPhpRuntime:R(e,this.fileLockManager),onPHPInstanceCreated:async o=>{await i.mountResources(o,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(o,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>n.sandboxedSpawnHandlerFactory(()=>{let o=e;return this.bootedWordPress||(o={...e,mountsAfterWpInstall:[]}),v(o,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),p()}catch(t){throw h(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function R(r,e){return async()=>await g.loadNodeRuntime(r.phpVersion||I.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?H:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v1"),s=n.consumeAPI(t.phpPort);return s.useFileLockManager(e),await s.bootRequestHandler({...r,processId:t.processId}),{php:s,reap:()=>{try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{k.logger.error("Unhandled rejection:",r)});const l=new P.MessageChannel,[p,h]=n.exposeAPI(new w(new b.EmscriptenDownloadMonitor),void 0,l.port1);P.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV1Worker=w; ++`)},phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt","curl.cainfo":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""},dataSqlPath:y,constants:f});const a=n.consumeAPI(t);await a.applyPostInstallMountsToAllWorkers(),a[n.releaseApiProxy](),p()}catch(a){throw h(a),a}}async bootRequestHandler(e){if(this.bootedRequestHandler)throw new Error("Playground already booted");this.bootedRequestHandler=!0;try{const t=await u.bootRequestHandler({siteUrl:e.siteUrl,phpVersion:e.phpVersion,maxPhpInstances:1,createPhpRuntime:R(e,this.fileLockManager),onPHPInstanceCreated:async o=>{await i.mountResources(o,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(o,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>n.sandboxedSpawnHandlerFactory(()=>{let o=e;return this.bootedWordPress||(o={...e,mountsAfterWpInstall:[]}),v(o,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),p()}catch(t){throw h(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function R(r,e){return async()=>await g.loadNodeRuntime(r.phpVersion||I.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?H:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v1"),s=n.consumeAPI(t.phpPort);return s.useFileLockManager(e),await s.bootRequestHandler({...r,processId:t.processId}),await s.mountAfterWordPressInstall(r.mountsAfterWpInstall),{php:s,reap:()=>{try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{k.logger.error("Unhandled rejection:",r)});const l=new P.MessageChannel,[p,h]=n.exposeAPI(new w(new b.EmscriptenDownloadMonitor),void 0,l.port1);P.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV1Worker=w; + //# sourceMappingURL=worker-thread-v1.cjs.map diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.js b/node_modules/@wp-playground/cli/worker-thread-v1.js -index 93b7099..a8ecae8 100644 +index 93b7099..a7b02ad 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v1.js +++ b/node_modules/@wp-playground/cli/worker-thread-v1.js @@ -125,6 +125,7 @@ function V(r, e) { @@ -30,6 +39,15 @@ index 93b7099..a8ecae8 100644 processId: r.processId, trace: r.trace ? x : void 0, nativeInternalDirPath: r.nativeInternalDirPath +@@ -141,7 +142,7 @@ async function C(r, e) { + return o.useFileLockManager(e), await o.bootRequestHandler({ + ...r, + processId: t.processId +- }), { ++ }), await o.mountAfterWordPressInstall(r.mountsAfterWpInstall), { + php: o, + reap: () => { + try { @@ -157,6 +158,8 @@ async function C(r, e) { } process.on("unhandledRejection", (r) => { @@ -39,8 +57,18 @@ index 93b7099..a8ecae8 100644 }); const i = new _(), [c, p] = y( new F(new f()), +diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.cjs b/node_modules/@wp-playground/cli/worker-thread-v2.cjs +index 0a1477e..55e5f09 100644 +--- a/node_modules/@wp-playground/cli/worker-thread-v2.cjs ++++ b/node_modules/@wp-playground/cli/worker-thread-v2.cjs +@@ -1,4 +1,4 @@ + "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("@php-wasm/node"),q=require("@php-wasm/progress"),o=require("@php-wasm/universal"),W=require("@php-wasm/util"),H=require("@wp-playground/common"),p=require("@wp-playground/wordpress"),h=require("tls"),c=require("worker_threads"),i=require("./run-cli-D2-Klk3s.cjs"),R=require("@php-wasm/logger");function _(r,e,...t){console.log(performance.now().toFixed(6).padStart(15,"0"),r.toString().padStart(16,"0"),W.sprintf(e,...t))}function P(r){return{"openssl.cafile":"/internal/shared/ca-bundle.crt","curl.cainfo":"/internal/shared/ca-bundle.crt",allow_url_fopen:r?"1":"0",disable_functions:r?"":"fsockopen,pfsockopen,curl_init,curl_exec,curl_multi_exec,mail"}}class f extends o.PHPWorker{constructor(e){super(void 0,e),this.bootedRequestHandler=!1,this.bootedWordPress=!1}async useFileLockManager(e){this.fileLockManager=await o.consumeAPISync(e)}async bootWordPress(e,t){if(this.bootedWordPress)throw new Error("WordPress already booted");this.bootedWordPress=!0;const{siteUrl:s,phpVersion:n,wordpressInstallMode:g,wordPressZip:d,networking:y=!0,sqliteIntegrationPluginZip:u,dataSqlPath:I,constants:b}=e;try{await p.bootWordPress(this.__internal_getRequestHandler(),{siteUrl:s,phpVersion:n,wordpressInstallMode:g,wordPressZip:d!==void 0?new File([d],"wordpress.zip"):void 0,sqliteIntegrationPluginZip:u!==void 0?new File([u],"sqlite-integration-plugin.zip"):void 0,createFiles:{"/internal/shared/ca-bundle.crt":h.rootCertificates.join(` + `)},phpIniEntries:P(y),dataSqlPath:I,constants:b});const a=o.consumeAPI(t);await a.applyPostInstallMountsToAllWorkers(),a[o.releaseApiProxy](),w()}catch(a){throw m(a),a}}async bootRequestHandler(e){if(this.bootedRequestHandler)throw new Error("Playground already booted");this.bootedRequestHandler=!0;try{const t=await p.bootRequestHandler({siteUrl:e.siteUrl,phpVersion:e.phpVersion,maxPhpInstances:1,createFiles:{"/internal/shared/ca-bundle.crt":h.rootCertificates.join(` +-`)},phpIniEntries:P(e.networking??!0),createPhpRuntime:A(e,this.fileLockManager),onPHPInstanceCreated:async n=>{await i.mountResources(n,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(n,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>o.sandboxedSpawnHandlerFactory(()=>{let n=e;return this.bootedWordPress||(n={...e,mountsAfterWpInstall:[]}),v(n,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),w()}catch(t){throw m(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function A(r,e){return async()=>await k.loadNodeRuntime(r.phpVersion||H.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?_:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v2"),s=o.consumeAPI(t.phpPort),n=new c.MessageChannel;return await o.exposeSyncAPI(e,n.port1),await s.useFileLockManager(n.port2),await s.bootRequestHandler({...r,processId:t.processId}),{php:s,reap:()=>{try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{R.logger.error("Unhandled rejection:",r)});const l=new c.MessageChannel,[w,m]=o.exposeAPI(new f(new q.EmscriptenDownloadMonitor),void 0,l.port1);c.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV2Worker=f; ++`)},phpIniEntries:P(e.networking??!0),createPhpRuntime:A(e,this.fileLockManager),onPHPInstanceCreated:async n=>{await i.mountResources(n,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(n,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>o.sandboxedSpawnHandlerFactory(()=>{let n=e;return this.bootedWordPress||(n={...e,mountsAfterWpInstall:[]}),v(n,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),w()}catch(t){throw m(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function A(r,e){return async()=>await k.loadNodeRuntime(r.phpVersion||H.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?_:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v2"),s=o.consumeAPI(t.phpPort),n=new c.MessageChannel;return await o.exposeSyncAPI(e,n.port1),await s.useFileLockManager(n.port2),await s.bootRequestHandler({...r,processId:t.processId}),await s.mountAfterWordPressInstall(r.mountsAfterWpInstall),{php:s,reap:()=>{try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{R.logger.error("Unhandled rejection:",r)});const l=new c.MessageChannel,[w,m]=o.exposeAPI(new f(new q.EmscriptenDownloadMonitor),void 0,l.port1);c.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV2Worker=f; + //# sourceMappingURL=worker-thread-v2.cjs.map diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.js b/node_modules/@wp-playground/cli/worker-thread-v2.js -index fb79a59..5197c68 100644 +index fb79a59..6af079f 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v2.js +++ b/node_modules/@wp-playground/cli/worker-thread-v2.js @@ -136,6 +136,7 @@ function V(r, e) { @@ -51,6 +79,15 @@ index fb79a59..5197c68 100644 processId: r.processId, trace: r.trace ? C : void 0, nativeInternalDirPath: r.nativeInternalDirPath +@@ -152,7 +153,7 @@ async function j(r, e) { + return await q(e, o.port1), await n.useFileLockManager(o.port2), await n.bootRequestHandler({ + ...r, + processId: t.processId +- }), { ++ }), await n.mountAfterWordPressInstall(r.mountsAfterWpInstall), { + php: n, + reap: () => { + try { @@ -168,6 +169,8 @@ async function j(r, e) { } process.on("unhandledRejection", (r) => { diff --git a/patches/README.md b/patches/README.md index b6b08743..9a60fc59 100644 --- a/patches/README.md +++ b/patches/README.md @@ -9,6 +9,11 @@ Without this narrow terminalization, a poisoned PHP-WASM worker remains alive and leaves the parent request pending until the recipe timeout. Remove the patch after the Playground CLI ships the same worker terminalization behavior. +The same patch also applies post-install mounts to sandboxed CLI subprocesses. +Spawned workers boot a request handler but do not install WordPress themselves, +so without this change they miss the plugin and Composer mounts used by the +parent. Remove this part when upstream attaches those mounts to child workers. + The manual `build-php-wasm-mysqli-poll-overlay.yml` workflow carries the C-level `select()` wrapper and Asyncify imports from WordPress Playground PR [#4170](https://github.com/WordPress/wordpress-playground/pull/4170). It diff --git a/tests/playground-phpunit-isolation.integration.test.ts b/tests/playground-phpunit-isolation.integration.test.ts new file mode 100644 index 00000000..a824501c --- /dev/null +++ b/tests/playground-phpunit-isolation.integration.test.ts @@ -0,0 +1,115 @@ +import assert from "node:assert/strict" +import { spawnSync } from "node:child_process" +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { test } from "node:test" + +for (const major of [9, 10, 11, 12]) { + test(`PHPUnit ${major} runs an isolated test between regular tests`, (t) => { + const root = mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-isolation-")) + t.after(() => rmSync(root, { recursive: true, force: true })) + const slug = "isolation-fixture" + const plugin = join(root, slug) + const sandboxPlugin = `/wordpress/wp-content/plugins/${slug}` + const managed = major === 9 + const phpVersion = major === 12 ? "8.4" : "8.3" + const harness = join(root, "harness") + mkdirSync(join(plugin, "tests"), { recursive: true }) + if (managed) { + cpSync("tests/fixtures/phpunit-playground-harness", harness, { recursive: true }) + } else { + writeFileSync(join(plugin, "composer.json"), JSON.stringify({ + require: { "phpunit/phpunit": `^${major}`, "wp-phpunit/wp-phpunit": "^6.8" }, + config: { platform: { php: `${phpVersion}.0` } }, + })) + } + const install = spawnSync("composer", ["install", "--no-interaction", "--prefer-dist"], { + cwd: managed ? harness : plugin, encoding: "utf8", timeout: 300_000, + }) + if (install.error?.code === "ENOENT") return t.skip("Composer is unavailable") + assert.ifError(install.error) + const installOutput = install.stdout + install.stderr + if (install.status !== 0 && /curl error (?:5|6|7|28|35|60)\b|network is unreachable|could not resolve host|connection timed out/i.test(installOutput)) { + return t.skip("Composer network access is unavailable") + } + assert.equal(install.status, 0, installOutput) + + writeFileSync(join(plugin, `${slug}.php`), " + tests + +`) + const testFile = join(plugin, "tests", "IsolationTest.php") + const testCode = `