browser-background-activity-smoke.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import { app, BrowserWindow, webContents } from "electron";
  2. const BACKGROUND_SETTLE_MS = 800;
  3. const ACTIVE_SAMPLE_MS = 400;
  4. const CAPTURING_SAMPLE_MS = 1000;
  5. const CAPTURING_GUEST_MIN_INTERVAL_MS = 200;
  6. // executeJavaScript 自身会短时调度少量帧;timer 计数用于补足后台静止的稳定判据。
  7. const THROTTLED_MAX_FRAMES = 12;
  8. const THROTTLED_MAX_TIMERS = 3;
  9. function wait(timeoutMs) {
  10. return new Promise((resolve) => setTimeout(resolve, timeoutMs));
  11. }
  12. function activityPageHtml(body = "") {
  13. return `<!doctype html>
  14. <html>
  15. <body>
  16. ${body}
  17. <script>
  18. window.activityStats = { frames: 0, timers: 0 };
  19. const countFrame = () => {
  20. window.activityStats.frames += 1;
  21. requestAnimationFrame(countFrame);
  22. };
  23. requestAnimationFrame(countFrame);
  24. setInterval(() => {
  25. window.activityStats.timers += 1;
  26. }, 10);
  27. window.resetActivityStats = () => {
  28. window.activityStats = { frames: 0, timers: 0 };
  29. };
  30. window.readActivityStats = () => ({
  31. ...window.activityStats,
  32. visibility: document.visibilityState,
  33. });
  34. </script>
  35. </body>
  36. </html>`;
  37. }
  38. function dataUrl(html) {
  39. return `data:text/html;base64,${Buffer.from(html).toString("base64")}`;
  40. }
  41. function hostPageHtml(targetGuestUrl, siblingGuestUrl) {
  42. return activityPageHtml(`
  43. <webview id="target-guest" src=${JSON.stringify(targetGuestUrl)} style="width: 320px; height: 200px"></webview>
  44. <webview id="sibling-guest" src=${JSON.stringify(siblingGuestUrl)} style="width: 1px; height: 1px"></webview>
  45. <script>
  46. window.waitForGuestIds = () =>
  47. new Promise((resolve, reject) => {
  48. let attempts = 100;
  49. const poll = () => {
  50. try {
  51. const targetId = document.getElementById("target-guest").getWebContentsId();
  52. const siblingId = document.getElementById("sibling-guest").getWebContentsId();
  53. if (targetId > 0 && siblingId > 0) {
  54. resolve({ targetId, siblingId });
  55. return;
  56. }
  57. } catch {}
  58. attempts -= 1;
  59. if (attempts === 0) {
  60. reject(new Error("guest webContents did not become ready"));
  61. return;
  62. }
  63. setTimeout(poll, 20);
  64. };
  65. poll();
  66. });
  67. </script>
  68. `);
  69. }
  70. async function resetStats(contents) {
  71. await contents.executeJavaScript("window.resetActivityStats()", true);
  72. }
  73. async function readStats(contents) {
  74. return await contents.executeJavaScript("window.readActivityStats()", true);
  75. }
  76. async function readAllStats(win, targetGuest, siblingGuest) {
  77. const [host, target, sibling] = await Promise.all([
  78. readStats(win.webContents),
  79. readStats(targetGuest),
  80. readStats(siblingGuest),
  81. ]);
  82. return { host, target, sibling };
  83. }
  84. function assertThrottled(label, stats) {
  85. if (
  86. stats.visibility !== "hidden" ||
  87. stats.frames > THROTTLED_MAX_FRAMES ||
  88. stats.timers > THROTTLED_MAX_TIMERS
  89. ) {
  90. throw new Error(`${label} did not throttle: ${JSON.stringify(stats)}`);
  91. }
  92. }
  93. function assertActive(label, before, after) {
  94. const frames = after.frames - before.frames;
  95. const timers = after.timers - before.timers;
  96. if (frames < 5 || timers < 10) {
  97. throw new Error(`${label} did not wake: ${JSON.stringify({ before, after })}`);
  98. }
  99. return { frames, timers };
  100. }
  101. function assertRestored(label, before, after) {
  102. const frames = after.frames - before.frames;
  103. const timers = after.timers - before.timers;
  104. if (
  105. after.visibility !== "hidden" ||
  106. frames > THROTTLED_MAX_FRAMES ||
  107. timers > THROTTLED_MAX_TIMERS
  108. ) {
  109. throw new Error(`${label} did not restore throttling: ${JSON.stringify({ before, after })}`);
  110. }
  111. return { frames, timers };
  112. }
  113. function assertPaced(label, before, after) {
  114. const frames = after.frames - before.frames;
  115. const timers = after.timers - before.timers;
  116. if (frames < 3 || timers < 3) {
  117. throw new Error(
  118. `${label} did not advance under paced activity: ${JSON.stringify({ before, after })}`,
  119. );
  120. }
  121. return { frames, timers };
  122. }
  123. function startCapturePump(contents, target, state, fail) {
  124. let captureCount = 0;
  125. const capture = async () => {
  126. captureCount += 1;
  127. try {
  128. await contents.capturePage({ x: 0, y: 0, width: 1, height: 1 });
  129. return true;
  130. } catch (error) {
  131. fail(target, error);
  132. return false;
  133. }
  134. };
  135. const settled = (async () => {
  136. let pendingStartedAt = Date.now();
  137. let pending = capture();
  138. while (pending) {
  139. const mode = !state.active
  140. ? "stopped"
  141. : !state.prepared
  142. ? "continuous"
  143. : target === "guest"
  144. ? "paced"
  145. : "stopped";
  146. if (mode === "stopped") {
  147. await pending;
  148. pending = undefined;
  149. continue;
  150. }
  151. if (mode === "continuous") {
  152. const nextStartedAt = Date.now();
  153. const next = capture();
  154. if (!(await pending)) {
  155. await next;
  156. pending = undefined;
  157. continue;
  158. }
  159. pending = next;
  160. pendingStartedAt = nextStartedAt;
  161. continue;
  162. }
  163. if (!(await pending)) {
  164. pending = undefined;
  165. continue;
  166. }
  167. pending = undefined;
  168. const remainingMs = Math.max(
  169. 0,
  170. CAPTURING_GUEST_MIN_INTERVAL_MS - (Date.now() - pendingStartedAt),
  171. );
  172. if (remainingMs > 0) await wait(remainingMs);
  173. if (!state.active) continue;
  174. pendingStartedAt = Date.now();
  175. pending = capture();
  176. }
  177. })();
  178. return {
  179. getCaptureCount: () => captureCount,
  180. settled,
  181. };
  182. }
  183. function startCaptureActivity(contentsList) {
  184. const state = { active: true, prepared: false };
  185. let resolveInvalidated;
  186. const invalidated = new Promise((resolve) => {
  187. resolveInvalidated = resolve;
  188. });
  189. let failure;
  190. const fail = (target, error) => {
  191. if (failure) return;
  192. failure = new Error(
  193. `activity capture failed for ${target}: ${error instanceof Error ? error.message : String(error)}`,
  194. );
  195. state.active = false;
  196. resolveInvalidated(failure);
  197. };
  198. const pumps = contentsList.map((contents, index) =>
  199. startCapturePump(contents, index === 0 ? "owner" : "guest", state, fail),
  200. );
  201. return {
  202. getCaptureCounts: () => ({
  203. owner: pumps[0].getCaptureCount(),
  204. guest: pumps[1].getCaptureCount(),
  205. }),
  206. invalidated,
  207. markPrepared: () => {
  208. state.prepared = true;
  209. },
  210. ownerSettled: pumps[0].settled,
  211. release: () => {
  212. state.active = false;
  213. },
  214. settled: Promise.all(pumps.map((pump) => pump.settled)),
  215. };
  216. }
  217. async function run() {
  218. let win;
  219. let targetGuest;
  220. let siblingGuest;
  221. let activity;
  222. let exitCode = 0;
  223. try {
  224. await app.whenReady();
  225. const targetGuestUrl = dataUrl(activityPageHtml());
  226. const siblingGuestUrl = dataUrl(activityPageHtml());
  227. win = new BrowserWindow({
  228. width: 480,
  229. height: 320,
  230. show: true,
  231. webPreferences: {
  232. webviewTag: true,
  233. },
  234. });
  235. await win.loadURL(dataUrl(hostPageHtml(targetGuestUrl, siblingGuestUrl)));
  236. const guestIds = await win.webContents.executeJavaScript("window.waitForGuestIds()", true);
  237. targetGuest = webContents.fromId(guestIds.targetId);
  238. siblingGuest = webContents.fromId(guestIds.siblingId);
  239. if (!targetGuest || !siblingGuest) {
  240. throw new Error(`guest webContents not found: ${JSON.stringify(guestIds)}`);
  241. }
  242. if (
  243. targetGuest.hostWebContents?.id !== win.webContents.id ||
  244. siblingGuest.hostWebContents?.id !== win.webContents.id
  245. ) {
  246. throw new Error("webview guests must belong to the smoke owner BrowserWindow");
  247. }
  248. await Promise.all([
  249. targetGuest.executeJavaScript("document.readyState", true),
  250. siblingGuest.executeJavaScript("document.readyState", true),
  251. ]);
  252. await wait(200);
  253. win.hide();
  254. await wait(200);
  255. if (!win.webContents.getBackgroundThrottling()) {
  256. throw new Error("BrowserWindow must default to background throttling enabled");
  257. }
  258. await Promise.all([
  259. resetStats(win.webContents),
  260. resetStats(targetGuest),
  261. resetStats(siblingGuest),
  262. ]);
  263. await wait(BACKGROUND_SETTLE_MS);
  264. const throttled = await readAllStats(win, targetGuest, siblingGuest);
  265. assertThrottled("background host renderer", throttled.host);
  266. assertThrottled("background target webview guest", throttled.target);
  267. assertThrottled("background sibling webview guest", throttled.sibling);
  268. activity = startCaptureActivity([win.webContents, targetGuest]);
  269. await wait(ACTIVE_SAMPLE_MS);
  270. const active = await readAllStats(win, targetGuest, siblingGuest);
  271. const activeDelta = {
  272. host: assertActive("activity host renderer", throttled.host, active.host),
  273. target: assertActive("activity target webview guest", throttled.target, active.target),
  274. sibling: assertRestored("activity sibling webview guest", throttled.sibling, active.sibling),
  275. };
  276. activity.markPrepared();
  277. await activity.ownerSettled;
  278. const capturingBefore = await readAllStats(win, targetGuest, siblingGuest);
  279. const captureCountsBefore = activity.getCaptureCounts();
  280. await wait(CAPTURING_SAMPLE_MS);
  281. const capturingAfter = await readAllStats(win, targetGuest, siblingGuest);
  282. const captureCountsAfter = activity.getCaptureCounts();
  283. const capturingDelta = {
  284. host: assertRestored("prepared host renderer", capturingBefore.host, capturingAfter.host),
  285. target: assertPaced(
  286. "prepared target webview guest",
  287. capturingBefore.target,
  288. capturingAfter.target,
  289. ),
  290. sibling: assertRestored(
  291. "prepared sibling webview guest",
  292. capturingBefore.sibling,
  293. capturingAfter.sibling,
  294. ),
  295. };
  296. const capturingCaptureDelta = {
  297. owner: captureCountsAfter.owner - captureCountsBefore.owner,
  298. guest: captureCountsAfter.guest - captureCountsBefore.guest,
  299. };
  300. if (capturingCaptureDelta.owner !== 0 || capturingCaptureDelta.guest > 7) {
  301. throw new Error(
  302. `prepared activity capture rate was not bounded: ${JSON.stringify(capturingCaptureDelta)}`,
  303. );
  304. }
  305. activity.release();
  306. await activity.settled;
  307. await Promise.all([
  308. resetStats(win.webContents),
  309. resetStats(targetGuest),
  310. resetStats(siblingGuest),
  311. ]);
  312. await wait(BACKGROUND_SETTLE_MS);
  313. const restored = await readAllStats(win, targetGuest, siblingGuest);
  314. assertThrottled("restored host renderer", restored.host);
  315. assertThrottled("restored target webview guest", restored.target);
  316. assertThrottled("restored sibling webview guest", restored.sibling);
  317. if (!win.webContents.getBackgroundThrottling()) {
  318. throw new Error("activity lease must not disable BrowserWindow background throttling");
  319. }
  320. const injectedFailure = startCaptureActivity([
  321. {
  322. capturePage: () => Promise.reject(new Error("injected capture failure")),
  323. },
  324. {
  325. capturePage: () => Promise.resolve(),
  326. },
  327. ]);
  328. const failure = await Promise.race([
  329. injectedFailure.invalidated,
  330. wait(500).then(() => undefined),
  331. ]);
  332. if (!(failure instanceof Error) || !failure.message.includes("injected capture failure")) {
  333. throw new Error("activity capture failure was not surfaced");
  334. }
  335. await injectedFailure.settled;
  336. const failureCaptureCounts = injectedFailure.getCaptureCounts();
  337. if (failureCaptureCounts.owner > 2 || failureCaptureCounts.guest > 2) {
  338. throw new Error(
  339. `activity capture failure did not stop pumps: ${JSON.stringify(failureCaptureCounts)}`,
  340. );
  341. }
  342. console.log(
  343. JSON.stringify({
  344. throttled,
  345. activeDelta,
  346. capturingDelta,
  347. capturingCaptureDelta,
  348. failureCaptureCounts,
  349. restored,
  350. }),
  351. );
  352. } catch (error) {
  353. exitCode = 1;
  354. console.error(error);
  355. } finally {
  356. activity?.release();
  357. await activity?.settled.catch(() => undefined);
  358. if (win && !win.isDestroyed()) win.destroy();
  359. app.exit(exitCode);
  360. }
  361. }
  362. void run();