Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(desktop): stop writing startup-metrics.log outside dev (closes #11165)
Elian Doran5dc67033b3ed
diff --git a/.gitignore b/.gitignoreindex 23d707912e..cfec86f157 100644--- a/.gitignore+++ b/.gitignore@@ -27,7 +27,6 @@ node_modulesnpm-debug.logyarn-error.logtestem.log-startup-metrics.log/typings# System Filesdiff --git a/apps/desktop/src/services/startup_metrics.spec.ts b/apps/desktop/src/services/startup_metrics.spec.tsindex 8712ce7af1..fa616cea9c 100644--- a/apps/desktop/src/services/startup_metrics.spec.ts+++ b/apps/desktop/src/services/startup_metrics.spec.ts@@ -4,6 +4,7 @@ type Handler = (...args: unknown[]) => void;const h = vi.hoisted(() => ({ipcOn: new Map<string, Handler>(),+ mkdirSync: vi.fn(),writeFileSync: vi.fn(),writeShouldThrow: false}));@@ -14,8 +15,13 @@ vi.mock("electron", () => ({}}));+vi.mock("@triliumnext/server/src/services/data_dir.js", () => ({+ default: { LOG_DIR: "/tmp/trilium-data/log" }+}));+vi.mock("fs", () => ({default: {+ mkdirSync: (...args: unknown[]) => h.mkdirSync(...args),writeFileSync: (...args: unknown[]) => {if (h.writeShouldThrow) {throw new Error("disk full");@@ -25,27 +31,29 @@ vi.mock("fs", () => ({}}));+const METRICS_PATH = ["/tmp/trilium-data/log", "startup-metrics.log"].join(process.platform === "win32" ? "\\" : "/");+describe("startup metrics", () => {let metrics: typeof import("./startup_metrics.js");beforeEach(async () => {h.ipcOn.clear();+ h.mkdirSync.mockClear();h.writeFileSync.mockClear();h.writeShouldThrow = false;+ vi.stubEnv("TRILIUM_ENV", "dev");vi.resetModules();metrics = await import("./startup_metrics.js");});- it("records a metric relative to the baseline and rewrites the metrics file", () => {+ it("records a metric relative to the baseline and rewrites the metrics file in the log directory", () => {metrics.markStartupMetric("test-phase");const elapsed = metrics.getStartupMetrics().get("test-phase");expect(elapsed).toBeGreaterThanOrEqual(0);+ expect(h.mkdirSync).toHaveBeenCalledWith("/tmp/trilium-data/log", { recursive: true, mode: 0o700 });expect(h.writeFileSync).toHaveBeenCalledTimes(1);- expect(h.writeFileSync).toHaveBeenCalledWith(- "startup-metrics.log",- expect.stringContaining("test-phase:")- );+ expect(h.writeFileSync).toHaveBeenCalledWith(METRICS_PATH, expect.stringContaining("test-phase:"));// Re-marking keeps the first measurement and does not rewrite the file.metrics.markStartupMetric("test-phase");@@ -70,6 +78,23 @@ describe("startup metrics", () => {expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("startup-metrics.log"));});+ it("writes no file outside dev unless TRILIUM_STARTUP_METRICS is set", async () => {+ vi.stubEnv("TRILIUM_ENV", "");+ vi.resetModules();+ metrics = await import("./startup_metrics.js");++ metrics.markStartupMetric("test-phase");+ expect(metrics.getStartupMetrics().has("test-phase")).toBe(true);+ expect(h.writeFileSync).not.toHaveBeenCalled();++ vi.stubEnv("TRILIUM_STARTUP_METRICS", "1");+ vi.resetModules();+ metrics = await import("./startup_metrics.js");++ metrics.markStartupMetric("test-phase");+ expect(h.writeFileSync).toHaveBeenCalledTimes(1);+ });+it("accepts allowlisted renderer metrics over IPC and rejects everything else", () => {metrics.setupStartupMetricsIpc();const handler = h.ipcOn.get("report-startup-metric");diff --git a/apps/desktop/src/services/startup_metrics.ts b/apps/desktop/src/services/startup_metrics.tsindex 2bcbe370d0..60dfe78194 100644--- a/apps/desktop/src/services/startup_metrics.ts+++ b/apps/desktop/src/services/startup_metrics.ts@@ -1,6 +1,8 @@import type { RendererStartupMetric } from "@triliumnext/commons";+import dataDir from "@triliumnext/server/src/services/data_dir.js";import { ipcMain } from "electron";import fs from "fs";+import path from "path";/*** Startup timing instrumentation for the desktop app.@@ -11,15 +13,19 @@ import fs from "fs";* Trilium controls. Falls back to the load time of this module in the rare* case the OS does not report a creation time.*- * The metrics are written to {@link STARTUP_METRICS_FILE} (rewritten on every- * mark, so the file always holds the complete picture of the current launch)- * to keep them out of the regular log stream.+ * The marks are always kept in memory, but they are only written to+ * {@link STARTUP_METRICS_FILE} when {@link metricsFileEnabled} — `pnpm+ * desktop:start` sets `TRILIUM_ENV=dev`, and `TRILIUM_STARTUP_METRICS=1` turns+ * the file on for a packaged build. The file is rewritten on every mark, so it+ * always holds the complete picture of the current launch.** Only the first occurrence of each metric is recorded: window reloads, extra* windows, and repeated phase marks do not overwrite the startup measurement.*/-const STARTUP_METRICS_FILE = "startup-metrics.log";+const STARTUP_METRICS_FILE = path.join(dataDir.LOG_DIR, "startup-metrics.log");++const metricsFileEnabled = process.env.TRILIUM_ENV === "dev" || !!process.env.TRILIUM_STARTUP_METRICS;const baselineEpochMs: number = process.getCreationTime?.() ?? Date.now();@@ -36,6 +42,10 @@ export function markStartupMetric(name: string) {recordedMetrics.set(name, Math.round(Date.now() - baselineEpochMs));+ if (!metricsFileEnabled) {+ return;+ }+// One line per metric: the duration of the phase (delta to the previous// metric), with the cumulative time since process creation in parentheses.let previousElapsedMs = 0;@@ -45,6 +55,8 @@ export function markStartupMetric(name: string) {return line;});try {+ // The first mark runs before ServerLogService has opened the log directory.+ fs.mkdirSync(dataDir.LOG_DIR, { recursive: true, mode: 0o700 });fs.writeFileSync(STARTUP_METRICS_FILE, `${lines.join("\n")}\n`);} catch (e) {// Instrumentation must never break startup; the metric stays available