Skip to content

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

:zap: Improve search cancellation and incremental rendering https://github.com/siyuan-note/siyuan/issues/20692

Daniel4f3b73dcb7a5
diff --git a/app/scripts/performance.mjs b/app/scripts/performance.mjs
new file mode 100644
index 0000000000..11ddce2c30
--- /dev/null
+++ b/app/scripts/performance.mjs
@@ -0,0 +1,85 @@
+import {createReadStream} from "node:fs";
+import {createInterface} from "node:readline";
+import {pathToFileURL} from "node:url";
+
+export const parsePerformanceLine = line => {
+ const marker = "siyuan-performance ";
+ const start = line.indexOf(marker);
+ if (start < 0) {
+ return undefined;
+ }
+ const record = JSON.parse(line.slice(start + marker.length));
+ if (typeof record.operation !== "string" || !record.operation ||
+ !Number.isFinite(record.duration_us) || record.duration_us < 0) {
+ throw new Error("Invalid performance record");
+ }
+ for (const fields of [record.stages_us, record.counts]) {
+ if (fields !== undefined && (!fields || typeof fields !== "object" || Array.isArray(fields) ||
+ Object.values(fields).some(value => !Number.isFinite(value) || value < 0))) {
+ throw new Error("Invalid performance fields");
+ }
+ }
+ return record;
+};
+
+const distribution = values => {
+ values.sort((a, b) => a - b);
+ const n = values.length;
+ const median = n % 2 ? values[(n - 1) / 2] : (values[n / 2 - 1] + values[n / 2]) / 2;
+ return {samples: n, median, ...(n >= 20 ? {p95: values[Math.ceil(n * 0.95) - 1]} : {}),
+ ...(n >= 100 ? {p99: values[Math.ceil(n * 0.99) - 1]} : {}), max: values[n - 1]};
+};
+
+export const summarizePerformance = records => {
+ const groups = new Map();
+ for (const record of records) {
+ let group = groups.get(record.operation);
+ if (!group) {
+ group = {duration_ms: [], stages_ms: new Map(), counts: new Map()};
+ groups.set(record.operation, group);
+ }
+ group.duration_ms.push(record.duration_us / 1000);
+ for (const [source, target, divisor] of [[record.stages_us, group.stages_ms, 1000], [record.counts, group.counts, 1]]) {
+ for (const [name, value] of Object.entries(source || {})) {
+ if (!target.has(name)) {
+ target.set(name, []);
+ }
+ target.get(name).push(value / divisor);
+ }
+ }
+ }
+ return Object.fromEntries(Array.from(groups, ([name, group]) => [name, {
+ duration_ms: distribution(group.duration_ms),
+ stages_ms: Object.fromEntries(Array.from(group.stages_ms, ([stage, values]) => [stage, distribution(values)])),
+ counts: Object.fromEntries(Array.from(group.counts, ([count, values]) => [count, distribution(values)])),
+ }]));
+};
+
+const main = async files => {
+ if (!files.length) {
+ throw new Error("Usage: node scripts/performance.mjs <capture.log> [other-capture.log ...]");
+ }
+ for (const file of files) {
+ const records = [];
+ let lineNumber = 0;
+ for await (const line of createInterface({input: createReadStream(file, {encoding: "utf8"}), crlfDelay: Infinity})) {
+ lineNumber++;
+ try {
+ const record = parsePerformanceLine(line);
+ if (record) {
+ records.push(record);
+ }
+ } catch (error) {
+ throw new Error(`${file}:${lineNumber}: ${error.message}`, {cause: error});
+ }
+ }
+ if (!records.length) {
+ throw new Error(`No performance records in ${file}`);
+ }
+ console.log(JSON.stringify({file, operations: summarizePerformance(records)}, null, 2));
+ }
+};
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ await main(process.argv.slice(2));
+}
diff --git a/app/scripts/performance.test.js b/app/scripts/performance.test.js
new file mode 100644
index 0000000000..19bf8cc86d
--- /dev/null
+++ b/app/scripts/performance.test.js
@@ -0,0 +1,59 @@
+const assert = require("node:assert/strict");
+const {test} = require("node:test");
+const {spawnSync} = require("node:child_process");
+const {mkdtempSync, writeFileSync, rmSync} = require("node:fs");
+const {tmpdir} = require("node:os");
+const path = require("node:path");
+
+test("performance logs accept prefixed JSON and reject corrupted measurements", async () => {
+ const {parsePerformanceLine} = await import("./performance.mjs");
+ assert.equal(parsePerformanceLine("ordinary log"), undefined);
+ assert.deepEqual(parsePerformanceLine('I 2026 kernel.go:10 siyuan-performance {"operation":"search","duration_us":1000}'),
+ {operation: "search", duration_us: 1000});
+ for (const record of ["{", '{"operation":"search","duration_us":-1}',
+ '{"operation":"search","duration_us":1,"counts":{"rows":"many"}}']) {
+ assert.throws(() => parsePerformanceLine("siyuan-performance " + record));
+ }
+});
+
+test("performance summaries separate operations and only report adequately sampled percentiles", async () => {
+ const {summarizePerformance} = await import("./performance.mjs");
+ const records = Array.from({length: 100}, (_value, index) => ({operation: "search", duration_us: (index + 1) * 1000,
+ stages_us: {query: (index + 1) * 500}, counts: {rows: 50}}));
+ const summary = summarizePerformance([...records, {operation: "editor.content", duration_us: 2000}]);
+ assert.deepEqual(summary.search.duration_ms, {samples: 100, median: 50.5, p95: 95, p99: 99, max: 100});
+ assert.equal(summary.search.stages_ms.query.median, 25.25);
+ assert.equal(summary.search.counts.rows.median, 50);
+ assert.deepEqual(summary["editor.content"].duration_ms, {samples: 1, median: 2, max: 2});
+ const small = summarizePerformance(records.slice(0, 20));
+ assert.equal(small.search.duration_ms.p95, 19);
+ assert.equal(small.search.duration_ms.p99, undefined);
+});
+
+test("performance CLI reads UTF-8 captures and reports empty or malformed input", () => {
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-performance-test-"));
+ const file = path.join(temporary, "测量.log");
+ const run = () => spawnSync(process.execPath, [path.join(__dirname, "performance.mjs"), file],
+ {encoding: "utf8", windowsHide: true});
+ try {
+ writeFileSync(file, 'ordinary log\r\nsiyuan-performance {"operation":"search","duration_us":1000}\r\n', "utf8");
+ const result = run();
+ assert.equal(result.status, 0, result.stderr);
+ const summary = JSON.parse(result.stdout);
+ assert.equal(summary.file, file);
+ assert.equal(summary.operations.search.duration_ms.median, 1);
+ writeFileSync(file, "ordinary log\nsiyuan-performance {\n", "utf8");
+ const malformed = run();
+ assert.equal(malformed.status, 1);
+ assert.ok(malformed.stderr.includes(file + ":2:"));
+ writeFileSync(file, "ordinary log\n", "utf8");
+ const empty = run();
+ assert.equal(empty.status, 1);
+ assert.match(empty.stderr, /No performance records/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&
+ path.basename(temporary).startsWith("siyuan-performance-test-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.ts
index 8c1d41fe37..a03d4953ba 100644
--- a/app/src/mobile/menu/search.ts
+++ b/app/src/mobile/menu/search.ts
@@ -313,7 +313,6 @@ export const updateSearchResult = (config: Config.IUILayoutTabSearchConfig, elem
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) => {
@@ -343,8 +342,8 @@ export const updateSearchResult = (config: Config.IUILayoutTabSearchConfig, elem
}
}
return {
- method: requestConfig.method,
version,
+ abortable: requestConfig.method !== 4,
run(signal: AbortSignal, isCurrent: () => boolean) {
return fetchPost(endpoint, searchParam, (response: APICallbackResponse<APIPOSTRoutes[typeof endpoint]["response"]>) => {
if (!isCurrent()) {
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index b473494eca..8ea0aacf0b 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -2,11 +2,8 @@ import type {BlockQueryRequestInput} from "../../types/api";
import {Constants} from "../../constants";
import {hideElements} from "../ui/hideElements";
import {fetchPost} from "../../util/fetch";
-import {processRender} from "./processCode";
import {migrateLegacyMindmapsBeforeRender} from "../render/listMindmap/migrate";
import {resolveVisibleListMindmapBlock} from "../render/listMindmap/render";
-import {highlightRender} from "../render/highlightRender";
-import {blockRender} from "../render/blockRender";
import {revealTabsForTarget} from "../render/tabsRender";
import {getTabReadingID} from "../wysiwyg/tabsReading";
import {bgFade, scrollCenter} from "../../util/highlightById";
@@ -48,6 +45,8 @@ import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";
import {updateBackgroundActions} from "../header/backgroundActions";
import {recordRestoredSpellcheckFocus} from "./spellcheckFocus";
import {applyPublishFoldStates} from "./viewFold";
+import {getInsertedRenderRoots, renderContent} from "./renderContent";
+import {beginPerformance} from "./performance";
/// #if MOBILE
import {updateMobileTitleReadonly} from "./setEditMode";
import {pauseMobileBarsScroll} from "../../mobile/util/mobileBars";
@@ -277,256 +276,264 @@ const setHTML = (options: {
if (protyle.contentElement.classList.contains("fn__none") && protyle.wysiwyg.element.innerHTML !== "") {
return;
}
- setCustomBlockRootReady(protyle.wysiwyg.element, false);
+ const timing = beginPerformance("editor.content");
+ try {
+ setCustomBlockRootReady(protyle.wysiwyg.element, false);
- // XSS in inline memo elements https://github.com/siyuan-note/siyuan/issues/15280
- const parser = new DOMParser();
- const doc = parser.parseFromString(options.content, "text/html");
- doc.querySelectorAll("[data-inline-memo-content]").forEach(item => {
- const content = item.getAttribute("data-inline-memo-content");
- if (content) {
- item.setAttribute("data-inline-memo-content", sanitizeInlineMemoContent(content));
- }
- });
- normalizeHTMLAssetIFrameSources(doc);
- updateWidgetCacheVersion(doc, Constants.SIYUAN_VERSION);
- protyle.wysiwyg.prepareBlockVirtualization(
- doc.body,
- !options.action.includes(Constants.CB_GET_APPEND) && !options.action.includes(Constants.CB_GET_BEFORE)
- );
- options.content = doc.body.innerHTML;
- const REMOVED_OVER_HEIGHT = protyle.contentElement.clientHeight * 8;
- const updateReadonly = typeof options.updateReadonly === "undefined" ? protyle.wysiwyg.element.innerHTML === "" : options.updateReadonly;
- if (options.action.includes(Constants.CB_GET_APPEND)) {
- // 动态加载移除
- if (!protyle.wysiwyg.element.querySelector(".protyle-wysiwyg--select") &&
- !protyle.scroll.shouldKeepLoadedContent() && protyle.contentElement.scrollHeight > REMOVED_OVER_HEIGHT) {
- let removeElement = protyle.wysiwyg.element.firstElementChild as HTMLElement;
- const removeElements = [];
- while (protyle.wysiwyg.element.childElementCount - removeElements.length > 2 &&
- protyle.wysiwyg.element.lastElementChild !== removeElement) {
- if (containsCurrentSelection(removeElement)) {
- break;
+ // XSS in inline memo elements https://github.com/siyuan-note/siyuan/issues/15280
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(options.content, "text/html");
+ doc.querySelectorAll("[data-inline-memo-content]").forEach(item => {
+ const content = item.getAttribute("data-inline-memo-content");
+ if (content) {
+ item.setAttribute("data-inline-memo-content", sanitizeInlineMemoContent(content));
+ }
+ });
+ normalizeHTMLAssetIFrameSources(doc);
+ updateWidgetCacheVersion(doc, Constants.SIYUAN_VERSION);
+ protyle.wysiwyg.prepareBlockVirtualization(
+ doc.body,
+ !options.action.includes(Constants.CB_GET_APPEND) && !options.action.includes(Constants.CB_GET_BEFORE)
+ );
+ options.content = doc.body.innerHTML;
+ timing?.stage("dom");
+ let renderRoots: Element[] = [protyle.wysiwyg.element];
+ const REMOVED_OVER_HEIGHT = protyle.contentElement.clientHeight * 8;
+ const updateReadonly = typeof options.updateReadonly === "undefined" ? protyle.wysiwyg.element.innerHTML === "" : options.updateReadonly;
+ if (options.action.includes(Constants.CB_GET_APPEND)) {
+ // 动态加载移除
+ if (!protyle.wysiwyg.element.querySelector(".protyle-wysiwyg--select") &&
+ !protyle.scroll.shouldKeepLoadedContent() && protyle.contentElement.scrollHeight > REMOVED_OVER_HEIGHT) {
+ let removeElement = protyle.wysiwyg.element.firstElementChild as HTMLElement;
+ const removeElements = [];
+ while (protyle.wysiwyg.element.childElementCount - removeElements.length > 2 &&
+ protyle.wysiwyg.element.lastElementChild !== removeElement) {
+ if (containsCurrentSelection(removeElement)) {
+ break;
+ }
+ if (protyle.contentElement.scrollHeight - removeElement.offsetTop > REMOVED_OVER_HEIGHT) {
+ removeElements.push(removeElement);
+ } else {
+ break;
+ }
+ removeElement = removeElement.nextElementSibling as HTMLElement;
}
- if (protyle.contentElement.scrollHeight - removeElement.offsetTop > REMOVED_OVER_HEIGHT) {
- removeElements.push(removeElement);
- } else {
- break;
+ if (removeElements.length > 0) {
+ const lastRemoveTop = removeElement.getBoundingClientRect().top;
+ removeElements.forEach(item => {
+ invalidateTrackedRangesInElement(protyle, item);
+ disposeCustomBlocksInElement(item);
+ item.remove();
+ });
+ protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + (removeElement.getBoundingClientRect().top - lastRemoveTop) - 1;
+ protyle.scroll.lastScrollTop = protyle.contentElement.scrollTop;
+ hideElements(["toolbar"], protyle);
}
- removeElement = removeElement.nextElementSibling as HTMLElement;
}
- if (removeElements.length > 0) {
- const lastRemoveTop = removeElement.getBoundingClientRect().top;
- removeElements.forEach(item => {
+ const boundary = protyle.wysiwyg.element.lastElementChild;
+ protyle.wysiwyg.element.insertAdjacentHTML("beforeend", options.content);
+ renderRoots = getInsertedRenderRoots(protyle.wysiwyg.element, boundary, false);
+ } else if (options.action.includes(Constants.CB_GET_BEFORE)) {
+ const firstElement = protyle.wysiwyg.element.firstElementChild as HTMLElement;
+ const lastTop = firstElement.getBoundingClientRect().top;
+ protyle.wysiwyg.element.insertAdjacentHTML("afterbegin", options.content);
+ renderRoots = getInsertedRenderRoots(protyle.wysiwyg.element, firstElement, true);
+ protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + (firstElement.getBoundingClientRect().top - lastTop);
+ protyle.scroll.lastScrollTop = protyle.contentElement.scrollTop;
+ // 动态加载移除
+ if (!protyle.wysiwyg.element.querySelector(".protyle-wysiwyg--select") &&
+ !protyle.scroll.shouldKeepLoadedContent()) {
+ const removeElements: Element[] = [];
+ let childCount = protyle.wysiwyg.element.childElementCount;
+ let scrollHeight = protyle.contentElement.scrollHeight;
+ let lastElement = protyle.wysiwyg.element.lastElementChild;
+ while (childCount > 2 && scrollHeight > REMOVED_OVER_HEIGHT && lastElement.getBoundingClientRect().top > window.innerHeight) {
+ if (containsCurrentSelection(lastElement)) {
+ break;
+ }
+ removeElements.push(lastElement);
+ lastElement = lastElement.previousElementSibling;
+ childCount--;
+ scrollHeight -= lastElement.clientHeight + 8; // 大部分元素的 margin
+ }
+ removeElements.forEach((item) => {
invalidateTrackedRangesInElement(protyle, item);
disposeCustomBlocksInElement(item);
item.remove();
});
- protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + (removeElement.getBoundingClientRect().top - lastRemoveTop) - 1;
- protyle.scroll.lastScrollTop = protyle.contentElement.scrollTop;
hideElements(["toolbar"], protyle);
}
- }
- protyle.wysiwyg.element.insertAdjacentHTML("beforeend", options.content);
- } else if (options.action.includes(Constants.CB_GET_BEFORE)) {
- const firstElement = protyle.wysiwyg.element.firstElementChild as HTMLElement;
- const lastTop = firstElement.getBoundingClientRect().top;
- protyle.wysiwyg.element.insertAdjacentHTML("afterbegin", options.content);
- protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + (firstElement.getBoundingClientRect().top - lastTop);
- protyle.scroll.lastScrollTop = protyle.contentElement.scrollTop;
- // 动态加载移除
- if (!protyle.wysiwyg.element.querySelector(".protyle-wysiwyg--select") &&
- !protyle.scroll.shouldKeepLoadedContent()) {
- const removeElements: Element[] = [];
- let childCount = protyle.wysiwyg.element.childElementCount;
- let scrollHeight = protyle.contentElement.scrollHeight;
- let lastElement = protyle.wysiwyg.element.lastElementChild;
- while (childCount > 2 && scrollHeight > REMOVED_OVER_HEIGHT && lastElement.getBoundingClientRect().top > window.innerHeight) {
- if (containsCurrentSelection(lastElement)) {
- break;
- }
- removeElements.push(lastElement);
- lastElement = lastElement.previousElementSibling;
- childCount--;
- scrollHeight -= lastElement.clientHeight + 8; // 大部分元素的 margin
+ } else {
+ invalidateTrackedRanges(protyle);
+ disposeCustomBlocksInElement(protyle.wysiwyg.element);
+ protyle.wysiwyg.element.innerHTML = options.content;
+ // 设置 innerHTML 会导致浏览器将 scrollTop 重置为 0,此处立即恢复以避免页面跳转到开头
+ // https://github.com/siyuan-note/siyuan/issues/17886
+ if (options.scrollAttr && typeof options.scrollAttr.scrollTop === "number") {
+ protyle.contentElement.scrollTop = options.scrollAttr.scrollTop;
+ protyle.scroll.lastScrollTop = options.scrollAttr.scrollTop;
}
- removeElements.forEach((item) => {
- invalidateTrackedRangesInElement(protyle, item);
- disposeCustomBlocksInElement(item);
- item.remove();
- });
- hideElements(["toolbar"], protyle);
}
- } else {
- invalidateTrackedRanges(protyle);
- disposeCustomBlocksInElement(protyle.wysiwyg.element);
- protyle.wysiwyg.element.innerHTML = options.content;
- // 设置 innerHTML 会导致浏览器将 scrollTop 重置为 0,此处立即恢复以避免页面跳转到开头
- // https://github.com/siyuan-note/siyuan/issues/17886
- if (options.scrollAttr && typeof options.scrollAttr.scrollTop === "number") {
- protyle.contentElement.scrollTop = options.scrollAttr.scrollTop;
- protyle.scroll.lastScrollTop = options.scrollAttr.scrollTop;
- }
- }
- void applyPublishFoldStates(protyle);
- if (options.eof) {
- const eofElement = options.action.includes(Constants.CB_GET_BEFORE) ?
- protyle.wysiwyg.element.firstElementChild : protyle.wysiwyg.element.lastElementChild;
- eofElement?.setAttribute("data-eof", options.action.includes(Constants.CB_GET_BEFORE) ? "1" : "2");
- }
- updateDocumentBottomEof(protyle.wysiwyg.element);
+ void applyPublishFoldStates(protyle);
+ if (options.eof) {
+ const eofElement = options.action.includes(Constants.CB_GET_BEFORE) ?
+ protyle.wysiwyg.element.firstElementChild : protyle.wysiwyg.element.lastElementChild;
+ eofElement?.setAttribute("data-eof", options.action.includes(Constants.CB_GET_BEFORE) ? "1" : "2");
+ }
+ updateDocumentBottomEof(protyle.wysiwyg.element);
- /// #if MOBILE
- protyle.wysiwyg.element.querySelectorAll("video, audio").forEach(item => {
- item.addEventListener("playing", () => {
- activeBlur();
- });
- });
- /// #endif
- // https://github.com/siyuan-note/siyuan/issues/10528
- if (!protyle.block.showAll && protyle.wysiwyg.element.childElementCount === 1 && protyle.wysiwyg.element.firstElementChild.classList.contains("p")) {
- const editElement = getContenteditableElement(protyle.wysiwyg.element.firstElementChild);
- if (editElement && editElement.textContent === "") {
- editElement.classList.add("protyle-wysiwyg--empty");
- /// #if MOBILE
- editElement.setAttribute("placeholder", window.siyuan.languages.emptyMobilePlaceholder);
- /// #else
- editElement.setAttribute("placeholder", window.siyuan.languages.emptyPlaceholder);
- /// #endif
+ /// #if MOBILE
+ renderRoots.forEach(root => root.querySelectorAll("video, audio").forEach(item => {
+ item.addEventListener("playing", () => {
+ activeBlur();
+ });
+ }));
+ /// #endif
+ // https://github.com/siyuan-note/siyuan/issues/10528
+ if (!protyle.block.showAll && protyle.wysiwyg.element.childElementCount === 1 && protyle.wysiwyg.element.firstElementChild.classList.contains("p")) {
+ const editElement = getContenteditableElement(protyle.wysiwyg.element.firstElementChild);
+ if (editElement && editElement.textContent === "") {
+ editElement.classList.add("protyle-wysiwyg--empty");
+ /// #if MOBILE
+ editElement.setAttribute("placeholder", window.siyuan.languages.emptyMobilePlaceholder);
+ /// #else
+ editElement.setAttribute("placeholder", window.siyuan.languages.emptyPlaceholder);
+ /// #endif
+ }
}
- }
- if (options.action.includes(Constants.CB_GET_BACKLINK)) {
- foldPassiveType(options.expand, protyle.wysiwyg.element);
- }
- processRender(protyle.wysiwyg.element);
- highlightRender(protyle.wysiwyg.element);
- options.beforeAVRender?.();
- const avRendering = avRender(protyle.wysiwyg.element, protyle);
- if (options.afterAVRender) {
- void avRendering.then(() => {
- if (!options.isValid || options.isValid()) {
- return options.afterAVRender();
+ if (options.action.includes(Constants.CB_GET_BACKLINK)) {
+ foldPassiveType(options.expand, protyle.wysiwyg.element);
+ }
+ timing?.stage("render");
+ timing?.count("render_roots", renderRoots.length);
+ timing?.count("loaded_blocks", protyle.wysiwyg.element.childElementCount);
+ const avRendering = renderContent(protyle, renderRoots, options.beforeAVRender, options.isValid);
+ void avRendering.then(rendered => {
+ if (rendered && (!options.isValid || options.isValid())) {
+ return options.afterAVRender?.();
}
}).catch(error => {
console.error(error);
options.onAVRenderError?.();
});
- }
- blockRender(protyle, protyle.wysiwyg.element);
- renderHeadingNumbers(protyle);
- if (options.refreshHeadingNumbers) {
- queueHeadingNumberRefresh(protyle);
- }
- protyle.databaseAttributePanel?.render();
- if (options.action.includes(Constants.CB_GET_HISTORY)) {
- return;
- }
- if (protyle.options.render.scroll) {
- protyle.scroll.update(protyle);
- }
- if (options.action.includes(Constants.CB_GET_FOCUSFIRST)) {
- // settimeout 时间需短一点,否则定位后快速滚动无效
- const headerHeight = protyle.wysiwyg.element.offsetTop - 16;
- preventScroll(protyle, headerHeight, Constants.TIMEOUT_INPUT);
- protyle.contentElement.scrollTop = headerHeight;
- }
- if (options.isSyncing) {
- disabledForeverProtyle(protyle);
- } else {
- // 移动端横屏的空白区域承载顶部栏控件,同步提示仅在桌面端清理。
- if (protyle.breadcrumb && !isMobile()) {
- protyle.breadcrumb.element.nextElementSibling.textContent = "";
+ timing?.stage("state");
+ renderHeadingNumbers(protyle);
+ if (options.refreshHeadingNumbers) {
+ queueHeadingNumberRefresh(protyle);
}
- if (protyle.element.hasAttribute("disabled-forever")) {
- if (protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_READONLY) !== "true") {
- protyle.disabled = false;
- }
- protyle.element.removeAttribute("disabled-forever");
+ protyle.databaseAttributePanel?.render();
+ if (options.action.includes(Constants.CB_GET_HISTORY)) {
+ return;
+ }
+ if (protyle.options.render.scroll) {
+ protyle.scroll.update(protyle);
+ }
+ if (options.action.includes(Constants.CB_GET_FOCUSFIRST)) {
+ // settimeout 时间需短一点,否则定位后快速滚动无效
+ const headerHeight = protyle.wysiwyg.element.offsetTop - 16;
+ preventScroll(protyle, headerHeight, Constants.TIMEOUT_INPUT);
+ protyle.contentElement.scrollTop = headerHeight;
}
- if (options.action.includes(Constants.CB_GET_OPENNEW) && window.siyuan.config.editor.readOnly && !window.siyuan.config.readonly) {
- enableProtyle(protyle);
+ if (options.isSyncing) {
+ disabledForeverProtyle(protyle);
} else {
- setReadonlyByConfig(protyle, updateReadonly);
+ // 移动端横屏的空白区域承载顶部栏控件,同步提示仅在桌面端清理。
+ if (protyle.breadcrumb && !isMobile()) {
+ protyle.breadcrumb.element.nextElementSibling.textContent = "";
+ }
+ if (protyle.element.hasAttribute("disabled-forever")) {
+ if (protyle.wysiwyg.element.getAttribute(Constants.CUSTOM_SY_READONLY) !== "true") {
+ protyle.disabled = false;
+ }
+ protyle.element.removeAttribute("disabled-forever");
+ }
+ if (options.action.includes(Constants.CB_GET_OPENNEW) && window.siyuan.config.editor.readOnly && !window.siyuan.config.readonly) {
+ enableProtyle(protyle);
+ } else {
+ setReadonlyByConfig(protyle, updateReadonly);
+ }
}
- }
- setCustomBlockRootReady(protyle.wysiwyg.element, true);
+ setCustomBlockRootReady(protyle.wysiwyg.element, true);
- const tabItem = protyle.wysiwyg.element.querySelector(`[data-type="NodeTabItem"][data-node-id="${protyle.block.id}"]`);
- if (tabItem) {
- // 浮窗和聚焦视图默认展示被引用的页签,不改写文档中的选中状态。
- revealTabsForTarget(tabItem, false);
- }
- focusElementById(protyle, options.action, options.scrollAttr, options.scrollPosition,
- options.focusAfterZoom, options.suppressFocus);
+ const tabItem = protyle.wysiwyg.element.querySelector(`[data-type="NodeTabItem"][data-node-id="${protyle.block.id}"]`);
+ if (tabItem) {
+ // 浮窗和聚焦视图默认展示被引用的页签,不改写文档中的选中状态。
+ revealTabsForTarget(tabItem, false);
+ }
+ focusElementById(protyle, options.action, options.scrollAttr, options.scrollPosition,
+ options.focusAfterZoom, options.suppressFocus);
- if (options.action.includes(Constants.CB_GET_SETID) ||
- (protyle.model && !protyle.block.showAll)) {
- // 完整文档在定位后需将 block.id 恢复为 rootID,聚焦状态下则保留聚焦块 ID
- protyle.block.id = protyle.block.rootID;
- protyle.wysiwyg.element.setAttribute("data-doc-type", "NodeDocument");
- }
- protyle.options.defIds?.forEach(item => {
- protyle.wysiwyg.element.querySelectorAll(`[data-id="${item}"]`).forEach(item => {
- item.classList.add("def--mark");
+ if (options.action.includes(Constants.CB_GET_SETID) ||
+ (protyle.model && !protyle.block.showAll)) {
+ // 完整文档在定位后需将 block.id 恢复为 rootID,聚焦状态下则保留聚焦块 ID
+ protyle.block.id = protyle.block.rootID;
+ protyle.wysiwyg.element.setAttribute("data-doc-type", "NodeDocument");
+ }
+ protyle.options.defIds?.forEach(item => {
+ protyle.wysiwyg.element.querySelectorAll(`[data-id="${item}"]`).forEach(item => {
+ item.classList.add("def--mark");
+ });
});
- });
- protyle.options.defIds = [];
- if (options.action.includes(Constants.CB_GET_APPEND) || options.action.includes(Constants.CB_GET_BEFORE)) {
- if (areProtylePluginExtensionsEnabled(protyle)) {
- forEachPluginSubscriber("loaded-protyle-dynamic", eventBus => {
- eventBus.emit("loaded-protyle-dynamic", {
- protyle,
- position: options.action.includes(Constants.CB_GET_APPEND) ? "afterend" : "beforebegin"
+ protyle.options.defIds = [];
+ if (options.action.includes(Constants.CB_GET_APPEND) || options.action.includes(Constants.CB_GET_BEFORE)) {
+ if (areProtylePluginExtensionsEnabled(protyle)) {
+ forEachPluginSubscriber("loaded-protyle-dynamic", eventBus => {
+ eventBus.emit("loaded-protyle-dynamic", {
+ protyle,
+ position: options.action.includes(Constants.CB_GET_APPEND) ? "afterend" : "beforebegin"
+ });
});
- });
+ }
+ return;
}
- return;
- }
- updateBackgroundActions(protyle);
+ updateBackgroundActions(protyle);
- if (protyle.options.render.breadcrumb) {
- protyle.breadcrumb.toggleExit(!options.action.includes(Constants.CB_GET_ALL));
- protyle.breadcrumb.render(protyle);
- }
- if (options.afterCB) {
- options.afterCB();
- }
- // 需等待 afterCB 执行后 resize 计算出高度后再进行计算
- // 屏幕太高的页签 https://github.com/siyuan-note/siyuan/issues/5018
- if (options.scrollAttr && !protyle.scroll.element.classList.contains("fn__none") &&
- !protyle.element.classList.contains("block__edit") && // 不能为浮窗,否则悬浮为根文档无法打开整个文档 https://github.com/siyuan-note/siyuan/issues/9082
- protyle.wysiwyg.element.lastElementChild.getAttribute("data-eof") !== "2" &&
- protyle.contentElement.scrollHeight > 0 && // 没有激活的页签 https://github.com/siyuan-note/siyuan/issues/5255
- !options.action.includes(Constants.CB_GET_FOCUSFIRST) && // 防止 eof 为true https://github.com/siyuan-note/siyuan/issues/5291
- protyle.contentElement.scrollHeight <= protyle.contentElement.clientHeight) {
- protyle.scroll.loadDynamic(protyle, 2);
- }
- // 动态滚动条拖拽到最后几个块时需多加载一点块 https://github.com/siyuan-note/siyuan/issues/16906
- if (options.action.includes(Constants.CB_GET_FOCUSFIRST) &&
- protyle.wysiwyg.element.getBoundingClientRect().top > protyle.breadcrumb.element.getBoundingClientRect().bottom) {
- protyle.scroll.loadDynamic(protyle, 1);
- }
- if (options.scrollAttr && !protyle.scroll.element.classList.contains("fn__none") && !protyle.element.classList.contains("fn__none")) {
- // 使用动态滚动条定位到最后一个块,重启后无法触发滚动事件,需要再次更新 index
- const startId = options.scrollAttr.startId || protyle.wysiwyg.element.firstElementChild?.getAttribute("data-node-id");
- if (startId) {
- protyle.scroll.updateIndex(protyle, startId, (index) => {
- // https://github.com/siyuan-note/siyuan/issues/8224
- // https://github.com/siyuan-note/siyuan/issues/10716
- if (index > 1 && protyle.block.blockCount > 1 && protyle.contentElement.scrollHeight <= protyle.contentElement.clientHeight) {
- showMessage(window.siyuan.languages.scrollGetMore);
- }
- });
+ if (protyle.options.render.breadcrumb) {
+ protyle.breadcrumb.toggleExit(!options.action.includes(Constants.CB_GET_ALL));
+ protyle.breadcrumb.render(protyle);
+ }
+ if (options.afterCB) {
+ options.afterCB();
+ }
+ // 需等待 afterCB 执行后 resize 计算出高度后再进行计算
+ // 屏幕太高的页签 https://github.com/siyuan-note/siyuan/issues/5018
+ if (options.scrollAttr && !protyle.scroll.element.classList.contains("fn__none") &&
+ !protyle.element.classList.contains("block__edit") && // 不能为浮窗,否则悬浮为根文档无法打开整个文档 https://github.com/siyuan-note/siyuan/issues/9082
+ protyle.wysiwyg.element.lastElementChild.getAttribute("data-eof") !== "2" &&
+ protyle.contentElement.scrollHeight > 0 && // 没有激活的页签 https://github.com/siyuan-note/siyuan/issues/5255
+ !options.action.includes(Constants.CB_GET_FOCUSFIRST) && // 防止 eof 为true https://github.com/siyuan-note/siyuan/issues/5291
+ protyle.contentElement.scrollHeight <= protyle.contentElement.clientHeight) {
+ protyle.scroll.loadDynamic(protyle, 2);
+ }
+ // 动态滚动条拖拽到最后几个块时需多加载一点块 https://github.com/siyuan-note/siyuan/issues/16906
+ if (options.action.includes(Constants.CB_GET_FOCUSFIRST) &&
+ protyle.wysiwyg.element.getBoundingClientRect().top > protyle.breadcrumb.element.getBoundingClientRect().bottom) {
+ protyle.scroll.loadDynamic(protyle, 1);
}
+ if (options.scrollAttr && !protyle.scroll.element.classList.contains("fn__none") && !protyle.element.classList.contains("fn__none")) {
+ // 使用动态滚动条定位到最后一个块,重启后无法触发滚动事件,需要再次更新 index
+ const startId = options.scrollAttr.startId || protyle.wysiwyg.element.firstElementChild?.getAttribute("data-node-id");
+ if (startId) {
+ protyle.scroll.updateIndex(protyle, startId, (index) => {
+ // https://github.com/siyuan-note/siyuan/issues/8224
+ // https://github.com/siyuan-note/siyuan/issues/10716
+ if (index > 1 && protyle.block.blockCount > 1 && protyle.contentElement.scrollHeight <= protyle.contentElement.clientHeight) {
+ showMessage(window.siyuan.languages.scrollGetMore);
+ }
+ });
+ }
- }
- if (areProtylePluginExtensionsEnabled(protyle)) {
- forEachPluginSubscriber("loaded-protyle-static", eventBus => {
- eventBus.emit("loaded-protyle-static", {protyle});
- });
+ }
+ if (areProtylePluginExtensionsEnabled(protyle)) {
+ forEachPluginSubscriber("loaded-protyle-static", eventBus => {
+ eventBus.emit("loaded-protyle-static", {protyle});
+ });
+ }
+ } finally {
+ timing?.finish();
}
};
diff --git a/app/src/protyle/util/performance.test.ts b/app/src/protyle/util/performance.test.ts
new file mode 100644
index 0000000000..5003ec9399
--- /dev/null
+++ b/app/src/protyle/util/performance.test.ts
@@ -0,0 +1,30 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {beginPerformance} from "./performance";
+
+test("performance sampling is opt-in and does not retain individual browser measures", () => {
+ performance.clearMarks("siyuan-performance");
+ assert.equal(beginPerformance("editor.render"), undefined);
+ performance.mark("siyuan-performance");
+ const records: string[] = [];
+ const original = console.info;
+ console.info = (message: string) => records.push(message);
+ try {
+ const record = beginPerformance("editor.render");
+ record.stage("content");
+ record.count("roots", 3);
+ record.finish();
+ record.count("roots", 99);
+ record.finish();
+ assert.equal(records.length, 1);
+ const data = JSON.parse(records[0].slice("siyuan-performance ".length));
+ assert.equal(data.operation, "editor.render");
+ assert.equal(data.counts.roots, 3);
+ assert.ok(data.duration_us >= 0);
+ assert.deepEqual(Object.keys(data.stages_us).sort(), ["content", "prepare"]);
+ assert.equal(performance.getEntriesByName("editor.render").length, 0);
+ } finally {
+ performance.clearMarks("siyuan-performance");
+ console.info = original;
+ }
+});
diff --git a/app/src/protyle/util/performance.ts b/app/src/protyle/util/performance.ts
new file mode 100644
index 0000000000..0d4e8879e3
--- /dev/null
+++ b/app/src/protyle/util/performance.ts
@@ -0,0 +1,42 @@
+// 通过开发者工具的 performance.mark("siyuan-performance") 临时启用,不持久化用户偏好。
+export const beginPerformance = (operation: string) => {
+ if (!performance.getEntriesByName("siyuan-performance", "mark").length) {
+ return undefined;
+ }
+ const started = performance.now();
+ let previous = started;
+ let stage = "prepare";
+ let finished = false;
+ const stages: Record<string, number> = {};
+ const counts: Record<string, number> = {};
+ const nextStage = (name: string) => {
+ if (finished) {
+ return;
+ }
+ const now = performance.now();
+ stages[stage] = (stages[stage] || 0) + Math.round((now - previous) * 1000);
+ previous = now;
+ stage = name;
+ };
+ return {
+ stage: nextStage,
+ count(name: string, value: number) {
+ if (!finished) {
+ counts[name] = value;
+ }
+ },
+ finish() {
+ if (finished) {
+ return;
+ }
+ nextStage("finished");
+ finished = true;
+ console.info("siyuan-performance " + JSON.stringify({
+ operation,
+ duration_us: Math.round((previous - started) * 1000),
+ stages_us: stages,
+ counts,
+ }));
+ },
+ };
+};
diff --git a/app/src/protyle/util/renderContent.test.ts b/app/src/protyle/util/renderContent.test.ts
new file mode 100644
index 0000000000..248f17d3ea
--- /dev/null
+++ b/app/src/protyle/util/renderContent.test.ts
@@ -0,0 +1,176 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {test} from "node:test";
+import {promisify} from "node:util";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (renderSource: string, onGetSource: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ const calls: {kind: string, root: Element}[] = [];
+ let releaseDatabase: (() => void) | undefined;
+ let holdDatabase = false;
+ const noop = (): undefined => undefined;
+ const renderers = {
+ processRender: (root: Element) => calls.push({kind: "process", root}),
+ highlightRender: (root: Element) => calls.push({kind: "highlight", root}),
+ avRender: async (root: Element) => {
+ calls.push({kind: "database", root});
+ if (holdDatabase) {
+ holdDatabase = false;
+ await new Promise<void>(resolve => { releaseDatabase = resolve; });
+ }
+ },
+ blockRender: (_protyle: IProtyle, root: Element) => calls.push({kind: "embed", root}),
+ beginPerformance: noop,
+ };
+ const {getInsertedRenderRoots, renderContent} = new Function(...Object.keys(renderers), renderSource +
+ "\nreturn {getInsertedRenderRoots, renderContent};")(...Object.values(renderers)) as {
+ getInsertedRenderRoots: (container: Element, boundary: Element | null, before: boolean) => Element[],
+ renderContent: (protyle: IProtyle, roots: Element[], before?: () => void, valid?: () => boolean) => Promise<boolean>,
+ };
+ const Constants = {CB_GET_APPEND: "append", CB_GET_BEFORE: "before", CB_GET_HISTORY: "history",
+ CB_GET_BACKLINK: "backlink", SIYUAN_VERSION: "test"};
+ let disposed: Element[] = [];
+ const dependencies = {Constants, getInsertedRenderRoots, renderContent,
+ migrateLegacyMindmapsBeforeRender: () => false, setCustomBlockRootReady: noop,
+ sanitizeInlineMemoContent: (value: string) => value, normalizeHTMLAssetIFrameSources: noop,
+ updateWidgetCacheVersion: noop, containsCurrentSelection: () => false,
+ invalidateTrackedRangesInElement: noop, disposeCustomBlocksInElement: (root: Element) => disposed.push(root),
+ hideElements: noop, invalidateTrackedRanges: noop, applyPublishFoldStates: noop,
+ updateDocumentBottomEof: noop, activeBlur: noop, getContenteditableElement: (): HTMLElement | null => null,
+ foldPassiveType: noop, renderHeadingNumbers: noop, queueHeadingNumberRefresh: noop, beginPerformance: noop};
+ const setHTML = new Function(...Object.keys(dependencies), onGetSource + "\nreturn setHTML;")(
+ ...Object.values(dependencies)) as (options: Record<string, unknown>, protyle: IProtyle) => void;
+ const content = document.createElement("div");
+ const container = document.createElement("div");
+ content.style.cssText = "height: 200px; width: 300px; overflow: auto; overflow-anchor: none";
+ container.className = "protyle-wysiwyg";
+ content.append(container);
+ document.body.append(content);
+ const protyle = {contentElement: content, wysiwyg: {element: container, prepareBlockVirtualization: noop},
+ block: {rootID: "root", showAll: true}, scroll: {shouldKeepLoadedContent: () => true}} as unknown as IProtyle;
+ const load = (action: string[], html: string) => setHTML({action: [...action, "history"], content: html,
+ eof: true, isSyncing: false, expand: false}, protyle);
+ const settle = async () => { for (let i = 0; i < 20; i++) { await Promise.resolve(); } };
+ const oldHTML = Array.from({length: 100}, (_v, index) =>
+ `<div data-node-id="old-${index}" style="height: 20px"><span contenteditable="true">Old ${index}</span></div>`).join("");
+ container.innerHTML = oldHTML;
+ const oldFirst = container.firstElementChild;
+ const selection = window.getSelection();
+ const range = document.createRange();
+ range.selectNodeContents(oldFirst.firstElementChild);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ load(["append"], '<div data-node-id="new-math" data-type="NodeMathBlock"></div>' +
+ '<div data-node-id="new-av" data-type="NodeAttributeView"></div>' +
+ '<div data-node-id="new-embed" data-type="NodeBlockQueryEmbed"></div>');
+ await settle();
+ check.deepEqual(calls.slice(0, 6).map(call => call.kind),
+ ["process", "process", "process", "highlight", "highlight", "highlight"], "render phases keep their order");
+ for (const kind of ["process", "highlight", "database", "embed"]) {
+ check.deepEqual(calls.filter(call => call.kind === kind).map(call => call.root.getAttribute("data-node-id")),
+ ["new-math", "new-av", "new-embed"], `${kind} visits inserted roots including the root itself`);
+ }
+ check.equal(container.firstElementChild, oldFirst);
+ check.equal(selection.anchorNode, oldFirst.firstElementChild, "appending keeps the existing selection node");
+ check.equal(disposed.length, 0, "retained components are not disposed");
+ calls.length = 0;
+ content.scrollTop = 500;
+ const beforeTop = oldFirst.getBoundingClientRect().top;
+ load(["before"], '<div data-node-id="new-list" style="height: 60px"><div data-type="NodeMathBlock"></div></div>');
+ await settle();
+ check.equal(oldFirst.getBoundingClientRect().top, beforeTop, "prepending keeps the existing scroll anchor");
+ check.deepEqual(calls.filter(call => call.kind === "process").map(call => call.root.getAttribute("data-node-id")), ["new-list"]);
+ check.equal(container.firstElementChild.getAttribute("data-eof"), "1");
+ calls.length = 0;
+ load(["append"], "");
+ await settle();
+ check.equal(calls.length, 0, "an empty append does not rescan old content");
+ load([], '<div data-node-id="replacement"></div>');
+ await settle();
+ check.equal(calls.find(call => call.kind === "process").root, container, "full replacements retain whole-root rendering");
+ check.equal(disposed.at(-1), container, "full replacements retain disposal");
+
+ // 裁剪可能移除已收集的新节点,异步数据库工作必须再次检查实际归属。
+ container.innerHTML = '<div id="a"></div><div id="b"></div><div id="c"></div>';
+ const [a, b, c] = Array.from(container.children);
+ calls.length = 0;
+ holdDatabase = true;
+ let valid = true;
+ const pending = renderContent(protyle, [a, b, c], undefined, () => valid);
+ b.remove();
+ valid = false;
+ releaseDatabase();
+ check.equal(await pending, false, "invalidated content must not trigger completion callbacks");
+ check.deepEqual(calls.filter(call => call.kind === "database").map(call => call.root.id), ["a"],
+ "an invalidated document does not start later database renders");
+ calls.length = 0;
+ valid = true;
+ await renderContent(protyle, [b, c]);
+ check.equal(calls.some(call => call.root === b), false, "removed nodes do not render");
+ check.equal(calls.some(call => call.root === c), true);
+
+ // 大文档追加的扫描规模由新块数决定;这里只比较遍历工作量,不代表整页耗时。
+ container.innerHTML = Array.from({length: 20000}, () => '<div><span class="target"></span></div>').join("");
+ const boundary = container.lastElementChild;
+ container.insertAdjacentHTML("beforeend", '<div><span class="target"></span></div>'.repeat(20));
+ const roots = getInsertedRenderRoots(container, boundary, false);
+ check.equal(container.querySelectorAll(".target").length, 20020);
+ check.equal(roots.reduce((count, root) => count + root.querySelectorAll(".target").length, 0), 20);
+ check.equal(roots.length, 20);
+ container.innerHTML = "";
+ check.deepEqual(getInsertedRenderRoots(container, null, false), []);
+ container.innerHTML = '<div id="only"></div>';
+ check.deepEqual(getInsertedRenderRoots(container, null, true), [container.firstElementChild]);
+ disposed = [];
+ content.remove();
+ return "Content rendering cases passed; scanned targets 20020 -> 20";
+};
+
+test("dynamic content renders inserted roots and preserves replacement, selection and scroll behavior", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 30000,
+}, async () => {
+ const compile = (source: string) => transpileModule(source, {compilerOptions: {target: ScriptTarget.ES2022}}).outputText;
+ const renderSource = readFileSync(path.join(__dirname, "renderContent.ts"), "utf8")
+ .replace(/^import .*;\r?\n/gm, "").replaceAll("export const", "const");
+ const onGetSource = readFileSync(path.join(__dirname, "onGet.ts"), "utf8");
+ const start = onGetSource.indexOf("const setHTML = ");
+ const end = onGetSource.indexOf("export const disabledForeverProtyle", start);
+ assert.ok(start > 0 && end > start);
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-render-content-test-"));
+ const script = path.join(temporary, "run.cjs");
+ const code = "const __name = value => value; (" + browserCases.toString() + ")(" +
+ JSON.stringify(compile(renderSource)) + "," + JSON.stringify(compile(onGetSource.slice(start, end))) + ")";
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(code)}));
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ app.exit(1);
+ }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],
+ {env, timeout: 25000, windowsHide: true});
+ assert.match(result.stdout, /Content rendering cases passed; scanned targets 20020 -> 20/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&
+ path.basename(temporary).startsWith("siyuan-render-content-test-")) {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});
diff --git a/app/src/protyle/util/renderContent.ts b/app/src/protyle/util/renderContent.ts
new file mode 100644
index 0000000000..53fb4cdd25
--- /dev/null
+++ b/app/src/protyle/util/renderContent.ts
@@ -0,0 +1,50 @@
+import {processRender} from "./processCode";
+import {highlightRender} from "../render/highlightRender";
+import {avRender} from "../render/av/render";
+import {blockRender} from "../render/blockRender";
+import {beginPerformance} from "./performance";
+
+// 只遍历插入边界以外的新兄弟节点,不扫描、搬移旧内容。
+export const getInsertedRenderRoots = (container: Element, boundary: Element | null, before: boolean) => {
+ const roots: Element[] = [];
+ let node = before || !boundary ? container.firstElementChild : boundary.nextElementSibling;
+ while (node && (!before || node !== boundary)) {
+ roots.push(node);
+ node = node.nextElementSibling;
+ }
+ return roots;
+};
+
+export const renderContent = (protyle: IProtyle, roots: Element[], beforeAVRender?: () => void,
+ isValid?: () => boolean) => {
+ const container = protyle.wysiwyg.element;
+ const rootID = protyle.block.rootID;
+ const canRender = (root: Element) => (!isValid || isValid()) && protyle.block.rootID === rootID &&
+ (root === container || (root.isConnected && root.parentElement === container));
+ const currentRoots = roots.filter(canRender);
+ currentRoots.forEach(root => processRender(root));
+ currentRoots.forEach(root => highlightRender(root));
+ beforeAVRender?.();
+ // 数据库仍按文档顺序串行初始化,保留原来的请求并发和完成回调边界。
+ const renderDatabases = async () => {
+ const timing = beginPerformance("editor.databases");
+ timing?.count("roots", currentRoots.length);
+ try {
+ for (const root of currentRoots) {
+ if (canRender(root)) {
+ await avRender(root, protyle);
+ }
+ }
+ return (!isValid || isValid()) && protyle.block.rootID === rootID && currentRoots.every(canRender);
+ } finally {
+ timing?.finish();
+ }
+ };
+ const databases = renderDatabases();
+ currentRoots.forEach(root => {
+ if (canRender(root)) {
+ blockRender(protyle, root);
+ }
+ });
+ return databases;
+};
diff --git a/app/src/search/request.test.ts b/app/src/search/request.test.ts
index 4135f15574..24dcf7488a 100644
--- a/app/src/search/request.test.ts
+++ b/app/src/search/request.test.ts
@@ -54,7 +54,6 @@ describe("search request scheduling", () => {
onIdle: idle.resolve,
createTask(version) {
return {
- method: 0,
version,
run(_signal, isCurrent) {
firstIsCurrent = isCurrent;
@@ -76,7 +75,6 @@ describe("search request scheduling", () => {
onIdle: idle.resolve,
createTask(version) {
return {
- method: 0,
version,
run() {
activeRequests++;
@@ -97,12 +95,12 @@ describe("search request scheduling", () => {
assert.equal(maxActiveRequests, 1);
});
- it("aborts a running SQL request when a newer search is scheduled", async () => {
+ it("aborts a running search when a newer search is scheduled", async () => {
const element = {isConnected: true} as Element;
const firstStarted = deferred();
const secondStarted = deferred();
const idle = deferred();
- let sqlSignal!: AbortSignal;
+ let firstSignal!: AbortSignal;
scheduleSearchRequest({
element,
@@ -110,10 +108,9 @@ describe("search request scheduling", () => {
onIdle: idle.resolve,
createTask(version) {
return {
- method: 2,
version,
run(signal) {
- sqlSignal = signal;
+ firstSignal = signal;
firstStarted.resolve();
return new Promise<void>((resolve) => {
signal.addEventListener("abort", () => resolve(), {once: true});
@@ -130,7 +127,6 @@ describe("search request scheduling", () => {
onIdle: idle.resolve,
createTask(version) {
return {
- method: 0,
version,
run() {
secondStarted.resolve();
@@ -139,14 +135,91 @@ describe("search request scheduling", () => {
},
});
- assert.equal(sqlSignal.aborted, true);
+ assert.equal(firstSignal.aborted, true);
await secondStarted.promise;
await idle.promise;
});
+ it("keeps non-cancelable backend searches serialized while invalidating their response", async () => {
+ const element = {isConnected: true} as Element;
+ const started = deferred();
+ const done = deferred();
+ const idle = deferred();
+ let signal: AbortSignal;
+ let isCurrent: () => boolean;
+ let nextRuns = 0;
+ scheduleSearchRequest({
+ element, delay: 0, onIdle: idle.resolve,
+ createTask: version => ({version, abortable: false, run(currentSignal, current) {
+ signal = currentSignal;
+ isCurrent = current;
+ started.resolve();
+ return done.promise;
+ }}),
+ });
+ await started.promise;
+ scheduleSearchRequest({
+ element, delay: 0, onIdle: idle.resolve,
+ createTask: version => ({version, run() { nextRuns++; }}),
+ });
+ await nextTimer();
+ assert.equal(signal.aborted, false);
+ assert.equal(isCurrent(), false);
+ assert.equal(nextRuns, 0);
+ done.resolve();
+ await idle.promise;
+ assert.equal(nextRuns, 1);
+ });
+
+ it("continues with the newest request after an aborted request rejects", async () => {
+ const element = {isConnected: true} as Element;
+ const started = deferred();
+ const idle = deferred();
+ let obsoleteRuns = 0;
+ let currentRuns = 0;
+ scheduleSearchRequest({
+ element, delay: 0, onIdle: idle.resolve,
+ createTask: version => ({version, run(signal) {
+ started.resolve();
+ return new Promise<void>((_resolve, reject) => {
+ signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), {once: true});
+ });
+ }}),
+ });
+ await started.promise;
+ scheduleSearchRequest({
+ element, delay: 10, onIdle: idle.resolve,
+ createTask: version => ({version, run() { obsoleteRuns++; }}),
+ });
+ scheduleSearchRequest({
+ element, delay: 0, onIdle: idle.resolve,
+ createTask: version => ({version, run(_signal, isCurrent) {
+ assert.equal(isCurrent(), true);
+ currentRuns++;
+ }}),
+ });
+ await idle.promise;
+ assert.equal(obsoleteRuns, 0);
+ assert.equal(currentRuns, 1);
+ });
+
+ it("does not dispatch a search after its scope is disconnected", async () => {
+ const element = {isConnected: true} as Element;
+ let runs = 0;
+ scheduleSearchRequest({
+ element, delay: 0, onIdle() { /* 已销毁的作用域无需更新 */ },
+ createTask: version => ({version, run() { runs++; }}),
+ });
+ Object.assign(element, {isConnected: false});
+ await nextTimer();
+ assert.equal(runs, 0);
+ cancelSearchRequest(element);
+ });
+
it("aborts the active request and drops the queued request when canceled", async () => {
const element = {isConnected: true} as Element;
const firstStarted = deferred();
+ const firstDone = deferred();
let firstSignal!: AbortSignal;
let secondStarted = false;
@@ -158,14 +231,12 @@ describe("search request scheduling", () => {
},
createTask(version) {
return {
- method: 0,
version,
run(signal) {
firstSignal = signal;
firstStarted.resolve();
- return new Promise<void>((resolve) => {
- signal.addEventListener("abort", () => resolve(), {once: true});
- });
+ // 保持旧请求未结束,让新任务真正排队后再销毁作用域。
+ return firstDone.promise;
},
};
},
@@ -180,7 +251,6 @@ describe("search request scheduling", () => {
},
createTask(version) {
return {
- method: 0,
version,
run() {
secondStarted = true;
@@ -190,6 +260,7 @@ describe("search request scheduling", () => {
});
await nextTimer();
cancelSearchRequest(element);
+ firstDone.resolve();
await nextTimer();
assert.equal(firstSignal.aborted, true);
diff --git a/app/src/search/request.ts b/app/src/search/request.ts
index e4028d65a0..147ede932a 100644
--- a/app/src/search/request.ts
+++ b/app/src/search/request.ts
@@ -1,6 +1,6 @@
interface ISearchRequestTask {
- method: number,
version: number,
+ abortable?: boolean,
run: (signal: AbortSignal, isCurrent: () => boolean) => Promise<unknown> | void,
}
@@ -42,7 +42,16 @@ const runRequestTask = (element: Element, state: ISearchRequestState, task: ISea
return element.isConnected && state.version === task.version && state.running === running;
};
void Promise.resolve()
- .then(() => task.run(controller.signal, isCurrent))
+ .then(() => {
+ if (!controller.signal.aborted && isCurrent()) {
+ return task.run(controller.signal, isCurrent);
+ }
+ })
+ .catch(error => {
+ if (!controller.signal.aborted) {
+ console.error("Search request failed", error);
+ }
+ })
.finally(() => {
if (state.running !== running) {
return;
@@ -71,7 +80,7 @@ export const scheduleSearchRequest = (options: {
if (state.timeout !== undefined) {
window.clearTimeout(state.timeout);
}
- if (state.running?.task.method === 2) {
+ if (state.running && state.running.task.abortable !== false) {
state.running.controller.abort();
}
const version = state.version;
diff --git a/app/src/search/util.ts b/app/src/search/util.ts
index 1dcbd246ff..176046dbb8 100644
--- a/app/src/search/util.ts
+++ b/app/src/search/util.ts
@@ -1568,7 +1568,6 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCo
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) => {
@@ -1600,8 +1599,8 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCo
}
}
return {
- method: requestConfig.method,
version,
+ abortable: requestConfig.method !== 4,
run(signal: AbortSignal, isCurrent: () => boolean) {
return fetchPost(endpoint, searchParam, (response: APICallbackResponse<APIPOSTRoutes[typeof endpoint]["response"]>) => {
if (!isCurrent()) {
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
new file mode 100644
index 0000000000..2e757411fd
--- /dev/null
+++ b/docs/PERFORMANCE.md
@@ -0,0 +1,86 @@
+# Performance measurement
+
+[中文](PERFORMANCE.zh-CN.md)
+
+## Scope
+
+Performance measurements separate synchronous kernel work, asynchronous component initialization, and browser layout. Stage records are local diagnostics. They do not change API responses, transaction completion, search counts, notebook access checks, or persisted formats. They do not upload measurements.
+
+## Stage records
+
+Set the environment variable `SIYUAN_PERFORMANCE=1` before starting a development kernel to enable records in its existing log. Stop sampling by removing the variable before the next start. The developer controls building and restarting the kernel. With sampling disabled, the kernel recorder performs no allocations.
+
+In the renderer's developer tools, run `performance.mark("siyuan-performance")` to enable console records and `performance.clearMarks("siyuan-performance")` to disable them. The mark is temporary and is not a saved preference. The recorder does not create a growing collection of per-operation browser marks or measures.
+
+Records start with `siyuan-performance ` followed by JSON. `duration_us` and `stages_us` are elapsed microseconds; `counts` contains operation sizes or explicitly named durations such as `oldest_wait_us`. Names are fixed in code. Records contain no query strings, note content, document identifiers, paths, credentials, or keys. Existing logs outside these records can contain other diagnostics; review a capture before sharing it.
+
+| Operation | Stage boundary and counters |
+|---|---|
+| `transaction` | Begin, automations, apply, finalize, commit; operation count |
+| `document.load` | Transaction barrier, load/parse tree, locate blocks, render response; block count |
+| `document.save` | Prepare/serialize, encrypt, compare, write, notify; prepared and written bytes |
+| `index.flush` | Lock wait, take queue, begin/execute/commit, notify, persist queue completion; batch size and oldest enqueue age |
+| `database.view`, `database.fields`, `database.rows` | Load and sync wait, field calculation, filter, sort, aggregation, pagination, conditional colors; row counts before filtering, after filtering and after pagination |
+| `search`, `search.fts`, `search.path`, `search.regexp`, `search.document` | Query, result processing, exact count, grouping/references; method, returned results, matches and cancellation |
+| `editor.content` | Parse/normalize, DOM insertion, synchronous render dispatch, global state; render roots and loaded top-level blocks |
+| `editor.databases` | Elapsed time until serial database initialization finishes; candidate root count |
+
+The initial stage is named `prepare`. Repeated stages accumulate time. A canceled search has `counts.canceled = 1`; analyze canceled requests separately from successful requests. The multiword document query computes counts inside the query, so its stage is `query_count`. Regex matching and highlighting share a stage. A save skipped by the existing equality check has no written-byte counter. The index age is the oldest known enqueue time in the captured batch; recovered operations can lack that timestamp. It is not transaction queue wait time.
+
+Nested operations overlap: do not add a parent duration to its children. `editor.content` measures synchronous work and dispatch, excluding later math/chart script loading, embedded queries and browser layout. `editor.databases` includes asynchronous database waits and does not represent all components becoming visible. Global heading numbering, fold state, readonly state, focus and plugin events retain their existing scope.
+
+Export kernel and browser captures separately as UTF-8 files. From `app/`, summarize each run with:
+
+```text
+node scripts/performance.mjs before.log after.log
+```
+
+The summarizer groups each capture by operation and reports sample counts, medians and maxima. P95 requires at least 20 samples; P99 requires at least 100. Stage samples and counters retain their own sample counts. Keep workload, result status and size consistent within a capture. Empty or malformed measurements fail explicitly. Keep the raw files alongside summaries.
+
+## Reproducible microbenchmarks
+
+Run from `kernel/` using the same Go toolchain, machine, power settings and otherwise idle environment:
+
+```text
+go test ./filesys -run '^$' -bench '^BenchmarkDocumentJSON$' -benchmem -benchtime=200ms -count=3
+go test ./model -run '^$' -bench '^BenchmarkDatabaseDisplayPage$' -benchmem -benchtime=200ms -count=3
+go test ./model -run '^$' -bench '^BenchmarkDocumentSearch$' -benchmem -benchtime=200ms -count=3
+```
+
+| Benchmark | Fixed workload | Included work |
+|---|---|---|
+| `BenchmarkDocumentJSON` | 1,000 / 5,000 / 20,000 paragraph blocks, 112 ASCII content bytes per block, no references/assets, flat structure | Document preparation/JSON serialization or JSON parsing/validation; preparation uses a temporary directory; no product binary or workspace is replaced |
+| `BenchmarkDatabaseDisplayPage` | 1,000 / 10,000 / 50,000 detached rows, block/text/display-template fields, page size 50, no filter/group/sort | Render fields using the existing display-template deferral, paginate and evaluate the current page's template |
+| `BenchmarkDocumentSearch` | 10,000 / 100,000 / 1,000,000 indexed blocks, 100 blocks per document, two keywords in separate paragraphs, every document matches, first 50 documents | Warm in-memory SQLite document query, exact count and result-row decoding; no FTS, disk I/O, full API formatting or frontend |
+
+Use sub-benchmark filters for smaller runs, for example `-bench '^BenchmarkDocumentSearch$/^10000$'`. Database setup and fixture generation are outside measured loops. The database benchmark reuses the attribute view across iterations; it is not a cold-open measurement. `-benchmem` measures Go allocations, not SQLite native allocations or total RSS. Benchmark results are baselines for those paths, not application latency or a general speedup claim.
+
+## Product captures
+
+For each comparison, record commit, toolchain and Electron versions, OS, hardware, build mode, actual data sizes, query hit rate, sample count, cache state and concurrent background work. Keep fixed content length, nesting, reference/asset count, database field definitions and templates. Capture cold open, warm reopen, subsequent pages, continuous typing and interaction during sync/indexing separately. Include small workspaces, low-hit queries, encrypted notebooks and desktop/browser/mobile paths.
+
+Use the browser Performance panel for long tasks, style/layout work and time until affected content is visible. Use OS process measurements for kernel and renderer RSS separately. Go profiles measure Go heap/CPU; they do not include all SQLite or Electron native memory. Kernel profiling endpoints require explicit `--enable-pprof` and existing administrator authentication. Collect profiler runs separately from low-overhead timings. No profiler endpoint is enabled by the recorder.
+
+Do not infer SQL changed-row counts, query counts, cache hit rates or peak RSS from stage durations; collect those metrics separately when evaluating the corresponding optimization. Do not infer UI correctness, encrypted-data recovery, or concurrency correctness from microbenchmark throughput.
+
+## Regression checks
+
+Frontend tests are discovered by `app/scripts/test.mjs`; Go tests and benchmarks are discovered by their package commands. Focused checks from `app/`:
+
+```text
+node --import tsx --test --test-concurrency=1 src/search/request.test.ts src/protyle/util/renderContent.test.ts src/protyle/util/performance.test.ts src/protyle/util/onGetPositioning.test.ts
+node --test scripts/performance.test.js
+pnpm run lint
+```
+
+The test launcher initializes Electron before parallel browser tests. When running browser tests directly after installing dependencies, first load `require("electron")` once to finish installation. Do not start several first-time Electron installations concurrently.
+
+Focused checks from `kernel/`:
+
+```text
+go test -tags fts5 ./model -run 'TestFullTextSearchRejectsCanceledRequest|TestSearchContextPreservesResultsCountsAndPagination' -count=1
+go test ./sql -run 'TestParameterizedSearchQueriesCancelAndReleaseConnection|TestSearchQueriesRejectCanceledContextBeforeReading|TestBlockQueriesBeyondVariableLimit' -count=1
+go test ./util -run Performance -count=1
+```
+
+Cancellation tests cover running SQLite work and connection reuse in global and notebook-routed databases. The scoped in-memory database fixture tests routing, not SQLCipher format compatibility. Rendering tests use real browser DOM for insertion roots, whole replacement, selection identity, prepend scroll compensation and stale/removed roots, with component renderers replaced by spies. Component behavior and real device IME/touch interactions require their own regression checks. Semantic search retains serial scheduling because its backend cancellation is a separate change.
diff --git a/docs/PERFORMANCE.zh-CN.md b/docs/PERFORMANCE.zh-CN.md
new file mode 100644
index 0000000000..2f61e16e16
--- /dev/null
+++ b/docs/PERFORMANCE.zh-CN.md
@@ -0,0 +1,86 @@
+# 性能测量
+
+[English](PERFORMANCE.md)
+
+## 范围
+
+性能测量区分内核同步工作、组件异步初始化和浏览器布局。阶段记录是本地诊断信息,不改变 API 响应、事务完成、搜索计数、笔记本访问检查或持久化格式,也不会上传测量数据。
+
+## 阶段记录
+
+在启动开发内核前设置环境变量 `SIYUAN_PERFORMANCE=1`,即可在现有内核日志中输出记录。下次启动前移除变量即可停止采样。构建和重启内核由开发者控制。关闭采样时,内核记录器不产生分配。
+
+在渲染进程开发者工具中执行 `performance.mark("siyuan-performance")` 开启控制台记录,执行 `performance.clearMarks("siyuan-performance")` 关闭。标记是临时状态,不会保存为用户偏好。记录器不会不断积累每次操作的浏览器标记或测量条目。
+
+记录以 `siyuan-performance ` 开头,后接 JSON。`duration_us` 和 `stages_us` 是经过时间,单位为微秒;`counts` 是操作规模,或 `oldest_wait_us` 等明确命名的耗时。名称在代码中固定。记录不包含查询字符串、笔记正文、文档标识、路径、凭证或密钥。记录之外的现有日志可能包含其他诊断信息,分享采样文件前应检查其内容。
+
+| 操作 | 阶段边界和计数 |
+|---|---|
+| `transaction` | 开始、自动化、应用操作、整理、提交;操作数 |
+| `document.load` | 事务屏障、加载/解析树、定位块、渲染响应;块数 |
+| `document.save` | 准备/序列化、加密、比对、写入、通知;待保存字节数和实际写入字节数 |
+| `index.flush` | 等锁、提取队列、开始/执行/提交、通知、持久化队列完成状态;批次大小和最老入队任务的等待时间 |
+| `database.view`、`database.fields`、`database.rows` | 加载和同步等待、字段计算、筛选、排序、汇总、分页、条件色;筛选前、筛选后及分页后的条目数 |
+| `search`、`search.fts`、`search.path`、`search.regexp`、`search.document` | 查询、结果加工、精确计数、分组/引用;方法、返回结果数、命中数和取消状态 |
+| `editor.content` | 解析/规范化、DOM 插入、同步渲染调度、全局状态;渲染根节点数和已加载的顶层块数 |
+| `editor.databases` | 串行数据库初始化完成前的经过时间;候选根节点数 |
+
+初始阶段名为 `prepare`,同名阶段累计耗时。被取消的搜索包含 `counts.canceled = 1`,应与成功请求分开分析。多词文档搜索在查询内部计数,因此阶段为 `query_count`;正则匹配和高亮共用一个阶段。被现有相等性检查跳过的保存没有实际写入字节计数。索引等待时间取已提取批次中已知的最早入队时间,恢复的操作可能缺少该时间戳;它不是编辑事务排队时间。
+
+嵌套操作耗时有重叠,不能将父操作与子操作相加。`editor.content` 测量同步工作和调度,不含后续公式/图表脚本加载、嵌入查询及浏览器布局。`editor.databases` 包含数据库异步等待,不代表所有组件已经可见。全局标题编号、折叠状态、只读状态、焦点和插件事件保持原有范围。
+
+将内核与浏览器采样分别导出为 UTF-8 文件。在 `app/` 下汇总每次运行:
+
+```text
+node scripts/performance.mjs before.log after.log
+```
+
+汇总器按每份采样的操作分类,输出样本数、中位数和最大值。P95 至少需要 20 个样本,P99 至少需要 100 个样本。各阶段和计数保留各自的样本数。同一采样中应保持工作负载、结果状态和规模一致。没有测量记录或记录损坏时明确报错。原始文件与汇总结果一起保留。
+
+## 可复现微基准
+
+在 `kernel/` 下使用相同 Go 工具链、机器、电源设置及尽量空闲的环境运行:
+
+```text
+go test ./filesys -run '^$' -bench '^BenchmarkDocumentJSON$' -benchmem -benchtime=200ms -count=3
+go test ./model -run '^$' -bench '^BenchmarkDatabaseDisplayPage$' -benchmem -benchtime=200ms -count=3
+go test ./model -run '^$' -bench '^BenchmarkDocumentSearch$' -benchmem -benchtime=200ms -count=3
+```
+
+| 基准 | 固定工作负载 | 包含的工作 |
+|---|---|---|
+| `BenchmarkDocumentJSON` | 1 千 / 5 千 / 2 万个段落块,每块 112 字节 ASCII 正文,无引用/资源,扁平结构 | 文档准备/JSON 序列化,或 JSON 解析/校验;准备过程使用临时目录,不替换产品内核或工作区 |
+| `BenchmarkDatabaseDisplayPage` | 1 千 / 1 万 / 5 万个游离条目,块/文本/显示模板字段,每页 50 条,无筛选/分组/排序 | 通过已有显示模板延迟计算生成字段、分页并求值当前页模板 |
+| `BenchmarkDocumentSearch` | 1 万 / 10 万 / 100 万个索引块,每篇 100 块,两个词分别位于不同段落,每篇均命中,取前 50 篇 | 热内存 SQLite 文档查询、精确计数及结果行解码;不含 FTS、磁盘 I/O、完整 API 加工或前端 |
+
+可通过子基准筛选缩小规模,例如 `-bench '^BenchmarkDocumentSearch$/^10000$'`。数据库建立和夹具生成不在计时循环内。数据库视图基准在迭代间复用属性视图,不代表冷启动打开。`-benchmem` 测量 Go 分配,不是 SQLite 原生分配或总 RSS。基准结果是对应路径的基线,不是应用延迟或整体提速结论。
+
+## 产品采样
+
+每组对照记录提交、工具链与 Electron 版本、操作系统、硬件、构建方式、实际数据规模、查询命中率、样本数、缓存状态和并发后台工作。固定正文长度、嵌套、引用/资源数量、数据库字段和模板。冷打开、热重开、后续翻页、连续输入及同步/索引期间交互分别采样,同时覆盖小工作区、低命中率查询、加密笔记本和桌面/浏览器/移动端路径。
+
+使用浏览器 Performance 面板采集长任务、样式/布局及内容可见时间;通过操作系统分别采集内核与渲染进程 RSS。Go 分析数据测量 Go 堆和 CPU,不包含全部 SQLite 或 Electron 原生内存。内核分析端点需要显式设置 `--enable-pprof` 并沿用管理员鉴权。分析器采样与低开销计时分开运行。记录器不会启用任何分析端点。
+
+不能从阶段耗时推断 SQL 改动行数、查询次数、缓存命中率或峰值 RSS;评估对应优化时应另行采集。微基准吞吐也不能证明 UI、加密数据恢复或并发行为正确。
+
+## 回归检查
+
+前端测试由 `app/scripts/test.mjs` 发现,Go 测试与基准由对应包命令发现。在 `app/` 下执行的定向检查:
+
+```text
+node --import tsx --test --test-concurrency=1 src/search/request.test.ts src/protyle/util/renderContent.test.ts src/protyle/util/performance.test.ts src/protyle/util/onGetPositioning.test.ts
+node --test scripts/performance.test.js
+pnpm run lint
+```
+
+测试启动器在并行浏览器测试前初始化 Electron。安装依赖后直接运行浏览器测试时,应先单独加载一次 `require("electron")` 完成安装,不能并发启动多个首次 Electron 安装。
+
+在 `kernel/` 下执行的定向检查:
+
+```text
+go test -tags fts5 ./model -run 'TestFullTextSearchRejectsCanceledRequest|TestSearchContextPreservesResultsCountsAndPagination' -count=1
+go test ./sql -run 'TestParameterizedSearchQueriesCancelAndReleaseConnection|TestSearchQueriesRejectCanceledContextBeforeReading|TestBlockQueriesBeyondVariableLimit' -count=1
+go test ./util -run Performance -count=1
+```
+
+取消测试覆盖全局及笔记本路由数据库中运行的 SQLite 工作和连接复用。使用独立内存库的夹具验证路由,不验证 SQLCipher 格式兼容性。渲染测试使用真实浏览器 DOM,覆盖插入范围、全量替换、选区节点身份、前插滚动补偿以及过期/已移除节点;组件渲染器以调用记录器替代。组件行为及真机输入法/触摸交互还需各自的回归检查。语义搜索继续保持串行调度,其内核取消另行实施。
diff --git a/docs/README.md b/docs/README.md
index b8fa0e95fb..6d37d6acd7 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -12,6 +12,7 @@
| Encrypted notebooks | [ENCRYPTED-NOTEBOOK.md](ENCRYPTED-NOTEBOOK.md) | [ENCRYPTED-NOTEBOOK.zh-CN.md](ENCRYPTED-NOTEBOOK.zh-CN.md) |
| Document titles and addressing (design draft) | [DOCUMENT-ADDRESSING.md](DOCUMENT-ADDRESSING.md) | [DOCUMENT-ADDRESSING.zh-CN.md](DOCUMENT-ADDRESSING.zh-CN.md) |
| Pinned documents | [PINNED-DOCUMENTS.md](PINNED-DOCUMENTS.md) | [PINNED-DOCUMENTS.zh-CN.md](PINNED-DOCUMENTS.zh-CN.md) |
+| Performance measurement | [PERFORMANCE.md](PERFORMANCE.md) | [PERFORMANCE.zh-CN.md](PERFORMANCE.zh-CN.md) |
| Tab blocks | [TAB-BLOCK.md](TAB-BLOCK.md) | [TAB-BLOCK.zh-CN.md](TAB-BLOCK.zh-CN.md) |
| Template manager | [TEMPLATE-MANAGER.md](TEMPLATE-MANAGER.md) | [TEMPLATE-MANAGER.zh-CN.md](TEMPLATE-MANAGER.zh-CN.md) |
| `.sy` file structure | [SY-FORMAT.md](SY-FORMAT.md) | [SY-FORMAT.zh-CN.md](SY-FORMAT.zh-CN.md) |
diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md
index 80f0925c01..a9bcb10a00 100644
--- a/docs/README.zh-CN.md
+++ b/docs/README.zh-CN.md
@@ -12,6 +12,7 @@
| 加密笔记本 | [ENCRYPTED-NOTEBOOK.md](ENCRYPTED-NOTEBOOK.md) | [ENCRYPTED-NOTEBOOK.zh-CN.md](ENCRYPTED-NOTEBOOK.zh-CN.md) |
| 文档标题与寻址(设计草案) | [DOCUMENT-ADDRESSING.md](DOCUMENT-ADDRESSING.md) | [DOCUMENT-ADDRESSING.zh-CN.md](DOCUMENT-ADDRESSING.zh-CN.md) |
| 文档树面板置顶区 | [PINNED-DOCUMENTS.md](PINNED-DOCUMENTS.md) | [PINNED-DOCUMENTS.zh-CN.md](PINNED-DOCUMENTS.zh-CN.md) |
+| 性能测量 | [PERFORMANCE.md](PERFORMANCE.md) | [PERFORMANCE.zh-CN.md](PERFORMANCE.zh-CN.md) |
| 页签块 | [TAB-BLOCK.md](TAB-BLOCK.md) | [TAB-BLOCK.zh-CN.md](TAB-BLOCK.zh-CN.md) |
| 模板管理 | [TEMPLATE-MANAGER.md](TEMPLATE-MANAGER.md) | [TEMPLATE-MANAGER.zh-CN.md](TEMPLATE-MANAGER.zh-CN.md) |
| `.sy` 文件结构 | [SY-FORMAT.md](SY-FORMAT.md) | [SY-FORMAT.zh-CN.md](SY-FORMAT.zh-CN.md) |
diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.go
index 0181456114..d5ba4c2f35 100644
--- a/kernel/filesys/tree.go
+++ b/kernel/filesys/tree.go
@@ -487,11 +487,15 @@ func TreeSize(tree *parse.Tree) (size uint64) {
}
func WriteTree(tree *parse.Tree) (size uint64, err error) {
+ timing := util.BeginPerformance("document.save")
+ defer timing.Finish()
data, filePath, err := prepareWriteTree(tree)
if err != nil {
return
}
+ timing.Count("bytes", int64(len(data)))
+ timing.Stage("encrypt")
dek, encrypted, releaseCryptoLease, leaseErr := acquireCryptoLease(tree.Box)
if leaseErr != nil {
err = leaseErr
@@ -507,6 +511,7 @@ func WriteTree(tree *parse.Tree) (size uint64, err error) {
}
// 缓存与待写入数据一致时跳过落盘;缓存未命中时再读盘比对,避免无变更的重复写入
+ timing.Stage("compare")
if cachedData, ok := cache.GetTreeDataInBox(tree.ID, tree.Box); ok {
if len(cachedData) == len(data) && bytes.Equal(cachedData, data) {
return
@@ -522,6 +527,7 @@ func WriteTree(tree *parse.Tree) (size uint64, err error) {
}
}
+ timing.Stage("write")
if encrypted {
// 加密密文必须通过临时文件原子替换,避免 mmap 先截断目标后崩溃导致认证密文永久损坏。
if err = writeTreeByWriteFile(filePath, encData); nil != err {
@@ -538,6 +544,8 @@ func WriteTree(tree *parse.Tree) (size uint64, err error) {
util.PushErrMsg(msg, 7000)
}
+ timing.Stage("notify")
+ timing.Count("written_bytes", int64(len(data)))
cache.SetTreeDataInBox(tree.ID, tree.Box, data)
afterWriteTree(tree)
size = uint64(len(data))
diff --git a/kernel/filesys/tree_benchmark_test.go b/kernel/filesys/tree_benchmark_test.go
new file mode 100644
index 0000000000..687aa69a60
--- /dev/null
+++ b/kernel/filesys/tree_benchmark_test.go
@@ -0,0 +1,52 @@
+package filesys
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func BenchmarkDocumentJSON(b *testing.B) {
+ previousDataDir := util.DataDir
+ util.DataDir = b.TempDir()
+ b.Cleanup(func() { util.DataDir = previousDataDir })
+ for _, size := range []int{1000, 5000, 20000} {
+ tree := treenode.NewTree("20261019000000-box0001", "/20261019000000-doc0001.sy", "/Baseline", "Baseline")
+ for tree.Root.FirstChild != nil {
+ tree.Root.FirstChild.Unlink()
+ }
+ for i := range size {
+ paragraph := treenode.NewParagraph(fmt.Sprintf("20261019000000-%07d", i))
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(strings.Repeat("baseline text ", 8))})
+ tree.Root.AppendChild(paragraph)
+ }
+ data, _, err := prepareWriteTree(tree)
+ if err != nil {
+ b.Fatal(err)
+ }
+ b.Run(fmt.Sprintf("serialize/%d", size), func(b *testing.B) {
+ b.ReportAllocs()
+ b.SetBytes(int64(len(data)))
+ for i := 0; i < b.N; i++ {
+ if _, _, err := prepareWriteTree(tree); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+ b.Run(fmt.Sprintf("parse/%d", size), func(b *testing.B) {
+ luteEngine := util.NewLute()
+ b.ReportAllocs()
+ b.SetBytes(int64(len(data)))
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ if _, err := parseJSON2Tree(tree.Box, tree.Path, data, luteEngine); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+ }
+}
diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.go
index 430c2c1156..ba89a51fbc 100644
--- a/kernel/model/attribute_view_render.go
+++ b/kernel/model/attribute_view_render.go
@@ -429,6 +429,8 @@ type AttributeViewRenderOptions struct {
// RenderAttributeViewWithTargetOptions 在分页前应用临时排序;临时排序和只读请求均不创建或保存数据库。
func RenderAttributeViewWithTargetOptions(blockID, avID, viewID, query string, page, pageSize int, groupPaging map[string]any, initialLayout av.LayoutType, createIfNotExist, ignoreRows bool, targetItemID, targetGroupID string, options AttributeViewRenderOptions) (viewable av.Viewable, attrView *av.AttributeView, target *AttributeViewRenderTarget, err error) {
+ timing := util.BeginPerformance("database.view")
+ defer timing.Finish()
writable := !options.ReadOnly && options.TemporarySort == nil
createIfNotExist = createIfNotExist && writable
if !ast.IsNodeIDPattern(avID) {
@@ -439,7 +441,9 @@ func RenderAttributeViewWithTargetOptions(blockID, avID, viewID, query string, p
return
}
+ timing.Stage("wait_sync")
waitForSyncingStorages()
+ timing.Stage("load")
avBoxID, exactBox, resolveErr := resolveAttributeViewCarrierBoxID(blockID)
if nil != resolveErr {
@@ -493,6 +497,7 @@ func RenderAttributeViewWithTargetOptions(blockID, avID, viewID, query string, p
}
}
+ timing.Stage("render")
viewable, err = renderAttributeView(attrView, blockID, viewID, "", query, page, pageSize, groupPaging, ignoreRows, writable, target, targetGroupID, options.CalendarRange)
return
}
@@ -521,6 +526,8 @@ const (
)
func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierViewID, query string, page, pageSize int, groupPaging map[string]any, ignoreRows, writable bool, target *AttributeViewRenderTarget, targetGroupID string, calendarRanges ...*av.CalendarRange) (viewable av.Viewable, err error) {
+ timing := util.BeginPerformance("database.fields")
+ defer timing.Finish()
if err = attrView.ValidateLayouts(); nil != err {
return
}
@@ -553,6 +560,7 @@ func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierView
renderContext.ReadOnly = !writable
defer renderContext.PushTemplateErrors()
deferTemplateValues := shouldDeferAttributeViewTemplateValues(attrView, view, query, ignoreRows)
+ timing.Stage("fields")
if deferTemplateValues {
viewable = sql.RenderViewWithDeferredTemplatesContext(attrView, view, query, ignoreRows, renderContext)
} else {
@@ -562,6 +570,7 @@ func renderAttributeView(attrView *av.AttributeView, nodeID, viewID, carrierView
calendar.CalendarRange = calendarRanges[0]
}
var groupRenderSource *sql.GroupViewRenderSource
+ timing.Stage("rows_groups")
if !ignoreRows && view.IsGroupView() {
// 在父视图分页前保存完整条目索引,各分组复用已经生成的字段值。
groupRenderSource = sql.NewGroupViewRenderSource(viewable, query)
@@ -1068,6 +1077,9 @@ func attrViewFiltersUseRenderedValues(filters []*av.ViewFilter, renderTemplateKe
func renderViewableInstance(viewable av.Viewable, view *av.View, attrView *av.AttributeView, page, pageSize int,
ignoreRows bool, targetItemID string,
renderContext *sql.AttributeViewRenderContext, filterContexts ...*av.FilterContext) (targetIndex, targetOffset int, err error) {
+ timing := util.BeginPerformance("database.rows")
+ defer timing.Finish()
+ timing.Count("page_size", int64(pageSize))
targetIndex = -1
if nil == viewable {
err = av.ErrViewNotFound
@@ -1079,6 +1091,11 @@ func renderViewableInstance(viewable av.Viewable, view *av.View, attrView *av.At
if ignoreRows {
return
}
+ if timing != nil {
+ if collection, ok := viewable.(av.Collection); ok {
+ timing.Count("rows_before", int64(collection.CountItems()))
+ }
+ }
cachedAttrViews := map[string]*av.AttributeView{}
rollupFurtherCollections := sql.GetFurtherCollectionsWithContext(attrView, cachedAttrViews, renderContext)
@@ -1086,9 +1103,18 @@ func renderViewableInstance(viewable av.Viewable, view *av.View, attrView *av.At
if 0 < len(filterContexts) {
filterContext = filterContexts[0]
}
+ timing.Stage("filter")
av.FilterWithContext(viewable, attrView, rollupFurtherCollections, cachedAttrViews, filterContext)
+ if timing != nil {
+ if collection, ok := viewable.(av.Collection); ok {
+ timing.Count("rows_filtered", int64(collection.CountItems()))
+ }
+ }
+ timing.Stage("sort")
av.Sort(viewable, attrView)
+ timing.Stage("calculate")
av.Calc(viewable, attrView)
+ timing.Stage("paginate")
// 日历按可见范围读取,不使用普通条目分页。
switch viewable.GetType() {
@@ -1138,6 +1164,12 @@ func renderViewableInstance(viewable av.Viewable, view *av.View, attrView *av.At
}
kanban.Cards = kanban.Cards[start:end]
}
+ timing.Stage("colors")
+ if timing != nil {
+ if collection, ok := viewable.(av.Collection); ok {
+ timing.Count("rows_page", int64(collection.CountItems()))
+ }
+ }
av.RenderConditionalColors(viewable, view, attrView, rollupFurtherCollections, cachedAttrViews)
return
}
diff --git a/kernel/model/attribute_view_render_benchmark_test.go b/kernel/model/attribute_view_render_benchmark_test.go
new file mode 100644
index 0000000000..7b30394863
--- /dev/null
+++ b/kernel/model/attribute_view_render_benchmark_test.go
@@ -0,0 +1,48 @@
+package model
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+)
+
+func BenchmarkDatabaseDisplayPage(b *testing.B) {
+ for _, size := range []int{1000, 10000, 50000} {
+ b.Run(fmt.Sprint(size), func(b *testing.B) {
+ attrView, view := newDeferredTemplateTestAttributeView()
+ view.PageSize = 50
+ view.ItemIDs = nil
+ for _, keyValues := range attrView.KeyValues {
+ keyValues.Values = nil
+ }
+ for i := range size {
+ id := fmt.Sprintf("20261019000000-%07d", i)
+ view.ItemIDs = append(view.ItemIDs, id)
+ attrView.KeyValues[0].Values = append(attrView.KeyValues[0].Values, &av.Value{
+ ID: id + "-block", KeyID: "block", BlockID: id, Type: av.KeyTypeBlock, IsDetached: true,
+ Block: &av.ValueBlock{Content: "Baseline"},
+ })
+ attrView.KeyValues[1].Values = append(attrView.KeyValues[1].Values, &av.Value{
+ ID: id + "-text", KeyID: "text", BlockID: id, Type: av.KeyTypeText,
+ Text: &av.ValueText{Content: "Baseline"},
+ })
+ }
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ renderContext := sql.NewAttributeViewRenderContext()
+ viewable := sql.RenderViewWithDeferredTemplatesContext(attrView, view, "", false, renderContext)
+ if _, _, err := renderViewableInstance(viewable, view, attrView, 1, 50, false, "", renderContext); err != nil {
+ b.Fatal(err)
+ }
+ sql.FillAttributeViewTemplateValuesWithContext(attrView, view, viewable.(*av.Table), renderContext)
+ if rows := viewable.(*av.Table).Rows; len(rows) != 50 || rows[0].GetValue("template").Template.Content != "Baseline" {
+ b.Fatal("unexpected database page or template value")
+ }
+ }
+ b.ReportMetric(float64(size), "rows/op")
+ })
+ }
+}
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 47e7892910..d0e86a2e1a 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -650,6 +650,11 @@ func GetDoc(startID, endID, id string, index int, query string, queryTypes, quer
// 加密笔记本打开文档时传入 boxID,blocktree/content 查询走加密 db;boxID 为空时 fall-through 全局 db。
func GetDocInBox(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight, includeDocInfo bool, boxID string) (
blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxIDOut, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, docInfo *BlockInfo, err error) {
+ timing := util.BeginPerformance("document.load")
+ defer func() {
+ timing.Count("blocks", int64(blockCount))
+ timing.Finish()
+ }()
confEditorSnapshot := Conf.LoadEditor()
//os.MkdirAll("pprof", 0755)
@@ -657,7 +662,9 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,
//pprof.StartCPUProfile(cpuProfile)
//defer pprof.StopCPUProfile()
+ timing.Stage("wait_transactions")
FlushTxQueue() // 写入数据时阻塞,避免获取到的数据不一致
+ timing.Stage("load_tree")
inputIndex := index
tree, err := loadTreeByBlockIDInBox0(id, boxID, false)
@@ -677,6 +684,7 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,
docInfo = getDocInfoByTree(tree.Root.ID, tree)
}
+ timing.Stage("locate")
luteEngine := NewLute()
node := treenode.GetNodeInTree(tree, id)
if nil == node {
@@ -965,6 +973,7 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,
}
luteEngine.RenderOptions.NodeIndexStart = index
+ timing.Stage("render")
dom = luteEngine.Tree2BlockDOM(subTree, luteEngine.RenderOptions, luteEngine.ParseOptions)
if 1 > len(keywords) {
diff --git a/kernel/model/search.go b/kernel/model/search.go
index 53aa4a4ce1..99f02e34b8 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -1671,10 +1671,28 @@ type BlockSearchOptions struct {
// Method:0 为关键字,1 为查询语法,2 为 SQL,3 为正则表达式;GroupBy:0 不分组,1 按文档分组。
// OrderBy:0 按块类型,1/2 按创建时间升/降序,3/4 按更新时间升/降序,5 按文档内内容顺序,6/7 按相关度升/降序。
func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {
+ timing := util.BeginPerformance("search")
+ timing.Count("method", int64(options.Method))
+ defer func() {
+ timing.Count("results", int64(len(ret)))
+ timing.Count("matches", int64(matchedBlockCount))
+ timing.Finish()
+ }()
ctx := options.Context
if ctx == nil {
ctx = context.Background()
}
+ defer func() {
+ if ctx.Err() != nil {
+ timing.Count("canceled", 1)
+ ret = []*Block{}
+ matchedBlockCount, matchedRootCount, pageCount = 0, 0, 0
+ docMode = false
+ }
+ }()
+ if ctx.Err() != nil {
+ return
+ }
query := options.Query
boxes := options.Boxes
paths := options.Paths
@@ -1716,6 +1734,7 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
beforeLen := 36
var blocks []*Block
orderByClause := buildOrderBy(query, method, orderBy)
+ timing.Stage("query")
switch method {
case 1: // 查询语法
typeFilter := buildTypeFilter(types, subTypes)
@@ -1726,9 +1745,9 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
boxArgs = append(boxArgs, excludeArgs...)
pathFilter, pathArgs := buildPathsFilter(paths)
if ast.IsNodeIDPattern(query) {
- blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'"+excludeInline, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = searchBySQLInBoxContext(ctx, "SELECT * FROM `blocks` WHERE `id` = '"+query+"'"+excludeInline, beforeLen, page, pageSize, boxID)
} else {
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
}
case 2: // SQL
blocks, matchedBlockCount, matchedRootCount = searchBySQLInBoxContext(ctx, query, beforeLen, page, pageSize, boxID)
@@ -1743,7 +1762,7 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
boxArgs = append(boxArgs, boxDocArgs...)
boxArgs = append(boxArgs, excludeArgs...)
pathFilter, pathArgs := buildPathsFilter(paths)
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByRegexpInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByRegexpInBox(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
default: // 关键字
typeFilter := buildTypeFilter(types, subTypes)
boxFilter, boxArgs := buildBoxesFilter(boxes)
@@ -1753,24 +1772,28 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
boxArgs = append(boxArgs, excludeArgs...)
pathFilter, pathArgs := buildPathsFilter(paths)
if ast.IsNodeIDPattern(query) {
- blocks, matchedBlockCount, matchedRootCount = searchBySQLInBox("SELECT * FROM `blocks` WHERE `id` = '"+query+"'"+excludeInline, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = searchBySQLInBoxContext(ctx, "SELECT * FROM `blocks` WHERE `id` = '"+query+"'"+excludeInline, beforeLen, page, pageSize, boxID)
} else {
if 2 > len(strings.Split(strings.TrimSpace(query), " ")) {
ftsQuery, hPathQuery := buildKeywordSearchQueries(query)
if "" != hPathQuery && searchHPath && isDocumentSearchEnabled(types) {
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSAndHPathInBox(hPathQuery, ftsQuery, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSAndHPathInBox(ctx, hPathQuery, ftsQuery, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, boxID)
} else {
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(ftsQuery, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByFTSInBox(ctx, ftsQuery, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize, boxID)
}
} else {
docMode = true // 文档全文搜索模式 https://github.com/siyuan-note/siyuan/issues/10584
- blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, boxID, searchHPath)
+ blocks, matchedBlockCount, matchedRootCount = fullTextSearchByLikeWithRootInBox(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, orderBy, beforeLen, page, pageSize, boxID, searchHPath)
}
}
}
+ if ctx.Err() != nil {
+ return
+ }
pageCount = (matchedBlockCount + pageSize - 1) / pageSize
+ timing.Stage("format")
if 2 != method {
- compactAttributeViewSearchResults(blocks)
+ compactAttributeViewSearchResultsContext(ctx, blocks)
}
switch groupBy {
@@ -1782,11 +1805,17 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
contentSorts := map[string]int{}
var btsID []string
for _, b := range blocks {
+ if ctx.Err() != nil {
+ return
+ }
btsID = append(btsID, b.RootID)
}
btsID = gulu.Str.RemoveDuplicatedElem(btsID)
bts := treenode.GetBlockTreesInBox(btsID, boxID)
for _, b := range blocks {
+ if ctx.Err() != nil {
+ return
+ }
if _, ok := rootMap[b.RootID]; !ok {
rootMap[b.RootID] = true
rootIDs = append(rootIDs, b.RootID)
@@ -1798,6 +1827,9 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
if 5 == orderBy { // 按内容顺序(仅在按文档分组时)
sortVal := 0
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if ctx.Err() != nil {
+ return ast.WalkStop
+ }
if !entering || !n.IsBlock() {
return ast.WalkContinue
}
@@ -1810,10 +1842,13 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
}
}
- sqlRoots := sql.GetBlocksInBox(rootIDs, boxID)
- roots := fromSQLBlocks(&sqlRoots, "", beforeLen)
+ sqlRoots := sql.GetBlocksInBoxContext(ctx, rootIDs, boxID)
+ roots := fromSQLBlocksContext(ctx, &sqlRoots, "", beforeLen)
for _, root := range roots {
for _, b := range blocks {
+ if ctx.Err() != nil {
+ return
+ }
if 5 == orderBy { // 按内容顺序(仅在按文档分组时)
b.Sort = contentSorts[b.ID]
}
@@ -1878,7 +1913,8 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlock
}
}
- refCount := sql.QueryRefCountInBox(nodeIDs, boxID)
+ timing.Stage("references")
+ refCount := sql.QueryRefCountInBoxContext(ctx, nodeIDs, boxID)
for _, b := range ret {
if 0 == groupBy {
b.RefCount = refCount[b.ID]
@@ -2262,7 +2298,7 @@ func searchBySQLInBoxContext(ctx context.Context, stmt string, beforeLen, page,
if err != nil {
return
}
- ret = fromSQLBlocks(&blocks, "", beforeLen)
+ ret = fromSQLBlocksContext(ctx, &blocks, "", beforeLen)
if 1 > len(ret) {
ret = []*Block{}
return
@@ -2453,7 +2489,9 @@ func extractID(content string) (ret string) {
return
}
-func fullTextSearchByRegexpInBox(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+func fullTextSearchByRegexpInBox(ctx context.Context, exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ timing := util.BeginPerformance("search.regexp")
+ defer timing.Finish()
confSearchSnapshot := Conf.LoadSearch()
fieldFilter := fieldRegexp(exp)
@@ -2467,22 +2505,25 @@ func fullTextSearchByRegexpInBox(exp, boxFilter, pathFilter string, boxArgs, pat
// box/path 过滤值通过绑定参数传递,避免 SQL 拼接注入
args := append(append([]any{}, boxArgs...), pathArgs...)
- blocks := sql.SelectBlocksRegexArgsInBox(stmt, regex, confSearchSnapshot.Name, confSearchSnapshot.Alias, confSearchSnapshot.Memo, confSearchSnapshot.IAL, page, pageSize, boxID, args...)
- ret = fromSQLBlocks(&blocks, "", beforeLen)
+ timing.Stage("query_highlight")
+ blocks, _ := sql.SelectBlocksRegexArgsInBoxContext(ctx, stmt, regex, confSearchSnapshot.Name, confSearchSnapshot.Alias, confSearchSnapshot.Memo, confSearchSnapshot.IAL, page, pageSize, boxID, args...)
+ timing.Stage("format")
+ ret = fromSQLBlocksContext(ctx, &blocks, "", beforeLen)
if 1 > len(ret) {
ret = []*Block{}
}
- matchedBlockCount, matchedRootCount = fullTextSearchCountByRegexpInBox(exp, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, boxID)
+ timing.Stage("count")
+ matchedBlockCount, matchedRootCount = fullTextSearchCountByRegexpInBox(ctx, exp, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, boxID)
return
}
-func fullTextSearchCountByRegexpInBox(exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, boxID string) (matchedBlockCount, matchedRootCount int) {
+func fullTextSearchCountByRegexpInBox(ctx context.Context, exp, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, boxID string) (matchedBlockCount, matchedRootCount int) {
fieldFilter := fieldRegexp(exp)
stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilter + ignoreFilter
stmt += boxFilter + pathFilter
args := append(append([]any{}, boxArgs...), pathArgs...)
- result, _ := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)
+ result, _ := sql.QueryNoLimitArgsInBoxContext(ctx, stmt, boxID, args...)
if 1 > len(result) {
return
}
@@ -2491,7 +2532,9 @@ func fullTextSearchCountByRegexpInBox(exp, boxFilter, pathFilter string, boxArgs
return
}
-func fullTextSearchByFTSInBox(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+func fullTextSearchByFTSInBox(ctx context.Context, query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ timing := util.BeginPerformance("search.fts")
+ defer timing.Finish()
table := "blocks_fts"
projections := "id, parent_id, root_id, hash, box, path, " +
// Search result content snippet returns more text https://github.com/siyuan-note/siyuan/issues/10707
@@ -2510,23 +2553,32 @@ func fullTextSearchByFTSInBox(query, boxFilter, pathFilter string, boxArgs, path
args := []any{columnFilter() + ":(" + query + ")"}
args = append(args, boxArgs...)
args = append(args, pathArgs...)
- blocks := sql.SelectBlocksRawStmtArgsInBox(stmt, args, pageSize, boxID)
- ret = fromSQLBlocks(&blocks, "", beforeLen)
+ timing.Stage("query")
+ blocks, _ := sql.SelectBlocksRawStmtArgsInBoxContext(ctx, stmt, args, pageSize, boxID)
+ timing.Stage("format")
+ ret = fromSQLBlocksContext(ctx, &blocks, "", beforeLen)
if 1 > len(ret) {
ret = []*Block{}
}
- matchedBlockCount, matchedRootCount = fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, boxID)
+ timing.Stage("count")
+ matchedBlockCount, matchedRootCount = fullTextSearchCountByFTSInBox(ctx, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter, boxID)
return
}
-func fullTextSearchByFTSAndHPathInBox(rawQuery, query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string, orderBy, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+func fullTextSearchByFTSAndHPathInBox(ctx context.Context, rawQuery, query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string, orderBy, beforeLen, page, pageSize int, boxID string) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ timing := util.BeginPerformance("search.path")
+ defer timing.Finish()
cte, args := buildFTSAndHPathMatchesCTE(rawQuery, query, boxFilter, pathFilter, boxArgs, pathArgs, typeFilter, ignoreFilter)
stmt := cte + " SELECT b.rowid AS block_rowid, matches.match_source FROM matches JOIN blocks b ON b.rowid = matches.block_rowid"
stmt += " " + buildHPathSearchOrderBy(rawQuery, orderBy)
stmt += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)
- result, err := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)
+ timing.Stage("query")
+ result, err := sql.QueryNoLimitArgsInBoxContext(ctx, stmt, boxID, args...)
if err != nil {
+ if ctx.Err() != nil {
+ return
+ }
logging.LogErrorf("query blocks by FTS and hpath failed: %s", err)
ret = []*Block{}
return
@@ -2539,8 +2591,12 @@ func fullTextSearchByFTSAndHPathInBox(rawQuery, query, boxFilter, pathFilter str
source: int(row["match_source"].(int64)),
})
}
- ret, err = loadFTSAndHPathMatchBlocks(matches, rawQuery, query, beforeLen, boxID)
+ timing.Stage("format")
+ ret, err = loadFTSAndHPathMatchBlocks(ctx, matches, rawQuery, query, beforeLen, boxID)
if err != nil {
+ if ctx.Err() != nil {
+ return
+ }
logging.LogErrorf("load blocks by FTS and hpath failed: %s", err)
ret = []*Block{}
return
@@ -2551,8 +2607,12 @@ func fullTextSearchByFTSAndHPathInBox(rawQuery, query, boxFilter, pathFilter str
countStmt := cte + " SELECT COUNT(*) AS matches, COUNT(DISTINCT b.root_id) AS docs" +
" FROM matches JOIN blocks b ON b.rowid = matches.block_rowid"
- countResult, err := sql.QueryNoLimitArgsInBox(countStmt, boxID, args...)
+ timing.Stage("count")
+ countResult, err := sql.QueryNoLimitArgsInBoxContext(ctx, countStmt, boxID, args...)
if err != nil {
+ if ctx.Err() != nil {
+ return
+ }
logging.LogErrorf("count blocks by FTS and hpath failed: %s", err)
return
}
@@ -2568,9 +2628,12 @@ type ftsAndHPathMatch struct {
source int
}
-func loadFTSAndHPathMatchBlocks(matches []ftsAndHPathMatch, rawQuery, query string, beforeLen int, boxID string) (ret []*Block, err error) {
+func loadFTSAndHPathMatchBlocks(ctx context.Context, matches []ftsAndHPathMatch, rawQuery, query string, beforeLen int, boxID string) (ret []*Block, err error) {
var ftsRowIDs, hPathRowIDs []int64
for _, match := range matches {
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
if 0 == match.source {
ftsRowIDs = append(ftsRowIDs, match.rowID)
} else {
@@ -2578,16 +2641,19 @@ func loadFTSAndHPathMatchBlocks(matches []ftsAndHPathMatch, rawQuery, query stri
}
}
- ftsBlocks, err := queryFTSSnippetBlocksByRowID(query, ftsRowIDs, boxID)
+ ftsBlocks, err := queryFTSSnippetBlocksByRowID(ctx, query, ftsRowIDs, boxID)
if err != nil {
return nil, err
}
- hPathBlocks, err := queryRawBlocksByRowID(hPathRowIDs, boxID)
+ hPathBlocks, err := queryRawBlocksByRowID(ctx, hPathRowIDs, boxID)
if err != nil {
return nil, err
}
for _, match := range matches {
sqlBlock := ftsBlocks[match.rowID]
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
if 0 != match.source {
sqlBlock = hPathBlocks[match.rowID]
}
@@ -2606,14 +2672,14 @@ func fromFTSAndHPathMatchSQLBlock(sqlBlock *sql.Block, source int, rawQuery stri
return fromHPathSearchSQLBlock(sqlBlock, rawQuery, beforeLen)
}
-func queryFTSSnippetBlocksByRowID(query string, rowIDs []int64, boxID string) (ret map[int64]*sql.Block, err error) {
+func queryFTSSnippetBlocksByRowID(ctx context.Context, query string, rowIDs []int64, boxID string) (ret map[int64]*sql.Block, err error) {
ret = map[int64]*sql.Block{}
if 1 > len(rowIDs) {
return
}
stmt, args := buildFTSSnippetBlocksByRowIDQuery(query, rowIDs)
- result, err := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)
+ result, err := sql.QueryNoLimitArgsInBoxContext(ctx, stmt, boxID, args...)
if err != nil {
return nil, err
}
@@ -2641,7 +2707,7 @@ func buildFTSSnippetBlocksByRowIDQuery(query string, rowIDs []int64) (stmt strin
return
}
-func queryRawBlocksByRowID(rowIDs []int64, boxID string) (ret map[int64]*sql.Block, err error) {
+func queryRawBlocksByRowID(ctx context.Context, rowIDs []int64, boxID string) (ret map[int64]*sql.Block, err error) {
ret = map[int64]*sql.Block{}
if 1 > len(rowIDs) {
return
@@ -2652,7 +2718,7 @@ func queryRawBlocksByRowID(rowIDs []int64, boxID string) (ret map[int64]*sql.Blo
for i, rowID := range rowIDs {
args[i] = rowID
}
- result, err := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)
+ result, err := sql.QueryNoLimitArgsInBoxContext(ctx, stmt, boxID, args...)
if err != nil {
return nil, err
}
@@ -2772,7 +2838,7 @@ func hPathOnlyOrderBy() string {
"CASE WHEN matches.match_source = 1 THEN b.hpath END ASC"
}
-func fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, boxID string) (matchedBlockCount, matchedRootCount int) {
+func fullTextSearchCountByFTSInBox(ctx context.Context, query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter, boxID string) (matchedBlockCount, matchedRootCount int) {
table := "blocks_fts"
stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `" + table + "` WHERE (`" + table + "` MATCH ?"
@@ -2782,7 +2848,7 @@ func fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter string, boxArgs,
args := []any{columnFilter() + ":(" + query + ")"}
args = append(args, boxArgs...)
args = append(args, pathArgs...)
- result, _ := sql.QueryNoLimitArgsInBox(stmt, boxID, args...)
+ result, _ := sql.QueryNoLimitArgsInBoxContext(ctx, stmt, boxID, args...)
if 1 > len(result) {
return
}
@@ -2791,7 +2857,9 @@ func fullTextSearchCountByFTSInBox(query, boxFilter, pathFilter string, boxArgs,
return
}
-func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string, orderBy, beforeLen, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+func fullTextSearchByLikeWithRootInBox(ctx context.Context, query, boxFilter, pathFilter string, boxArgs, pathArgs []any, typeFilter, ignoreFilter string, orderBy, beforeLen, page, pageSize int, boxID string, searchHPath bool) (ret []*Block, matchedBlockCount, matchedRootCount int) {
+ timing := util.BeginPerformance("search.document")
+ defer timing.Finish()
rawQuery := query
query = strings.ReplaceAll(query, "'", "''") // 不需要转义双引号,因为条件都是通过单引号包裹的,只需要转义单引号即可
keywords := strings.Split(query, " ")
@@ -2799,7 +2867,12 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxA
args := append(append([]any{}, boxArgs...), pathArgs...)
args = append(args, append(append([]any{}, boxArgs...), pathArgs...)...)
selectStmt := buildDocumentSearchStatement(rawQuery, keywords, typeFilter, boxFilter, pathFilter, ignoreFilter, orderBy, page, pageSize, searchHPath)
- result, _ := sql.QueryNoLimitArgsInBox(selectStmt, boxID, args...)
+ timing.Stage("query_count")
+ result, _ := sql.QueryNoLimitArgsInBoxContext(ctx, selectStmt, boxID, args...)
+ if ctx.Err() != nil {
+ return
+ }
+ timing.Stage("format")
resultBlocks := sql.ToBlocks(result)
if 0 < len(resultBlocks) {
matchedRootCount = int(result[0]["docs"].(int64))
@@ -2810,6 +2883,9 @@ func fullTextSearchByLikeWithRootInBox(query, boxFilter, pathFilter string, boxA
terms := strings.Join(keywords, search.TermSep)
terms = strings.ReplaceAll(terms, "''", "'")
for i, resultBlock := range resultBlocks {
+ if ctx.Err() != nil {
+ return nil, 0, 0
+ }
if 1 == result[i]["matchSource"].(int64) {
docContent, _ := result[i]["docContent"].(string)
contentTerms, hPathTerms := partitionSearchTerms(docContent, terms)
@@ -3090,7 +3166,14 @@ func partitionSearchTerms(text, terms string) (matched, unmatched string) {
}
func fromSQLBlocks(sqlBlocks *[]*sql.Block, terms string, beforeLen int) (ret []*Block) {
+ return fromSQLBlocksContext(context.Background(), sqlBlocks, terms, beforeLen)
+}
+
+func fromSQLBlocksContext(ctx context.Context, sqlBlocks *[]*sql.Block, terms string, beforeLen int) (ret []*Block) {
for _, sqlBlock := range *sqlBlocks {
+ if ctx.Err() != nil {
+ return nil
+ }
ret = append(ret, fromSQLBlock(sqlBlock, terms, beforeLen))
}
return
diff --git a/kernel/model/search_attribute_view.go b/kernel/model/search_attribute_view.go
index 89de39b7df..790c345332 100644
--- a/kernel/model/search_attribute_view.go
+++ b/kernel/model/search_attribute_view.go
@@ -1,6 +1,7 @@
package model
import (
+ "context"
"encoding/json"
"html"
"strings"
@@ -28,7 +29,14 @@ type attributeViewSearchPart struct {
// compactAttributeViewSearchResults 只精简已命中的数据库块,不改变索引、结果数量和排序。
func compactAttributeViewSearchResults(blocks []*Block) {
+ compactAttributeViewSearchResultsContext(context.Background(), blocks)
+}
+
+func compactAttributeViewSearchResultsContext(ctx context.Context, blocks []*Block) {
for _, block := range blocks {
+ if ctx.Err() != nil {
+ return
+ }
if "NodeAttributeView" != block.Type || !strings.Contains(block.Content, "<mark>") {
continue
}
@@ -48,11 +56,15 @@ func compactAttributeViewSearchResults(blocks []*Block) {
if nil != err || nil == attrView {
continue
}
- block.Content = compactAttributeViewSearchContent(attrView, block.Content)
+ block.Content = compactAttributeViewSearchContentContext(ctx, attrView, block.Content)
}
}
func compactAttributeViewSearchContent(attrView *av.AttributeView, fallback string) string {
+ return compactAttributeViewSearchContentContext(context.Background(), attrView, fallback)
+}
+
+func compactAttributeViewSearchContentContext(ctx context.Context, attrView *av.AttributeView, fallback string) string {
// 按索引内容的顺序记录字段边界,将现有高亮映射回原文,不重新匹配关键词。
var source strings.Builder
var parts []*attributeViewSearchPart
@@ -69,11 +81,17 @@ func compactAttributeViewSearchContent(attrView *av.AttributeView, fallback stri
appendPart(view.Name, nil, nil, true)
}
for _, keyValues := range attrView.KeyValues {
+ if ctx.Err() != nil {
+ return fallback
+ }
if nil == keyValues || nil == keyValues.Key {
return fallback
}
appendPart(keyValues.Key.Name, keyValues.Key, nil, false)
for _, value := range keyValues.Values {
+ if ctx.Err() != nil {
+ return fallback
+ }
if nil != value {
appendPart(value.String(true), keyValues.Key, value, false)
}
@@ -84,6 +102,9 @@ func compactAttributeViewSearchContent(attrView *av.AttributeView, fallback stri
return fallback
}
for _, match := range ranges {
+ if ctx.Err() != nil {
+ return fallback
+ }
found := false
for _, part := range parts {
if part.start <= match.start && match.end <= part.start+len(part.text) {
@@ -102,6 +123,9 @@ func compactAttributeViewSearchContent(attrView *av.AttributeView, fallback stri
}
rowTitles := map[string]string{}
for _, part := range parts {
+ if ctx.Err() != nil {
+ return fallback
+ }
if nil != part.value && av.KeyTypeBlock == part.key.Type {
rowTitles[part.value.BlockID] = part.text
}
diff --git a/kernel/model/search_cancellation_fts5_test.go b/kernel/model/search_cancellation_fts5_test.go
new file mode 100644
index 0000000000..4aa2d58d9b
--- /dev/null
+++ b/kernel/model/search_cancellation_fts5_test.go
@@ -0,0 +1,73 @@
+//go:build fts5
+
+package model
+
+import (
+ "context"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+func TestSearchContextPreservesResultsCountsAndPagination(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ Conf.Search.Store(conf.NewSearch())
+ for _, rootID := range []string{fixture.sourceID, fixture.targetID} {
+ tree, err := LoadTreeByBlockID(rootID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for tree.Root.FirstChild != nil {
+ tree.Root.FirstChild.Unlink()
+ }
+ for _, content := range []string{"alpha content", "beta content"} {
+ paragraph := treenode.NewParagraph("")
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(content)})
+ tree.Root.AppendChild(paragraph)
+ }
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ }
+ sql.FlushQueue()
+ for _, test := range []struct {
+ name, query string
+ method int
+ }{
+ {"keyword", "alpha", 0}, {"syntax", "alpha", 1}, {"regexp", "a[a-z]+a", 3},
+ {"document", "alpha beta", 0},
+ {"sql", "SELECT * FROM blocks WHERE content LIKE '%alpha%' ORDER BY id", 2},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ for _, group := range []int{0, 1} {
+ for _, page := range []int{1, 2} {
+ options := BlockSearchOptions{Query: test.query, Method: test.method, GroupBy: group,
+ Page: page, PageSize: 1, Types: map[string]bool{"document": true, "paragraph": true}}
+ want, matched, roots, pages, docMode := FullTextSearchBlock(options)
+ ctx, cancel := context.WithCancel(context.Background())
+ options.Context = ctx
+ got, gotMatched, gotRoots, gotPages, gotDocMode := FullTextSearchBlock(options)
+ cancel()
+ if !reflect.DeepEqual(got, want) || matched != gotMatched || roots != gotRoots || pages != gotPages || docMode != gotDocMode {
+ t.Fatalf("context changed results for group=%d page=%d", group, page)
+ }
+ if len(got) == 0 || matched != 2 || roots != 2 || (test.method != 2 && pages != 2) {
+ t.Fatalf("unexpected search result: blocks=%d matched=%d roots=%d pages=%d", len(got), matched, roots, pages)
+ }
+ if group == 0 && test.method != 2 && test.name != "document" && !strings.Contains(got[0].Content, "<mark>") {
+ t.Fatalf("missing result highlight: %s", got[0].Content)
+ }
+ }
+ }
+ })
+ }
+}
diff --git a/kernel/model/search_document_test.go b/kernel/model/search_document_test.go
index 3375e3edad..30f3e27663 100644
--- a/kernel/model/search_document_test.go
+++ b/kernel/model/search_document_test.go
@@ -22,7 +22,7 @@ func TestDocumentTypeFilterFromSettings(t *testing.T) {
}
}
-func documentSearchRows(t *testing.T, database *gosql.DB, statement string, args []any) [][]any {
+func documentSearchRows(t testing.TB, database *gosql.DB, statement string, args []any) [][]any {
t.Helper()
rows, err := database.Query(statement, args...)
if err != nil {
@@ -56,6 +56,57 @@ func documentSearchRows(t *testing.T, database *gosql.DB, statement string, args
return result
}
+// BenchmarkDocumentSearch 固定每篇 100 块、跨块双词命中和 50 篇分页,测量热内存库查询及精确计数。
+func BenchmarkDocumentSearch(b *testing.B) {
+ setSearchCaseSensitive(b, false)
+ for _, size := range []int{10000, 100000, 1000000} {
+ b.Run(fmt.Sprint(size), func(b *testing.B) {
+ database := newSearchHPathTestDB(b)
+ if _, err := database.Exec("CREATE INDEX idx_blocks_root_id ON blocks(root_id)"); err != nil {
+ b.Fatal(err)
+ }
+ tx, err := database.Begin()
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer tx.Rollback()
+ insert, err := tx.Prepare("INSERT INTO blocks VALUES (?, '', ?, '', '20261019000000-box0001', ?, '', '', '', '', '', ?, '', '', 32, ?, '', '', 0, '20261019000000', '20261019000000')")
+ if err != nil {
+ b.Fatal(err)
+ }
+ defer insert.Close()
+ for i := range size {
+ rootID := fmt.Sprintf("20261019000000-%07d", (i/100)*100)
+ content, typ := "common text repeated for baseline", "p"
+ switch i % 100 {
+ case 0:
+ typ = "d"
+ case 1:
+ content = "alpha content across blocks"
+ case 2:
+ content = "beta content across blocks"
+ }
+ if _, err = insert.Exec(fmt.Sprintf("20261019000000-%07d", i), rootID, "/"+rootID+".sy", content, typ); err != nil {
+ b.Fatal(err)
+ }
+ }
+ if err = tx.Commit(); err != nil {
+ b.Fatal(err)
+ }
+ statement := buildDocumentSearchStatement("alpha beta", []string{"alpha", "beta"}, "(type IN ('d','p'))", "", "", "", 0, 1, 50, false)
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ rows := documentSearchRows(b, database, statement, nil)
+ if len(rows) != 50 {
+ b.Fatalf("expected 50 documents matching keywords across blocks, got %d", len(rows))
+ }
+ }
+ b.ReportMetric(float64(size), "blocks/op")
+ })
+ }
+}
+
func TestDocumentSearchPartialIndexResults(t *testing.T) {
for _, sensitive := range []bool{false, true} {
t.Run(fmt.Sprintf("case=%t", sensitive), func(t *testing.T) {
diff --git a/kernel/model/search_test.go b/kernel/model/search_test.go
index 604dc43340..b728baf333 100644
--- a/kernel/model/search_test.go
+++ b/kernel/model/search_test.go
@@ -17,6 +17,7 @@
package model
import (
+ "context"
gosql "database/sql"
"regexp"
"slices"
@@ -30,6 +31,23 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+func TestFullTextSearchRejectsCanceledRequest(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ for _, method := range []int{0, 1, 2, 3} {
+ blocks, matched, roots, pages, docMode := FullTextSearchBlock(BlockSearchOptions{
+ Context: ctx, Query: "alpha beta", Method: method, GroupBy: 1, Page: 1, PageSize: 1,
+ })
+ if len(blocks) != 0 || matched != 0 || roots != 0 || pages != 0 || docMode {
+ t.Fatalf("method %d returned a canceled result: %v %d %d %d %t", method, blocks, matched, roots, pages, docMode)
+ }
+ }
+ blocks := []*sql.Block{{ID: "must-not-format"}}
+ if got := fromSQLBlocksContext(ctx, &blocks, "alpha", 36); len(got) != 0 {
+ t.Fatalf("canceled result formatting returned %v", got)
+ }
+}
+
func TestFromSQLBlockMapsTimestamps(t *testing.T) {
previousConf := Conf
Conf = NewAppConf()
@@ -850,7 +868,7 @@ func TestDocumentSearchFieldMatchesMultipleHPathLevels(t *testing.T) {
}
}
-func newSearchHPathTestDB(t *testing.T) *gosql.DB {
+func newSearchHPathTestDB(t testing.TB) *gosql.DB {
t.Helper()
testDB, err := gosql.Open("sqlite3_extended", ":memory:")
if err != nil {
@@ -875,7 +893,7 @@ func insertSearchHPathTestBlock(t *testing.T, testDB *gosql.DB, id, rootID, hPat
}
}
-func setSearchCaseSensitive(t *testing.T, caseSensitive bool) {
+func setSearchCaseSensitive(t testing.TB, caseSensitive bool) {
t.Helper()
previousConf := Conf
Conf = NewAppConf()
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index 15bcbc590c..e026cae077 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -275,6 +275,9 @@ func performTx(tx *Transaction) (ret *TxErr) {
if 1 > len(tx.DoOperations) {
return
}
+ timing := util.BeginPerformance("transaction")
+ timing.Count("operations", int64(len(tx.DoOperations)))
+ defer timing.Finish()
diagnostic := util.WatchOperation("editing transaction", "begin transaction")
defer diagnostic.Finish()
@@ -307,11 +310,13 @@ func performTx(tx *Transaction) (ret *TxErr) {
}()
diagnostic.Stage("prepare database automations")
+ timing.Stage("automations")
if err = tx.prepareAttributeViewAutomations(); err != nil {
tx.rollback()
return &TxErr{code: TxErrHandleAttributeView, msg: err.Error()}
}
diagnostic.Stage("process bulk operations")
+ timing.Stage("apply")
isLargeInsert, ret := tx.processLargeInsert()
if ret != nil {
tx.rollback()
@@ -562,6 +567,7 @@ func performTx(tx *Transaction) (ret *TxErr) {
}
diagnostic.Stage("finalize database bindings and block structure")
+ timing.Stage("finalize")
if err = tx.runAttributeViewAutomations(); err != nil {
tx.rollback()
return &TxErr{code: TxErrHandleAttributeView, msg: err.Error()}
@@ -581,6 +587,7 @@ func performTx(tx *Transaction) (ret *TxErr) {
tx.UndoOperations = append(tx.UndoOperations, tx.attributeViewDeletionUndo...)
diagnostic.Stage("commit transaction")
+ timing.Stage("commit")
if cr := tx.commit(); nil != cr {
logging.LogErrorf("commit tx failed: %s", cr)
if 1 == tx.state.Load() {
diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.go
index 826e291749..98916d6a16 100644
--- a/kernel/sql/block_query.go
+++ b/kernel/sql/block_query.go
@@ -1047,19 +1047,30 @@ func GetBlocks(ids []string) (ret []*Block) {
// queryBlocksInBatches 限制每批参数数量,并在读取下一批前关闭游标,保留笔记本查询边界。
func queryBlocksInBatches(ids []string, boxID string, blocks map[string]*Block, populateCache bool) error {
+ return queryBlocksInBatchesContext(context.Background(), ids, boxID, blocks, populateCache)
+}
+
+func queryBlocksInBatchesContext(ctx context.Context, ids []string, boxID string, blocks map[string]*Block, populateCache bool) error {
const batchSize = 512
for start := 0; start < len(ids); start += batchSize {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
batch := ids[start:min(start+batchSize, len(ids))]
statement := "SELECT * FROM blocks WHERE id IN (" + strings.Repeat("?,", len(batch)-1) + "?)"
args := make([]any, len(batch))
for i, id := range batch {
args[i] = id
}
- rows, err := queryForBox(boxID, statement, args...)
+ rows, err := queryForBoxContext(ctx, boxID, statement, args...)
if err != nil {
return err
}
for rows.Next() {
+ if err = ctx.Err(); err != nil {
+ rows.Close()
+ return err
+ }
if block := scanBlockRows(rows); block != nil {
if populateCache {
putBlockCache(block)
diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.go
index 9088ce9537..c614b5abfb 100644
--- a/kernel/sql/encrypted_query.go
+++ b/kernel/sql/encrypted_query.go
@@ -91,13 +91,21 @@ func GetBlockInBox(id, boxID string) (ret *Block) {
// GetBlocksInBox 按 ids 在指定 box 的 db 里批量查 block。
func GetBlocksInBox(ids []string, boxID string) (ret []*Block) {
- if 1 > len(ids) {
+ return GetBlocksInBoxContext(context.Background(), ids, boxID)
+}
+
+// GetBlocksInBoxContext 保留缓存、分批查询和输入顺序,并在请求取消后停止读取。
+func GetBlocksInBoxContext(ctx context.Context, ids []string, boxID string) (ret []*Block) {
+ if 1 > len(ids) || ctx.Err() != nil {
return
}
var notHitIDs []string
cached := map[string]*Block{}
for _, id := range ids {
+ if ctx.Err() != nil {
+ return nil
+ }
if block := getBlockCacheInBox(id, boxID); nil != block {
cached[id] = block
} else {
@@ -112,8 +120,10 @@ func GetBlocksInBox(ids []string, boxID string) (ret []*Block) {
return
}
- if err := queryBlocksInBatches(notHitIDs, boxID, cached, false); err != nil {
- logging.LogErrorf("query blocks in box [%s] failed: %s", boxID, err)
+ if err := queryBlocksInBatchesContext(ctx, notHitIDs, boxID, cached, false); err != nil {
+ if ctx.Err() == nil {
+ logging.LogErrorf("query blocks in box [%s] failed: %s", boxID, err)
+ }
return
}
for _, id := range ids {
@@ -340,18 +350,28 @@ func SelectBlocksRawStmtBoundedInBoxContext(ctx context.Context, stmt string, li
// QueryRefCountInBox 按 defBlockIDs 在指定 box 的 db 里查引用计数。
func QueryRefCountInBox(defIDs []string, boxID string) (ret map[string]int) {
+ return QueryRefCountInBoxContext(context.Background(), defIDs, boxID)
+}
+
+// QueryRefCountInBoxContext 在搜索取消后停止引用计数,沿用原有的笔记本隔离。
+func QueryRefCountInBoxContext(ctx context.Context, defIDs []string, boxID string) (ret map[string]int) {
ret = map[string]int{}
- if 1 > len(defIDs) {
+ if 1 > len(defIDs) || ctx.Err() != nil {
return
}
ids := "('" + strings.Join(defIDs, "','") + "')"
- rows, err := queryForBox(boxID, "SELECT def_block_id, COUNT(*) AS ref_cnt FROM refs WHERE def_block_id IN "+ids+" GROUP BY def_block_id")
+ rows, err := queryForBoxContext(ctx, boxID, "SELECT def_block_id, COUNT(*) AS ref_cnt FROM refs WHERE def_block_id IN "+ids+" GROUP BY def_block_id")
if err != nil {
- logging.LogErrorf("sql query failed: %s", err)
+ if ctx.Err() == nil {
+ logging.LogErrorf("sql query failed: %s", err)
+ }
return
}
defer rows.Close()
for rows.Next() {
+ if ctx.Err() != nil {
+ return map[string]int{}
+ }
var id string
var cnt int
if err = rows.Scan(&id, &cnt); err != nil {
@@ -360,6 +380,9 @@ func QueryRefCountInBox(defIDs []string, boxID string) (ret map[string]int) {
}
ret[id] = cnt
}
+ if rows.Err() != nil || ctx.Err() != nil {
+ return map[string]int{}
+ }
return
}
@@ -377,16 +400,30 @@ func QueryNoLimitArgsInBox(stmt, boxID string, args ...any) (ret []map[string]an
return queryRawStmtArgsForBox(boxID, stmt, args, math.MaxInt)
}
+// QueryNoLimitArgsInBoxContext 在请求取消时中断参数化查询,并保留笔记本数据库路由。
+func QueryNoLimitArgsInBoxContext(ctx context.Context, stmt, boxID string, args ...any) (ret []map[string]any, err error) {
+ return queryRawStmtArgsForBoxContext(ctx, boxID, stmt, args, math.MaxInt)
+}
+
// SelectBlocksRawStmtArgsInBox 在指定 box 的 db 里执行参数化原始 SQL 查询 blocks。
// 与 SelectBlocksRawStmtArgs 对应,绕开 sqlparser 对 "?" 占位的改写。
func SelectBlocksRawStmtArgsInBox(stmt string, args []any, limit int, boxID string) (ret []*Block) {
+ ret, _ = SelectBlocksRawStmtArgsInBoxContext(context.Background(), stmt, args, limit, boxID)
+ return
+}
+
+// SelectBlocksRawStmtArgsInBoxContext 取消参数化块查询,不将取消后的部分行作为完整结果返回。
+func SelectBlocksRawStmtArgsInBoxContext(ctx context.Context, stmt string, args []any, limit int, boxID string) (ret []*Block, err error) {
+ if err = ctx.Err(); err != nil {
+ return
+ }
if !checkRawBlockQueryStmt(stmt, boxID) {
return
}
- rows, err := queryForBox(boxID, stmt, args...)
+ rows, err := queryForBoxContext(ctx, boxID, stmt, args...)
if err != nil {
- if strings.Contains(err.Error(), "syntax error") {
+ if ctx.Err() != nil || strings.Contains(err.Error(), "syntax error") {
return
}
logging.LogWarnf("sql query [%s] failed: %s", stmt, err)
@@ -397,6 +434,9 @@ func SelectBlocksRawStmtArgsInBox(stmt string, args []any, limit int, boxID stri
noLimit := !containsLimitClause(stmt)
var count, errCount int
for rows.Next() {
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
count++
if block := scanBlockRows(rows); nil != block {
ret = append(ret, block)
@@ -409,6 +449,9 @@ func SelectBlocksRawStmtArgsInBox(stmt string, args []any, limit int, boxID stri
break
}
}
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
return
}
@@ -445,21 +488,32 @@ func SelectBlocksRegexInBox(stmt string, exp *regexp.Regexp, name, alias, memo,
// SelectBlocksRegexArgsInBox 与 SelectBlocksRegexInBox 一致,但通过绑定参数执行。
func SelectBlocksRegexArgsInBox(stmt string, exp *regexp.Regexp, name, alias, memo, ial bool, page, pageSize int, boxID string, args ...any) (ret []*Block) {
- rows, err := queryForBox(boxID, stmt, args...)
+ ret, _ = SelectBlocksRegexArgsInBoxContext(context.Background(), stmt, exp, name, alias, memo, ial, page, pageSize, boxID, args...)
+ return
+}
+
+// SelectBlocksRegexArgsInBoxContext 同时中断数据库扫描和逐块正则高亮。
+func SelectBlocksRegexArgsInBoxContext(ctx context.Context, stmt string, exp *regexp.Regexp, name, alias, memo, ial bool, page, pageSize int, boxID string, args ...any) (ret []*Block, err error) {
+ rows, err := queryForBoxContext(ctx, boxID, stmt, args...)
if err != nil {
- logging.LogErrorf("sql query [%s] failed: %s", stmt, err)
+ if ctx.Err() == nil {
+ logging.LogErrorf("sql query [%s] failed: %s", stmt, err)
+ }
return
}
defer rows.Close()
count := 0
for rows.Next() {
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
count++
if count <= (page-1)*pageSize {
continue
}
var block Block
- if err := rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); err != nil {
+ if err = rows.Scan(&block.ID, &block.ParentID, &block.RootID, &block.Hash, &block.Box, &block.Path, &block.HPath, &block.Name, &block.Alias, &block.Memo, &block.Tag, &block.Content, &block.FContent, &block.Markdown, &block.Length, &block.Type, &block.SubType, &block.IAL, &block.Sort, &block.Created, &block.Updated); err != nil {
logging.LogErrorf("query scan field failed: %s\n%s", err, logging.ShortStack())
return
}
@@ -471,6 +525,9 @@ func SelectBlocksRegexArgsInBox(stmt string, exp *regexp.Regexp, name, alias, me
}
}
}
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
return
}
@@ -847,7 +904,11 @@ func queryRawStmtForBox(boxID, stmt string, limit int) (ret []map[string]any, er
}
func queryRawStmtForBoxContext(ctx context.Context, boxID, stmt string, limit int) (ret []map[string]any, err error) {
- rows, err := queryForBoxContext(ctx, boxID, stmt)
+ return queryRawStmtArgsForBoxContext(ctx, boxID, stmt, nil, limit)
+}
+
+func queryRawStmtArgsForBoxContext(ctx context.Context, boxID, stmt string, args []any, limit int) (ret []map[string]any, err error) {
+ rows, err := queryForBoxContext(ctx, boxID, stmt, args...)
if err != nil {
return nil, err
}
@@ -861,6 +922,9 @@ func queryRawStmtForBoxContext(ctx context.Context, boxID, stmt string, limit in
noLimit := !containsLimitClause(stmt)
var count int
for rows.Next() {
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
columns := make([]any, len(cols))
columnPointers := make([]any, len(cols))
for i := range columns {
@@ -882,6 +946,9 @@ func queryRawStmtForBoxContext(ctx context.Context, boxID, stmt string, limit in
}
}
err = rows.Err()
+ if err != nil {
+ return nil, err
+ }
return
}
diff --git a/kernel/sql/encrypted_query_test.go b/kernel/sql/encrypted_query_test.go
index 91cc97cd96..3ff7921c86 100644
--- a/kernel/sql/encrypted_query_test.go
+++ b/kernel/sql/encrypted_query_test.go
@@ -21,6 +21,7 @@ import (
gosql "database/sql"
"errors"
"fmt"
+ "regexp"
"testing"
"time"
)
@@ -303,6 +304,88 @@ func TestSelectBlocksRawStmtInBoxContextCancellation(t *testing.T) {
}
}
+func TestParameterizedSearchQueriesCancelAndReleaseConnection(t *testing.T) {
+ testDB, boxID := useEncryptedQueryTestDB(t)
+ insertEncryptedQueryTestBlock(t, testDB, "block", "", "block", "d")
+ previousDB := db
+ db = testDB
+ t.Cleanup(func() { db = previousDB })
+ const sequence = `WITH RECURSIVE sequence(value) AS (
+ VALUES(0) UNION ALL SELECT value + 1 FROM sequence WHERE value < ?)
+ SELECT blocks.* FROM blocks WHERE (SELECT COUNT(*) FROM sequence) > 0`
+ queries := map[string]func(context.Context, string) (int, error){
+ "count": func(ctx context.Context, box string) (int, error) {
+ rows, err := QueryNoLimitArgsInBoxContext(ctx, sequence, box, 100000000)
+ return len(rows), err
+ },
+ "blocks": func(ctx context.Context, box string) (int, error) {
+ rows, err := SelectBlocksRawStmtArgsInBoxContext(ctx, sequence, []any{100000000}, 32, box)
+ return len(rows), err
+ },
+ "regexp": func(ctx context.Context, box string) (int, error) {
+ rows, err := SelectBlocksRegexArgsInBoxContext(ctx, sequence, regexp.MustCompile("block"), false, false, false, false, 1, 32, box, 100000000)
+ return len(rows), err
+ },
+ }
+ for name, query := range queries {
+ for scope, targetBox := range map[string]string{"global": "", "encrypted": boxID} {
+ t.Run(name+"/"+scope, func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() {
+ count, err := query(ctx, targetBox)
+ if count != 0 {
+ done <- fmt.Errorf("canceled query returned %d rows", count)
+ return
+ }
+ done <- err
+ }()
+ // 等到查询占用唯一连接,确保覆盖运行中的 SQLite 查询。
+ deadline := time.Now().Add(time.Second)
+ for testDB.Stats().InUse == 0 && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if testDB.Stats().InUse == 0 {
+ t.Fatal("query did not acquire a connection")
+ }
+ time.Sleep(10 * time.Millisecond)
+ cancel()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("expected cancellation, got %v", err)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("running query was not canceled")
+ }
+ followup, stop := context.WithTimeout(context.Background(), time.Second)
+ defer stop()
+ rows, err := SelectBlocksRawStmtArgsInBoxContext(followup, "SELECT * FROM blocks WHERE id = ?", []any{"block"}, 32, targetBox)
+ if err != nil || len(rows) != 1 || rows[0].ID != "block" {
+ t.Fatalf("connection was not reusable: rows=%v err=%v", rows, err)
+ }
+ })
+ }
+ }
+}
+
+func TestSearchQueriesRejectCanceledContextBeforeReading(t *testing.T) {
+ testDB, boxID := useEncryptedQueryTestDB(t)
+ insertEncryptedQueryTestBlock(t, testDB, "block", "", "block", "d")
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if rows, err := QueryNoLimitArgsInBoxContext(ctx, "SELECT * FROM blocks WHERE id = ?", boxID, "block"); !errors.Is(err, context.Canceled) || len(rows) != 0 {
+ t.Fatalf("canceled raw query returned rows=%v err=%v", rows, err)
+ }
+ if rows := GetBlocksInBoxContext(ctx, []string{"block"}, boxID); len(rows) != 0 {
+ t.Fatalf("canceled block lookup returned %v", rows)
+ }
+ if counts := QueryRefCountInBoxContext(ctx, []string{"block"}, boxID); len(counts) != 0 {
+ t.Fatalf("canceled reference lookup returned %v", counts)
+ }
+}
+
func useEncryptedQueryTestDB(t *testing.T) (*gosql.DB, string) {
t.Helper()
testDB, err := gosql.Open("sqlite3_extended", ":memory:")
diff --git a/kernel/sql/queue.go b/kernel/sql/queue.go
index 2aa42dcee4..fe3a175fe8 100644
--- a/kernel/sql/queue.go
+++ b/kernel/sql/queue.go
@@ -216,17 +216,22 @@ func clearQueue() {
var flushingTx = atomic.Bool{}
func FlushQueue() {
+ timing := util.BeginPerformance("index.flush")
+ timing.Stage("wait_lock")
diagnostic := util.WatchOperation("flush database index", "wait for index lock")
defer diagnostic.Finish()
initDatabaseLock.Lock()
defer initDatabaseLock.Unlock()
diagnostic.Stage("take queued operations")
+ timing.Stage("take_queue")
ops, indexSnapshot := getOperations()
total := len(ops)
if 1 > total && !flushingTx.Load() {
return
}
+ defer timing.Finish()
+ timing.Count("operations", int64(total))
flushingTx.Store(true)
defer func() {
@@ -261,6 +266,17 @@ func FlushQueue() {
for _, op := range ops {
groupOpsTotal[op.action]++
}
+ if timing != nil {
+ var oldest time.Time
+ for _, op := range ops {
+ if !op.inQueueTime.IsZero() && (oldest.IsZero() || op.inQueueTime.Before(oldest)) {
+ oldest = op.inQueueTime
+ }
+ }
+ if !oldest.IsZero() {
+ timing.Count("oldest_wait_us", time.Since(oldest).Microseconds())
+ }
+ }
groupOpsCurrent := map[string]int{}
backlinkChange := newBacklinkIndexChange()
@@ -294,6 +310,7 @@ func FlushQueue() {
}
diagnostic.Stage("begin " + op.action)
+ timing.Stage("begin")
tx, err := beginTxForBox(op.boxID())
if err != nil {
logging.LogWarnf("skip queue operation [%s] for box [%s]: %s", op.action, op.boxID(), err)
@@ -314,6 +331,7 @@ func FlushQueue() {
context["current"] = groupOpsCurrent[op.action]
context["total"] = groupOpsTotal[op.action]
diagnostic.Stage("execute " + op.action)
+ timing.Stage("execute")
if err = execOp(op, tx, context); err != nil {
tx.Rollback()
closeTxPreparedStmts(tx)
@@ -327,6 +345,7 @@ func FlushQueue() {
}
diagnostic.Stage("commit " + op.action)
+ timing.Stage("commit")
if err = commitTx(tx); err != nil {
invalidateRefsCacheForOperation(op)
logging.LogErrorf("commit tx failed: %s", err)
@@ -369,12 +388,14 @@ func FlushQueue() {
// Push database index commit event https://github.com/siyuan-note/siyuan/issues/8814
diagnostic.Stage("notify index completion")
+ timing.Stage("notify")
util.BroadcastByType("main", "databaseIndexCommit", 0, "", backlinkChange.data())
eventbus.Publish(eventbus.EvtSQLIndexFlushed)
// 刷新期间追加的操作仍在内存队列中,磁盘队列仅用于进程重启恢复,不能在这里重复执行。
diagnostic.Stage("persist index queue completion")
+ timing.Stage("persist_queue")
clearIndexQueue(indexSnapshot)
}
diff --git a/kernel/util/performance.go b/kernel/util/performance.go
new file mode 100644
index 0000000000..9088d64588
--- /dev/null
+++ b/kernel/util/performance.go
@@ -0,0 +1,81 @@
+package util
+
+import (
+ "encoding/json"
+ "os"
+ "time"
+
+ "github.com/siyuan-note/logging"
+)
+
+var performanceEnabled = os.Getenv("SIYUAN_PERFORMANCE") == "1"
+
+type performanceRecord struct {
+ Operation string `json:"operation"`
+ DurationUS int64 `json:"duration_us"`
+ StagesUS map[string]int64 `json:"stages_us"`
+ Counts map[string]int64 `json:"counts,omitempty"`
+}
+
+// Performance 记录单次同步操作的阶段耗时;名称和计数键仅使用代码内固定值,不写入正文或路径。
+type Performance struct {
+ record performanceRecord
+ started time.Time
+ previous time.Time
+ stage string
+ now func() time.Time
+ report func(performanceRecord)
+ finished bool
+}
+
+// BeginPerformance 仅在进程启动前设置 SIYUAN_PERFORMANCE=1 时分配记录,默认不采样。
+func BeginPerformance(operation string) *Performance {
+ if !performanceEnabled {
+ return nil
+ }
+ return newPerformance(operation, time.Now, func(record performanceRecord) {
+ data, err := json.Marshal(record)
+ if err == nil {
+ logging.LogInfof("siyuan-performance %s", data)
+ }
+ })
+}
+
+func newPerformance(operation string, now func() time.Time, report func(performanceRecord)) *Performance {
+ started := now()
+ return &Performance{
+ record: performanceRecord{Operation: operation, StagesUS: map[string]int64{}},
+ started: started, previous: started, stage: "prepare", now: now, report: report,
+ }
+}
+
+// Stage 结束上一个阶段;相同名称的多个阶段累计耗时。
+func (p *Performance) Stage(stage string) {
+ if p == nil || p.finished {
+ return
+ }
+ now := p.now()
+ p.record.StagesUS[p.stage] += now.Sub(p.previous).Microseconds()
+ p.stage, p.previous = stage, now
+}
+
+// Count 保存当前操作的规模,不采集进程全局内存以免混淆并发请求的归属。
+func (p *Performance) Count(name string, value int64) {
+ if p == nil || p.finished {
+ return
+ }
+ if p.record.Counts == nil {
+ p.record.Counts = map[string]int64{}
+ }
+ p.record.Counts[name] = value
+}
+
+func (p *Performance) Finish() {
+ if p == nil || p.finished {
+ return
+ }
+ p.Stage("finished")
+ p.record.DurationUS = p.previous.Sub(p.started).Microseconds()
+ p.finished = true
+ p.report(p.record)
+}
diff --git a/kernel/util/performance_test.go b/kernel/util/performance_test.go
new file mode 100644
index 0000000000..9eb48e6e88
--- /dev/null
+++ b/kernel/util/performance_test.go
@@ -0,0 +1,47 @@
+package util
+
+import (
+ "testing"
+ "time"
+)
+
+func TestPerformanceAccumulatesStagesAndReportsOnce(t *testing.T) {
+ now := time.Unix(0, 0)
+ var records []performanceRecord
+ p := newPerformance("search", func() time.Time { return now }, func(record performanceRecord) {
+ records = append(records, record)
+ })
+ now = now.Add(time.Millisecond)
+ p.Stage("query")
+ now = now.Add(2 * time.Millisecond)
+ p.Stage("format")
+ now = now.Add(time.Millisecond)
+ p.Stage("query")
+ now = now.Add(3 * time.Millisecond)
+ p.Count("rows", 20)
+ p.Finish()
+ p.Count("rows", 99)
+ p.Finish()
+ if len(records) != 1 {
+ t.Fatalf("operation produced %d records", len(records))
+ }
+ r := records[0]
+ if r.Operation != "search" || r.DurationUS != 7000 || r.StagesUS["prepare"] != 1000 ||
+ r.StagesUS["query"] != 5000 || r.StagesUS["format"] != 1000 || r.Counts["rows"] != 20 {
+ t.Fatalf("incorrect timing or mutation after completion: %+v", r)
+ }
+}
+
+func TestDisabledPerformanceDoesNotAllocate(t *testing.T) {
+ if performanceEnabled {
+ t.Skip("performance logging was explicitly enabled")
+ }
+ if allocations := testing.AllocsPerRun(100, func() {
+ p := BeginPerformance("search")
+ p.Stage("query")
+ p.Count("rows", 10)
+ p.Finish()
+ }); allocations != 0 {
+ t.Fatalf("disabled instrumentation allocated %v objects", allocations)
+ }
+}