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
feat(sync): show where a pull request timed out
Elian Doran09935838242f
diff --git a/apps/server/src/routes/route_api.spec.ts b/apps/server/src/routes/route_api.spec.tsindex 1864425d96..c9916bf89d 100644--- a/apps/server/src/routes/route_api.spec.ts+++ b/apps/server/src/routes/route_api.spec.ts@@ -1,8 +1,10 @@-import { cls, NotFoundError } from "@triliumnext/core";+import { cls, getLog, NotFoundError } from "@triliumnext/core";import express from "express";import { existsSync } from "fs";+import http, { type Server } from "http";+import type { AddressInfo } from "net";import request from "supertest";-import { beforeAll, describe, expect, it, vi } from "vitest";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import {apiResultHandler,@@ -346,3 +348,52 @@ describe("internalRoute without a result handler", () => {expect(res.body).toEqual({ message: "missing" });});});++describe("internalRoute response delivery", () => {+ let server: Server;+ let port: number;++ beforeAll(async () => {+ route("get", "/delivery/large", [], () => ({ payload: "x".repeat(64 * 1024 * 1024) }), apiResultHandler);+ route("get", "/delivery/small", [], () => ({ ok: true }), apiResultHandler);++ const app = express();+ app.use(router);+ server = app.listen(0);+ await new Promise((resolve) => server.once("listening", resolve));+ port = (server.address() as AddressInfo).port;+ });++ afterAll(() => {+ server.close();+ });++ it("logs a client that disconnects before the response is delivered", async () => {+ const info = vi.spyOn(getLog(), "info");++ await new Promise<void>((resolve, reject) => {+ const req = http.get({ port, path: "/delivery/large?logMarkerId=m1" }, (res) => {+ res.once("data", () => {+ req.destroy();+ resolve();+ });+ });+ req.on("error", (e: NodeJS.ErrnoException) => e.code === "ECONNRESET" ? resolve() : reject(e));+ });++ await vi.waitFor(() => expect(info).toHaveBeenCalledWith(expect.stringMatching(+ /^Aborted 200 GET \/delivery\/large\?logMarkerId=m1 after \d+ms: the client disconnected before receiving the \d+-byte response$/+ )));+ info.mockRestore();+ });++ it("logs nothing extra for a response the client receives in full", async () => {+ const info = vi.spyOn(getLog(), "info");++ await request(server).get("/delivery/small").expect(200);+ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(info.mock.calls.flat().some((line) => String(line).startsWith("Aborted"))).toBe(false);+ info.mockRestore();+ });+});diff --git a/apps/server/src/routes/route_api.ts b/apps/server/src/routes/route_api.tsindex 5f24dca90f..1c1d72703b 100644--- a/apps/server/src/routes/route_api.ts+++ b/apps/server/src/routes/route_api.ts@@ -131,6 +131,16 @@ function handleResponse(resultHandler: ApiResultHandler, req: express.Request, rconst responseLength = resultHandler(req, res, result);getLog().request(req, res, Date.now() - start, responseLength);++ // The request log above measures only the handler, so a client that times out during the+ // transfer would otherwise leave nothing but a successful entry behind.+ res.once("close", () => {+ if (!res.writableFinished) {+ const elapsedMs = Date.now() - start;+ getLog().info(`Aborted ${res.statusCode} ${req.method} ${req.url} after ${elapsedMs}ms: `+ + `the client disconnected before receiving the ${responseLength}-byte response`);+ }+ });}function handleException(e: unknown | Error, method: HttpMethod, path: string, res: express.Response) {diff --git a/apps/standalone/src/lightweight/request_provider.spec.ts b/apps/standalone/src/lightweight/request_provider.spec.tsindex 46f06d0bda..b4d5df85ae 100644--- a/apps/standalone/src/lightweight/request_provider.spec.ts+++ b/apps/standalone/src/lightweight/request_provider.spec.ts@@ -113,7 +113,24 @@ describe("FetchRequestProvider.exec", () => {(init?.signal as AbortSignal).addEventListener("abort", () => reject(abortErr));}));const promise = provider.exec({ method: "GET", url: `${location.origin}/x`, timeout: 50 } as ExecOpts);- const rejection = expect(promise).rejects.toThrow("timeout after 50ms");+ const rejection = expect(promise).rejects.toThrow("timeout after 50ms waiting for the response headers");+ await vi.advanceTimersByTimeAsync(50);+ await rejection;+ });++ it("reports a timeout while reading the body with the status and when the headers arrived", async () => {+ vi.useFakeTimers();+ const abortErr = Object.assign(new Error("aborted"), { name: "AbortError" });+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => ({+ status: 200,+ text: () => new Promise<string>((_resolve, reject) => {+ (init?.signal as AbortSignal).addEventListener("abort", () => reject(abortErr));+ })+ }) as unknown as Response);+ const promise = provider.exec({ method: "GET", url: `${location.origin}/x`, timeout: 50 } as ExecOpts);+ const rejection = expect(promise).rejects.toThrow(+ /timeout after 50ms while reading the response body \(status 200 received after 0ms\)$/+ );await vi.advanceTimersByTimeAsync(50);await rejection;});diff --git a/apps/standalone/src/lightweight/request_provider.ts b/apps/standalone/src/lightweight/request_provider.tsindex e5c7563f4c..89a705bb8f 100644--- a/apps/standalone/src/lightweight/request_provider.ts+++ b/apps/standalone/src/lightweight/request_provider.ts@@ -42,6 +42,8 @@ export default class FetchRequestProvider implements RequestProvider {const timeoutId = opts.timeout? setTimeout(() => controller.abort(), opts.timeout): undefined;+ const startTime = Date.now();+ let headersReceived: { status: number; afterMs: number } | undefined;try {const response = await fetch(opts.url, {@@ -51,6 +53,7 @@ export default class FetchRequestProvider implements RequestProvider {signal: controller.signal,credentials: "include"});+ headersReceived = { status: response.status, afterMs: Date.now() - startTime };if ([200, 201, 204].includes(response.status)) {const text = await response.text();@@ -68,7 +71,15 @@ export default class FetchRequestProvider implements RequestProvider {} catch (e: any) {if (e.name === "AbortError") {- throw new Error(`${opts.method} ${opts.url} failed, error: timeout after ${opts.timeout}ms`);+ // The timeout covers the body download too, so a slow transfer of a large sync+ // response looks like an unresponsive server unless the phase is reported.+ const phase = headersReceived+ ? `while reading the response body (status ${headersReceived.status} `+ + `received after ${headersReceived.afterMs}ms)`+ : "waiting for the response headers";+ throw new Error(+ `${opts.method} ${opts.url} failed, error: timeout after ${opts.timeout}ms ${phase}`+ );}if (e instanceof TypeError && e.message === "Failed to fetch") {const isCrossOrigin = !opts.url.startsWith(location.origin);diff --git a/packages/trilium-core/src/routes/api/sync.spec.ts b/packages/trilium-core/src/routes/api/sync.spec.tsindex 83a93cebbf..f47458aab6 100644--- a/packages/trilium-core/src/routes/api/sync.spec.ts+++ b/packages/trilium-core/src/routes/api/sync.spec.ts@@ -3,6 +3,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import consistencyChecksService from "../../services/consistency_checks";import entityChangesService from "../../services/entity_changes";+import { getLog } from "../../services/log";import optionService from "../../services/options";import { getSql } from "../../services/sql/index";import sqlInit from "../../services/sql_init";@@ -157,6 +158,19 @@ describe("Sync API (core)", () => {expect(typeof res.body.outstandingPullCount).toBe("number");});+ it("logs the returned changes under the client's log marker", async () => {+ const info = vi.spyOn(getLog(), "info");++ const res = await api.get("/api/sync/changed", {+ query: { instanceId: "someOtherInstance", lastEntityChangeId: "0", logMarkerId: "marker1234" }+ });++ expect(res.status).toBe(200);+ expect(info).toHaveBeenCalledWith(expect.stringMatching(+ /^Sync marker1234: returning \d+ entity changes after entity change 0 \(~\d+ bytes, \d+ outstanding\) in \d+ms$/+ ));+ });+it("advances past batches that are fully filtered out by instanceId", async () => {// Seed a contiguous block of synced rows beyond the existing max id, all// belonging to a single instanceId. Querying with that instanceId and adiff --git a/packages/trilium-core/src/routes/api/sync.ts b/packages/trilium-core/src/routes/api/sync.tsindex bb9f31b166..0b0cc2689e 100644--- a/packages/trilium-core/src/routes/api/sync.ts+++ b/packages/trilium-core/src/routes/api/sync.ts@@ -158,7 +158,9 @@ function getChanged(req: Request) {}let lastEntityChangeId = parseInt(req.query.lastEntityChangeId);+ const requestedEntityChangeId = lastEntityChangeId;const clientInstanceId = req.query.instanceId;+ const logMarkerId = typeof req.query.logMarkerId === "string" ? req.query.logMarkerId : "?";// Optional per-client limit: blob rows whose content exceeds this many bytes are served with// empty content (a stub). Only clients that opt in (currently mobile) send it; the entity_change@@ -227,10 +229,6 @@ function getChanged(req: Request) {}}- if (entityChangeRecords.length > 0) {- getLog().info(`Returning ${entityChangeRecords.length} entity changes in ${Date.now() - startTime}ms`);- }-// `outstandingPullCount` is a progress estimate returned on every pull request. Counting with// only `isSynced` + `id` is an index-only range scan on IDX_entity_changes_isSynced_id; adding// an `instanceId != ?` filter (instanceId is not in the index) forces a table lookup per row,@@ -249,6 +247,12 @@ function getChanged(req: Request) {[lastEntityChangeId]);+ if (entityChangeRecords.length > 0) {+ getLog().info(`Sync ${logMarkerId}: returning ${entityChangeRecords.length} entity changes `+ + `after entity change ${requestedEntityChangeId} (~${estimatedResponseBytes} bytes, `+ + `${outstandingPullCount} outstanding) in ${Date.now() - startTime}ms`);+ }+return {entityChanges: entityChangeRecords,lastEntityChangeId,