示例工程 42-startup-and-memory

42-startup-and-memory/app/.tsc/src/App.js

javascript · 15 KB

function escape(text) {
    return text.replace(/[&<>"]/g, (char) => {
        if (char === "&")
            return "&amp;";
        if (char === "<")
            return "&lt;";
        if (char === ">")
            return "&gt;";
        return "&quot;";
    });
}
function time(at) {
    return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function mb(value) {
    return `${value.toFixed(1)} MB`;
}
function chart(samples) {
    if (samples.length < 2) {
        return `<p class="muted small">采样至少 2 次后绘制趋势。</p>`;
    }
    const width = 340;
    const height = 84;
    const values = samples.map((sample) => sample.totalMb);
    const min = Math.min(...values);
    const max = Math.max(...values);
    const span = Math.max(1, max - min);
    const points = samples
        .map((sample, index) => {
        const x = 8 + (index / (samples.length - 1)) * (width - 16);
        const y = height - 10 - ((sample.totalMb - min) / span) * (height - 24);
        return `${x.toFixed(1)},${y.toFixed(1)}`;
    })
        .join(" ");
    return `<svg viewBox="0 0 ${width} ${height}" class="spark" role="img" aria-label="总内存趋势">
    <polyline points="${points}" fill="none" stroke="#2563eb" stroke-width="2" />
    ${samples
        .map((sample, index) => {
        const x = 8 + (index / (samples.length - 1)) * (width - 16);
        const y = height - 10 - ((sample.totalMb - min) / span) * (height - 24);
        return `<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="2" fill="#2563eb" />`;
    })
        .join("")}
  </svg>
  <div class="muted small">${min.toFixed(1)}–${max.toFixed(1)} MB · ${samples.length} 个采样</div>`;
}
export function mountApp(root) {
    root.innerHTML = `
    <div class="app">
      <header class="header">
        <div class="brand">
          <span class="logo">⏱</span>
          <div>
            <h1>启动与内存实验室</h1>
            <span class="muted small">冷启动分段 · 延迟初始化 · 内存采样 · 后台节流</span>
          </div>
        </div>
        <div class="header-side">
          <span class="pill" data-testid="total">—</span>
          <span class="pill" data-testid="versions">—</span>
          <button class="btn" data-testid="refresh">刷新</button>
          <span class="muted small" data-testid="status"></span>
        </div>
      </header>

      <main class="layout">
        <div class="column">
          <section class="card pad startup-card">
            <div class="card-head">
              <h2>启动时间线</h2>
              <span class="muted small" data-testid="lazy-state">—</span>
            </div>
            <div class="total" data-testid="startup-total">0 ms</div>
            <ul class="stages" data-testid="stages"></ul>
            <div class="lazy-row">
              <span>延迟索引</span>
              <b data-testid="lazy-ms">—</b>
              <button class="btn mini" data-testid="lazy-run">重建索引</button>
            </div>
          </section>

          <section class="card pad memory-card">
            <div class="card-head">
              <h2>内存</h2>
              <span class="muted small" data-testid="allocated">0 MB 额外分配</span>
            </div>
            <div class="metrics">
              <div><span>主进程 heap</span><b data-testid="main-heap">—</b></div>
              <div><span>主进程 RSS</span><b data-testid="main-rss">—</b></div>
              <div><span>渲染进程</span><b data-testid="renderer-mem">—</b></div>
              <div><span>总计</span><b data-testid="total-mem">—</b></div>
            </div>
            <div class="actions wrap">
              <button class="btn primary" data-testid="alloc">分配 24MB</button>
              <button class="btn" data-testid="release">释放</button>
              <button class="btn" data-testid="sample">采样</button>
              <button class="btn" data-testid="heap">生成 heap snapshot</button>
            </div>
            <div class="chart" data-testid="chart"></div>
            <div class="heap-file muted small" data-testid="heap-file"></div>
          </section>

          <section class="card pad">
            <div class="card-head">
              <h2>进程内存</h2>
              <span class="muted small">app.getAppMetrics()</span>
            </div>
            <table class="process-table" data-testid="processes"></table>
          </section>
        </div>

        <div class="column">
          <section class="card pad throttle-card">
            <div class="card-head">
              <h2>后台节流</h2>
              <button class="btn" data-testid="throttle-run">运行 2 秒测试</button>
            </div>
            <ul class="throttle-facts" data-testid="throttle-facts"></ul>
            <p class="hint muted small">
              两个隐藏窗口分别 backgroundThrottling=true/false,统计 50ms 定时器
              触发次数。节流行为依赖平台与窗口状态,本机可能没有差异;不能把它
              当作省电保证。
            </p>
          </section>

          <section class="card pad">
            <div class="card-head">
              <h2>优化清单</h2>
            </div>
            <ul class="bullets">
              <li>首帧前只做窗口与最小状态;索引、解析、网络放到首帧后。</li>
              <li>延迟初始化要能观测:记录开始、完成与耗时。</li>
              <li>commandLine 开关必须在 ready 前追加,ready 后不再生效。</li>
              <li>泄漏看趋势:多次采样 + heap snapshot,而不是一次数字。</li>
              <li>隐藏窗口的定时器可能被节流,也可能不会;业务暂停要显式做。</li>
            </ul>
          </section>

          <section class="card pad">
            <div class="card-head">
              <h2>活动</h2>
              <span class="muted small">采样 / 节流 / 索引</span>
            </div>
            <ul class="activity" data-testid="events"></ul>
          </section>
        </div>
      </main>
    </div>
  `;
    const total = root.querySelector('[data-testid="total"]');
    const versions = root.querySelector('[data-testid="versions"]');
    const startupTotal = root.querySelector('[data-testid="startup-total"]');
    const stagesEl = root.querySelector('[data-testid="stages"]');
    const lazyState = root.querySelector('[data-testid="lazy-state"]');
    const lazyMs = root.querySelector('[data-testid="lazy-ms"]');
    const mainHeap = root.querySelector('[data-testid="main-heap"]');
    const mainRss = root.querySelector('[data-testid="main-rss"]');
    const rendererMem = root.querySelector('[data-testid="renderer-mem"]');
    const totalMem = root.querySelector('[data-testid="total-mem"]');
    const allocatedEl = root.querySelector('[data-testid="allocated"]');
    const chartEl = root.querySelector('[data-testid="chart"]');
    const heapFile = root.querySelector('[data-testid="heap-file"]');
    const processesEl = root.querySelector('[data-testid="processes"]');
    const throttleFacts = root.querySelector('[data-testid="throttle-facts"]');
    const eventsEl = root.querySelector('[data-testid="events"]');
    const status = root.querySelector('[data-testid="status"]');
    let state = null;
    let leak = [];
    let allocatedMb = 0;
    function renderStartup() {
        if (!state)
            return;
        if (total)
            total.textContent = `${state.startup.totalMs.toFixed(0)} ms`;
        if (startupTotal)
            startupTotal.textContent = `${state.startup.totalMs.toFixed(0)} ms`;
        if (stagesEl) {
            const max = Math.max(1, ...state.startup.stages.map((stage) => stage.deltaMs));
            stagesEl.innerHTML = state.startup.stages
                .map((stage) => `
          <li class="stage" data-testid="stage-row">
            <span class="stage-label">${escape(stage.label)}</span>
            <span class="bar"><i style="width:${Math.max(2, (stage.deltaMs / max) * 100)}%"></i></span>
            <b>${stage.deltaMs.toFixed(1)} ms</b>
          </li>`)
                .join("");
        }
        if (lazyState) {
            lazyState.textContent =
                state.startup.lazy.status === "ready"
                    ? "索引已就绪"
                    : state.startup.lazy.status === "building"
                        ? "索引构建中"
                        : "等待首帧";
        }
        if (lazyMs) {
            lazyMs.textContent =
                state.startup.lazy.status === "ready"
                    ? `${state.startup.lazy.ms} ms`
                    : "—";
        }
    }
    function renderMemory() {
        if (!state)
            return;
        const memory = state.memory;
        if (mainHeap)
            mainHeap.textContent = mb(memory.main.heapUsedMb);
        if (mainRss)
            mainRss.textContent = mb(memory.main.rssMb);
        if (rendererMem)
            rendererMem.textContent = mb(memory.rendererMb);
        if (totalMem)
            totalMem.textContent = mb(memory.totalMb);
        if (allocatedEl)
            allocatedEl.textContent = `${memory.allocatedMb} MB 额外分配`;
        if (chartEl)
            chartEl.innerHTML = chart(memory.samples);
        if (heapFile) {
            heapFile.textContent = memory.heapSnapshot
                ? `${memory.heapSnapshot.file} · ${mb(memory.heapSnapshot.bytes / 1024 / 1024)}`
                : "";
        }
        if (processesEl) {
            processesEl.innerHTML = `
        <thead><tr><th>类型</th><th>PID</th><th>工作集</th><th>峰值</th><th>CPU</th></tr></thead>
        <tbody>${memory.processes
                .map((row) => `<tr>
              <td>${escape(row.type)}</td>
              <td>${row.pid}</td>
              <td>${mb(row.workingSetMb)}</td>
              <td>${mb(row.peakMb)}</td>
              <td>${row.cpu}%</td>
            </tr>`)
                .join("")}</tbody>`;
        }
    }
    function renderThrottle() {
        if (!throttleFacts || !state)
            return;
        const result = state.throttle;
        throttleFacts.innerHTML = result
            ? `<li><span>backgroundThrottling=true</span><b data-testid="true-ticks">${result.trueTicks} ticks</b></li>
         <li><span>backgroundThrottling=false</span><b data-testid="false-ticks">${result.falseTicks} ticks</b></li>
         <li><span>测量时长</span><b>${result.durationMs} ms</b></li>
         <li><span>差异</span><b>${result.trueTicks === result.falseTicks ? "本机未观察到" : "存在差异"}</b></li>`
            : `<li class="muted small">尚未运行</li>`;
    }
    function renderEvents() {
        if (!eventsEl || !state)
            return;
        eventsEl.innerHTML =
            state.events.length === 0
                ? `<li class="muted small">暂无活动</li>`
                : state.events
                    .slice(0, 8)
                    .map((row) => `
              <li class="event-row" data-testid="event-row">
                <span class="muted">${time(row.at)}</span>
                <span class="kind">${escape(row.kind)}</span>
                <span>${escape(row.detail)}</span>
              </li>`)
                    .join("");
    }
    function render(next) {
        state = next;
        if (versions) {
            versions.textContent = `Electron ${next.electronVersion} · Node ${next.nodeVersion}`;
        }
        renderStartup();
        renderMemory();
        renderThrottle();
        renderEvents();
    }
    void window.api.perf.snapshot().then(render);
    const unsubscribe = window.api.perf.onEvent(() => {
        void window.api.perf.snapshot().then(render);
    });
    requestAnimationFrame(() => {
        requestAnimationFrame(() => {
            const paint = performance
                .getEntriesByType("paint")
                .find((entry) => entry.name === "first-paint");
            const navigation = performance.getEntriesByType("navigation")[0];
            const firstPaint = performance.timeOrigin + (paint?.startTime ?? performance.now());
            const dcl = performance.timeOrigin +
                (navigation?.domContentLoadedEventEnd ?? performance.now());
            void window.api.perf
                .reportPaint(firstPaint, dcl)
                .then(render)
                .catch(() => undefined);
        });
    });
    const allocate = (value) => {
        const count = Math.floor((value * 1024 * 1024) / 8);
        leak.push(new Array(count).fill(1));
        allocatedMb += value;
    };
    const release = () => {
        leak = [];
        allocatedMb = 0;
    };
    root
        .querySelector('[data-testid="alloc"]')
        ?.addEventListener("click", async () => {
        allocate(24);
        render(await window.api.perf.sample(allocatedMb));
    });
    root
        .querySelector('[data-testid="release"]')
        ?.addEventListener("click", async () => {
        release();
        render(await window.api.perf.sample(0));
    });
    root
        .querySelector('[data-testid="sample"]')
        ?.addEventListener("click", async () => {
        render(await window.api.perf.sample(allocatedMb));
    });
    root
        .querySelector('[data-testid="heap"]')
        ?.addEventListener("click", async () => {
        render(await window.api.perf.heap());
    });
    root
        .querySelector('[data-testid="lazy-run"]')
        ?.addEventListener("click", async () => {
        render(await window.api.perf.lazy());
    });
    root
        .querySelector('[data-testid="throttle-run"]')
        ?.addEventListener("click", async () => {
        render(await window.api.perf.throttle());
        if (status)
            status.textContent = "节流测试完成";
    });
    root
        .querySelector('[data-testid="refresh"]')
        ?.addEventListener("click", async () => {
        render(await window.api.perf.refresh());
    });
    const sleep = (value) => new Promise((resolve) => setTimeout(resolve, value));
    window.__prepareShots = async (stage) => {
        document.body.dataset.shot = stage;
        if (stage === "startup") {
            render(await window.api.perf.refresh());
            return;
        }
        if (stage === "memory") {
            allocate(24);
            render(await window.api.perf.sample(24));
            return;
        }
        release();
        render(await window.api.perf.throttle());
        await sleep(150);
    };
    window.__smoke = async () => {
        const api = window.api.perf;
        const first = await api.snapshot();
        await api.sample(0);
        allocate(24);
        const allocated = await api.sample(24);
        release();
        await api.sample(0);
        const throttleResult = await api.throttle();
        await sleep(400);
        const final = await api.refresh();
        unsubscribe();
        return {
            startupTotal: first.startup.totalMs,
            stageCount: first.startup.stages.length,
            firstPaint: first.startup.firstPaintMs,
            mainHeap: final.memory.main.heapUsedMb,
            rendererMb: final.memory.rendererMb,
            processCount: final.memory.processes.length,
            sampleCount: final.memory.samples.length,
            allocatedMb: allocated.memory.allocatedMb,
            trueTicks: throttleResult.throttle?.trueTicks ?? 0,
            falseTicks: throttleResult.throttle?.falseTicks ?? 0,
            throttleDuration: throttleResult.throttle?.durationMs ?? 0,
            lazyMs: final.startup.lazy.ms,
            lazyStatus: final.startup.lazy.status,
            events: final.events.length,
        };
    };
}
//# sourceMappingURL=App.js.map