Skip to content

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

:bug: Prevent stale configuration writes during settings reset https://github.com/siyuan-note/siyuan/issues/20044

Daniel604446e6c911
diff --git a/app/src/config/setting/pending.test.ts b/app/src/config/setting/pending.test.ts
index 6bb1edc8e5..3447fd8de2 100644
--- a/app/src/config/setting/pending.test.ts
+++ b/app/src/config/setting/pending.test.ts
@@ -42,3 +42,18 @@ test("reset does not wait for its own acknowledgement or unrelated fetches", asy
}
await flushSettingSaves();
});
+
+test("reset waits for graph writes and rejects failed graph saves", async () => {
+ for (const name of ["setGraphConf", "resetGraph", "resetLocalGraph", "getGraph", "getLocalGraph"]) {
+ let release: (result: {code: number}) => void;
+ const before = settingSaveFailures();
+ trackSettingRequest("/api/graph/" + name, new Promise(resolve => { release = resolve; }));
+ let flushed = false;
+ const flush = flushSettingSaves(before).then(() => { flushed = true; });
+ await Promise.resolve();
+ await Promise.resolve();
+ assert.equal(flushed, false);
+ release({code: -1});
+ await assert.rejects(flush);
+ }
+});
diff --git a/app/src/config/setting/pending.ts b/app/src/config/setting/pending.ts
index bb46eda9d4..71a245dd44 100644
--- a/app/src/config/setting/pending.ts
+++ b/app/src/config/setting/pending.ts
@@ -17,7 +17,7 @@ export const trackSettingSave = <T>(promise: Promise<T>): Promise<T> => {
};
export const trackSettingRequest = <T>(url: string, promise: Promise<T>): Promise<T> =>
- /^\/api\/(setting\/(set|patch)|storage\/(set|remove)LocalStorage|system\/set)/.test(url)
+ /^\/api\/(setting\/(set|patch)|storage\/(set|remove)LocalStorage|system\/set|graph\/(setGraphConf|resetGraph|resetLocalGraph|getGraph|getLocalGraph)$)/.test(url)
? trackSettingSave(promise) : promise;
export const flushSettingSaves = async (previousFailures = failures) => {
diff --git a/app/src/config/setting/reset.test.ts b/app/src/config/setting/reset.test.ts
index 1d983fbe36..7335869af6 100644
--- a/app/src/config/setting/reset.test.ts
+++ b/app/src/config/setting/reset.test.ts
@@ -16,6 +16,10 @@ const loadReset = (browser: boolean, mobile: boolean, failed = false) => {
calls.push("save editor");
if (failed) throw new Error("offline");
}}],
+ getAllModels: () => ({graph: [{suspendSettingsSaving: () => {
+ calls.push("save graph");
+ return () => calls.push("resume graph");
+ }}]}),
setNativeSettingTask: (_id: string, active: boolean) => calls.push(active ? "block" : "unblock"),
suspendLayoutSaving: async () => { calls.push("suspend layout"); return () => calls.push("resume layout"); },
settingSaveFailures: () => 0,
@@ -38,7 +42,7 @@ for (const [browser, mobile] of [[false, false], [true, false], [true, true]]) {
test(`reset saves before reloading and only the local desktop exits (${browser}, ${mobile})`, async () => {
const {api, calls} = loadReset(browser, mobile);
await api.prepareSettingsReset({id: "reset", token: "one-use"});
- assert.deepEqual(calls, ["block", "blur", "save editor", ...mobile ? [] : ["suspend layout"], "save settings", "ack true"]);
+ assert.deepEqual(calls, ["block", "blur", "save editor", ...mobile ? [] : ["suspend layout", "save graph"], "save settings", "ack true"]);
api.completeSettingsReset({id: "reset", exit: true});
api.exitAfterSettingsReset();
assert.deepEqual(calls.slice(-(!browser ? 2 : 1)), !browser ? ["reload", "exit"] : ["reload"]);
@@ -60,7 +64,7 @@ test("cancellation resumes layout saving and prepared reconnect reloads without
api.cancelSettingsReset("unrelated");
assert.equal(calls.includes("resume layout"), false);
api.cancelSettingsReset("first");
- assert.deepEqual(calls.slice(-2), ["resume layout", "unblock"]);
+ assert.deepEqual(calls.slice(-3), ["resume layout", "resume graph", "unblock"]);
await api.prepareSettingsReset({id: "second", token: "b"});
assert.equal(api.reloadSettingsResetOnReconnect(), true);
assert.equal(calls.at(-1), "reload");
diff --git a/app/src/config/setting/reset.ts b/app/src/config/setting/reset.ts
index 921ff45f73..454a655ad4 100644
--- a/app/src/config/setting/reset.ts
+++ b/app/src/config/setting/reset.ts
@@ -1,6 +1,6 @@
import {confirmDialog} from "../../dialog/confirmDialog";
import {fetchSyncPost} from "../../util/fetch";
-import {getAllEditor} from "../../layout/getAll";
+import {getAllEditor, getAllModels} from "../../layout/getAll";
import {setNativeSettingTask} from "./taskBlocker";
import {flushSettingSaves, settingSaveFailures} from "./pending";
import {getHostCapabilities} from "../../util/hostCapabilities";
@@ -42,7 +42,12 @@ export const prepareSettingsReset = async (data: {id: string; token: string}) =>
resume();
return;
}
- preparation.resume = resume;
+ const resumeGraphs: Array<() => void> = [];
+ preparation.resume = () => {
+ resume();
+ resumeGraphs.forEach(resumeGraph => resumeGraph());
+ };
+ getAllModels().graph.forEach(graph => resumeGraphs.push(graph.suspendSettingsSaving()));
/// #endif
await flushSettingSaves(previousFailures);
if (preparation?.id !== data.id) return;
diff --git a/app/src/layout/dock/Graph.test.ts b/app/src/layout/dock/Graph.test.ts
new file mode 100644
index 0000000000..26e4c107b6
--- /dev/null
+++ b/app/src/layout/dock/Graph.test.ts
@@ -0,0 +1,63 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {flushSettingSaves, trackSettingRequest} from "../../config/setting/pending";
+
+for (const type of ["global", "local", "pin"]) {
+ test(`reset flushes the latest delayed graph settings before acknowledging (${type})`, async () => {
+ const timers = new Map<number, () => void>();
+ const writes: Array<{type: string, conf: {dailyNote: boolean}}> = [];
+ let timerID = 0;
+ let release: () => void;
+ const request = new Promise<void>(resolve => { release = resolve; });
+ const exports = {} as typeof import("./Graph");
+ const code = transpileModule(readFileSync("src/layout/dock/Graph.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ runInNewContext(code, {
+ exports,
+ require: () => ({Model: class {}, fetchPost: (url: string, data: typeof writes[number]) => {
+ writes.push(data);
+ return trackSettingRequest(url, request);
+ }}),
+ window: {
+ siyuan: {config: {graph: {}}},
+ setTimeout: (callback: () => void) => { timers.set(++timerID, callback); return timerID; },
+ clearTimeout: (id: number) => timers.delete(id),
+ },
+ });
+ let conf = {dailyNote: false};
+ const graph = Object.assign(Object.create(exports.Graph.prototype), {
+ type, getGraphConf: () => conf, onGraph() {},
+ });
+ graph.updateGraphOptions();
+ conf = {dailyNote: true};
+ graph.updateGraphOptions();
+ assert.equal(writes.length, 0);
+ assert.equal(timers.size, 1);
+ graph.scheduleGraphSearch();
+ const resume = graph.suspendSettingsSaving();
+ assert.equal(timers.size, 0);
+ assert.equal(writes.length, 1);
+ assert.equal(writes[0].type, type === "global" ? "global" : "local");
+ assert.equal(writes[0].conf, conf);
+ graph.searchGraph();
+ assert.equal(writes.length, 1);
+ let flushed = false;
+ const flush = flushSettingSaves().then(() => { flushed = true; });
+ await Promise.resolve();
+ await Promise.resolve();
+ assert.equal(flushed, false);
+ release();
+ await flush;
+ graph.flushPendingSettings();
+ assert.equal(writes.length, 1);
+ let refreshed = false;
+ graph.searchGraph = () => { refreshed = true; };
+ resume();
+ assert.equal(refreshed, true);
+ assert.equal(graph.settingsSavingSuspended, false);
+ });
+}
diff --git a/app/src/layout/dock/Graph.ts b/app/src/layout/dock/Graph.ts
index 24d8e2c070..5349149328 100644
--- a/app/src/layout/dock/Graph.ts
+++ b/app/src/layout/dock/Graph.ts
@@ -31,6 +31,7 @@ export class Graph extends Model {
private element: HTMLElement;
private saveTimeout: number;
private searchTimeout: number;
+ private settingsSavingSuspended = false;
private pendingGraphConf: IGraphCommon & {dailyNote: boolean, minRefs?: number};
public blockId: string; // "local" / "pin" 必填
public rootId: string; // "local" 必填
@@ -445,6 +446,7 @@ export class Graph extends Model {
}
public searchGraph(options: IGraphSearchOptions = {}) {
+ if (this.settingsSavingSuspended) return;
const refresh = options.refresh || false;
const resetLayout = options.resetLayout ?? refresh;
const id = options.id;
@@ -457,9 +459,7 @@ export class Graph extends Model {
this.searchTimeout = 0;
}
if (this.saveTimeout) {
- window.clearTimeout(this.saveTimeout);
- this.saveTimeout = 0;
- this.persistGraphConf();
+ this.flushPendingSettings();
}
const requestVersion = ++this.requestVersion;
element.classList.add("fn__rotate");
@@ -533,11 +533,7 @@ export class Graph extends Model {
if (this.searchTimeout) {
window.clearTimeout(this.searchTimeout);
}
- if (this.saveTimeout) {
- window.clearTimeout(this.saveTimeout);
- this.saveTimeout = 0;
- }
- this.persistGraphConf();
+ this.flushPendingSettings();
this.graphEngine?.destroy();
this.graphEngine = undefined;
this.renderedGraphData = undefined;
@@ -601,12 +597,30 @@ export class Graph extends Model {
}
this.pendingGraphConf = conf;
this.saveTimeout = window.setTimeout(() => {
- this.saveTimeout = 0;
- this.persistGraphConf();
+ this.flushPendingSettings();
}, 300);
}
- private persistGraphConf() {
+ // 重置期间暂停会保存配置的查询,取消重置后恢复面板刷新。
+ public suspendSettingsSaving() {
+ if (this.searchTimeout) {
+ window.clearTimeout(this.searchTimeout);
+ this.searchTimeout = 0;
+ this.pendingGraphConf = this.getGraphConf();
+ }
+ this.flushPendingSettings();
+ this.settingsSavingSuspended = true;
+ return () => {
+ this.settingsSavingSuspended = false;
+ this.searchGraph();
+ };
+ }
+
+ private flushPendingSettings() {
+ if (this.saveTimeout) {
+ window.clearTimeout(this.saveTimeout);
+ this.saveTimeout = 0;
+ }
if (!this.pendingGraphConf) {
return;
}
diff --git a/kernel/api/contract.go b/kernel/api/contract.go
index 1b2df80dec..7fbfdec5bd 100644
--- a/kernel/api/contract.go
+++ b/kernel/api/contract.go
@@ -45,7 +45,7 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D
if namespace := additionalSettingNamespace(endpoint.Definition().Path); namespace != "" {
handler = serializeSetting(namespace, handler)
}
- if endpoint.Definition().Path == "/api/system/getConf" || settingsResetStoragePath(endpoint.Definition().Path) {
+ if endpoint.Definition().Path == "/api/system/getConf" || settingsResetWritePath(endpoint.Definition().Path) {
read := handler
handler = func(c *gin.Context, request Request) apicontract.Response[Data] {
settingMutationMu.Lock()
@@ -132,12 +132,13 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D
}
}
-// settingsResetStoragePath 让重置事务与布局及本地偏好写入互斥,不改变这些接口的通知语义。
-func settingsResetStoragePath(path string) bool {
+// settingsResetWritePath 让重置事务与布局、本地偏好及关系图配置写入互斥,不改变这些接口的通知语义。
+func settingsResetWritePath(path string) bool {
switch path {
case "/api/system/setUILayout", "/api/storage/setLocalStorage", "/api/storage/setLocalStorageVal",
"/api/storage/setLocalStorageVals", "/api/storage/removeLocalStorageVal", "/api/storage/removeLocalStorageVals",
- "/api/setting/setBootAppearance":
+ "/api/setting/setBootAppearance", "/api/graph/setGraphConf", "/api/graph/resetGraph", "/api/graph/resetLocalGraph",
+ "/api/graph/getGraph", "/api/graph/getLocalGraph":
return true
}
return false
diff --git a/kernel/api/settings_reset_test.go b/kernel/api/settings_reset_test.go
index a981b3ce5d..2bcacfbc21 100644
--- a/kernel/api/settings_reset_test.go
+++ b/kernel/api/settings_reset_test.go
@@ -6,9 +6,11 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -98,3 +100,57 @@ func TestAPIContractSettingsResetAuthorization(t *testing.T) {
}
}
}
+
+func TestAPIContractSettingsResetSerializesGraphWrites(t *testing.T) {
+ previousConf, previousReadOnly := model.Conf, util.ReadOnly
+ model.Conf, util.ReadOnly = model.NewAppConf(), true
+ t.Cleanup(func() { model.Conf, util.ReadOnly = previousConf, previousReadOnly })
+ gin.SetMode(gin.TestMode)
+ for _, entry := range []struct {
+ path string
+ handler gin.HandlerFunc
+ body string
+ changed bool
+ }{
+ {"/api/graph/setGraphConf", setGraphConf, `{"type":"global","conf":{"minRefs":20}}`, true},
+ {"/api/graph/setGraphConf", setGraphConf, `{"type":"local","conf":{"dailyNote":false}}`, true},
+ {"/api/graph/resetGraph", resetGraph, `{}`, true},
+ {"/api/graph/resetLocalGraph", resetLocalGraph, `{}`, true},
+ {"/api/graph/getGraph", getGraph, `{"conf":{"d3":false}}`, false},
+ {"/api/graph/getLocalGraph", getLocalGraph, `{"id":"missing","conf":{"d3":false}}`, false},
+ } {
+ t.Run(entry.path+entry.body, func(t *testing.T) {
+ model.Conf.Graph = conf.NewGraph()
+ model.Conf.Graph.Global.MinRefs = 7
+ model.Conf.Graph.Local.DailyNote = true
+ before := string(graphJSON(t, model.Conf.Graph))
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Set(model.RoleContextKey, model.RoleAdministrator)
+ c.Request = httptest.NewRequest(http.MethodPost, entry.path, strings.NewReader(entry.body))
+ started, finished := make(chan struct{}), make(chan struct{})
+ settingMutationMu.Lock()
+ go func() {
+ close(started)
+ entry.handler(c)
+ close(finished)
+ }()
+ <-started
+ select {
+ case <-finished:
+ t.Error("graph write bypassed the settings reset lock")
+ case <-time.After(50 * time.Millisecond):
+ }
+ settingMutationMu.Unlock()
+ select {
+ case <-finished:
+ case <-time.After(5 * time.Second):
+ t.Fatal("graph write did not resume after settings reset unlocked")
+ }
+ requireAPIContract(t, http.MethodPost, entry.path, recorder)
+ if changed := before != string(graphJSON(t, model.Conf.Graph)); changed != entry.changed {
+ t.Fatal("graph write or validation changed after unlocking")
+ }
+ })
+ }
+}
diff --git a/kernel/model/settings_reset.go b/kernel/model/settings_reset.go
index a3a494d782..eaf5ed188f 100644
--- a/kernel/model/settings_reset.go
+++ b/kernel/model/settings_reset.go
@@ -81,6 +81,7 @@ func ResetSettings() error {
defer localStorageLock.Unlock()
defer bootAppearanceConfLock.Unlock()
if err := recoverSettingsReset(); err != nil {
+ util.ReportFileSysFatalError(err)
return err
}
next := defaultWorkspaceSettings(Conf)
@@ -194,15 +195,23 @@ func writeSettingsReset(next [][]byte, write func(string, []byte) error) error {
err = write(path, next[i])
}
if err != nil {
- return errors.Join(err, recoverSettingsReset())
+ return rollbackSettingsReset(err)
}
}
if err = os.Remove(settingsResetJournalPath()); err != nil {
- return errors.Join(err, recoverSettingsReset())
+ return rollbackSettingsReset(err)
}
return nil
}
+// 回滚失败时停止内核,保留恢复日志,避免后续保存被下次启动的回滚覆盖。
+func rollbackSettingsReset(cause error) error {
+ if err := recoverSettingsReset(); err != nil {
+ util.ReportFileSysFatalError(errors.Join(cause, err))
+ }
+ return cause
+}
+
// recoverSettingsReset 在读取主配置之前回滚未提交操作,未知日志保持原样并阻止继续启动。
func recoverSettingsReset() error {
data, err := os.ReadFile(settingsResetJournalPath())
diff --git a/kernel/model/settings_reset_test.go b/kernel/model/settings_reset_test.go
index f8cc7d11e8..75eeb4463e 100644
--- a/kernel/model/settings_reset_test.go
+++ b/kernel/model/settings_reset_test.go
@@ -2,14 +2,18 @@ package model
import (
"bytes"
+ "context"
"encoding/json"
"errors"
"os"
+ "os/exec"
"path/filepath"
"reflect"
"testing"
+ "time"
"github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -234,3 +238,100 @@ func TestSettingsResetRejectsCorruptionAndReadonly(t *testing.T) {
t.Fatal("corrupt recovery must not overwrite existing files")
}
}
+
+func TestSettingsResetRollbackFailureStopsWrites(t *testing.T) {
+ const rootEnv = "SIYUAN_TEST_SETTINGS_RESET_ROOT"
+ const modeEnv = "SIYUAN_TEST_SETTINGS_RESET_MODE"
+ if root := os.Getenv(rootEnv); root != "" {
+ util.ConfDir, util.DataDir = filepath.Join(root, "conf"), filepath.Join(root, "data")
+ Conf = NewAppConf()
+ paths := settingsResetPaths()
+ if os.Getenv(modeEnv) == "pending" {
+ journal := settingsResetJournal{Version: 1}
+ for _, path := range paths {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ journal.Files = append(journal.Files, settingsResetFile{Exists: true, Data: data})
+ }
+ data, err := json.Marshal(journal)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(settingsResetJournalPath(), data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ blockRollback := func() {
+ if err := os.Remove(paths[1]); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(paths[1], 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if os.Getenv(modeEnv) == "pending" {
+ blockRollback()
+ _ = ResetSettings()
+ } else {
+ _ = writeSettingsReset([][]byte{[]byte(`{}`), []byte(`{}`), []byte(`{}`)}, func(path string, data []byte) error {
+ if path == paths[1] {
+ blockRollback()
+ return errors.New("simulated disk failure")
+ }
+ return filelock.WriteFile(path, data)
+ })
+ }
+ t.Fatal("failed recovery allowed further writes")
+ }
+ for _, mode := range []string{"rollback", "pending"} {
+ t.Run(mode, func(t *testing.T) {
+ settingsResetTestEnvironment(t)
+ paths := settingsResetPaths()
+ original, err := os.ReadFile(paths[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ originals := [][]byte{original, []byte(`{"plugin":"retained"}`), []byte(`{}`)}
+ for i, path := range paths {
+ if err = filelock.WriteFile(path, originals[i]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSettingsResetRollbackFailureStopsWrites$")
+ cmd.Env = append(os.Environ(), rootEnv+"="+filepath.Dir(util.ConfDir), modeEnv+"="+mode)
+ output, err := cmd.CombinedOutput()
+ var exitErr *exec.ExitError
+ if !errors.As(err, &exitErr) || exitErr.ExitCode() != logging.ExitCodeFileSysErr {
+ t.Fatalf("expected fatal file-system exit, got %v\n%s", err, output)
+ }
+ if _, err = os.Stat(settingsResetJournalPath()); err != nil {
+ t.Fatalf("recovery journal was not preserved: %v", err)
+ }
+ if err = os.Remove(paths[1]); err != nil {
+ t.Fatal(err)
+ }
+ if err = recoverSettingsReset(); err != nil {
+ t.Fatal(err)
+ }
+ for i, path := range paths {
+ data, readErr := os.ReadFile(path)
+ if readErr != nil || !bytes.Equal(data, originals[i]) {
+ t.Fatalf("original configuration was not recovered: %s, %v", path, readErr)
+ }
+ }
+ Conf.Api.Token = "token-after-successful-recovery"
+ Conf.Save()
+ if err = recoverSettingsReset(); err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(paths[0])
+ if err != nil || !bytes.Contains(data, []byte(Conf.Api.Token)) {
+ t.Fatal("recovery reverted a later configuration save")
+ }
+ })
+ }
+}