-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathworker-thread-v2.ts
More file actions
636 lines (600 loc) · 16.8 KB
/
worker-thread-v2.ts
File metadata and controls
636 lines (600 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
import { errorLogPath, logger } from '@php-wasm/logger';
import type { FileLockManager } from '@php-wasm/universal';
import {
bindUserSpace,
createNodeFsMountHandler,
loadNodeRuntime,
type WasmUserSpaceContext,
} from '@php-wasm/node';
import { EmscriptenDownloadMonitor } from '@php-wasm/progress';
import type {
PathAlias,
PHP,
FileTree,
RemoteAPI,
SupportedPHPVersion,
SpawnHandler,
} from '@php-wasm/universal';
import {
PHPExecutionFailureError,
PHPResponse,
PHPWorker,
releaseApiProxy,
consumeAPI,
consumeAPISync,
exposeAPI,
sandboxedSpawnHandlerFactory,
setPhpIniEntries,
writeFiles,
} from '@php-wasm/universal';
import { joinPaths, sprintf } from '@php-wasm/util';
import {
type BlueprintMessage,
runBlueprintV2,
type BlueprintV1Declaration,
} from '@wp-playground/blueprints';
import {
type ParsedBlueprintV2String,
type RawBlueprintV2Data,
} from '@wp-playground/blueprints';
import {
bootRequestHandler,
preloadPhpInfoRoute,
setupPlatformLevelMuPlugins,
} from '@wp-playground/wordpress';
import { existsSync } from 'fs';
import path from 'path';
import { rootCertificates } from 'tls';
import { MessageChannel, type MessagePort, parentPort } from 'worker_threads';
import { type RunCLIArgs, spawnWorkerThread } from '../run-cli';
import type {
PhpIniOptions,
PHPInstanceCreatedHook,
} from '@wp-playground/wordpress';
import { shouldRenderProgress } from '../utils/progress';
import type { Mount } from '@php-wasm/cli-util';
async function mountResources(php: PHP, mounts: Mount[]) {
for (const mount of mounts) {
try {
php.mkdir(mount.vfsPath);
await php.mount(
mount.vfsPath,
createNodeFsMountHandler(mount.hostPath)
);
} catch (error) {
const errorSummary =
error instanceof Error ? error.message : String(error);
throw new Error(
`Error mounting path ${mount.hostPath} at ${mount.vfsPath}: ${errorSummary}`,
{ cause: error }
);
}
}
}
/**
* Print trace messages from PHP-WASM.
*
* @param {number} processId - The process ID.
* @param {string} format - The format string.
* @param {...any} args - The arguments.
*/
function tracePhpWasm(processId: number, format: string, ...args: any[]) {
// eslint-disable-next-line no-console
console.log(
performance.now().toFixed(6).padStart(15, '0'),
processId.toString().padStart(16, '0'),
sprintf(format, ...args)
);
}
/**
* Force TTY status to preserve ANSI control codes in the output
* when the environment is interactive.
*
* This script is spawned as `new Worker()` and process.stdout and process.stderr are
* WritableWorkerStdio objects. By default, they strip ANSI control codes from the output
* causing every progress bar update to be printed in a new line instead of updating the
* same line.
*/
Object.defineProperty(process.stdout, 'isTTY', { value: true });
Object.defineProperty(process.stderr, 'isTTY', { value: true });
/**
* Output writer that ensures that progress bars are not printed on the same line as other output.
*/
const output = {
lastWriteWasProgress: false,
progress(data: string) {
if (!shouldRenderProgress(process.stdout)) {
return;
}
if (!process.stdout.isTTY) {
// eslint-disable-next-line no-console
console.log(data);
} else {
if (!output.lastWriteWasProgress) {
process.stdout.write('\n');
}
process.stdout.write('\r\x1b[K' + data);
output.lastWriteWasProgress = true;
}
},
stdout(data: string) {
process.stdout.write('\n\n\n');
if (output.lastWriteWasProgress) {
output.lastWriteWasProgress = false;
}
process.stdout.write(data);
},
stderr(data: string) {
process.stdout.write('\n\n\n');
if (output.lastWriteWasProgress) {
output.lastWriteWasProgress = false;
}
process.stderr.write(data);
},
};
export type WorkerWordPressBootArgs = Omit<
RunCLIArgs,
'mount-before-install' | 'mount'
> & {
siteUrl: string;
blueprint:
| RawBlueprintV2Data
| ParsedBlueprintV2String
| BlueprintV1Declaration;
};
type WorkerRunBlueprintArgs = Omit<
RunCLIArgs,
'mount-before-install' | 'mount'
> & {
siteUrl: string;
blueprint:
| RawBlueprintV2Data
| ParsedBlueprintV2String
| BlueprintV1Declaration;
mountsAfterWpInstall?: Array<Mount>;
};
export type SecondaryWorkerBootArgs = {
siteUrl: string;
allow?: string;
phpVersion: SupportedPHPVersion;
phpIniEntries?: PhpIniOptions;
constants?: Record<string, string | number | boolean | null>;
createFiles?: FileTree;
processId: number;
trace: boolean;
nativeInternalDirPath: string;
withIntl?: boolean;
withRedis?: boolean;
withMemcached?: boolean;
withXdebug?: boolean;
pathAliases?: PathAlias[];
mountsBeforeWpInstall?: Array<Mount>;
mountsAfterWpInstall?: Array<Mount>;
};
export type WorkerBootRequestHandlerOptions = Omit<
SecondaryWorkerBootArgs,
'mountsBeforeWpInstall' | 'mountsAfterWpInstall'
> & {
onPHPInstanceCreated: PHPInstanceCreatedHook;
spawnHandler: () => SpawnHandler;
};
export class PlaygroundCliBlueprintV2Worker extends PHPWorker {
booted = false;
blueprintTargetResolved = false;
phpInstancesThatNeedMountsAfterTargetResolved = new Set<PHP>();
fileLockManager: FileLockManager | undefined;
constructor(monitor: EmscriptenDownloadMonitor) {
super(undefined, monitor);
}
/**
* Call this method before boot() to use file locking.
*
* This method is separate from boot() to simplify the related Comlink.transferHandlers
* setup – if an argument is a MessagePort, we're transferring it, not copying it.
*
* @see comlink-sync.ts
* @see phpwasm-emscripten-library-file-locking-for-node.js
*/
async useFileLockManager(port: MessagePort) {
/**
* If JSPI is not available, php.js only supports synchronous locking syscalls.
* Let's use the synchronous API. Every method call will block this thread
* until the result is available.
*
* @see comlink-sync.ts
* @see phpwasm-emscripten-library-file-locking-for-node.js
*/
this.fileLockManager = await consumeAPISync<FileLockManager>(port);
}
async bootWordPress(
args: WorkerWordPressBootArgs,
workerPostInstallMountsPort: MessagePort
) {
// TODO: Should we move a process like this back into the
// `@wp-playground/wordpress` package?
const php = await this.__internal_getRequestHandler()!.getPrimaryPhp();
php.defineConstant('WP_DEBUG', 'true');
php.defineConstant('WP_DEBUG_LOG', 'true');
php.defineConstant('WP_DEBUG_DISPLAY', 'false');
php.defineConstant('WP_HOME', args.siteUrl);
php.defineConstant('WP_SITEURL', args.siteUrl);
await setPhpIniEntries(php, {
'openssl.cafile': '/internal/shared/ca-bundle.crt',
allow_url_fopen: '1',
disable_functions: '',
});
await setupPlatformLevelMuPlugins(php);
await writeFiles(php, '/', {
'/internal/shared/ca-bundle.crt': rootCertificates.join('\n'),
});
await preloadPhpInfoRoute(
php,
joinPaths(new URL(args.siteUrl).pathname, 'phpinfo.php')
);
if (args.mode === 'mount-only') {
await this.applyPostInstallMountsToAllWorkers(
workerPostInstallMountsPort
);
return;
}
await this.runBlueprintV2(
{
// TODO: Do we really want to create a new object or can we pass args directly?
...args,
},
workerPostInstallMountsPort
);
}
async bootWorker(args: SecondaryWorkerBootArgs) {
await this.bootRequestHandler({
...args,
onPHPInstanceCreated: async (php: PHP) => {
await mountResources(php, args.mountsBeforeWpInstall || []);
await mountResources(php, args.mountsAfterWpInstall || []);
// Temporary workaround for LOCK_EX in sqlite-database-integration.
// Creation of these files results in this error:
// PHP Warning: file_put_contents(): Exclusive locks are not supported for this stream
// in
// /wordpress/wp-content/plugins/sqlite-database-integration/wp-includes/sqlite/class-wp-sqlite-db.php
// on line 670
if (!php.isDir('/wordpress/wp-content')) {
php.mkdir('/wordpress/wp-content');
}
if (!php.isDir('/wordpress/wp-content/database')) {
php.mkdir('/wordpress/wp-content/database');
}
if (!php.isFile('/wordpress/wp-content/database/.htaccess')) {
php.writeFile(
'/wordpress/wp-content/database/.htaccess',
'deny from all'
);
}
if (!php.isFile('/wordpress/wp-content/database/index.php')) {
php.writeFile(
'/wordpress/wp-content/database/index.php',
'deny from all'
);
}
},
spawnHandler: () =>
sandboxedSpawnHandlerFactory(() =>
createPHPWorker(args, this.fileLockManager!)
),
});
}
async runBlueprintV2(
args: WorkerRunBlueprintArgs,
workerPostInstallMountsPort: MessagePort
) {
const requestHandler = this.__internal_getRequestHandler()!;
const { php, reap } =
await requestHandler.instanceManager.acquirePHPInstance();
// Mount the current working directory to the PHP runtime for the purposes of
// Blueprint resolution.
const primaryPhp = this.__internal_getPHP()!;
let unmountCwd = () => {};
if (typeof args.blueprint === 'string') {
const blueprintPath = path.resolve(process.cwd(), args.blueprint);
if (existsSync(blueprintPath)) {
primaryPhp.mkdir('/internal/shared/cwd');
unmountCwd = await primaryPhp.mount(
'/internal/shared/cwd',
createNodeFsMountHandler(path.dirname(blueprintPath))
);
args.blueprint = path.join(
'/internal/shared/cwd',
path.basename(args.blueprint)
);
}
}
try {
const cliArgsToPass: (keyof WorkerRunBlueprintArgs)[] = [
'mode',
'db-engine',
'db-host',
'db-user',
'db-pass',
'db-name',
'db-path',
'truncate-new-site-directory',
'allow',
];
const cliArgs = cliArgsToPass
.filter((arg) => arg in args)
.map((arg) => `--${arg}=${args[arg]}`);
cliArgs.push(`--site-url=${args.siteUrl}`);
const streamedResponse = await runBlueprintV2({
php,
blueprint: args.blueprint,
blueprintOverrides: {
additionalSteps: args['additional-blueprint-steps'],
wordpressVersion: args.wp,
},
cliArgs,
onMessage: async (message: BlueprintMessage) => {
switch (message.type) {
case 'blueprint.target_resolved': {
if (!this.blueprintTargetResolved) {
this.blueprintTargetResolved = true;
await this.applyPostInstallMountsToAllWorkers(
workerPostInstallMountsPort
);
}
break;
}
case 'blueprint.progress': {
const progressMessage = `${message.caption.trim()} – ${message.progress.toFixed(
2
)}%`;
output.progress(progressMessage);
break;
}
case 'blueprint.error': {
const red = '\x1b[31m';
const bold = '\x1b[1m';
const reset = '\x1b[0m';
if (args.verbosity === 'debug' && message.details) {
output.stderr(
`${red}${bold}Fatal error:${reset} Uncaught ${message.details.exception}: ${message.details.message}\n` +
` at ${message.details.file}:${message.details.line}\n` +
(message.details.trace
? message.details.trace + '\n'
: '')
);
} else {
output.stderr(
`${red}${bold}Error:${reset} ${message.message}\n`
);
}
break;
}
}
},
});
/**
* When we're debugging, every bit of information matters – let's immediately output
* everything we get from the PHP output streams.
*/
if (args.verbosity === 'debug') {
streamedResponse!.stdout.pipeTo(
new WritableStream({
write(chunk) {
process.stdout.write(chunk);
},
})
);
streamedResponse!.stderr.pipeTo(
new WritableStream({
write(chunk) {
process.stderr.write(chunk);
},
})
);
}
await streamedResponse!.finished;
if ((await streamedResponse!.exitCode) !== 0) {
// exitCode != 1 means the blueprint execution failed. Let's throw an error.
// and clean up.
const syncResponse =
await PHPResponse.fromStreamedResponse(streamedResponse);
throw new PHPExecutionFailureError(
`PHP.run() failed with exit code ${syncResponse.exitCode}. ${syncResponse.errors} ${syncResponse.text}`,
syncResponse,
'request'
);
}
} catch (error) {
// Capture the PHP error log details to provide more context for debugging.
let phpLogs = '';
try {
// @TODO: Don't assume errorLogPath starts with /wordpress/
// ...or maybe we can assume that in Playground CLI?
phpLogs = php.readFileAsText(errorLogPath);
} catch {
// Ignore errors reading the PHP error log.
}
(error as any).phpLogs = phpLogs;
throw error;
} finally {
reap();
unmountCwd();
}
}
async bootRequestHandler({
siteUrl,
allow,
phpVersion,
processId,
createFiles,
constants,
phpIniEntries,
trace,
nativeInternalDirPath,
withIntl,
withRedis,
withMemcached,
withXdebug,
pathAliases,
onPHPInstanceCreated,
spawnHandler,
}: WorkerBootRequestHandlerOptions) {
if (this.booted) {
throw new Error('Playground already booted');
}
this.booted = true;
try {
const requestHandler = await bootRequestHandler({
siteUrl,
createPhpRuntime: async () => {
return await loadNodeRuntime(phpVersion, {
fileLockManager: this.fileLockManager!,
emscriptenOptions: {
processId,
trace: trace ? tracePhpWasm : undefined,
ENV: {
DOCROOT: '/wordpress',
},
nativeInternalDirPath,
bindUserSpace: (
userSpaceContext: WasmUserSpaceContext
) => {
return bindUserSpace(
{
fileLockManager: this.fileLockManager!,
},
userSpaceContext
);
},
},
followSymlinks: allow?.includes('follow-symlinks'),
withIntl: withIntl,
withRedis,
withMemcached,
withXdebug,
});
},
maxPhpInstances: 1,
onPHPInstanceCreated,
sapiName: 'cli',
createFiles,
constants,
phpIniEntries,
pathAliases,
cookieStore: false,
spawnHandler,
});
this.__internal_setRequestHandler(requestHandler);
const primaryPhp = await requestHandler.getPrimaryPhp();
await this.setPrimaryPHP(primaryPhp);
setApiReady();
} catch (e) {
setAPIError(e as Error);
throw e;
}
}
async mountAfterWordPressInstall(mounts: Array<Mount>) {
await mountResources(this.__internal_getPHP()!, mounts);
}
async applyPostInstallMountsToAllWorkers(
postInstallMountsPort: MessagePort
): Promise<void> {
const applyPostInstallMountsToAllWorkers = consumeAPI<
() => Promise<void>
>(postInstallMountsPort);
await applyPostInstallMountsToAllWorkers();
applyPostInstallMountsToAllWorkers[releaseApiProxy]();
}
// Provide a named disposal method that can be invoked via comlink.
async dispose() {
await this[Symbol.asyncDispose]();
}
}
/**
* Spawns a new PHP process to be used in the PHP spawn handler (in proc_open() etc. calls).
* It boots from this worker-thread-v1.ts file, but is a separate process.
*
* We explicitly avoid using PHPProcessManager.acquirePHPInstance() here.
*
* Why?
*
* Because each PHP instance acquires actual OS-level file locks via fcntl() and LockFileEx()
* syscalls. Running multiple PHP instances from the same OS process would allow them to
* acquire overlapping locks. Running every PHP instance in a separate OS process ensures
* any locks that overlap between PHP instances conflict with each other as expected.
*
* @param options - The options for the worker.
* @param fileLockManager - The file lock manager to use.
* @returns A promise that resolves to the PHP worker.
*/
async function createPHPWorker(
{
siteUrl,
allow,
phpVersion,
createFiles,
constants,
phpIniEntries,
trace,
nativeInternalDirPath,
withXdebug,
pathAliases,
mountsBeforeWpInstall,
mountsAfterWpInstall,
}: // NOTE: We explicitly remove processId from the options
// type so the type system will catch if we try to reuse
// our parent's process ID.
Omit<SecondaryWorkerBootArgs, 'processId'>,
fileLockManager: FileLockManager | RemoteAPI<FileLockManager>
) {
const spawnedWorker = await spawnWorkerThread('v2');
const handler = consumeAPI<PlaygroundCliBlueprintV2Worker>(
spawnedWorker.phpPort
);
handler.useFileLockManager(fileLockManager as any);
await handler.bootWorker({
siteUrl,
allow,
phpVersion,
createFiles,
constants,
phpIniEntries,
processId: spawnedWorker.processId,
trace,
nativeInternalDirPath,
withXdebug,
pathAliases,
mountsBeforeWpInstall,
mountsAfterWpInstall,
});
return {
php: handler,
reap: () => {
try {
handler.dispose();
} catch {
/** */
}
try {
spawnedWorker.worker.terminate();
} catch {
/** */
}
},
};
}
process.on('unhandledRejection', (e: any) => {
logger.error('Unhandled rejection:', e);
});
const phpChannel = new MessageChannel();
const [setApiReady, setAPIError] = exposeAPI(
new PlaygroundCliBlueprintV2Worker(new EmscriptenDownloadMonitor()),
undefined,
phpChannel.port1
);
parentPort?.postMessage(
{
command: 'worker-script-initialized',
phpPort: phpChannel.port2,
},
[phpChannel.port2 as any]
);