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
client: increase the HTTP request timeout for vacuuming the DB
Adorian Doran3e902243943c
diff --git a/apps/client/src/services/server.ts b/apps/client/src/services/server.tsindex c7c6be0927..56b542baef 100644--- a/apps/client/src/services/server.ts+++ b/apps/client/src/services/server.ts@@ -61,6 +61,20 @@ async function postWithSilentInternalServerError<T>(url: string, data?: unknown,return await call<T>("POST", url, componentId, { data, silentInternalServerError: true });}+/**+ * For an operation that runs in minutes rather than seconds — see {@link CallOptions.timeoutMs}. The+ * work carries on server-side whatever the client does, so giving up early does not stop it; it only+ * loses the answer, and reports a failure for something that is still succeeding.+ */+async function getWithTimeout<T>(url: string, timeoutMs: number, componentId?: string) {+ return await call<T>("GET", url, componentId, { timeoutMs });+}++/** The POST counterpart of {@link getWithTimeout}. */+async function postWithTimeout<T>(url: string, timeoutMs: number, data?: unknown, componentId?: string) {+ return await call<T>("POST", url, componentId, { data, timeoutMs });+}+async function put<T>(url: string, data?: unknown, componentId?: string) {return await call<T>("PUT", url, componentId, { data });}@@ -156,8 +170,20 @@ interface CallOptions {raw?: boolean;/** Used internally to prevent infinite retry loops on CSRF refresh. */csrfRetried?: boolean;+ /**+ * How long to wait before giving up, for the few operations that legitimately run past+ * {@link DEFAULT_TIMEOUT} — a database rebuild, an erasure sweeping a large database. Left unset+ * everywhere else, so an ordinary request that hangs still fails rather than hanging its caller.+ */+ timeoutMs?: number;}+/**+ * Long enough for any request the UI makes while someone waits on it. Operations measured in+ * minutes state their own — see {@link CallOptions.timeoutMs}.+ */+const DEFAULT_TIMEOUT = 60000;+async function call<T>(method: string, url: string, componentId?: string, options: CallOptions = {}) {const headers = await getHeaders({"trilium-component-id": componentId@@ -185,7 +211,7 @@ function ajax(url: string, method: string, data: unknown, headers: Headers, optsurl: window.glob.baseApiUrl + url,type: method,headers,- timeout: 60000,+ timeout: opts.timeoutMs ?? DEFAULT_TIMEOUT,success: (body, _textStatus, jqXhr) => {const respHeaders: Headers = {};@@ -309,8 +335,10 @@ export default {get,getWithSilentNotFound,getWithSilentUnauthorized,+ getWithTimeout,post,postWithSilentInternalServerError,+ postWithTimeout,put,patch,remove,diff --git a/apps/client/src/widgets/type_widgets/options/advanced.tsx b/apps/client/src/widgets/type_widgets/options/advanced.tsxindex 7b8a92e7bf..2eed56c640 100644--- a/apps/client/src/widgets/type_widgets/options/advanced.tsx+++ b/apps/client/src/widgets/type_widgets/options/advanced.tsx@@ -86,7 +86,9 @@ function DatabaseOptions() {buttonText={t("vacuum_database.button_text")}onClick={async () => {toast.showMessage(t("vacuum_database.vacuuming_database"));- await server.post("database/vacuum-database");+ // A rebuild runs in minutes on a large database — half an hour on 36 GiB — so+ // the default minute would report a failure for something still succeeding.+ await server.postWithTimeout("database/vacuum-database", VACUUM_TIMEOUT_MS);toast.showMessage(t("vacuum_database.database_vacuumed"));}}/>@@ -94,6 +96,9 @@ function DatabaseOptions() {);}+/** Rebuilding runs in minutes on a large database, and the client must not give up before it ends. */+const VACUUM_TIMEOUT_MS = 60 * 60 * 1000;+function DatabaseAnonymizationOptions() {const [databases, setDatabases] = useState<AnonymizedDbResponse[]>([]);const [anonymizedFolderPath, setAnonymizedFolderPath] = useState<string | null>(null);diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsxindex 81a1473a19..c8e5b22458 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx@@ -42,38 +42,47 @@ vi.mock("../../../../../services/options", () => ({}}));-vi.mock("../../../../../services/server", () => ({- default: {- // The aggressive reading and the trimmed one differ only in the retention they were asked- // for, which is what the URL carries. Everything else the client loads on the way past is- // answered emptily rather than with a usage payload it would choke on.- get: (url: string) => {- mocks.get(url);-- if (url === "database/compaction-estimate") {- return Promise.resolve({ reclaimableBytes: FREE_PAGES });- }-- if (!url.startsWith("space-usage/")) {- return Promise.resolve(url === "keyboard-actions" ? [] : {});- }-- // The overview is what the run weighs itself against, before and after.- if (url.startsWith("space-usage/overview")) {- const size = mocks.weighed.shift() ?? MEASURED_AFTER;- return Promise.resolve({ content: { size }, deletedNotes: { size: 0 } });- }-- const keeping = /snapshotsToKeep=(\d+)/.exec(url)?.[1];- return Promise.resolve({- subtreeRevisionsContentSize: keeping === "0" ? REVISIONS_ALL : REVISIONS_TRIMMED,- deletedNotes: { size: DELETED, noteCount: 1, attachmentCount: 0 },- unusedAttachments: { size: UNUSED, attachmentCount: 1 }- });- },- post: mocks.post- }-}));+vi.mock("../../../../../services/server", () => {+ // The aggressive reading and the trimmed one differ only in the retention they were asked for,+ // which is what the URL carries. Everything else the client loads on the way past is answered+ // emptily rather than with a usage payload it would choke on.+ const get = (url: string) => {+ mocks.get(url);++ if (url === "database/compaction-estimate") {+ return Promise.resolve({ reclaimableBytes: FREE_PAGES });+ }++ if (!url.startsWith("space-usage/")) {+ return Promise.resolve(url === "keyboard-actions" ? [] : {});+ }++ // The overview is what the run weighs itself against, before and after.+ if (url.startsWith("space-usage/overview")) {+ const size = mocks.weighed.shift() ?? MEASURED_AFTER;+ return Promise.resolve({ content: { size }, deletedNotes: { size: 0 } });+ }++ const keeping = /snapshotsToKeep=(\d+)/.exec(url)?.[1];+ return Promise.resolve({+ subtreeRevisionsContentSize: keeping === "0" ? REVISIONS_ALL : REVISIONS_TRIMMED,+ deletedNotes: { size: DELETED, noteCount: 1, attachmentCount: 0 },+ unusedAttachments: { size: UNUSED, attachmentCount: 1 }+ });+ };++ // The run's whole-database calls go through the long-timeout variants, which answer exactly as+ // their plain counterparts do here — the timeout is dropped, leaving the (url, data) the+ // assertions read.+ return {+ default: {+ get,+ getWithTimeout: get,+ post: mocks.post,+ postWithTimeout: (url: string, _timeoutMs: number, data?: object) => mocks.post(url, data)+ }+ };+});vi.mock("../../../../../services/dialog", () => ({ default: { confirm: mocks.confirm } }));vi.mock("../../../../../services/toast", () => ({ default: { showMessage: mocks.showMessage } }));@@ -214,7 +223,7 @@ describe("showCleanupDialog", () => {const measured = MEASURED_BEFORE - MEASURED_AFTER;expect(measured).not.toBe(UNUSED);await expect(closed).resolves.toBe(measured);- expect(mocks.post).toHaveBeenCalledWith("notes/erase-unused-attachments-now");+ expect(mocks.post.mock.calls.map(([ url ]) => url)).toContain("notes/erase-unused-attachments-now");expect(mocks.showMessage).toHaveBeenCalledWith(t("space_usage.cleanup_done", { size: formatSize(measured) }));// Gone from the page: it is mounted for the run and unmounted with it.diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.tsindex be48a2ea63..b3fc0391d1 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts@@ -12,10 +12,17 @@ const mocks = vi.hoisted(() => ({}));vi.mock("../../../../../services/options", () => ({ default: { getInt: mocks.getInt } }));+// The run reaches for the long-timeout variants throughout: every request it makes is a+// whole-database operation. The timeout itself is dropped here, leaving (url, data) as the calls+// under test.vi.mock("../../../../../services/server", () => ({default: {+ // The whole-database operations reach for the long-timeout variants; recording the outcome+ // is an ordinary write and keeps the default. Both funnel here, so the assertions below read+ // the run's calls in order regardless of which variant made them.post: mocks.post,- get: (url: string) => {+ postWithTimeout: (url: string, _timeoutMs: number, data?: object) => mocks.post(url, data),+ getWithTimeout: (url: string) => {mocks.get(url);const size = mocks.occupied.shift() ?? 0;return Promise.resolve({ content: { size }, deletedNotes: { size: 0 } });diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.tsindex 55874ce795..73e8333e56 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts@@ -38,6 +38,14 @@ export interface CleanupToolOptions {/** Where the snapshots field starts when no useful limit is configured. */export const FALLBACK_SNAPSHOTS_TO_KEEP = 4;+/**+ * Every request a run makes is a whole-database operation, and the default minute is nowhere near+ * enough for any of them on a large database: a rebuild alone has been measured at half an hour on+ * 36 GiB. Giving up early would not stop the server working — it would only lose the answer and+ * report a failure for something that went on to succeed.+ */+const CLEANUP_TIMEOUT_MS = 60 * 60 * 1000;+/*** Fills a stored setting out into the full set the dialog works with. Nothing is picked unless it* was picked before — an uninitialized setting erases nothing, which is the only safe reading of an@@ -148,18 +156,18 @@ export async function runCleanup(options: CleanupToolOptions): Promise<number> {const before = options.compactDatabase ? 0 : await measureOccupiedBytes();if (options.revisionSnapshots) {- await server.post("revisions/erase-all-excess-revisions", {+ await server.postWithTimeout("revisions/erase-all-excess-revisions", CLEANUP_TIMEOUT_MS, {snapshotsToKeep: options.snapshotsToKeep,keepNamedSnapshots: options.keepNamedSnapshots});}if (options.unusedAttachments) {- await server.post("notes/erase-unused-attachments-now");+ await server.postWithTimeout("notes/erase-unused-attachments-now", CLEANUP_TIMEOUT_MS);}if (options.deletedEntities) {- await server.post("notes/erase-deleted-notes-now");+ await server.postWithTimeout("notes/erase-deleted-notes-now", CLEANUP_TIMEOUT_MS);}const reclaimed = options.compactDatabase@@ -178,7 +186,8 @@ export async function runCleanup(options: CleanupToolOptions): Promise<number> {/** Rebuilds the database file, reporting what it handed back to the disk. */async function compactDatabase(): Promise<number> {- const { sizeBefore, sizeAfter } = await server.post<VacuumDatabaseResponse>("database/vacuum-database");+ const { sizeBefore, sizeAfter } = await server.postWithTimeout<VacuumDatabaseResponse>(+ "database/vacuum-database", CLEANUP_TIMEOUT_MS);return Math.max(sizeBefore - sizeAfter, 0);}@@ -203,7 +212,8 @@ export async function measureCompactionEstimate(): Promise<number> {async function measureOccupiedBytes(): Promise<number> {// The smallest ranking the endpoint will do: the totals are whole-database figures either way,// and the listing this would return is of no use here.- const overview = await server.get<SpaceUsageOverviewResponse>("space-usage/overview?limit=1");+ const overview = await server.getWithTimeout<SpaceUsageOverviewResponse>(+ "space-usage/overview?limit=1", CLEANUP_TIMEOUT_MS);return overview.content.size + overview.deletedNotes.size;}