Skip to content

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

:art: Improve concurrent search request handling https://github.com/siyuan-note/siyuan/issues/15449

Danielc95a08b14d4d
diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.ts
index 86672d316d..5e96358ad8 100644
--- a/app/src/layout/Wnd.ts
+++ b/app/src/layout/Wnd.ts
@@ -751,8 +751,7 @@ export class Wnd {
return;
}
if (model instanceof Search) {
- model.editors.edit.destroy();
- model.editors.unRefEdit.destroy();
+ model.destroy();
return;
}
if (model instanceof Asset) {
diff --git a/app/src/mobile/menu/model.ts b/app/src/mobile/menu/model.ts
index 443917ba3d..1bb3c97aa3 100644
--- a/app/src/mobile/menu/model.ts
+++ b/app/src/mobile/menu/model.ts
@@ -1,9 +1,18 @@
+let modelDestroyCallback: (() => void) | undefined;
+
+export const destroyModel = () => {
+ modelDestroyCallback?.();
+ modelDestroyCallback = undefined;
+};
+
export const openModel = (obj: {
html: string,
icon?: string,
title: string,
- bindEvent: (element: HTMLElement) => void
+ bindEvent: (element: HTMLElement) => void,
+ destroyCallback?: () => void,
}) => {
+ destroyModel();
const modelElement = document.getElementById("model");
modelElement.style.transform = "translateY(0px)";
modelElement.style.zIndex = (++window.siyuan.zIndex).toString();
@@ -18,4 +27,5 @@ export const openModel = (obj: {
const modelMainElement = modelElement.querySelector("#modelMain") as HTMLElement;
modelMainElement.innerHTML = obj.html;
obj.bindEvent(modelMainElement);
+ modelDestroyCallback = obj.destroyCallback;
};
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.ts
index ef4419e713..b8afcfd454 100644
--- a/app/src/mobile/menu/search.ts
+++ b/app/src/mobile/menu/search.ts
@@ -33,6 +33,7 @@ import {
toggleReplaceHistory,
toggleSearchHistory
} from "../../search/toggleHistory";
+import {cancelSearchRequest, scheduleSearchRequest} from "../../search/request";
const replace = (element: Element, config: Config.IUILayoutTabSearchConfig, isAll: boolean) => {
if (config.method === 2) {
@@ -255,71 +256,99 @@ ${childItem.tag ? `<span class="b3-list-item__meta b3-list-item__meta--ellipsis"
}
};
-let toolbarSearchTimeout = 0;
export const updateSearchResult = (config: Config.IUILayoutTabSearchConfig, element: Element, rmCurrentCriteria = false,
focusId?: {
currentId?: string,
newId?: string
}) => {
- clearTimeout(toolbarSearchTimeout);
- toolbarSearchTimeout = window.setTimeout(() => {
- if (rmCurrentCriteria) {
- element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");
- }
- const loadingElement = element.querySelector(".fn__loading") as HTMLElement;
- loadingElement.classList.remove("fn__none");
- loadingElement.style.top = element.querySelector(".b3-list--background").getBoundingClientRect().top + "px";
- const previousElement = element.querySelector('[data-type="previous"]');
- const nextElement = element.querySelector('[data-type="next"]');
- const inputElement = document.getElementById("toolbarSearch") as HTMLInputElement;
- config.query = inputElement.value;
- if (config.query === "" && (!config.idPath || config.idPath.length === 0)) {
- fetchPost("/api/block/getRecentUpdatedBlocks", {}, (response) => {
- onRecentBlocks(response.data, config, undefined, focusId);
+ if (rmCurrentCriteria) {
+ element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");
+ element.querySelector("#searchList").innerHTML = "";
+ element.querySelector('[data-type="result"]').innerHTML = "";
+ element.querySelector('[data-type="previous"]').setAttribute("disabled", "disabled");
+ element.querySelector('[data-type="next"]').setAttribute("disabled", "disabled");
+ }
+ const loadingElement = element.querySelector(".fn__loading") as HTMLElement;
+ loadingElement.classList.remove("fn__none");
+ scheduleSearchRequest({
+ element,
+ delay: Constants.TIMEOUT_INPUT,
+ onIdle: () => {
+ if (element.isConnected) {
loadingElement.classList.add("fn__none");
- previousElement.setAttribute("disabled", "true");
- nextElement.setAttribute("disabled", "true");
- });
- } else {
+ }
+ },
+ createTask(version) {
+ loadingElement.style.top = element.querySelector(".b3-list--background").getBoundingClientRect().top + "px";
+ const previousElement = element.querySelector('[data-type="previous"]');
+ const nextElement = element.querySelector('[data-type="next"]');
+ const inputElement = document.getElementById("toolbarSearch") as HTMLInputElement;
+ config.query = inputElement.value;
if (!config.page) {
config.page = 1;
}
- if (config.page > 1) {
+ const requestConfig = JSON.parse(JSON.stringify(config)) as Config.IUILayoutTabSearchConfig;
+ const requestFocusId = focusId ? Object.assign({}, focusId) : undefined;
+ if (requestConfig.query === "" && (!requestConfig.idPath || requestConfig.idPath.length === 0)) {
+ return {
+ method: requestConfig.method,
+ version,
+ run(signal: AbortSignal, isCurrent: () => boolean) {
+ return fetchPost("/api/block/getRecentUpdatedBlocks", {}, (response) => {
+ if (!isCurrent()) {
+ return;
+ }
+ onRecentBlocks(response.data, requestConfig, undefined, requestFocusId);
+ previousElement.setAttribute("disabled", "true");
+ nextElement.setAttribute("disabled", "true");
+ }, undefined, undefined, signal);
+ }
+ };
+ }
+ if (requestConfig.page > 1) {
previousElement.removeAttribute("disabled");
} else {
previousElement.setAttribute("disabled", "disabled");
}
- const endpoint = config.method === 4 ? "/api/search/semanticSearchBlock" : "/api/search/fullTextSearchBlock";
+ const endpoint = requestConfig.method === 4 ? "/api/search/semanticSearchBlock" : "/api/search/fullTextSearchBlock";
const searchParam: Record<string, any> = {
- query: config.query,
- method: config.method,
- types: config.types,
- subTypes: config.subTypes,
- paths: config.idPath || [],
- groupBy: config.group,
- orderBy: config.sort,
- page: config.page,
+ query: requestConfig.query,
+ method: requestConfig.method,
+ types: requestConfig.types,
+ subTypes: requestConfig.subTypes,
+ paths: requestConfig.idPath || [],
+ groupBy: requestConfig.group,
+ orderBy: requestConfig.sort,
+ page: requestConfig.page,
pageSize: 32,
};
// 限定在单个加密 box 内搜索时带 notebook,让内核走加密 db;跨 box 或全局搜索走原函数
- const idPaths = config.idPath || [];
+ const idPaths = requestConfig.idPath || [];
if (idPaths.length > 0) {
const box = idPaths[0].split("/")[0];
if (isEncryptedBox(box) && idPaths.every(p => p.split("/")[0] === box)) {
searchParam.notebook = box;
}
}
- fetchPost(endpoint, searchParam, (response) => {
- onRecentBlocks(response.data.blocks, config, response, focusId);
- loadingElement.classList.add("fn__none");
- if (config.page < response.data.pageCount) {
- nextElement.removeAttribute("disabled");
- } else {
- nextElement.setAttribute("disabled", "disabled");
+ return {
+ method: requestConfig.method,
+ version,
+ run(signal: AbortSignal, isCurrent: () => boolean) {
+ return fetchPost(endpoint, searchParam, (response) => {
+ if (!isCurrent()) {
+ return;
+ }
+ onRecentBlocks(response.data.blocks, requestConfig, response, requestFocusId);
+ if (requestConfig.page < response.data.pageCount) {
+ nextElement.removeAttribute("disabled");
+ } else {
+ nextElement.setAttribute("disabled", "disabled");
+ }
+ }, undefined, undefined, signal);
}
- });
+ };
}
- }, Constants.TIMEOUT_INPUT);
+ });
};
const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTabSearchConfig) => {
@@ -352,7 +381,7 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTab
className: "toolbar__icon",
clearCB() {
config.page = 1;
- updateSearchResult(config, element);
+ updateSearchResult(config, element, true);
}
});
const replaceInputElement = element.querySelector(".toolbar .toolbar__title") as HTMLInputElement;
@@ -845,6 +874,9 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf
</div>
<div class="fn__loading"><img width="120px" src="/stage/loading-pure.svg"></div>
</div>`,
+ destroyCallback() {
+ cancelSearchRequest(document.getElementById("modelMain"));
+ },
bindEvent(element) {
document.querySelector("#toolbarSearchNew").addEventListener("click", () => {
newFile(app, (document.querySelector("#toolbarSearch") as HTMLInputElement).value);
diff --git a/app/src/mobile/util/MobileBackFoward.ts b/app/src/mobile/util/MobileBackFoward.ts
index 36c0b2559d..da8260e51c 100644
--- a/app/src/mobile/util/MobileBackFoward.ts
+++ b/app/src/mobile/util/MobileBackFoward.ts
@@ -2,6 +2,7 @@ import {showMessage} from "../../dialog/message";
import {hideElements} from "../../protyle/ui/hideElements";
import {getCurrentEditor} from "../editor";
import {closePanel} from "./closePanel";
+import {destroyModel} from "../menu/model";
export const clearMobileBackForward = (notebookId?: string) => {
if (notebookId) {
@@ -34,6 +35,7 @@ export const goBack = () => {
} else if (document.getElementById("model").style.transform === "translateY(0px)") {
const searchAssetsPanelElement = document.getElementById("searchAssetsPanel");
if (!searchAssetsPanelElement || searchAssetsPanelElement.classList.contains("fn__none")) {
+ destroyModel();
document.getElementById("model").style.transform = "";
} else {
searchAssetsPanelElement.classList.add("fn__none");
diff --git a/app/src/search/index.ts b/app/src/search/index.ts
index 519ec547fa..6d49e1acf0 100644
--- a/app/src/search/index.ts
+++ b/app/src/search/index.ts
@@ -5,6 +5,7 @@ import {genSearch} from "./util";
import {setPanelFocus} from "../layout/util";
import type {App} from "../index";
import {clearOBG} from "../layout/dock/util";
+import {cancelSearchRequest} from "./request";
export class Search extends Model {
public element: HTMLElement;
@@ -48,4 +49,10 @@ export class Search extends Model {
inputElement.select();
inputElement.dispatchEvent(new CustomEvent("input"));
}
+
+ public destroy() {
+ cancelSearchRequest(this.element);
+ this.editors.edit.destroy();
+ this.editors.unRefEdit.destroy();
+ }
}
diff --git a/app/src/search/request.ts b/app/src/search/request.ts
new file mode 100644
index 0000000000..e4028d65a0
--- /dev/null
+++ b/app/src/search/request.ts
@@ -0,0 +1,106 @@
+interface ISearchRequestTask {
+ method: number,
+ version: number,
+ run: (signal: AbortSignal, isCurrent: () => boolean) => Promise<unknown> | void,
+}
+
+interface ISearchRequestState {
+ version: number,
+ timeout?: number,
+ running?: {
+ controller: AbortController,
+ task: ISearchRequestTask,
+ },
+ queued?: ISearchRequestTask,
+ onIdle?: () => void,
+}
+
+const requestStates = new WeakMap<Element, ISearchRequestState>();
+
+const getRequestState = (element: Element) => {
+ let state = requestStates.get(element);
+ if (!state) {
+ state = {
+ version: 0,
+ };
+ requestStates.set(element, state);
+ }
+ return state;
+};
+
+const runRequestTask = (element: Element, state: ISearchRequestState, task: ISearchRequestTask) => {
+ if (task.version !== state.version || !element.isConnected) {
+ return;
+ }
+ const controller = new AbortController();
+ const running = {
+ controller,
+ task,
+ };
+ state.running = running;
+ const isCurrent = () => {
+ return element.isConnected && state.version === task.version && state.running === running;
+ };
+ void Promise.resolve()
+ .then(() => task.run(controller.signal, isCurrent))
+ .finally(() => {
+ if (state.running !== running) {
+ return;
+ }
+ state.running = undefined;
+ const queued = state.queued;
+ state.queued = undefined;
+ if (queued && queued.version === state.version) {
+ runRequestTask(element, state, queued);
+ } else if (state.timeout === undefined) {
+ state.onIdle?.();
+ }
+ });
+};
+
+export const scheduleSearchRequest = (options: {
+ element: Element,
+ delay: number,
+ createTask: (version: number) => ISearchRequestTask,
+ onIdle: () => void,
+}) => {
+ const state = getRequestState(options.element);
+ state.version++;
+ state.queued = undefined;
+ state.onIdle = options.onIdle;
+ if (state.timeout !== undefined) {
+ window.clearTimeout(state.timeout);
+ }
+ if (state.running?.task.method === 2) {
+ state.running.controller.abort();
+ }
+ const version = state.version;
+ state.timeout = window.setTimeout(() => {
+ state.timeout = undefined;
+ if (version !== state.version || !options.element.isConnected) {
+ return;
+ }
+ const task = options.createTask(version);
+ if (state.running) {
+ state.queued = task;
+ } else {
+ runRequestTask(options.element, state, task);
+ }
+ }, options.delay);
+};
+
+export const cancelSearchRequest = (element: Element) => {
+ const state = requestStates.get(element);
+ if (!state) {
+ return;
+ }
+ state.version++;
+ state.queued = undefined;
+ if (state.timeout !== undefined) {
+ window.clearTimeout(state.timeout);
+ state.timeout = undefined;
+ }
+ state.running?.controller.abort();
+ state.running = undefined;
+ requestStates.delete(element);
+};
diff --git a/app/src/search/spread.ts b/app/src/search/spread.ts
index d24287c691..3821dd24df 100644
--- a/app/src/search/spread.ts
+++ b/app/src/search/spread.ts
@@ -5,6 +5,7 @@ import {fetchPost, fetchSyncPost} from "../util/fetch";
import {focusByRange} from "../protyle/util/selection";
import {genSearch, updateConfig} from "./util";
import type {App} from "../index";
+import {cancelSearchRequest} from "./request";
export const openSearch = async (options: {
app: App,
@@ -106,6 +107,7 @@ export const openSearch = async (options: {
if (range && !options) {
focusByRange(range);
}
+ cancelSearchRequest(dialog.element.querySelector(".b3-dialog__body"));
dialog.editors.edit.destroy();
dialog.editors.unRefEdit.destroy();
},
diff --git a/app/src/search/util.ts b/app/src/search/util.ts
index 1e69349c8b..51256a6eea 100644
--- a/app/src/search/util.ts
+++ b/app/src/search/util.ts
@@ -50,6 +50,7 @@ import {getSelectionOffset} from "../protyle/util/selection";
import {electronUndo} from "../protyle/undo";
import {getContenteditableElement} from "../protyle/wysiwyg/getBlock";
import {IDatabaseRowOpenData, openDatabaseRowByData} from "../protyle/render/av/openDatabaseRow";
+import {scheduleSearchRequest} from "./request";
export const openGlobalSearch = (app: App, text: string, replace: boolean, searchData?: Config.IUILayoutTabSearchConfig) => {
text = text.trim();
@@ -942,7 +943,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, ele
height: searchInputElement.clientHeight,
clearCB() {
config.page = 1;
- inputEvent(element, config, edit);
+ inputEvent(element, config, edit, true);
}
});
addClearButton({
@@ -1376,101 +1377,119 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCo
currentId?: string,
newId?: string
}) => {
- let inputTimeout = parseInt(element.getAttribute("data-timeout") || "0");
- clearTimeout(inputTimeout);
- inputTimeout = window.setTimeout(() => {
- if (rmCurrentCriteria) {
- element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");
- }
- const listElement = element.querySelector("#searchList") as HTMLElement;
- const loadingElement = element.querySelector(".fn__loading") as HTMLElement;
- loadingElement.classList.remove("fn__none");
- loadingElement.style.top = listElement.offsetTop + "px";
- const searchInputElement = element.querySelector("#searchInput") as HTMLInputElement;
- config.query = searchInputElement.value;
- listElement.scrollTo(0, 0);
- const previousElement = element.querySelector('[data-type="previous"]');
- const nextElement = element.querySelector('[data-type="next"]');
- edit.protyle?.app.plugins.forEach(item => {
- item.eventBus.emit("input-search", {
- protyle: edit,
- config,
- searchElement: searchInputElement,
- });
- });
- const searchResultElement = element.querySelector("#searchResult");
- if (config.query === "" && (!config.idPath || config.idPath.length === 0)) {
- fetchPost("/api/block/getRecentUpdatedBlocks", {}, (response) => {
- if (window.siyuan.reqIds["/api/block/getRecentUpdatedBlocks"] && window.siyuan.reqIds["/api/search/fullTextSearchBlock"] &&
- window.siyuan.reqIds["/api/block/getRecentUpdatedBlocks"] < window.siyuan.reqIds["/api/search/fullTextSearchBlock"]) {
- return;
- }
- onSearch(response.data, edit, element, config);
+ if (rmCurrentCriteria) {
+ element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");
+ element.querySelector("#searchList").innerHTML = "";
+ element.querySelector("#searchResult").innerHTML = "";
+ element.querySelector('[data-type="previous"]').setAttribute("disabled", "disabled");
+ element.querySelector('[data-type="next"]').setAttribute("disabled", "disabled");
+ edit.protyle.element.classList.add("fn__none");
+ element.querySelector(".search__drag").classList.add("fn__none");
+ }
+ const loadingElement = element.querySelector(".fn__loading") as HTMLElement;
+ loadingElement.classList.remove("fn__none");
+ scheduleSearchRequest({
+ element,
+ delay: Constants.TIMEOUT_INPUT,
+ onIdle: () => {
+ if (element.isConnected) {
loadingElement.classList.add("fn__none");
- searchResultElement.innerHTML = "";
- previousElement.setAttribute("disabled", "true");
- nextElement.setAttribute("disabled", "true");
+ }
+ },
+ createTask(version) {
+ const listElement = element.querySelector("#searchList") as HTMLElement;
+ loadingElement.style.top = listElement.offsetTop + "px";
+ const searchInputElement = element.querySelector("#searchInput") as HTMLInputElement;
+ config.query = searchInputElement.value;
+ if (!config.page) {
+ config.page = 1;
+ }
+ listElement.scrollTo(0, 0);
+ const previousElement = element.querySelector('[data-type="previous"]');
+ const nextElement = element.querySelector('[data-type="next"]');
+ edit.protyle?.app.plugins.forEach(item => {
+ item.eventBus.emit("input-search", {
+ protyle: edit,
+ config,
+ searchElement: searchInputElement,
+ });
});
- } else {
- if (config.page > 1) {
+ const requestConfig = JSON.parse(JSON.stringify(config)) as Config.IUILayoutTabSearchConfig;
+ const requestFocusId = focusId ? Object.assign({}, focusId) : undefined;
+ const searchResultElement = element.querySelector("#searchResult");
+ if (requestConfig.query === "" && (!requestConfig.idPath || requestConfig.idPath.length === 0)) {
+ return {
+ method: requestConfig.method,
+ version,
+ run(signal: AbortSignal, isCurrent: () => boolean) {
+ return fetchPost("/api/block/getRecentUpdatedBlocks", {}, (response) => {
+ if (!isCurrent()) {
+ return;
+ }
+ onSearch(response.data, edit, element, requestConfig);
+ searchResultElement.innerHTML = "";
+ previousElement.setAttribute("disabled", "true");
+ nextElement.setAttribute("disabled", "true");
+ }, undefined, undefined, signal);
+ }
+ };
+ }
+ if (requestConfig.page > 1) {
previousElement.removeAttribute("disabled");
} else {
previousElement.setAttribute("disabled", "disabled");
}
- const endpoint = config.method === 4 ? "/api/search/semanticSearchBlock" : "/api/search/fullTextSearchBlock";
+ const endpoint = requestConfig.method === 4 ? "/api/search/semanticSearchBlock" : "/api/search/fullTextSearchBlock";
const searchParam: Record<string, any> = {
- query: config.query,
- method: config.method,
- types: config.types,
- subTypes: config.subTypes,
- paths: config.idPath || [],
- groupBy: config.group,
- orderBy: config.sort,
- page: config.page || 1,
+ query: requestConfig.query,
+ method: requestConfig.method,
+ types: requestConfig.types,
+ subTypes: requestConfig.subTypes,
+ paths: requestConfig.idPath || [],
+ groupBy: requestConfig.group,
+ orderBy: requestConfig.sort,
+ page: requestConfig.page || 1,
pageSize: 32,
- searchHPath: !config.hasReplace,
+ searchHPath: !requestConfig.hasReplace,
};
// 限定在单个加密 box 内搜索时带 notebook,让内核走加密 db;跨 box 或全局搜索走原函数
- const idPaths = config.idPath || [];
+ const idPaths = requestConfig.idPath || [];
if (idPaths.length > 0) {
const box = idPaths[0].split("/")[0];
if (isEncryptedBox(box) && idPaths.every(p => p.split("/")[0] === box)) {
searchParam.notebook = box;
}
}
- fetchPost(endpoint, searchParam, (response) => {
- const searchReqId = config.method === 4
- ? window.siyuan.reqIds["/api/search/semanticSearchBlock"]
- : window.siyuan.reqIds["/api/search/fullTextSearchBlock"];
- if (window.siyuan.reqIds["/api/block/getRecentUpdatedBlocks"] && searchReqId &&
- window.siyuan.reqIds["/api/block/getRecentUpdatedBlocks"] > searchReqId) {
- return;
- }
- if (!config.page) {
- config.page = 1;
- }
- if (config.page < response.data.pageCount) {
- nextElement.removeAttribute("disabled");
- } else {
- nextElement.setAttribute("disabled", "disabled");
- }
- onSearch(response.data.blocks, edit, element, config, focusId);
- if (response.data.matchedBlockCount > 0) {
- let text = window.siyuan.languages.findInDoc.replace("${x}", response.data.matchedRootCount).replace("${y}", response.data.matchedBlockCount);
- if (response.data.docMode) {
- text = window.siyuan.languages.matchDoc.replace("${x}", response.data.matchedRootCount);
- }
- searchResultElement.innerHTML = `${config.page}/${response.data.pageCount || 1}<span class="fn__space"></span>
+ return {
+ method: requestConfig.method,
+ version,
+ run(signal: AbortSignal, isCurrent: () => boolean) {
+ return fetchPost(endpoint, searchParam, (response) => {
+ if (!isCurrent()) {
+ return;
+ }
+ if (requestConfig.page < response.data.pageCount) {
+ nextElement.removeAttribute("disabled");
+ } else {
+ nextElement.setAttribute("disabled", "disabled");
+ }
+ onSearch(response.data.blocks, edit, element, requestConfig, requestFocusId);
+ if (response.data.matchedBlockCount > 0) {
+ let text = window.siyuan.languages.findInDoc.replace("${x}", response.data.matchedRootCount).replace("${y}", response.data.matchedBlockCount);
+ if (response.data.docMode) {
+ text = window.siyuan.languages.matchDoc.replace("${x}", response.data.matchedRootCount);
+ }
+ searchResultElement.innerHTML = `${requestConfig.page}/${response.data.pageCount || 1}<span class="fn__space"></span>
<span class="ft__on-surface">${text}</span>`;
- } else {
- searchResultElement.innerHTML = "";
+ } else {
+ searchResultElement.innerHTML = "";
+ }
+ searchResultElement.setAttribute("data-pagecount", response.data.pageCount || 1);
+ }, undefined, undefined, signal);
}
- loadingElement.classList.add("fn__none");
- searchResultElement.setAttribute("data-pagecount", response.data.pageCount || 1);
- });
+ };
}
- }, Constants.TIMEOUT_INPUT);
- element.setAttribute("data-timeout", inputTimeout.toString());
+ });
};
export const getAttr = (block: IBlock) => {
diff --git a/app/src/util/fetch.ts b/app/src/util/fetch.ts
index 893032872f..3f9a7d7c4f 100644
--- a/app/src/util/fetch.ts
+++ b/app/src/util/fetch.ts
@@ -16,8 +16,7 @@ export const fetchPost = (
method: "POST",
};
if (data) {
- if (["/api/search/searchRefBlock", "/api/graph/getGraph", "/api/graph/getLocalGraph",
- "/api/block/getRecentUpdatedBlocks", "/api/search/fullTextSearchBlock"].includes(url)) {
+ if (["/api/search/searchRefBlock", "/api/graph/getGraph", "/api/graph/getLocalGraph"].includes(url)) {
window.siyuan.reqIds[url] = Date.now();
if (data.type === "local" && url === "/api/graph/getLocalGraph") {
// 当打开文档A的关系图、关系图、文档A后刷新,由于防止请求重复处理,文档A关系图无法渲染。
@@ -83,8 +82,7 @@ export const fetchPost = (
}
return;
}
- if (["/api/search/searchRefBlock", "/api/graph/getGraph", "/api/graph/getLocalGraph",
- "/api/block/getRecentUpdatedBlocks", "/api/search/fullTextSearchBlock"].includes(url)) {
+ if (["/api/search/searchRefBlock", "/api/graph/getGraph", "/api/graph/getLocalGraph"].includes(url)) {
if (response.data.reqId && window.siyuan.reqIds[url] && window.siyuan.reqIds[url] > response.data.reqId) {
return;
}
diff --git a/kernel/api/search.go b/kernel/api/search.go
index 6dcc226e93..cda426b052 100644
--- a/kernel/api/search.go
+++ b/kernel/api/search.go
@@ -557,9 +557,12 @@ func fullTextSearchBlock(c *gin.Context) {
ret.Msg = "encrypted notebook locked"
return
}
- blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBoxWithHPath(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, notebook, searchHPath)
+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBoxWithHPathContext(c.Request.Context(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, notebook, searchHPath)
} else {
- blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockWithHPath(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, searchHPath)
+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode = model.FullTextSearchBlockInBoxWithHPathContext(c.Request.Context(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, "", searchHPath)
+ }
+ if c.Request.Context().Err() != nil {
+ return
}
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
diff --git a/kernel/model/search.go b/kernel/model/search.go
index 40dd006b67..a8ca036036 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -18,6 +18,7 @@ package model
import (
"bytes"
+ "context"
"errors"
"fmt"
stdhtml "html"
@@ -1634,6 +1635,10 @@ func FullTextSearchBlockInBox(query string, boxes, paths []string, types, subTyp
// FullTextSearchBlockInBoxWithHPath 与 FullTextSearchBlockInBox 一致,并可控制是否搜索文档层级路径。
func FullTextSearchBlockInBoxWithHPath(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {
+ return FullTextSearchBlockInBoxWithHPathContext(context.Background(), query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize, boxID, searchHPath)
+}
+
+func FullTextSearchBlockInBoxWithHPathContext(ctx context.Context, query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {
ret = []*Block{}
if "" == query {
return
@@ -1671,7 +1676,10 @@ func FullTextSearchBlockInBoxWithHPath(query string, boxes, paths []string, type
blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
}
case 2: // SQL
- blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox(query, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = searchBySQLInBoxContext(ctx, query, beforeLen, page, pageSize, boxID)
+ if ctx.Err() != nil {
+ return
+ }
case 3: // 正则表达式
typeFilter := buildTypeFilter(types, subTypes)
boxFilter, boxArgs := buildBoxesFilter(boxes)
@@ -2129,8 +2137,15 @@ func searchBySQL(stmt string, beforeLen, page, pageSize int) (ret []*Block, matc
// searchBySQLInBox 与 searchBySQL 一致,但按 boxID 路由到加密 db 或全局 db。
func searchBySQLInBox(stmt string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ return searchBySQLInBoxContext(context.Background(), stmt, beforeLen, page, pageSize, boxID)
+}
+
+func searchBySQLInBoxContext(ctx context.Context, stmt string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
stmt = strings.TrimSpace(stmt)
- blocks := sql.SelectBlocksRawStmtInBox(stmt, page, pageSize, boxID)
+ blocks, err := sql.SelectBlocksRawStmtInBoxContext(ctx, stmt, page, pageSize, boxID)
+ if err != nil {
+ return
+ }
ret = fromSQLBlocks(&blocks, "", beforeLen)
if 1 > len(ret) {
ret = []*Block{}
@@ -2147,7 +2162,10 @@ func searchBySQLInBox(stmt string, beforeLen, page, pageSize int, boxID string)
}
}
stmt = removeLimitClause(stmt)
- result, _ := sql.QueryNoLimitInBox(stmt, boxID)
+ result, err := sql.QueryNoLimitInBoxContext(ctx, stmt, boxID)
+ if err != nil {
+ return
+ }
if 1 > len(result) {
return
}
diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.go
index 072fada2ca..7204f6bdca 100644
--- a/kernel/sql/block_query.go
+++ b/kernel/sql/block_query.go
@@ -18,6 +18,7 @@ package sql
import (
"bytes"
+ "context"
"database/sql"
"errors"
"math"
@@ -723,6 +724,9 @@ func selectBlocksRawStmtWithQuery(stmt string, page, limit int, queryFn queryRow
stmt = strings.ReplaceAll(stmt, "from dual", "")
rows, err := queryFn(stmt)
if err != nil {
+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return
+ }
if strings.Contains(err.Error(), "syntax error") {
return
}
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index b89fc4c8cf..542a690429 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -18,6 +18,7 @@ package sql
import (
"bytes"
+ "context"
"crypto/sha256"
"database/sql"
"encoding/hex"
@@ -1508,6 +1509,23 @@ func queryForBox(boxID, query string, args ...any) (*sql.Rows, error) {
return db.Query(query, args...)
}
+func queryForBoxContext(ctx context.Context, boxID, query string, args ...any) (*sql.Rows, error) {
+ query = strings.TrimSpace(query)
+ if "" == query {
+ return nil, errors.New("statement is empty")
+ }
+ if boxDB := GetEncryptedDB(boxID); boxDB != nil {
+ return boxDB.QueryContext(ctx, query, args...)
+ }
+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(boxID) {
+ return nil, errors.New("encrypted box db not opened for box " + boxID)
+ }
+ if nil == db {
+ return nil, errors.New("database is nil")
+ }
+ return db.QueryContext(ctx, query, args...)
+}
+
func Exec(stmt string, args ...any) error {
stmt = strings.TrimSpace(stmt)
if "" == stmt {
diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.go
index e66fb75740..d36a62ecfc 100644
--- a/kernel/sql/encrypted_query.go
+++ b/kernel/sql/encrypted_query.go
@@ -18,6 +18,7 @@ package sql
import (
"bytes"
+ "context"
"database/sql"
"math"
"regexp"
@@ -165,6 +166,15 @@ func SelectBlocksRawStmtInBox(stmt string, page, limit int, boxID string) (ret [
return selectBlocksRawStmtWithQuery(stmt, page, limit, queryFn)
}
+func SelectBlocksRawStmtInBoxContext(ctx context.Context, stmt string, page, limit int, boxID string) (ret []*Block, err error) {
+ queryFn := func(stmt string, args ...any) (*sql.Rows, error) {
+ return queryForBoxContext(ctx, boxID, stmt, args...)
+ }
+ ret = selectBlocksRawStmtWithQuery(stmt, page, limit, queryFn)
+ err = ctx.Err()
+ return
+}
+
// QueryRefCountInBox 按 defBlockIDs 在指定 box 的 db 里查引用计数。
func QueryRefCountInBox(defIDs []string, boxID string) (ret map[string]int) {
ret = map[string]int{}
@@ -195,6 +205,10 @@ func QueryNoLimitInBox(stmt, boxID string) (ret []map[string]any, err error) {
return queryRawStmtForBox(boxID, stmt, math.MaxInt)
}
+func QueryNoLimitInBoxContext(ctx context.Context, stmt, boxID string) (ret []map[string]any, err error) {
+ return queryRawStmtForBoxContext(ctx, boxID, stmt, math.MaxInt)
+}
+
// QueryNoLimitArgsInBox 与 QueryNoLimitInBox 一致,但支持参数化查询。
func QueryNoLimitArgsInBox(stmt, boxID string, args ...any) (ret []map[string]any, err error) {
return queryRawStmtArgsForBox(boxID, stmt, args, math.MaxInt)
@@ -622,6 +636,45 @@ func queryRawStmtForBox(boxID, stmt string, limit int) (ret []map[string]any, er
return
}
+func queryRawStmtForBoxContext(ctx context.Context, boxID, stmt string, limit int) (ret []map[string]any, err error) {
+ rows, err := queryForBoxContext(ctx, boxID, stmt)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ cols, err := rows.Columns()
+ if err != nil || nil == cols {
+ return nil, err
+ }
+
+ noLimit := !containsLimitClause(stmt)
+ var count int
+ for rows.Next() {
+ columns := make([]any, len(cols))
+ columnPointers := make([]any, len(cols))
+ for i := range columns {
+ columnPointers[i] = &columns[i]
+ }
+ if err = rows.Scan(columnPointers...); err != nil {
+ return nil, err
+ }
+
+ m := make(map[string]any)
+ for i, colName := range cols {
+ val := columnPointers[i].(*any)
+ m[colName] = *val
+ }
+ ret = append(ret, m)
+ count++
+ if noLimit && limit < count {
+ break
+ }
+ }
+ err = rows.Err()
+ return
+}
+
// queryRawStmtArgsForBox 与 queryRawStmtArgs 一致,但按 boxID 路由到加密 db 或全局 db。
func queryRawStmtArgsForBox(boxID, stmt string, args []any, limit int) (ret []map[string]any, err error) {
rows, err := queryForBox(boxID, stmt, args...)
diff --git a/kernel/sql/encrypted_query_test.go b/kernel/sql/encrypted_query_test.go
index 91f26843af..451f628ae2 100644
--- a/kernel/sql/encrypted_query_test.go
+++ b/kernel/sql/encrypted_query_test.go
@@ -17,9 +17,12 @@
package sql
import (
+ "context"
gosql "database/sql"
+ "errors"
"fmt"
"testing"
+ "time"
)
func TestGetBlocksInBoxPreservesInputOrder(t *testing.T) {
@@ -128,6 +131,43 @@ func TestSelectBlocksRawStmtInBoxPaginatesExistingLimit(t *testing.T) {
}
}
+func TestQueryNoLimitInBoxContextCancellation(t *testing.T) {
+ testDB, boxID := useEncryptedQueryTestDB(t)
+ previousDB := db
+ db = testDB
+ t.Cleanup(func() {
+ db = previousDB
+ })
+
+ for name, targetBoxID := range map[string]string{"global": "", "encrypted": boxID} {
+ t.Run(name, func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() {
+ _, err := QueryNoLimitInBoxContext(ctx, `
+ WITH RECURSIVE sequence(value) AS (
+ VALUES(0)
+ UNION ALL
+ SELECT value + 1 FROM sequence WHERE value < 100000000
+ )
+ SELECT COUNT(*) FROM sequence`, targetBoxID)
+ done <- err
+ }()
+
+ time.Sleep(10 * time.Millisecond)
+ cancel()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("unexpected cancellation error: %v", err)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("SQL query was not canceled")
+ }
+ })
+ }
+}
+
func useEncryptedQueryTestDB(t *testing.T) (*gosql.DB, string) {
t.Helper()
testDB, err := gosql.Open("sqlite3_extended", ":memory:")