unresponsive.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import type { BrowserWindow } from "electron"
  2. import { write as writeLog } from "./logging"
  3. const sampleInterval = 1000
  4. const samplePeriod = 15000
  5. export function createUnresponsiveSampler(win: BrowserWindow, name: string) {
  6. let sampleTimer: ReturnType<typeof setTimeout> | undefined
  7. let stopTimer: ReturnType<typeof setTimeout> | undefined
  8. let sampling = false
  9. const samples = new Map<string, number>()
  10. const active = () => sampling && !win.isDestroyed() && !win.webContents.isDestroyed()
  11. const clearTimers = () => {
  12. if (sampleTimer) clearTimeout(sampleTimer)
  13. if (stopTimer) clearTimeout(stopTimer)
  14. sampleTimer = undefined
  15. stopTimer = undefined
  16. }
  17. const schedule = () => {
  18. sampleTimer = setTimeout(() => {
  19. void collect()
  20. }, sampleInterval)
  21. }
  22. const collect = async () => {
  23. if (!active()) return
  24. const stack = await win.webContents.mainFrame.collectJavaScriptCallStack().catch((error) => {
  25. writeLog("window", "failed to collect unresponsive sample", { window: name, error }, "error")
  26. return undefined
  27. })
  28. if (!active()) return
  29. if (stack) samples.set(stack, (samples.get(stack) ?? 0) + 1)
  30. schedule()
  31. }
  32. const stopAndFlush = () => {
  33. const wasSampling = sampling
  34. sampling = false
  35. clearTimers()
  36. if (samples.size === 0) return wasSampling
  37. const entries = [...samples.entries()].sort((a, b) => b[1] - a[1])
  38. const total = entries.reduce((sum, entry) => sum + entry[1], 0)
  39. const message = [
  40. "renderer unresponsive samples",
  41. `Window: ${name}`,
  42. `URL: ${win.isDestroyed() ? "<destroyed>" : win.webContents.getURL()}`,
  43. ...entries.map((entry) => `<${entry[1]}> ${entry[0]}`),
  44. `Total Samples: ${total}`,
  45. ].join("\n")
  46. writeLog("window", message, undefined, "error")
  47. samples.clear()
  48. return wasSampling
  49. }
  50. const start = () => {
  51. if (sampling || win.isDestroyed() || win.webContents.isDestroyed() || win.webContents.isDevToolsOpened()) return
  52. sampling = true
  53. samples.clear()
  54. schedule()
  55. stopTimer = setTimeout(stopAndFlush, samplePeriod)
  56. }
  57. win.on("closed", stopAndFlush)
  58. return { start, stopAndFlush }
  59. }