fix(etcd): preserve raw key identity in browser actions

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-07-27 13:18:53 +08:00
1 parent 122853d089
commit 39d0f5b30f
69 files changed
+6577 -742

No files matched your search

@@ -0,0 +1,28 @@
export type EtcdDashboardErrorKind = "unsupported" | "request";
export interface EtcdDashboardError {
kind: EtcdDashboardErrorKind;
message: string;
}
const unsupportedStatusPatterns = ["etcd_status_unsupported", "unknown method: kv_status", "method not found: kv_status", "method not found: `kv_status`"];
function errorText(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error || "");
}
export function sanitizeEtcdDashboardError(error: unknown): string {
const raw = errorText(error).trim();
const withoutStderr = raw.split(/\s*(?:\.\s*)?recent stderr\s*:/i, 1)[0]?.trim() || raw;
return withoutStderr.replace(/^ETCD_STATUS_UNSUPPORTED:\s*/i, "").slice(0, 600);
}
export function classifyEtcdDashboardError(error: unknown): EtcdDashboardError {
const raw = errorText(error);
const normalized = raw.toLowerCase();
return {
kind: unsupportedStatusPatterns.some((pattern) => normalized.includes(pattern)) ? "unsupported" : "request",
message: sanitizeEtcdDashboardError(error),
};
}
@@ -0,0 +1,95 @@
import type { KvPrometheusMetrics } from "@/lib/backend/tauri";
type NumericMetricKey = Exclude<
{
[K in keyof KvPrometheusMetrics]: KvPrometheusMetrics[K] extends number | null | undefined ? K : never;
}[keyof KvPrometheusMetrics],
undefined
>;
type MetricMapKey = Exclude<
{
[K in keyof KvPrometheusMetrics]: KvPrometheusMetrics[K] extends Record<string, number> ? K : never;
}[keyof KvPrometheusMetrics],
undefined
>;
function finiteMetric(metrics: KvPrometheusMetrics | null | undefined, key: NumericMetricKey): number | null {
const value = metrics?.[key];
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function comparableWindowSeconds(current: KvPrometheusMetrics, previous: KvPrometheusMetrics | null | undefined): number | null {
if (!previous || current.sourceUrl !== previous.sourceUrl) return null;
const currentTime = finiteMetric(current, "collectedAtMs");
const previousTime = finiteMetric(previous, "collectedAtMs");
if (currentTime == null || previousTime == null || currentTime <= previousTime) return null;
return (currentTime - previousTime) / 1000;
}
export function counterRate(current: KvPrometheusMetrics | null | undefined, previous: KvPrometheusMetrics | null | undefined, key: NumericMetricKey): number | null {
if (!current?.available || !previous?.available) return null;
const seconds = comparableWindowSeconds(current, previous);
const currentValue = finiteMetric(current, key);
const previousValue = finiteMetric(previous, key);
if (seconds == null || currentValue == null || previousValue == null || currentValue < previousValue) return null;
return (currentValue - previousValue) / seconds;
}
export function histogramAverageMilliseconds(current: KvPrometheusMetrics | null | undefined, previous: KvPrometheusMetrics | null | undefined, sumKey: NumericMetricKey, countKey: NumericMetricKey): number | null {
if (!current?.available) return null;
const currentSum = finiteMetric(current, sumKey);
const currentCount = finiteMetric(current, countKey);
if (currentSum == null || currentCount == null || currentCount <= 0) return null;
const previousSum = finiteMetric(previous, sumKey);
const previousCount = finiteMetric(previous, countKey);
const hasComparableWindow = comparableWindowSeconds(current, previous) != null;
if (hasComparableWindow && previousSum != null && previousCount != null && currentSum >= previousSum && currentCount > previousCount) {
return ((currentSum - previousSum) / (currentCount - previousCount)) * 1000;
}
return (currentSum / currentCount) * 1000;
}
export function ratePercentage(numerator: number | null, denominator: number | null): number | null {
if (numerator == null || denominator == null || denominator <= 0) return null;
return Math.min(100, Math.max(0, (numerator / denominator) * 100));
}
export function counterMapRates(current: KvPrometheusMetrics | null | undefined, previous: KvPrometheusMetrics | null | undefined, key: MetricMapKey): Record<string, number> {
if (!current?.available || !previous?.available) return {};
const seconds = comparableWindowSeconds(current, previous);
const currentValues = current[key];
const previousValues = previous[key];
if (seconds == null || !currentValues || !previousValues) return {};
return Object.fromEntries(
Object.entries(currentValues).flatMap(([name, currentValue]) => {
const previousValue = previousValues[name];
return Number.isFinite(currentValue) && Number.isFinite(previousValue) && currentValue >= previousValue ? [[name, (currentValue - previousValue) / seconds]] : [];
}),
);
}
export function histogramMapAverageMilliseconds(current: KvPrometheusMetrics | null | undefined, previous: KvPrometheusMetrics | null | undefined, sumKey: MetricMapKey, countKey: MetricMapKey): Record<string, number> {
if (!current?.available) return {};
const currentSums = current[sumKey];
const currentCounts = current[countKey];
if (!currentSums || !currentCounts) return {};
const previousSums = previous?.[sumKey];
const previousCounts = previous?.[countKey];
const useDelta = comparableWindowSeconds(current, previous) != null;
return Object.fromEntries(
Object.entries(currentSums).flatMap(([name, currentSum]) => {
const currentCount = currentCounts[name];
if (!Number.isFinite(currentSum) || !Number.isFinite(currentCount) || currentCount <= 0) return [];
const previousSum = previousSums?.[name];
const previousCount = previousCounts?.[name];
if (useDelta && Number.isFinite(previousSum) && Number.isFinite(previousCount) && currentSum >= previousSum! && currentCount > previousCount!) {
return [[name, ((currentSum - previousSum!) / (currentCount - previousCount!)) * 1000]];
}
return [[name, (currentSum / currentCount) * 1000]];
}),
);
}
+36
View File
@@ -0,0 +1,36 @@
import type { KvValue } from "@/lib/backend/api";
export type KvExportScopeKind = "key" | "prefix";
export interface KvExportScopeRequest {
path: string;
kind: KvExportScopeKind;
keyBytes?: KvValue | null;
}
export function kvDirectoryPrefix(path: string): string {
if (!path || path === "/") return path;
return `${path.replace(/\/+$/, "")}/`;
}
export function isKeyInKvExportScope(key: string, request: KvExportScopeRequest): boolean {
if (request.kind === "key") return key === request.path;
return key === request.path || key.startsWith(kvDirectoryPrefix(request.path));
}
export function kvExportFilenameStem(path: string): string {
const normalized = path
.split("/")
.filter(Boolean)
.join("-")
.replace(/[<>:"\\|?*\u0000-\u001f]/g, "-")
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
return normalized.slice(0, 80) || "root";
}
export function kvValueByteIdentity(value: KvValue): string {
const bytes = value.encoding === "utf8" ? new TextEncoder().encode(value.data) : Uint8Array.from(atob(value.data.replace(/\s+/g, "")), (character) => character.charCodeAt(0));
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
+14
View File
@@ -0,0 +1,14 @@
import type { KvKeySummary } from "@/lib/backend/api";
export function normalizeKvKeySearchQuery(query: string): string {
return query.trim().toLocaleLowerCase();
}
export function kvKeyMatchesSearch(key: string, query: string): boolean {
const normalized = normalizeKvKeySearchQuery(query);
return !normalized || key.toLocaleLowerCase().includes(normalized);
}
export function filterKvKeysBySearch(keys: readonly KvKeySummary[], query: string): KvKeySummary[] {
return keys.filter((key) => kvKeyMatchesSearch(key.key, query));
}
+76 -10
View File
@@ -1,15 +1,17 @@
import type { KvKeySummary } from "@/lib/backend/api";
import type { KvKeySummary, KvValue } from "@/lib/backend/api";
export interface KvKeyTreeLeafNode {
kind: "leaf";
id: string;
label: string;
key: string;
keyIdentity?: string | null;
keyBytes?: KvValue | null;
pathSegments: string[];
createRevision?: number | null;
modRevision?: number | null;
version?: number | null;
lease?: number | null;
createRevision?: string | number | null;
modRevision?: string | number | null;
version?: string | number | null;
lease?: string | number | null;
valueSize?: number | null;
}
@@ -19,6 +21,14 @@ export interface KvKeyTreeGroupNode {
label: string;
pathSegments: string[];
children: KvKeyTreeNode[];
key?: string;
keyIdentity?: string | null;
keyBytes?: KvValue | null;
createRevision?: string | number | null;
modRevision?: string | number | null;
version?: string | number | null;
lease?: string | number | null;
valueSize?: number | null;
}
export type KvKeyTreeNode = KvKeyTreeLeafNode | KvKeyTreeGroupNode;
@@ -36,8 +46,12 @@ function groupId(pathSegments: string[]): string {
return `group:${pathSegments.join("\u0000")}`;
}
function leafId(key: string): string {
return `leaf:${key}`;
function summaryIdentity(key: KvKeySummary): string {
return key.keyIdentity ?? key.key;
}
function leafId(key: KvKeySummary): string {
return `leaf:${summaryIdentity(key)}`;
}
function sortNodes(nodes: KvKeyTreeNode[]): KvKeyTreeNode[] {
@@ -58,9 +72,11 @@ export function buildKvKeyTree(keys: KvKeySummary[]): KvKeyTreeNode[] {
if (segments.length <= 1) {
root.push({
kind: "leaf",
id: leafId(key.key),
id: leafId(key),
label: segments[0] || key.key || "/",
key: key.key,
keyIdentity: key.keyIdentity,
keyBytes: key.keyBytes,
pathSegments: segments,
createRevision: key.createRevision,
modRevision: key.modRevision,
@@ -78,18 +94,49 @@ export function buildKvKeyTree(keys: KvKeySummary[]): KvKeyTreeNode[] {
const id = groupId(groupSegments);
let group = groups.get(id);
if (!group) {
group = { kind: "group", id, label: segment, pathSegments: [...groupSegments], children: [] };
const leafIndex = current.findIndex((candidate) => candidate.kind === "leaf" && candidate.pathSegments.join("\u0000") === groupSegments.join("\u0000"));
const existingLeaf = leafIndex >= 0 ? (current.splice(leafIndex, 1)[0] as KvKeyTreeLeafNode) : null;
group = {
kind: "group",
id,
label: segment,
pathSegments: [...groupSegments],
children: [],
key: existingLeaf?.key,
keyIdentity: existingLeaf?.keyIdentity,
keyBytes: existingLeaf?.keyBytes,
createRevision: existingLeaf?.createRevision,
modRevision: existingLeaf?.modRevision,
version: existingLeaf?.version,
lease: existingLeaf?.lease,
valueSize: existingLeaf?.valueSize,
};
groups.set(id, group);
current.push(group);
}
current = group.children;
}
const existingGroup = groups.get(groupId(segments));
if (existingGroup) {
existingGroup.key = key.key;
existingGroup.keyIdentity = key.keyIdentity;
existingGroup.keyBytes = key.keyBytes;
existingGroup.createRevision = key.createRevision;
existingGroup.modRevision = key.modRevision;
existingGroup.version = key.version;
existingGroup.lease = key.lease;
existingGroup.valueSize = key.valueSize;
continue;
}
current.push({
kind: "leaf",
id: leafId(key.key),
id: leafId(key),
label: segments[segments.length - 1],
key: key.key,
keyIdentity: key.keyIdentity,
keyBytes: key.keyBytes,
pathSegments: segments,
createRevision: key.createRevision,
modRevision: key.modRevision,
@@ -134,3 +181,22 @@ export function flattenVisibleKvKeyTree(nodes: KvKeyTreeNode[], expandedGroupIds
}
return rows;
}
export function kvKeyTreeNodePath(node: KvKeyTreeNode): string {
if (node.kind === "leaf") return node.key;
if (node.key) return node.key;
const descendantKey = firstDescendantKey(node);
const joined = node.pathSegments.join("/");
return descendantKey?.startsWith("/") ? `/${joined}` : joined;
}
function firstDescendantKey(node: KvKeyTreeGroupNode): string | null {
for (const child of node.children) {
if (child.kind === "leaf") return child.key;
if (child.key) return child.key;
const nested = firstDescendantKey(child);
if (nested) return nested;
}
return null;
}
+16 -7
View File
@@ -45,18 +45,27 @@ export function mergeKvValueRefresh(current: KvGetResponse | null, incoming: KvG
return current;
}
export function removeMissingKvKey(keys: readonly KvKeySummary[], missingKey: string): KvKeySummary[] {
return keys.filter((key) => key.key !== missingKey);
function matchesKvKey(summary: KvKeySummary, key: string, keyIdentity?: string | null): boolean {
return keyIdentity != null ? (summary.keyIdentity ?? summary.key) === keyIdentity : summary.key === key;
}
export function knownKvLeaseKeys(keys: readonly KvKeySummary[], selectedKey: string | null): string[] {
return keys.filter((key) => key.key !== selectedKey && typeof key.lease === "number" && key.lease > 0).map((key) => key.key);
export function removeMissingKvKey(keys: readonly KvKeySummary[], missingKey: string, missingKeyIdentity?: string | null): KvKeySummary[] {
return keys.filter((summary) => !matchesKvKey(summary, missingKey, missingKeyIdentity));
}
export function mergeKvKeyMetadata(keys: readonly KvKeySummary[], key: string, incoming: KvGetResponse): KvKeySummary[] {
if (!incoming.found) return removeMissingKvKey(keys, key);
export function hasPositiveKvLease(lease: string | number | null | undefined): boolean {
if (typeof lease === "number") return Number.isInteger(lease) && lease > 0;
return typeof lease === "string" && /^[1-9]\d*$/.test(lease.trim());
}
export function knownKvLeaseSummaries(keys: readonly KvKeySummary[], selectedKeyIdentity: string | null): KvKeySummary[] {
return keys.filter((key) => (key.keyIdentity ?? key.key) !== selectedKeyIdentity && hasPositiveKvLease(key.lease));
}
export function mergeKvKeyMetadata(keys: readonly KvKeySummary[], key: string, incoming: KvGetResponse, keyIdentity?: string | null): KvKeySummary[] {
if (!incoming.found) return removeMissingKvKey(keys, key, keyIdentity);
if (!incoming.metadata) return [...keys];
return keys.map((item) => (item.key === key ? { ...item, ...incoming.metadata, key: item.key, valueSize: item.valueSize } : item));
return keys.map((item) => (matchesKvKey(item, key, keyIdentity) ? { ...item, ...incoming.metadata, key: item.key, valueSize: item.valueSize } : item));
}
export function nextKvLeaseRefreshDelay(currentDelayMs: number, failed: boolean, baseDelayMs = 2000, maxDelayMs = 30000): number {
@@ -0,0 +1,40 @@
export type KvMutationErrorKind = "keyAlreadyExists" | "conflict" | "request";
export interface KvMutationError {
kind: KvMutationErrorKind;
message: string;
}
export interface KvMutationErrorMessages {
keyAlreadyExists?: string;
conflict?: string;
}
function errorText(error: unknown): string {
return error instanceof Error ? error.message : String(error || "");
}
export function sanitizeKvMutationError(error: unknown): string {
const raw = errorText(error).trim();
const withoutStderr = raw.split(/\s*(?:\.\s*)?recent stderr\s*:/i, 1)[0]?.trim() || raw;
return withoutStderr.replace(/^Agent RPC error(?:\s*\([^)]*\))?\s*:\s*/i, "").slice(0, 600);
}
export function classifyKvMutationError(error: unknown, creating: boolean, messages: KvMutationErrorMessages = {}): KvMutationError {
const sanitized = sanitizeKvMutationError(error);
const normalized = sanitized.toLowerCase();
if (normalized.includes("etcd_key_already_exists") || (creating && normalized.includes("etcd_cas_conflict"))) {
return {
kind: "keyAlreadyExists",
message: messages.keyAlreadyExists || "A Key with this name already exists. Choose another name or edit the existing Key.",
};
}
if (normalized.includes("etcd_cas_conflict")) {
return {
kind: "conflict",
message: messages.conflict || "The Key changed after it was loaded. Refresh it and try again.",
};
}
return { kind: "request", message: sanitized };
}
@@ -1,6 +1,6 @@
import type { KvKeySummary } from "@/lib/backend/api";
export function refreshedKvSelectionKey(previousKey: string | null | undefined, refreshedKeys: readonly KvKeySummary[]): string | null {
if (!previousKey) return null;
return refreshedKeys.some((item) => item.key === previousKey) ? previousKey : null;
export function refreshedKvSelectionSummary(previousIdentity: string | null | undefined, refreshedKeys: readonly KvKeySummary[]): KvKeySummary | null {
if (!previousIdentity) return null;
return refreshedKeys.find((item) => (item.keyIdentity ?? item.key) === previousIdentity) ?? null;
}
+13
View File
@@ -1,3 +1,5 @@
import type { KvInt64 } from "@/lib/backend/api";
export type ParsedOptionalTtl = { ok: true; ttl: number | null } | { ok: false };
export function parseOptionalTtl(value: string | number | null | undefined): ParsedOptionalTtl {
@@ -11,3 +13,14 @@ export function parseOptionalTtl(value: string | number | null | undefined): Par
if (!Number.isSafeInteger(ttl)) return { ok: false };
return { ok: true, ttl };
}
export function parseKvLeaseId(value: string | number | null | undefined): KvInt64 | null {
const normalized = String(value ?? "").trim();
if (!/^[1-9]\d*$/.test(normalized)) return null;
try {
if (BigInt(normalized) > 9_223_372_036_854_775_807n) return null;
} catch {
return null;
}
return normalized;
}
+1 -1
View File
@@ -28,7 +28,7 @@ export function prettyPrintJsonText(text: string): PrettyPrintJsonResult {
}
}
function valueLabel(value: number | null | undefined): string {
function valueLabel(value: string | number | null | undefined): string {
return value == null ? "-" : String(value);
}
+102
View File
@@ -0,0 +1,102 @@
import { jsonLanguage } from "@codemirror/lang-json";
import { yamlLanguage } from "@codemirror/lang-yaml";
import { xmlLanguage } from "@codemirror/lang-xml";
export type KvValueFormat = "text" | "base64" | "json" | "yaml" | "xml" | "sql" | "properties" | "shell" | "dockerfile" | "nginx" | "kubernetes";
const DOCKERFILE_INSTRUCTIONS = new Set(["ADD", "ARG", "CMD", "COPY", "ENTRYPOINT", "ENV", "EXPOSE", "FROM", "HEALTHCHECK", "LABEL", "MAINTAINER", "ONBUILD", "RUN", "SHELL", "STOPSIGNAL", "USER", "VOLUME", "WORKDIR"]);
function syntaxError(language: { parser: { parse: (text: string) => { cursor: () => { type: { isError: boolean }; next: () => boolean } } } }, text: string): boolean {
const cursor = language.parser.parse(text).cursor();
do {
if (cursor.type.isError) return true;
} while (cursor.next());
return false;
}
export function detectKvValueFormat(text: string, encoding: "utf8" | "base64" = "utf8"): KvValueFormat {
if (encoding === "base64") return "base64";
const trimmed = text.trim();
if (!trimmed) return "text";
if ((trimmed.startsWith("{") || trimmed.startsWith("[")) && !syntaxError(jsonLanguage, text)) return "json";
if (trimmed.startsWith("<") && !syntaxError(xmlLanguage, text)) return "xml";
if (/^#!\s*\/(?:usr\/bin\/env\s+)?(?:ba|z|k)?sh\b/m.test(text)) return "shell";
if (/^(?:#\s*syntax=\S+\s*)?(?:FROM|ARG)\s+\S+/im.test(text)) return "dockerfile";
if (/^\s*(?:events|http|server|upstream|location)\b[^{;]*\{/m.test(text)) return "nginx";
if (/^\s*apiVersion\s*:\s*\S+/m.test(text) && /^\s*kind\s*:\s*\S+/m.test(text) && !syntaxError(yamlLanguage, text)) return "kubernetes";
if (/^\s*(?:SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH|GRANT|REVOKE)\b/im.test(text)) return "sql";
if (/^(?:[#!].*\n)*\s*[A-Za-z0-9_.-]+\s*=\s*\S/m.test(text)) return "properties";
if (/^(---\s*$|[A-Za-z0-9_.-]+\s*:)/m.test(text) && !syntaxError(yamlLanguage, text)) return "yaml";
return "text";
}
export function validateKvValue(text: string, format: KvValueFormat): string | null {
if (format === "json") {
try {
JSON.parse(text);
return null;
} catch (error) {
return error instanceof Error ? error.message : String(error);
}
}
if ((format === "yaml" || format === "kubernetes") && syntaxError(yamlLanguage, text)) return "Invalid YAML syntax";
if (format === "xml" && syntaxError(xmlLanguage, text)) return "Invalid XML syntax";
if (format === "base64") {
const normalized = text.replace(/\s+/g, "");
if (normalized && (!/^[A-Za-z0-9+/]*={0,2}$/.test(normalized) || normalized.length % 4 !== 0)) return "Invalid Base64 data";
}
if (format === "kubernetes" && text.trim()) {
const documents = text
.split(/^---\s*$/m)
.map((document) => document.trim())
.filter(Boolean);
if (documents.some((document) => !/^\s*apiVersion\s*:\s*\S+/m.test(document) || !/^\s*kind\s*:\s*\S+/m.test(document))) {
return "Each Kubernetes document must contain apiVersion and kind";
}
}
if (format === "properties") {
let continuing = false;
const invalidLine = text.split(/\r?\n/).find((line) => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith("!")) return false;
if (continuing) {
continuing = trimmed.endsWith("\\");
return false;
}
continuing = trimmed.endsWith("\\");
return !/[=:]/.test(trimmed) && !continuing;
});
if (invalidLine) return `Invalid Properties entry: ${invalidLine}`;
if (continuing) return "Invalid Properties entry: unfinished continuation";
}
if (format === "dockerfile") {
let continuing = false;
const invalidInstruction = text.split(/\r?\n/).find((line) => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) return false;
if (continuing) {
continuing = trimmed.endsWith("\\");
return false;
}
continuing = trimmed.endsWith("\\");
return !DOCKERFILE_INSTRUCTIONS.has(trimmed.split(/\s+/, 1)[0].toUpperCase());
});
if (invalidInstruction) return `Unknown Dockerfile instruction: ${invalidInstruction.split(/\s+/, 1)[0]}`;
if (continuing) return "Invalid Dockerfile: unfinished line continuation";
}
if (format === "nginx") {
let depth = 0;
for (const character of text.replace(/#[^\r\n]*/g, "")) {
if (character === "{") depth++;
if (character === "}") depth--;
if (depth < 0) return "Invalid Nginx configuration: unexpected closing brace";
}
if (depth !== 0) return "Invalid Nginx configuration: unbalanced braces";
}
return null;
}
export function formatKvValue(text: string, format: KvValueFormat): string {
if (format === "json") return JSON.stringify(JSON.parse(text), null, 2);
return text;
}