feat(nacos): enhance configuration management

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-07-26 11:20:05 +08:00
1 parent 406b7acdbb
commit 1ebc3fd12b
52 files changed
+7139 -263

No files matched your search

+250
View File
@@ -1,19 +1,31 @@
import { describe, expect, it } from "vitest";
import {
buildNacosContentSearchCsv,
buildNacosConfigExportFileName,
buildNacosConfigDeleteConfirm,
buildNacosInlineDiff,
buildNacosInstanceConfirm,
buildNacosRawRequest,
buildNacosSideBySideDiff,
canDeleteNacosConfig,
canStartNacosConfigDelete,
canStartNacosConfigSave,
createNacosConfigDeleteSnapshot,
createNacosConfigSaveSnapshot,
createNacosLatestRequestGuard,
isNacosRawMutation,
isNacosErrorCode,
isNacosConfigSaveSnapshotCurrent,
isNacosConfigDeleteSnapshotInScope,
nacosConfigFileExtension,
parseNacosRawBody,
parseNacosRawQuery,
normalizeNacosEndpoint,
resolveRNacosOpenApiFallback,
resolveNacosConfigCopyText,
resolveNacosConfigSaveCompletion,
sanitizeNacosConfigFileNameSegment,
splitNacosContentLiteralMatches,
summarizeNacosConfigDiff,
} from "@/lib/nacos/nacosAdmin";
@@ -49,6 +61,12 @@ describe("nacosAdmin helpers", () => {
expect(isNacosRawMutation("DELETE")).toBe(true);
});
it("recognizes structured Nacos errors without matching unrelated failures", () => {
expect(isNacosErrorCode(new Error("NACOS_ERROR[stalePreview]: preview again"), "stalePreview")).toBe(true);
expect(isNacosErrorCode("NACOS_ERROR[authFailed]: forbidden", "stalePreview")).toBe(false);
expect(isNacosErrorCode(new Error("stalePreview"), "stalePreview")).toBe(false);
});
it("redirects r-nacos console settings to the compatible OpenAPI endpoint", () => {
expect(resolveRNacosOpenApiFallback("http://rnacos.example:10848", "/rnacos")).toEqual({
serverAddr: "http://rnacos.example:8848",
@@ -113,4 +131,236 @@ describe("nacosAdmin helpers", () => {
expect(resolveNacosConfigCopyText("", "editor", "state")).toBe("editor");
expect(resolveNacosConfigCopyText("", "", "state")).toBe("state");
});
it("rejects stale config detail requests after a newer selection or invalidation", () => {
const guard = createNacosLatestRequestGuard();
const first = guard.begin();
const second = guard.begin();
expect(guard.isCurrent(first)).toBe(false);
expect(guard.isCurrent(second)).toBe(true);
guard.invalidate();
expect(guard.isCurrent(second)).toBe(false);
});
it("keeps a late A detail response from replacing a newer B selection", async () => {
const guard = createNacosLatestRequestGuard();
let resolveA!: (value: string) => void;
let resolveB!: (value: string) => void;
const responseA = new Promise<string>((resolve) => {
resolveA = resolve;
});
const responseB = new Promise<string>((resolve) => {
resolveB = resolve;
});
let selected = "";
const load = async (response: Promise<string>) => {
const requestId = guard.begin();
const detail = await response;
if (guard.isCurrent(requestId)) selected = detail;
};
const loadingA = load(responseA);
const loadingB = load(responseB);
resolveB("B");
await loadingB;
resolveA("A");
await loadingA;
expect(selected).toBe("B");
});
it("keeps save payloads immutable and applies them only to the unchanged editor session", () => {
const editedConfig = {
namespace: "dev",
dataId: "application.yaml",
group: "DEFAULT_GROUP",
configType: "yaml",
appName: "gateway",
desc: "published settings",
tags: "prod",
};
const snapshot = createNacosConfigSaveSnapshot({
requestId: 4,
editorSessionId: 9,
connectionId: "nacos-a",
originalKey: { namespace: "dev", dataId: "application.yaml", group: "DEFAULT_GROUP" },
config: editedConfig,
content: "server:\n port: 8080",
configType: "yaml",
});
editedConfig.desc = "changed after publish started";
expect(snapshot.config.desc).toBe("published settings");
expect(snapshot.content).toBe("server:\n port: 8080");
expect(
isNacosConfigSaveSnapshotCurrent(snapshot, {
latestRequestId: 4,
editorSessionId: 9,
connectionId: "nacos-a",
originalKey: { namespace: "dev", dataId: "application.yaml", group: "DEFAULT_GROUP" },
config: { ...snapshot.config },
content: snapshot.content,
configType: snapshot.configType,
}),
).toBe(true);
});
it("does not apply a completed save to another selection or to later edits", () => {
const snapshot = createNacosConfigSaveSnapshot({
requestId: 1,
editorSessionId: 3,
connectionId: "nacos-a",
originalKey: { namespace: "dev", dataId: "a.yaml", group: "DEFAULT_GROUP" },
config: { namespace: "dev", dataId: "a.yaml", group: "DEFAULT_GROUP", desc: "A" },
content: "value: A",
configType: "yaml",
});
const matchingState = {
latestRequestId: 1,
editorSessionId: 3,
connectionId: "nacos-a",
originalKey: { namespace: "dev", dataId: "a.yaml", group: "DEFAULT_GROUP" },
config: { ...snapshot.config },
content: snapshot.content,
configType: snapshot.configType,
};
expect(isNacosConfigSaveSnapshotCurrent(snapshot, { ...matchingState, editorSessionId: 4, config: { ...snapshot.config, dataId: "b.yaml" } })).toBe(false);
expect(isNacosConfigSaveSnapshotCurrent(snapshot, { ...matchingState, content: "value: edited while saving" })).toBe(false);
expect(isNacosConfigSaveSnapshotCurrent(snapshot, { ...matchingState, latestRequestId: 2 })).toBe(false);
});
it("advances the published baseline without overwriting edits made while saving", () => {
const originalContent = "value: O";
const publishedContent = "value: S";
const laterContent = "value: T";
const snapshot = createNacosConfigSaveSnapshot({
requestId: 7,
editorSessionId: 12,
connectionId: "nacos-a",
originalKey: { namespace: "dev", dataId: "a.yaml", group: "DEFAULT_GROUP" },
config: { namespace: "dev", dataId: "a.yaml", group: "DEFAULT_GROUP", desc: "snapshot metadata" },
content: publishedContent,
configType: "yaml",
});
const completion = resolveNacosConfigSaveCompletion(snapshot, {
latestRequestId: 7,
editorSessionId: 12,
connectionId: "nacos-a",
originalKey: { namespace: "dev", dataId: "a.yaml", group: "DEFAULT_GROUP" },
config: { ...snapshot.config, desc: "edited metadata" },
content: laterContent,
configType: "yaml",
});
expect(completion.kind).toBe("saved-with-later-edits");
if (completion.kind === "stale") throw new Error("expected a relevant save completion");
expect(completion.baseline.content).toBe(publishedContent);
expect(laterContent).not.toBe(completion.baseline.content);
expect(originalContent).not.toBe(completion.baseline.content);
});
it("keeps a renamed draft separate from the identity published by an in-flight save", () => {
const snapshot = createNacosConfigSaveSnapshot({
requestId: 8,
editorSessionId: 13,
connectionId: "nacos-a",
originalKey: null,
config: { namespace: "dev", dataId: "draft-a.yaml", group: "DEFAULT_GROUP" },
content: "value: S",
configType: "yaml",
});
const completion = resolveNacosConfigSaveCompletion(snapshot, {
latestRequestId: 8,
editorSessionId: 13,
connectionId: "nacos-a",
originalKey: null,
config: { ...snapshot.config, dataId: "draft-b.yaml" },
content: "value: T",
configType: "yaml",
});
expect(completion).toEqual({ kind: "stale" });
});
it("never allows a draft or read-only config to enter the delete flow", () => {
const publishedKey = { namespace: "dev", dataId: "application.yaml", group: "DEFAULT_GROUP" };
expect(canDeleteNacosConfig(false, publishedKey)).toBe(true);
expect(canDeleteNacosConfig(false, null)).toBe(false);
expect(canDeleteNacosConfig(true, publishedKey)).toBe(false);
});
it("keeps save and delete mutations mutually exclusive in both directions", () => {
const idle = {
readOnly: false,
saving: false,
deleting: false,
hasPendingDelete: false,
hasPendingSave: false,
};
const publishedKey = { namespace: "dev", dataId: "application.yaml", group: "DEFAULT_GROUP" };
expect(canStartNacosConfigSave(idle)).toBe(true);
expect(canStartNacosConfigSave({ ...idle, saving: true })).toBe(false);
expect(canStartNacosConfigSave({ ...idle, deleting: true })).toBe(false);
expect(canStartNacosConfigSave({ ...idle, hasPendingDelete: true })).toBe(false);
expect(canStartNacosConfigDelete(idle, publishedKey)).toBe(true);
expect(canStartNacosConfigDelete({ ...idle, saving: true }, publishedKey)).toBe(false);
expect(canStartNacosConfigDelete({ ...idle, deleting: true }, publishedKey)).toBe(false);
expect(canStartNacosConfigDelete({ ...idle, hasPendingSave: true }, publishedKey)).toBe(false);
expect(canStartNacosConfigDelete({ ...idle, hasPendingDelete: true }, publishedKey)).toBe(false);
});
it("freezes delete confirmation scope and never redirects it to a newly selected connection", async () => {
const key = { namespace: "dev", dataId: "application.yaml", group: "DEFAULT_GROUP" };
const config = { ...key, desc: "old connection config" };
const snapshot = createNacosConfigDeleteSnapshot("old-connection", key, config);
key.dataId = "mutated.yaml";
config.desc = "mutated after confirmation";
const deletedConnections: string[] = [];
const executeIfCurrent = async (connectionId: string, namespace: string) => {
if (!isNacosConfigDeleteSnapshotInScope(snapshot, connectionId, namespace)) return;
deletedConnections.push(snapshot.connectionId);
};
await executeIfCurrent("new-connection", "dev");
expect(deletedConnections).toEqual([]);
expect(snapshot).toMatchObject({
connectionId: "old-connection",
key: { namespace: "dev", dataId: "application.yaml", group: "DEFAULT_GROUP" },
config: { desc: "old connection config" },
});
});
it("splits every case-sensitive literal content match for safe highlighting", () => {
expect(splitNacosContentLiteralMatches("url=/deploy/deploy?mode=Deploy", "deploy")).toEqual([
{ text: "url=/", matched: false },
{ text: "deploy", matched: true },
{ text: "/", matched: false },
{ text: "deploy", matched: true },
{ text: "?mode=Deploy", matched: false },
]);
expect(splitNacosContentLiteralMatches("<script>alert(1)</script>", "alert")).toEqual([
{ text: "<script>", matched: false },
{ text: "alert", matched: true },
{ text: "(1)</script>", matched: false },
]);
});
it("exports content search matches as UTF-8 CSV and neutralizes spreadsheet formulas", () => {
const csv = buildNacosContentSearchCsv([
{
namespace: "",
group: "dev",
dataId: '=IMPORTXML("https://example.test")',
lineNumber: 12,
snippet: 'url: "jdbc:mysql://db/a,b"\nuser: root',
},
]);
expect(csv.startsWith("\uFEFF")).toBe(true);
expect(csv).toContain('"public","dev","\'=IMPORTXML(""https://example.test"")","12"');
expect(csv).toContain('"url: ""jdbc:mysql://db/a,b""\nuser: root"');
});
});
@@ -0,0 +1,81 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createNacosNamespaceRequestGuard, NACOS_NAMESPACES_CHANGED_EVENT, notifyNacosNamespacesChanged, subscribeNacosNamespacesChanged } from "@/lib/nacos/nacosNamespaceCache";
afterEach(() => {
vi.unstubAllGlobals();
});
describe("Nacos namespace request guard", () => {
it("prevents an older response from replacing a newer namespace list", async () => {
const guard = createNacosNamespaceRequestGuard();
const committedLists: string[][] = [];
let resolveOlder!: (value: string[]) => void;
let resolveNewer!: (value: string[]) => void;
const olderResponse = new Promise<string[]>((resolve) => {
resolveOlder = resolve;
});
const newerResponse = new Promise<string[]>((resolve) => {
resolveNewer = resolve;
});
const olderRequest = guard.start("conn-1");
const commitOlder = olderResponse.then((namespaces) => {
if (guard.isCurrent(olderRequest, "conn-1")) committedLists.push(namespaces);
});
const newerRequest = guard.start("conn-1");
const commitNewer = newerResponse.then((namespaces) => {
if (guard.isCurrent(newerRequest, "conn-1")) committedLists.push(namespaces);
});
resolveNewer(["public", "new-space"]);
await commitNewer;
resolveOlder(["public"]);
await commitOlder;
expect(committedLists).toEqual([["public", "new-space"]]);
});
it("rejects pending responses after invalidation or a connection change", () => {
const guard = createNacosNamespaceRequestGuard();
const request = guard.start("conn-1");
expect(guard.isCurrent(request, "conn-2")).toBe(false);
guard.invalidate();
expect(guard.isCurrent(request, "conn-1")).toBe(false);
});
});
describe("Nacos namespace change events", () => {
it("notifies open views for the affected connection and supports unsubscribe", () => {
const listeners = new Map<string, Set<(event: Event) => void>>();
vi.stubGlobal("window", {
addEventListener: (type: string, listener: (event: Event) => void) => {
const handlers = listeners.get(type) ?? new Set();
handlers.add(listener);
listeners.set(type, handlers);
},
removeEventListener: (type: string, listener: (event: Event) => void) => {
listeners.get(type)?.delete(listener);
},
dispatchEvent: (event: Event) => {
listeners.get(event.type)?.forEach((listener) => listener(event));
return true;
},
});
const listener = vi.fn();
const unsubscribe = subscribeNacosNamespacesChanged(listener);
notifyNacosNamespacesChanged("conn-1");
expect(listener).toHaveBeenCalledOnce();
expect(listener).toHaveBeenCalledWith({ connectionId: "conn-1" });
expect(listeners.get(NACOS_NAMESPACES_CHANGED_EVENT)?.size).toBe(1);
unsubscribe();
notifyNacosNamespacesChanged("conn-1");
expect(listener).toHaveBeenCalledOnce();
expect(listeners.get(NACOS_NAMESPACES_CHANGED_EVENT)?.size).toBe(0);
});
});