-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathphp-worker.js
More file actions
921 lines (844 loc) · 32 KB
/
Copy pathphp-worker.js
File metadata and controls
921 lines (844 loc) · 32 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
import { loadPlaygroundConfig } from "./src/shared/config.js";
import { createPhpBridgeChannel, createShellChannel } from "./src/shared/protocol.js";
import { bootstrapMoodle, startArchiveResolution } from "./src/runtime/bootstrap.js";
import { isFatalWasmError, isEmscriptenNetworkError, isSafeToReplay, formatErrorDetail, createSnapshotManager } from "./src/runtime/crash-recovery.js";
import { createPhpRuntime, createProvisioningRuntime } from "./src/runtime/php-loader.js";
import {
getBranchMetadata,
resolveRuntimeConfig,
resolveRuntimeSelection,
shouldTraceRuntimeSelection,
} from "./src/shared/version-resolver.js";
const workerUrl = new URL(self.location.href);
// __APP_ROOT__ is injected by esbuild and points to the project root.
// Falls back to self.location for unbundled contexts.
const appRootUrl = typeof __APP_ROOT__ !== "undefined" ? __APP_ROOT__ : new URL("./", self.location.href).toString();
// Runtime params are initially read from the worker URL as defaults,
// then overridden by the configure-blueprint message from remote.js.
// This is necessary because the Service Worker caches the worker bundle
// by URL path (stripping query params), so self.location.href may reflect
// stale params from a previously cached response.
let scopeId = workerUrl.searchParams.get("scope");
let forceCleanBoot = workerUrl.searchParams.get("clean") === "1";
let selection = resolveRuntimeSelection({
runtimeId: workerUrl.searchParams.get("runtime"),
phpVersion: workerUrl.searchParams.get("phpVersion"),
moodleBranch: workerUrl.searchParams.get("moodleBranch"),
});
let runtimeId = selection.runtimeId;
let phpVersion = selection.phpVersion;
let moodleBranch = selection.moodleBranch;
let phpCorsProxyUrlOverride = workerUrl.searchParams.get("phpCorsProxyUrl") || null;
let debug = workerUrl.searchParams.get("debug") || null;
let profile = workerUrl.searchParams.get("profile") || null;
let bridgeChannel = null;
let runtimeStatePromise = null;
// The ready PHP instance, exposed for the static fast path (see
// installBridgeListener). Set once boot completes, cleared on reset / boot
// error. Reading it is only ever a fast-path optimization — a stale or null
// value just routes the request through the normal serial queue.
let readyPhp = null;
let requestQueue = Promise.resolve();
let activeBlueprint = null;
let activeRuntimeConfig = null;
let activeWebRoot = "/www/moodle";
let phpInfoCapturePromise = null;
let automaticPhpInfoAttempted = false;
// --- Runtime rotation state ---
// The PHP WASM runtime can crash with "memory access out of bounds",
// "unreachable", or resource exhaustion ("No file descriptors available").
//
// Recovery strategy (reactive only, inspired by WordPress Playground):
// 1. Reactive rotation detects fatal WASM errors (isFatalWasmError) and
// discards the corrupted runtime, then replays idempotent requests once.
// 2. Bootstrap crashes reset the runtime promise so the next request
// triggers a clean bootstrap on a fresh WASM instance.
// 3. Anti-loop guard: if the runtime crashes before processing
// MIN_REQUESTS_BEFORE_RESTART requests, it is likely a fundamental bug
// — do not restart (avoids infinite boot-crash-boot loops).
//
// No preventive rotation is performed. WordPress Playground does not rotate
// preventively either; the correct fix for memory leaks is root-cause, not
// periodic restarts that cost 3-8s each.
const MAX_REACTIVE_RESTARTS = 20;
const MIN_REQUESTS_BEFORE_RESTART = 10;
let requestCount = 0;
let reactiveRestartCount = 0;
// --- DB snapshot for crash recovery state preservation ---
let snapshot = null;
function postShell(message) {
const channel = new BroadcastChannel(createShellChannel(scopeId));
channel.postMessage(message);
channel.close();
}
snapshot = createSnapshotManager({ postShell });
function traceRuntimeSelection(stage, detail) {
if (!shouldTraceRuntimeSelection({ debug, profile })) {
return;
}
postShell({
kind: "trace",
detail: `[runtime-selection][worker:${stage}] ${detail}`,
});
}
function respond(payload) {
bridgeChannel.postMessage(payload);
}
/**
* Build the DB file path from scope and runtime IDs.
*/
function buildDbPath() {
const scope = String(scopeId || "default").replace(/[^A-Za-z0-9_]/gu, "_");
const runtime = String(runtimeId || "php").replace(/[^A-Za-z0-9_]/gu, "_");
return `/persist/moodledata/moodle_${scope}_${runtime}.sq3.php`;
}
/**
* Frankenstyle plugin type → directory mapping under the webroot.
* Used to resolve plugin file paths from Moodle's installzipcomponent param.
*/
const PLUGIN_TYPE_DIRS = {
mod: "mod",
block: "blocks",
local: "local",
theme: "theme",
auth: "auth",
enrol: "enrol",
filter: "filter",
format: "course/format",
report: "report",
tool: "admin/tool",
editor: "lib/editor",
atto: "lib/editor/atto/plugins",
tiny: "lib/editor/tiny/plugins",
qtype: "question/type",
qbehaviour: "question/behaviour",
gradeexport: "grade/export",
gradeimport: "grade/import",
gradereport: "grade/report",
repository: "repository",
plagiarism: "plagiarism",
availability: "availability/condition",
calendartype: "calendar/type",
message: "message/output",
profilefield: "user/profile/field",
datafield: "mod/data/field",
assignsubmission: "mod/assign/submission",
assignfeedback: "mod/assign/feedback",
booktool: "mod/book/tool",
quizaccess: "mod/quiz/accessrule",
ltisource: "mod/lti/source",
workshopform: "mod/workshop/form",
workshopallocation: "mod/workshop/allocation",
workshopeval: "mod/workshop/eval",
contenttype: "contentbank/contenttype",
customfield: "customfield/field",
media: "media/player",
paygw: "payment/gateway",
qbank: "question/bank",
search: "search/engine",
aiprovider: "ai/provider",
aiplacement: "ai/placement",
};
/**
* Detect plugin installations from HTTP responses.
* When Moodle's native install addon UI succeeds, it redirects with
* installzipcomponent=TYPE_NAME in the URL. We extract the plugin type
* and name to track its directory for crash recovery.
*
* @param {object} serializedRequest - The original request
* @param {Response} response - The PHP response
* @param {string} webRoot - The Moodle webroot path (e.g. "/www/moodle")
*/
function detectPluginInstall(serializedRequest, response, webRoot) {
const url = serializedRequest.url || "";
if (!url.includes("/admin/tool/installaddon/")) return;
// Strategy 1: Check GET requests to installaddon that have installzipcomponent
// (this is the redirect target after a successful plugin upload)
if (url.includes("installzipcomponent=")) {
const match = url.match(/installzipcomponent=([a-z]+)_([a-z0-9_]+)/i);
if (match) {
const pluginType = match[1];
const pluginName = match[2];
const typeDir = PLUGIN_TYPE_DIRS[pluginType];
if (typeDir) {
snapshot.trackPluginDir(`${webRoot}/${typeDir}/${pluginName}`);
}
}
return;
}
// Strategy 2: Check POST redirects with Location header containing installzipcomponent
const method = String(serializedRequest.method || "").toUpperCase();
if (method !== "POST") return;
const status = response.status || 0;
if (status < 300 || status >= 400) return;
let location = "";
try {
if (response.headers?.get) {
location = response.headers.get("location") || "";
}
} catch {
// Headers might not be available
}
if (!location) return;
const match = location.match(/installzipcomponent=([a-z]+)_([a-z0-9_]+)/i);
if (!match) return;
const pluginType = match[1];
const pluginName = match[2];
const typeDir = PLUGIN_TYPE_DIRS[pluginType];
if (!typeDir) return;
const pluginDir = `${webRoot}/${typeDir}/${pluginName}`;
snapshot.trackPluginDir(pluginDir);
}
/**
* Re-create the admin session after DB snapshot restore.
* The restore overwrites the DB file (which contains the session table),
* invalidating the auto-login session that bootstrap just created.
* This creates a fresh session on top of the restored DB state.
*/
async function reLoginAfterRestore(php, webRoot) {
const AUTO_LOGIN_PATH = `${webRoot}/__playground_autologin.php`;
try {
const autoLoginPhp = [
"<?php",
"define('NO_OUTPUT_BUFFERING', true);",
"require(__DIR__ . '/config.php');",
"$admin = get_admin();",
"complete_user_login($admin);",
"echo json_encode(['ok' => true, 'user' => $admin->username]);",
].join("\n");
await php.writeFile(
AUTO_LOGIN_PATH,
new TextEncoder().encode(autoLoginPhp),
);
const loginResponse = await php.request(
new Request("http://localhost:8080/__playground_autologin.php"),
);
const loginText = await loginResponse.text();
if (loginResponse.status === 200 && loginText.includes('"ok"')) {
postShell({
kind: "trace",
detail: "[snapshot] re-created admin session after DB restore",
});
} else {
postShell({
kind: "error",
detail: `[snapshot] re-login returned unexpected response: ${loginText.slice(0, 200)}`,
});
}
} catch (err) {
postShell({
kind: "error",
detail: `[snapshot] re-login failed: ${err.message}`,
});
}
try {
await php.run(`<?php @unlink('${AUTO_LOGIN_PATH}');`);
} catch {
/* non-fatal */
}
}
/**
* After restoring plugin files onto a fresh runtime, Moodle's component cache
* doesn't know about them. Reset the cache and run the upgrade so the plugins
* are discovered and registered.
*/
async function reRegisterPluginsAfterRestore(php, webRoot, restoredPluginDirs = []) {
try {
// Build PHP code to refresh the component cache for each restored plugin
const webRootPrefix = webRoot.endsWith("/") ? webRoot : `${webRoot}/`;
const refreshCalls = restoredPluginDirs
.map((dir) => {
if (!dir.startsWith(webRootPrefix)) return "";
const relPath = dir.slice(webRootPrefix.length);
const pluginName = relPath.split("/").pop();
const typeDir = relPath.slice(0, relPath.lastIndexOf("/"));
const pluginType = Object.entries(PLUGIN_TYPE_DIRS).find(
([, d]) => d === typeDir,
)?.[0];
if (!pluginType || !pluginName) return "";
const safeDir = dir.replaceAll("'", "\\'");
return `\\core_component::playground_refresh_installed_plugin_cache('${pluginType}_${pluginName}', '${safeDir}');`;
})
.filter(Boolean)
.join("\n");
const code = `<?php
define('CLI_SCRIPT', true);
require('${webRoot}/config.php');
require_once($CFG->libdir . '/upgradelib.php');
require_once($CFG->libdir . '/clilib.php');
require_once($CFG->libdir . '/adminlib.php');
${refreshCalls}
\\core_component::reset();
if (function_exists('purge_all_caches')) {
purge_all_caches();
}
set_config('allversionshash', '');
try {
if (moodle_needs_upgrading()) {
upgrade_noncore(true);
}
echo json_encode(['ok' => true]);
} catch (\\Throwable $e) {
echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
`;
const result = await php.run(code);
const text = result?.text || "";
const errors = result?.errors || "";
if (errors) {
postShell({
kind: "trace",
detail: `[snapshot] plugin re-register PHP errors: ${errors.slice(0, 300)}`,
});
}
if (text.includes('"ok":true')) {
postShell({
kind: "trace",
detail: "[snapshot] re-registered plugins after restore",
});
} else {
postShell({
kind: "trace",
detail: `[snapshot] plugin re-register result: ${text.slice(0, 200)}`,
});
}
} catch (err) {
postShell({
kind: "error",
detail: `[snapshot] plugin re-register failed: ${err.message}`,
});
}
}
async function capturePhpInfoHtml(runtimeConfig, reason = "manual") {
if (!runtimeConfig) {
return {
detail: "PHP info capture skipped because the runtime configuration is not available yet.",
html: "",
};
}
if (phpInfoCapturePromise) {
return phpInfoCapturePromise;
}
phpInfoCapturePromise = (async () => {
const php = createProvisioningRuntime(runtimeConfig, { phpVersion });
try {
await php.refresh();
const response = await php.run(`<?php
ob_start();
phpinfo();
$html = ob_get_clean();
echo $html;
`);
return {
detail: `Captured PHP runtime diagnostics (${reason}).`,
html: response.text || "",
errorOutput: response.errors || "",
};
} catch (error) {
return {
detail: `Failed to capture PHP runtime diagnostics (${reason}).`,
html: `<!doctype html><meta charset="utf-8"><pre>${formatErrorDetail(error)}</pre>`,
errorOutput: "",
};
} finally {
phpInfoCapturePromise = null;
}
})();
return phpInfoCapturePromise;
}
async function publishPhpInfo(runtimeConfig, reason) {
let resolvedRuntimeConfig = runtimeConfig;
if (!resolvedRuntimeConfig) {
const config = await loadPlaygroundConfig();
resolvedRuntimeConfig = resolveRuntimeConfig(config, selection);
if (!resolvedRuntimeConfig) {
throw new Error("Unable to resolve a runtime configuration.");
}
activeRuntimeConfig = resolvedRuntimeConfig;
}
const payload = await capturePhpInfoHtml(resolvedRuntimeConfig, reason);
postShell({
kind: "phpinfo",
detail: payload.errorOutput
? `${payload.detail}\n${payload.errorOutput}`
: payload.detail,
html: payload.html,
reason,
});
}
function serializeResponse(response) {
return response.arrayBuffer().then((body) => ({
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
body,
}));
}
function deserializeRequest(requestLike) {
const init = {
method: requestLike.method,
headers: requestLike.headers,
};
if (!["GET", "HEAD"].includes(requestLike.method) && requestLike.body) {
init.body = requestLike.body;
}
return new Request(requestLike.url, init);
}
function escapeHtml(str) {
return String(str).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
}
function buildLoadingResponse(message, status = 503) {
return new Response(
`<!doctype html><meta charset="utf-8"><title>Moodle Playground</title><body><pre>${escapeHtml(message)}</pre></body>`,
{
status,
headers: {
"content-type": "text/html; charset=utf-8",
"cache-control": "no-store",
},
},
);
}
function resetRuntime(reason) {
if (reactiveRestartCount >= MAX_REACTIVE_RESTARTS) {
postShell({
kind: "error",
detail: `[runtime] restart limit reached (${reactiveRestartCount}/${MAX_REACTIVE_RESTARTS}), not restarting. Reason: ${reason}`,
});
return false;
}
if (requestCount < MIN_REQUESTS_BEFORE_RESTART) {
postShell({
kind: "error",
detail: `[runtime] crash after only ${requestCount} requests (minimum ${MIN_REQUESTS_BEFORE_RESTART}), likely a fundamental bug — not restarting. Reason: ${reason}`,
});
return false;
}
reactiveRestartCount += 1;
requestCount = 0;
runtimeStatePromise = null;
readyPhp = null;
phpInfoCapturePromise = null;
automaticPhpInfoAttempted = false;
activeRuntimeConfig = null;
postShell({
kind: "progress",
title: "Runtime rotation",
detail: `[runtime] restart (${reactiveRestartCount}/${MAX_REACTIVE_RESTARTS}): ${reason}`,
progress: 0.01,
});
return true;
}
async function getRuntimeState() {
if (runtimeStatePromise) {
return runtimeStatePromise;
}
runtimeStatePromise = (async () => {
const bootStart = performance.now();
const t0 = performance.now();
const config = await loadPlaygroundConfig();
const configMs = Math.round(performance.now() - t0);
const runtime = resolveRuntimeConfig(config, selection);
if (!runtime) {
throw new Error("Unable to resolve a runtime configuration.");
}
activeRuntimeConfig = {
...runtime,
corsProxyUrl: phpCorsProxyUrlOverride || config.phpCorsProxyUrl || null,
};
const branchMeta = moodleBranch ? getBranchMetadata(moodleBranch) : null;
const webRoot = branchMeta?.webRoot || "/www/moodle";
activeWebRoot = webRoot;
traceRuntimeSelection(
"resolved",
`runtimeId=${runtimeId} php=${phpVersion} moodleBranch=${moodleBranch} runtimeConfig=${runtime.id}`,
);
const php = createPhpRuntime(activeRuntimeConfig, {
appBaseUrl: appRootUrl,
phpVersion,
webRoot,
scopeId,
forceCleanBoot,
});
// Progress reporter, hoisted above refresh so the bundle-download band
// (0.16-0.44, emitted by startArchiveResolution running concurrently with
// refresh below) and the refresh band (0.12-0.14) can interleave. Clamp to
// monotonic so the bar never jumps backwards when the two interleave.
let maxProgress = 0;
const emitProgress = (title, detail, progress) => {
const elapsed = Math.round(performance.now() - bootStart);
const clamped =
typeof progress === "number" ? Math.max(maxProgress, progress) : progress;
if (typeof clamped === "number") {
maxProgress = clamped;
}
postShell({
kind: "progress",
title,
detail: `[${elapsed}ms] ${detail}`,
progress: clamped,
});
};
const publish = (detail, progress) =>
emitProgress("Bootstrapping Moodle", detail, progress);
emitProgress(
"Refreshing PHP runtime",
`[${configMs}ms config] Booting PHP ${phpVersion || "8.3"}${branchMeta ? ` + ${branchMeta.label}` : ""}.`,
0.12,
);
// Kick off the manifest resolution + bundle download NOW so it overlaps the
// WASM compile in php.refresh(). The no-op .catch prevents an
// unhandledrejection if refresh() throws first; the real error resurfaces
// at `await archivePromise` inside bootstrapMoodle and flows into the
// bootstrap-error catch below.
const archivePromise = startArchiveResolution({
moodleBranch,
appBaseUrl: appRootUrl,
publish,
});
archivePromise.catch(() => {});
const t1 = performance.now();
await php.refresh();
const refreshMs = Math.round(performance.now() - t1);
emitProgress(
"Refreshing PHP runtime",
`[${refreshMs}ms refresh] PHP runtime ready.`,
0.14,
);
const t2 = performance.now();
let bootstrapState;
try {
bootstrapState = await bootstrapMoodle({
appBaseUrl: appRootUrl,
config,
blueprint: activeBlueprint,
debug,
php,
publish,
runtimeId,
scopeId,
origin: self.location.origin,
moodleBranch,
profile,
webRoot,
onPluginInstalled: (dirPath) => snapshot.trackPluginDir(dirPath),
archivePromise,
});
} catch (error) {
if (!automaticPhpInfoAttempted) {
automaticPhpInfoAttempted = true;
void publishPhpInfo(runtime, "bootstrap-error");
}
// Clear the cached runtimeStatePromise so the next caller of
// getRuntimeState() creates a fresh runtime instead of re-throwing
// this cached rejection. The actual restart-count bookkeeping and
// retry decision live in the bridge listener (installBridgeListener),
// not here, to avoid double-counting restarts.
runtimeStatePromise = null;
readyPhp = null;
throw error;
}
const bootstrapMs = Math.round(performance.now() - t2);
const totalMs = Math.round(performance.now() - bootStart);
// downloadWaitMs = bundle download time that did NOT overlap the WASM
// compile (0 means the parallel download fully hid behind php.refresh()).
// A large value is the signal that bundle chunking could still help
// (plan F2.5 / ADR 0011).
const t = bootstrapState?.timings || {};
const downloadWaitDetail =
typeof t.downloadWaitMs === "number"
? ` | Bundle wait (post-refresh): ${t.downloadWaitMs}ms`
: "";
postShell({
kind: "progress",
title: "Boot timing summary",
detail: `Config: ${configMs}ms | PHP refresh: ${refreshMs}ms | Bootstrap: ${bootstrapMs}ms${downloadWaitDetail} | Total: ${totalMs}ms`,
progress: 0.95,
});
// Restore saved DB snapshot if recovering from a crash.
// This overwrites the fresh install snapshot with the pre-crash DB
// that contains all courses, users, and config changes.
if (snapshot.hasPendingRestore) {
const restoreResult = await snapshot.restore(php);
// If plugin files were restored, re-register them with Moodle
// (reset component cache + run upgrade) before re-login.
if (restoreResult?.pluginsRestored) {
await reRegisterPluginsAfterRestore(php, webRoot, restoreResult.restoredPluginDirs);
}
// The restore overwrites the DB, invalidating the auto-login session
// that bootstrap just created. Re-create it on the restored DB.
if (restoreResult?.restored) {
await reLoginAfterRestore(php, webRoot);
}
}
postShell({
kind: "ready",
detail: `Moodle bootstrapped for PHP ${phpVersion || "8.3"}${branchMeta ? ` + ${branchMeta.label}` : ""}. [${totalMs}ms total]`,
path: bootstrapState.readyPath || activeBlueprint?.landingPage || config.landingPath || "/",
});
// Expose the ready instance for the static fast path (installBridgeListener).
readyPhp = php;
return { php };
})();
return runtimeStatePromise;
}
/**
* Execute a single HTTP request against the PHP runtime, returning the
* Response object. Throws on fatal errors.
*/
async function executePhpRequest(state, serializedRequest) {
return state.php.request(deserializeRequest(serializedRequest));
}
/** Send an error page back through the bridge channel. */
async function respondError(id, message, status) {
const response = buildLoadingResponse(message, status);
respond({
kind: "http-response",
id,
response: await serializeResponse(response),
});
}
function installBridgeListener() {
bridgeChannel.addEventListener("message", (event) => {
const data = event.data;
if (data?.kind !== "http-request") {
return;
}
// Static fast path: serve non-.php MEMFS files (CSS/JS/images/fonts)
// WITHOUT waiting in the serial PHP request queue. readFileAsBuffer is a
// pure-JS Emscripten MEMFS read, safe to run while a php.run() is
// suspended (the worker is single-threaded). serveStaticSync returns null
// for PHP scripts, .php/PATH_INFO routes, traversals and missing files, so
// those fall through to the queue with today's exact semantics.
// requestCount and detectPluginInstall are intentionally skipped — both
// are PHP-execution concerns. HEAD/POST keep queueing.
if (data.request?.method === "GET" && readyPhp) {
let staticHit = null;
try {
const u = new URL(data.request.url);
staticHit = readyPhp.serveStaticSync(u.pathname + u.search);
} catch {
staticHit = null;
}
if (staticHit) {
respond({
kind: "http-response",
id: data.id,
response: {
status: staticHit.status,
statusText: "OK",
headers: staticHit.headers,
body: staticHit.bytes,
},
});
return;
}
}
requestQueue = requestQueue.then(async () => {
// Safety net: if this request was externally re-dispatched with
// _retried=true, skip the auto-retry path to prevent loops.
// In the current implementation, retry happens in-handler (below),
// so this is always false — but it guards against future changes.
const isRetry = Boolean(data._retried);
try {
requestCount += 1;
const state = await getRuntimeState();
const response = await executePhpRequest(state, data.request);
// Detect plugin installations from Moodle's native admin UI
detectPluginInstall(data.request, response, activeWebRoot);
respond({
kind: "http-response",
id: data.id,
response: await serializeResponse(response),
});
} catch (error) {
// Emscripten network errors (Firefox/Safari): outbound curl calls
// in WASM cannot reach external hosts. Notify the shell with a
// user-friendly warning instead of crashing the runtime.
if (isEmscriptenNetworkError(error)) {
const requestUrl = data.request?.url || "";
const pagePath = new URL(requestUrl, "http://localhost").pathname || "/";
postShell({
kind: "wasm-network-error",
detail: `Page "${pagePath}" failed — a network call could not complete in this browser's WebAssembly runtime.`,
path: pagePath,
});
await respondError(data.id, `Network call failed in WebAssembly runtime (errno 23). This is a known limitation on Firefox and Safari.`, 502);
return;
}
if (!isFatalWasmError(error)) {
// Non-fatal error: return 500 without runtime rotation.
const detail = formatErrorDetail(error);
await respondError(data.id, detail, 500);
postShell({ kind: "error", detail });
return;
}
// --- Fatal WASM error path ---
// Capture the current PHP instance reference BEFORE resetRuntime()
// clears runtimeStatePromise, but defer the actual hydration until
// we know a restart will happen. Hydration pulls the full DB, all
// uploaded files, and tracked plugin dirs into the JS heap — doing
// it when resetRuntime() returns false (e.g. the
// MIN_REQUESTS_BEFORE_RESTART guard fires on a first-boot OOM) would
// pin that large snapshot for the tab's life on an already
// memory-pressured worker, and leave hasPendingRestore stuck true.
let phpToHydrate = null;
try {
const currentState = await runtimeStatePromise;
phpToHydrate = currentState?.php?._php ? currentState.php : null;
} catch {
phpToHydrate = null;
}
const didReset = resetRuntime(`fatal WASM error: ${error.message}`);
const canReplay = isSafeToReplay(data.request);
// Only hydrate the snapshot when a restart will actually happen.
// When resetRuntime() returns false (e.g. the
// MIN_REQUESTS_BEFORE_RESTART guard fires on a first-boot OOM), no
// fresh runtime ever boots, so snapshot.restore() never runs and the
// hydrated buffers would stay pinned for the tab's life on an
// already memory-pressured worker (with hasPendingRestore stuck
// true). In that case discard any leftover snapshot instead.
//
// When resetRuntime() returns true, the next getRuntimeState() boot
// will consume the snapshot — either via the immediate replay below
// (idempotent requests) or on the next user-triggered request
// (non-idempotent requests that aren't replayed here).
if (didReset) {
// MEMFS lives in JS heap so readFileAsBuffer works even with a
// corrupted WASM linear memory.
if (phpToHydrate) {
try {
postShell({
kind: "trace",
detail: `[runtime] hydrating snapshot before runtime reset (dbPath=${buildDbPath()})`,
});
await snapshot.hydrate(phpToHydrate, buildDbPath());
} catch (hydrateErr) {
postShell({
kind: "error",
detail: `[runtime] snapshot hydration failed: ${hydrateErr.message}`,
});
}
} else {
postShell({
kind: "trace",
detail: `[runtime] no PHP instance available for snapshot hydration`,
});
}
} else {
snapshot.clear();
}
// If we already retried this request, or the request is not
// idempotent, or we hit the restart limit — give up.
if (isRetry || !canReplay || !didReset) {
const detail = formatErrorDetail(error);
const status = didReset || isRetry ? 503 : 500;
const message = isRetry
? `Runtime crashed again on retry. Manual reload required.\n\n${detail}`
: !canReplay
? `Runtime restarting after crash. Non-idempotent request was not retried.\n\n${detail}`
: `Runtime restart limit reached.\n\n${detail}`;
await respondError(data.id, message, status);
return;
}
// Automatic retry: boot a fresh runtime and replay the safe request.
postShell({
kind: "progress",
title: "Crash recovery",
detail: "[runtime] replaying request on fresh runtime…",
progress: 0.02,
});
try {
const freshState = await getRuntimeState();
const retryResponse = await executePhpRequest(freshState, data.request);
respond({
kind: "http-response",
id: data.id,
response: await serializeResponse(retryResponse),
});
} catch (retryError) {
// The retry itself failed — report but don't loop.
if (isFatalWasmError(retryError)) {
resetRuntime(`fatal WASM error on retry: ${retryError.message}`);
}
const detail = formatErrorDetail(retryError);
await respondError(
data.id,
`Runtime crashed again on retry. Manual reload required.\n\n${detail}`,
503,
);
}
}
});
});
}
function installMessageListener() {
self.addEventListener("message", (event) => {
if (event.data?.kind !== "configure-blueprint") {
if (event.data?.kind === "capture-phpinfo") {
void publishPhpInfo(activeRuntimeConfig, "manual");
}
return;
}
// Override URL-derived runtime params with authoritative values
// from remote.js, which has the correct user-selected runtime.
const params = event.data.runtimeParams;
if (params) {
if (params.scopeId !== undefined) scopeId = params.scopeId;
if (params.forceCleanBoot !== undefined)
forceCleanBoot = params.forceCleanBoot;
selection = resolveRuntimeSelection({
runtimeId: params.runtimeId,
phpVersion: params.phpVersion,
moodleBranch: params.moodleBranch,
});
runtimeId = selection.runtimeId;
phpVersion = selection.phpVersion;
moodleBranch = selection.moodleBranch;
if (params.phpCorsProxyUrl !== undefined) {
phpCorsProxyUrlOverride = params.phpCorsProxyUrl || null;
}
if (params.debug !== undefined) debug = params.debug;
if (params.profile !== undefined) profile = params.profile;
// Reset any cached runtime state so it boots with the new params.
// Discard any pending crash snapshot too: it was hydrated from the
// previous runtime/scope and must never be restored onto this freshly
// (re)configured — potentially foreign — runtime.
runtimeStatePromise = null;
snapshot.clear();
// Recreate bridge channel if scopeId changed
if (params.scopeId !== undefined && bridgeChannel) {
bridgeChannel.close();
bridgeChannel = new BroadcastChannel(createPhpBridgeChannel(scopeId));
installBridgeListener();
}
}
activeBlueprint = event.data.blueprint || null;
self.postMessage({
kind: "worker-ready",
scopeId,
runtimeId,
// Best initial landing path known before bootstrap runs. The
// authoritative post-bootstrap path (e.g. "/my/" after auto-login)
// is delivered later via the "ready" shell message; this hint lets
// remote.js point the very first navigation at the blueprint's
// landing page instead of a stale URL path from a previous session.
initialPath: activeBlueprint?.landingPage || null,
});
});
}
try {
bridgeChannel = new BroadcastChannel(createPhpBridgeChannel(scopeId));
installBridgeListener();
installMessageListener();
// Do not signal readiness here — wait for configure-blueprint message
// which carries authoritative runtime params from remote.js.
} catch (error) {
self.postMessage({
kind: "worker-startup-error",
scopeId,
runtimeId,
detail: formatErrorDetail(error),
});
throw error;
}