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(standalone): keep the backend log readable when its file is held
Elian Doran973c24b9277a
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex daa40aa7b5..376c07fde6 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -342,7 +342,8 @@},"backend_log": {"log-does-not-exist": "The backend log file '{{ fileName }}' does not exist (yet).",- "reading-log-failed": "Reading the backend log file '{{ fileName }}' failed."+ "reading-log-failed": "Reading the backend log file '{{ fileName }}' failed.",+ "log-file-unavailable": "The log file could not be opened, so only the most recent entries kept in memory are shown. Trilium keeps trying to open it and writes these entries to it once it can."},"content_renderer": {"note-cannot-be-displayed": "This note type cannot be displayed.",diff --git a/apps/standalone/src/lightweight/log_provider.spec.ts b/apps/standalone/src/lightweight/log_provider.spec.tsindex 0abfebde64..3fb00a7007 100644--- a/apps/standalone/src/lightweight/log_provider.spec.ts+++ b/apps/standalone/src/lightweight/log_provider.spec.ts@@ -1,7 +1,7 @@import type { LogFileInfo } from "@triliumnext/core";import { afterEach, describe, expect, it, vi } from "vitest";-import StandaloneLogService from "./log_provider.js";+import StandaloneLogService, { MAX_PENDING_ENTRIES } from "./log_provider.js";interface NavWithStorage {storage?: { getDirectory?: () => Promise<unknown> };@@ -20,6 +20,7 @@ interface LogInternals {currentFile: unknown;currentFileName: string;logDir: unknown;+ pendingEntries: string[];}const realStorageDescriptor = Object.getOwnPropertyDescriptor(navigator, "storage");@@ -160,10 +161,15 @@ describe("StandaloneLogService file handling", () => {expect(internal.currentFileName).toBe("");});- it("writeEntry logs to the console when no file is open", () => {+ it("keeps entries in memory while no file is open, dropping the oldest past the cap", () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- internalsOf(new StandaloneLogService()).writeEntry("console fallback");- expect(logSpy).toHaveBeenCalledWith("console fallback");+ const internal = internalsOf(new StandaloneLogService());+ for (let i = 0; i <= MAX_PENDING_ENTRIES; i++) {+ internal.writeEntry(`entry ${i}\n`);+ }+ expect(logSpy).not.toHaveBeenCalled();+ expect(internal.pendingEntries).toHaveLength(MAX_PENDING_ENTRIES);+ expect(internal.pendingEntries[0]).toBe("entry 1\n");});it("closeLogFile is a no-op when nothing is open", () => {@@ -184,6 +190,80 @@ describe("StandaloneLogService file handling", () => {});});+describe("StandaloneLogService when the log file is held elsewhere", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ /** Sync access handles fail until `release()` is called, as when another worker holds them. */+ function installHeldOpfs() {+ const handle = makeSyncHandle();+ let held = true;+ let attempts = 0;+ installOpfs({+ createSyncAccessHandle: async () => {+ attempts++;+ if (held) {+ throw new Error("locked");+ }+ return handle;+ }+ });+ return { handle, release: () => { held = false; }, attempts: () => attempts };+ }++ it("serves the in-memory entries, then writes them to the file once it opens", async () => {+ vi.useFakeTimers();+ vi.spyOn(console, "warn").mockImplementation(() => {});+ vi.spyOn(console, "log").mockImplementation(() => {});+ const opfs = installHeldOpfs();++ const service = new StandaloneLogService();+ const init = service.initialize();+ await vi.advanceTimersByTimeAsync(1_000);+ await init;+ expect(internalsOf(service).currentFile).toBeNull();++ service.info("while held");+ const inMemory = service.getLogContents();+ expect(inMemory).toContain("The log file could not be opened");+ expect(inMemory).toContain("while held");++ // Retries keep going in the background.+ const attemptsBefore = opfs.attempts();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(opfs.attempts()).toBeGreaterThan(attemptsBefore);++ opfs.release();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(internalsOf(service).currentFile).toBe(opfs.handle);+ expect(internalsOf(service).pendingEntries).toEqual([]);++ service.info("after release");+ const fromFile = service.getLogContents();+ expect(fromFile).not.toContain("The log file could not be opened");+ expect(fromFile).toMatch(/while held\n.*after release\n$/s);+ });++ it("stops retrying once the file is closed", async () => {+ vi.useFakeTimers();+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const opfs = installHeldOpfs();+ const internal = internalsOf(new StandaloneLogService());++ const open = internal.openLogFile("trilium-2024-07-01.log");+ await vi.advanceTimersByTimeAsync(1_000);+ await open;+ internal.closeLogFile();++ const attemptsAfterClose = opfs.attempts();+ opfs.release();+ await vi.advanceTimersByTimeAsync(120_000);+ expect(opfs.attempts()).toBe(attemptsAfterClose);+ expect(internal.currentFile).toBeNull();+ });+});+describe("StandaloneLogService listing and deletion", () => {it("lists only well-formed log files with parsed dates", async () => {installOpfs({diff --git a/apps/standalone/src/lightweight/log_provider.ts b/apps/standalone/src/lightweight/log_provider.tsindex eef89a007d..1cc8b3a983 100644--- a/apps/standalone/src/lightweight/log_provider.ts+++ b/apps/standalone/src/lightweight/log_provider.ts@@ -1,8 +1,15 @@import { FileBasedLogService, type LogFileInfo } from "@triliumnext/core";+import { t } from "i18next";const LOG_DIR_NAME = "logs";const LOG_FILE_PATTERN = /^trilium-\d{4}-\d{2}-\d{2}\.log$/;const DEFAULT_RETENTION_DAYS = 7;+const OPEN_ATTEMPTS = 3;+const OPEN_RETRY_DELAY_MS = 100;+const BACKGROUND_RETRY_INITIAL_MS = 1_000;+const BACKGROUND_RETRY_MAX_MS = 30_000;+/** Entries kept in memory while no log file is open. */+export const MAX_PENDING_ENTRIES = 5_000;/*** Standalone log service using OPFS (Origin Private File System).@@ -14,6 +21,13 @@ export default class StandaloneLogService extends FileBasedLogService {private currentFileName: string = "";private textEncoder = new TextEncoder();private textDecoder = new TextDecoder();+ /** Entries written while no file is open, flushed to the file once it opens. */+ private pendingEntries: string[] = [];+ /** Set while the background retry is the only thing that can open the log file. */+ private fileUnavailable = false;+ private retryTimer: ReturnType<typeof setTimeout> | null = null;+ /** Incremented on every open and close, so an attempt for an older file discards its handle. */+ private openGeneration = 0;constructor() {super();@@ -31,50 +45,47 @@ export default class StandaloneLogService extends FileBasedLogService {}protected override async openLogFile(fileName: string): Promise<void> {+ this.closeLogFile();+ const generation = this.openGeneration;+if (!this.logDir) {await this.ensureLogDirectory();}-- // Close existing file if open- if (this.currentFile) {- this.currentFile.close();- this.currentFile = null;+ if (!this.logDir) {+ return;}- const fileHandle = await this.logDir!.getFileHandle(fileName, { create: true });-- // Try to create sync access handle with retry logic for worker restarts- // Previous worker may have left handle open before being terminated- const maxRetries = 3;- const retryDelay = 100;+ const fileHandle = await this.logDir.getFileHandle(fileName, { create: true });- for (let attempt = 0; attempt < maxRetries; attempt++) {+ // A worker that was just replaced can still hold the handle for a moment.+ for (let attempt = 0; attempt < OPEN_ATTEMPTS; attempt++) {try {- this.currentFile = await fileHandle.createSyncAccessHandle();- break;+ this.adoptFile(await fileHandle.createSyncAccessHandle(), fileName, generation);+ return;} catch (error) {- if (attempt === maxRetries - 1) {- // Last attempt failed - fall back to console-only logging- console.warn("[LogService] Could not open log file, using console-only logging:", error);- this.currentFile = null;- this.currentFileName = "";+ if (attempt === OPEN_ATTEMPTS - 1) {+ console.warn(+ "[LogService] Could not open log file, retrying in the background:", error+ );+ this.fileUnavailable = true;+ this.scheduleRetry(+ fileHandle, fileName, generation, BACKGROUND_RETRY_INITIAL_MS+ );return;}- // Wait before retrying - previous handle may be released- await new Promise(resolve => setTimeout(resolve, retryDelay * (attempt + 1)));+ const delayMs = OPEN_RETRY_DELAY_MS * (attempt + 1);+ await new Promise(resolve => setTimeout(resolve, delayMs));}}-- this.currentFileName = fileName;-- // Seek to end for appending- if (this.currentFile) {- const size = this.currentFile.getSize();- this.currentFile.truncate(size); // No-op, but ensures we're at the right position- }}protected override closeLogFile(): void {+ this.openGeneration++;+ this.fileUnavailable = false;+ if (this.retryTimer) {+ clearTimeout(this.retryTimer);+ this.retryTimer = null;+ }if (this.currentFile) {this.currentFile.close();this.currentFile = null;@@ -84,7 +95,10 @@ export default class StandaloneLogService extends FileBasedLogService {protected override writeEntry(entry: string): void {if (!this.currentFile) {- console.log(entry); // Fallback to console if file not ready+ this.pendingEntries.push(entry);+ if (this.pendingEntries.length > MAX_PENDING_ENTRIES) {+ this.pendingEntries.shift();+ }return;}@@ -162,8 +176,55 @@ export default class StandaloneLogService extends FileBasedLogService {}}+ override getLogContents(): string | null {+ const contents = super.getLogContents();+ if (contents !== null || this.currentFile) {+ return contents;+ }+ const entries = this.pendingEntries.join("");+ return this.fileUnavailable+ ? `${t("backend_log.log-file-unavailable")}\n\n${entries}`+ : entries;+ }+protected override getRetentionDays(): number {// Standalone doesn't have config system, use defaultreturn DEFAULT_RETENTION_DAYS;}++ private adoptFile(+ accessHandle: FileSystemSyncAccessHandle, fileName: string, generation: number+ ): void {+ if (generation !== this.openGeneration) {+ accessHandle.close();+ return;+ }+ this.currentFile = accessHandle;+ this.currentFileName = fileName;+ this.fileUnavailable = false;+ if (this.pendingEntries.length > 0) {+ const entries = this.pendingEntries.join("");+ this.pendingEntries = [];+ this.writeEntry(entries);+ }+ }++ private scheduleRetry(+ fileHandle: FileSystemFileHandle, fileName: string, generation: number, delayMs: number+ ): void {+ this.retryTimer = setTimeout(async () => {+ this.retryTimer = null;+ let accessHandle: FileSystemSyncAccessHandle;+ try {+ accessHandle = await fileHandle.createSyncAccessHandle();+ } catch {+ if (generation === this.openGeneration) {+ const nextDelayMs = Math.min(delayMs * 2, BACKGROUND_RETRY_MAX_MS);+ this.scheduleRetry(fileHandle, fileName, generation, nextDelayMs);+ }+ return;+ }+ this.adoptFile(accessHandle, fileName, generation);+ }, delayMs);+ }}