retention-main.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import { app, BrowserWindow, ipcMain, protocol, webContents } from "electron";
  2. import assert from "node:assert/strict";
  3. import { readFile, writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import {
  6. installPluginSandboxHost,
  7. PLUGIN_SANDBOX_PRIVILEGED_SCHEME,
  8. } from "../../src/main/pluginSandbox/index.js";
  9. const [root, profile] = process.argv.slice(2);
  10. app.setPath("userData", profile!);
  11. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  12. app
  13. .whenReady()
  14. .then(async () => {
  15. const host = installPluginSandboxHost({
  16. rendererDir: root!,
  17. aliasDir: root!,
  18. preloadPath: join(root!, "guest.cjs"),
  19. });
  20. const win = new BrowserWindow({
  21. show: false,
  22. width: 1000,
  23. height: 900,
  24. webPreferences: {
  25. preload: join(root!, "preload.cjs"),
  26. webviewTag: true,
  27. backgroundThrottling: false,
  28. },
  29. });
  30. const pending: string[] = [];
  31. win.webContents.on("will-attach-webview", (event, webPreferences, params) => {
  32. const result = host.configureGuest({
  33. webPreferences,
  34. params,
  35. ownerWebContentsId: win.webContents.id,
  36. });
  37. if (result.ok) pending.push(result.sandboxId);
  38. else event.preventDefault();
  39. });
  40. win.webContents.on("did-attach-webview", (_event, guest) =>
  41. host.attachGuest({ guest, hostWebContents: win.webContents, sandboxId: pending.shift()! }),
  42. );
  43. const html = await readFile(join(root!, "widget.html"), "utf8");
  44. let generation = 0;
  45. const register = (key: string, task: string) =>
  46. host.registerFromHost({
  47. instance: {
  48. runtimeId: "retention",
  49. generation: ++generation,
  50. token: crypto.randomUUID(),
  51. appIdentity: "c".repeat(64),
  52. },
  53. ownerWebContentsId: win.webContents.id,
  54. workspacePath: "/retention",
  55. sessionId: task,
  56. pluginId: "fixture",
  57. serverName: "fixture",
  58. scopeId: key,
  59. html,
  60. });
  61. ipcMain.handle("fixture-bridge", (_event, method, params) => {
  62. assert.equal(method, "register");
  63. return register(params.key, params.task);
  64. });
  65. await win.loadFile(join(root!, "retention.html"));
  66. await win.webContents.executeJavaScript("window.harnessReady");
  67. const run = (code: string) => win.webContents.executeJavaScript(`window.retention.${code}`);
  68. const guestCount = () =>
  69. webContents.getAllWebContents().filter((contents) => contents.getType() === "webview").length;
  70. const started = performance.now();
  71. const counts: any[] = [];
  72. for (let n = 0; n < 64; n++) assert.ok((await run(`addPage('cap-${n}','capacity')`)).sandboxId);
  73. assert.equal(guestCount(), 64);
  74. counts.push({ phase: "capacity-full", guests: guestCount(), ...(await run("counts()")) });
  75. assert.match((await run("addPage('overflow','capacity')")).error, /capacity/);
  76. assert.equal(guestCount(), 64);
  77. assert.throws(() => register("native-overflow", "capacity"), /64/);
  78. assert.equal(guestCount(), 64);
  79. await run("visibility('cap-0',false)");
  80. await run("busy('cap-0',true)");
  81. assert.match((await run("addPage('busy-overflow','capacity')")).error, /capacity/);
  82. assert.equal(guestCount(), 64);
  83. await run("busy('cap-0',false)");
  84. assert.ok((await run("addPage('replacement','capacity')")).sandboxId);
  85. assert.equal(guestCount(), 64);
  86. assert.ok((await run("counts()")).released.includes("cap-0"));
  87. await run("clear()");
  88. assert.equal(guestCount(), 0);
  89. assert.equal((await run("counts()")).ports, 0);
  90. counts.push({ phase: "capacity-cleared", guests: guestCount(), ...(await run("counts()")) });
  91. for (let n = 0; n < 30; n++) {
  92. await run(`addPage('task-${n}','task-${n}',false)`);
  93. await run(`visibility('task-${n}',false)`);
  94. }
  95. await run("busy('task-0',true)");
  96. await run("addPage('task-30','task-30',false)");
  97. assert.equal(guestCount(), 30);
  98. const lru = await run("counts()");
  99. assert.equal(lru.pages, 30);
  100. assert.equal(lru.snapshots, 30);
  101. assert.ok(lru.released.includes("task-1"));
  102. assert.ok(!lru.released.includes("task-0"));
  103. counts.push({ phase: "task-lru", guests: guestCount(), ...lru });
  104. await run("clear()");
  105. assert.equal(guestCount(), 0);
  106. await run("addPage('deadline','deadline')");
  107. await run("visibility('deadline',false)");
  108. await run("advance(299999)");
  109. assert.equal(guestCount(), 1);
  110. await run("visibility('deadline',true)");
  111. await run("advance(600000)");
  112. assert.equal(guestCount(), 1);
  113. await run("visibility('deadline',false)");
  114. await run("busy('deadline',true)");
  115. await run("advance(300000)");
  116. assert.equal(guestCount(), 1);
  117. await run("busy('deadline',false)");
  118. // 释放完成由 guest destroyed 事件确认;不使用 sleep 作为同步依据。
  119. const remaining = webContents
  120. .getAllWebContents()
  121. .filter((contents) => contents.getType() === "webview");
  122. await Promise.all(
  123. remaining.map((guest) => new Promise<void>((resolve) => guest.once("destroyed", resolve))),
  124. );
  125. assert.equal(guestCount(), 0);
  126. assert.equal((await run("counts()")).snapshots, 1);
  127. await run("clear()");
  128. const cleared = await run("counts()");
  129. assert.equal(cleared.pages, 0);
  130. assert.equal(cleared.ports, 0);
  131. assert.equal(cleared.snapshots, 0);
  132. assert.equal(cleared.timers, 0);
  133. counts.push({ phase: "all-cleared", guests: guestCount(), ...cleared });
  134. await writeFile(
  135. join(root!, "retention-results.json"),
  136. JSON.stringify({ durationMs: performance.now() - started, counts }, null, 2),
  137. );
  138. process.stdout.write("PASS real Electron 64 guests / 30 tasks / offscreen / busy retention\n");
  139. win.destroy();
  140. app.exit(0);
  141. })
  142. .catch((error) => {
  143. process.stderr.write(String(error.stack ?? error) + "\n");
  144. app.exit(1);
  145. });