Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Prevent stalled kernel requests from blocking bazaar loading and exit https://github.com/siyuan-note/siyuan/issues/19355

Daniele777727602e9
diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.ts
index 23b529c6cc..c1f70aa440 100644
--- a/app/src/config/bazaar.ts
+++ b/app/src/config/bazaar.ts
@@ -791,7 +791,6 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}
if (!bazaar._isMountCurrent(mount)) {
return;
}
- contentElement.removeAttribute("data-loading");
const activeBtn = contentElement.previousElementSibling.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)') as HTMLElement;
if (activeBtn?.getAttribute("data-type") !== myType) {
return;
@@ -898,6 +897,8 @@ type="checkbox">
bazaar._refreshReadmeDetail(bazaarType, packageName);
}
}
+ }, undefined, undefined, undefined, 30000).finally(() => {
+ contentElement.removeAttribute("data-loading");
});
return true;
},
diff --git a/app/src/layout/util.ts b/app/src/layout/util.ts
index 92ab75db01..de15fe9b59 100644
--- a/app/src/layout/util.ts
+++ b/app/src/layout/util.ts
@@ -1,4 +1,5 @@
import {Layout} from "./index";
+import {withFetchTimeout} from "../util/fetchTimeout";
import {Wnd} from "./Wnd";
import {Tab} from "./Tab";
import type {Model} from "./Model";
@@ -210,9 +211,20 @@ export const exportLayout = async (options: {
errorExit: boolean
}) => {
const editors = getAllEditor();
- for (let i = 0; i < editors.length; i++) {
- await saveScroll(editors[i].protyle);
- }
+ await withFetchTimeout(async (signal) => {
+ for (let i = 0; i < editors.length; i++) {
+ if (signal?.aborted) {
+ return;
+ }
+ await saveScroll(editors[i].protyle);
+ }
+ }, undefined, options.errorExit ? 30000 : 0).catch((error) => {
+ if (error?.name !== "TimeoutError") {
+ throw error;
+ }
+ // 关闭时滚动位置保存超时,继续保存布局并执行退出流程。
+ console.warn("Save scroll timed out before closing");
+ });
if (isWindow()) {
const layoutJSON: any = {
layout: {},
diff --git a/app/src/util/fetch.test.ts b/app/src/util/fetch.test.ts
new file mode 100644
index 0000000000..abe27290b6
--- /dev/null
+++ b/app/src/util/fetch.test.ts
@@ -0,0 +1,60 @@
+import {it} from "node:test";
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {runInNewContext} from "node:vm";
+import * as ts from "typescript";
+import {withFetchTimeout} from "./fetchTimeout";
+
+const loadFetchPost = () => {
+ const sends: unknown[][] = [];
+ const timeouts: number[] = [];
+ const exports: {fetchPost?: (...args: any[]) => Promise<void>} = {};
+ const source = ts.transpileModule(readFileSync(join(__dirname, "fetch.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ runInNewContext(source, {
+ exports,
+ require: (name: string) => {
+ switch (name) {
+ case "../constants": return {Constants: {SIYUAN_QUIT: "quit"}};
+ case "electron": return {ipcRenderer: {send: (...args: unknown[]) => sends.push(args)}};
+ case "./processMessage": return {processMessage: () => true};
+ case "./kernelFault": return {kernelError: () => assert.fail("unexpected kernel error")};
+ case "./fetchTimeout": return {
+ withFetchTimeout: (request: (signal?: AbortSignal) => Promise<unknown>, signal: AbortSignal, timeout: number) => {
+ timeouts.push(timeout);
+ return withFetchTimeout(request, signal, timeout > 0 ? 10 : 0);
+ },
+ };
+ default: throw new Error(name);
+ }
+ },
+ fetch: () => new Promise(() => {}),
+ FormData,
+ location: {port: "6806"},
+ console: {warn: () => {}},
+ });
+ return {fetchPost: exports.fetchPost, sends, timeouts};
+};
+
+it("invokes the failure callback once when a request stalls", async () => {
+ const {fetchPost, sends} = loadFetchPost();
+ let failures = 0;
+ await fetchPost("/api/bazaar/getInstalledPlugin", {}, () => assert.fail("unexpected success"),
+ undefined, (response: {code: number}) => {
+ failures++;
+ assert.equal(response.code, 400);
+ }, undefined, 30000);
+ assert.equal(failures, 1);
+ assert.equal(sends.length, 0);
+});
+
+it("falls back to desktop quit when exit or closing layout requests stall", async () => {
+ for (const url of ["/api/system/exit", "/api/system/setUILayout", "/api/system/setWorkspaceDir"]) {
+ const {fetchPost, sends, timeouts} = loadFetchPost();
+ await fetchPost(url, {errorExit: true}, () => assert.fail("unexpected success"));
+ assert.deepEqual(timeouts, [30000]);
+ assert.deepEqual(sends, [["quit", "6806"]]);
+ }
+});
diff --git a/app/src/util/fetch.ts b/app/src/util/fetch.ts
index ce5985a0b2..66635dfeae 100644
--- a/app/src/util/fetch.ts
+++ b/app/src/util/fetch.ts
@@ -4,6 +4,7 @@ import {ipcRenderer} from "electron";
/// #endif
import {processMessage} from "./processMessage";
import {kernelError} from "./kernelFault";
+import {withFetchTimeout} from "./fetchTimeout";
export const fetchPost = (
url: string,
@@ -11,7 +12,9 @@ export const fetchPost = (
cb?: (response: IWebSocketData) => void,
headers?: Record<string, string>,
failCallback?: (response: IWebSocketData) => void,
- signal?: AbortSignal) => {
+ signal?: AbortSignal,
+ timeout = url === "/api/system/exit" || url === "/api/system/setWorkspaceDir" ||
+ (url === "/api/system/setUILayout" && data?.errorExit) ? 30000 : 0) => {
const init: RequestInit = {
method: "POST",
};
@@ -41,7 +44,7 @@ export const fetchPost = (
init.signal = signal;
}
let isGetFile202 = false;
- return fetch(url, init).then((response) => {
+ return withFetchTimeout((requestSignal) => fetch(url, {...init, signal: requestSignal}).then((response) => {
switch (response.status) {
case 403:
case 404:
@@ -71,7 +74,7 @@ export const fetchPost = (
return response.text();
}
}
- }).then((response: IWebSocketData) => {
+ }), signal, timeout).then((response: IWebSocketData) => {
if (failCallback && url === "/api/file/getFile" && isGetFile202) {
failCallback(response);
return;
diff --git a/app/src/util/fetchTimeout.test.ts b/app/src/util/fetchTimeout.test.ts
new file mode 100644
index 0000000000..5fdee0f40f
--- /dev/null
+++ b/app/src/util/fetchTimeout.test.ts
@@ -0,0 +1,50 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {withFetchTimeout} from "./fetchTimeout";
+
+describe("fetch timeout", () => {
+ it("settles a stalled request and aborts its network operation", async () => {
+ let signal: AbortSignal;
+ await assert.rejects(withFetchTimeout((value) => {
+ signal = value;
+ return new Promise(() => {});
+ }, undefined, 10), {name: "TimeoutError"});
+ assert.equal(signal.aborted, true);
+ });
+
+ it("covers a stalled response body", async () => {
+ await assert.rejects(withFetchTimeout(async () => {
+ const response = new Response(new ReadableStream());
+ return response.json();
+ }, undefined, 10), {name: "TimeoutError"});
+ });
+
+ it("preserves successful results and network errors", async () => {
+ assert.equal(await withFetchTimeout(async () => "ok", undefined, 1000), "ok");
+ const error = new TypeError("Failed to fetch");
+ await assert.rejects(withFetchTimeout(async () => {
+ throw error;
+ }, undefined, 1000), (value) => value === error);
+ });
+
+ it("forwards caller cancellation without turning it into a timeout", async () => {
+ const controller = new AbortController();
+ const pending = withFetchTimeout((signal) => new Promise((resolve, reject) => {
+ signal.addEventListener("abort", () => reject(signal.reason), {once: true});
+ controller.abort();
+ }), controller.signal, 1000);
+ await assert.rejects(pending, {name: "AbortError"});
+ });
+
+ it("preserves an already aborted signal and supports opting out", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await withFetchTimeout(async (signal) => {
+ assert.equal(signal.aborted, true);
+ assert.equal(signal.reason, controller.signal.reason);
+ }, controller.signal, 1000);
+ await withFetchTimeout(async (signal) => {
+ assert.equal(signal, controller.signal);
+ }, controller.signal);
+ });
+});
diff --git a/app/src/util/fetchTimeout.ts b/app/src/util/fetchTimeout.ts
new file mode 100644
index 0000000000..5a1cab5f4b
--- /dev/null
+++ b/app/src/util/fetchTimeout.ts
@@ -0,0 +1,28 @@
+export const withFetchTimeout = <T>(
+ request: (signal?: AbortSignal) => Promise<T>,
+ signal?: AbortSignal,
+ timeout = 0,
+): Promise<T> => {
+ if (timeout <= 0) {
+ return request(signal);
+ }
+ const controller = new AbortController();
+ const abort = () => controller.abort(signal.reason);
+ if (signal?.aborted) {
+ abort();
+ } else {
+ signal?.addEventListener("abort", abort, {once: true});
+ }
+ let timer: ReturnType<typeof setTimeout>;
+ const deadline = new Promise<never>((resolve, reject) => {
+ timer = setTimeout(() => {
+ // 先结束等待,再取消网络请求,确保超时不会被当作用户主动取消。
+ reject(new DOMException("Request timed out", "TimeoutError"));
+ controller.abort();
+ }, timeout);
+ });
+ return Promise.race([Promise.resolve().then(() => request(controller.signal)), deadline]).finally(() => {
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", abort);
+ });
+};